Skip to content

Commit

Permalink
feat(gadgets.ts): add rightShift function to perform right shift oper…
Browse files Browse the repository at this point in the history
…ation 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.
  • Loading branch information
MartinMinkov committed Oct 23, 2023
1 parent 29e2e9d commit c8f6776
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/lib/gadgets/gadgets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
},
};

0 comments on commit c8f6776

Please sign in to comment.