Skip to content
This repository has been archived by the owner on Jun 26, 2024. It is now read-only.

Commit

Permalink
BigInteger (fallback): add support for negative shift
Browse files Browse the repository at this point in the history
Native BigInts support negative shifts, which are needed for
noble-curves (secp256k1)
  • Loading branch information
larabr committed Jul 21, 2023
1 parent ca8b544 commit 79d1b86
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/biginteger/bn.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,10 @@ export default class BNBigInteger extends AbstractBigInteger {
* Shift this to the left by x, in place
* @param {BigInteger} x - Shift value
*/
ileftShift(x: BNBigInteger) {
ileftShift(x: BNBigInteger): this {
if (x.isNegative()) {
return this.irightShift(x.negate());
}
this.value.ishln(x.value.toNumber());
return this;
}
Expand All @@ -223,7 +226,10 @@ export default class BNBigInteger extends AbstractBigInteger {
* Shift this to the right by x, in place
* @param {BigInteger} x - Shift value
*/
irightShift(x: BNBigInteger) {
irightShift(x: BNBigInteger): this {
if (x.isNegative()) {
return this.ileftShift(x.negate());
}
this.value.ishrn(x.value.toNumber());
return this;
}
Expand Down
10 changes: 10 additions & 0 deletions test/biginteger.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,16 @@ function bigIntegerTests (implementation) {
});
});

should('support shifting by negative values', function() {
const four = BigInteger.new(4);
const two = BigInteger.new(2);
const eight = BigInteger.new(8);
const minusOne = BigInteger.new(-1);

ok(four.rightShift(minusOne).equal(eight));
ok(four.leftShift(minusOne).equal(two));
});

should('unary operators are consistent', function() {
const a = BigInteger.new(12);
const zero = BigInteger.new(0);
Expand Down

0 comments on commit 79d1b86

Please sign in to comment.