From c8f6776e3574bbf338a0a3a7e9092841ed48eb70 Mon Sep 17 00:00:00 2001 From: Martin Minkov Date: Mon, 23 Oct 2023 12:29:17 -0700 Subject: [PATCH] feat(gadgets.ts): add rightShift function to perform right shift operation on Field elements This function is similar to the `>>` shift operation in JavaScript, where bits are moved to the right. It throws an error if the input value exceeds 64 bits. This feature enhances the functionality of the Gadgets library by providing more operations for Field elements. --- src/lib/gadgets/gadgets.ts | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/lib/gadgets/gadgets.ts b/src/lib/gadgets/gadgets.ts index fd8f28da2a..56e98dd743 100644 --- a/src/lib/gadgets/gadgets.ts +++ b/src/lib/gadgets/gadgets.ts @@ -89,4 +89,31 @@ const Gadgets = { leftShift(word: Field, bits: number) { return rot(word, bits, 'left'); }, + + /** + * Performs a right shift operation on the provided {@link Field} element. + * This is similar to the `>>` shift operation in JavaScript, where bits are moved to the right. + * The `rightShift` function utilizes the rotation method internally to implement this operation. + * + * **Note:** You cannot shift {@link Field} elements that exceed 64 bits. + * For elements that exceed 64 bits, this operation will fail. + * + * @param word {@link Field} element to shift. + * @param bits Amount of bits to shift the {@link Field} element to the right. + * + * @throws Throws an error if the input value exceeds 64 bits. + * + * @example + * ```ts + * const x = Provable.witness(Field, () => Field(48)); + * const y = rightShift(x, 2); // right shift by 2 bits + * y.assertEquals(12); + * + * const xLarge = Provable.witness(Field, () => Field(12345678901234567890123456789012345678n)); + * rightShift(xLarge, 32); // throws an error since input exceeds 64 bits + * ``` + */ + rightShift(word: Field, bits: number) { + return rot(word, bits, 'right'); + }, };