Skip to content

Commit

Permalink
feat: add compare method to Felt class
Browse files Browse the repository at this point in the history
  • Loading branch information
zmalatrax committed Jul 30, 2024
1 parent 1a6c36a commit 80e05ca
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/hints/assertLeFindSmallArc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export const assertLeFindSmallArcs = (
{ value: aVal, pos: 0 },
{ value: bVal.sub(aVal), pos: 1 },
{ value: new Felt(-1n).sub(bVal), pos: 2 },
].sort((a, b) => (a.value > b.value ? 1 : a.value < b.value ? -1 : 0));
].sort((a, b) => a.value.compare(b.value));

vm.scopeManager.set('excluded_arc', arcs[2].pos);

Expand Down
2 changes: 1 addition & 1 deletion src/hints/dict/initSquashData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export const initSquashData = (
values.reverse();
vm.squashedDictManager.keys.push(new Felt(BigInt(key)));
});
vm.squashedDictManager.keys.sort((a, b) => (a < b ? 1 : a > b ? -1 : 0));
vm.squashedDictManager.keys.sort((a, b) => b.compare(a));

vm.memory.assertEq(
vm.cellRefToRelocatable(bigKeys),
Expand Down
12 changes: 12 additions & 0 deletions src/primitives/felt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,4 +139,16 @@ describe('Felt', () => {
expect(result).toStrictEqual(a);
});
});

describe('compare', () => {
test.each([
[new Felt(1n), new Felt(0n), 1],
[new Felt(1n), new Felt(1n), 0],
[new Felt(0n), new Felt(1n), -1],
[new Felt(-1n), new Felt(-10n), 1],
[new Felt(-1n), new Felt(Felt.PRIME - 1n), 0],
])('should properly compare two Felt', (a, b, expected) => {
expect(a.compare(b)).toEqual(expected);
});
});
});
11 changes: 11 additions & 0 deletions src/primitives/felt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,17 @@ export class Felt {
return !isRelocatable(other) && this.inner === other.inner;
}

/**
* Compare two Felt.
*
* @param other - The Felt to compare against.
* @returns {number} A positive value if `this > other`,
* a negative value if `this < other` and zero if they're equal.
*/
compare(other: Felt): number {
return this > other ? 1 : this < other ? -1 : 0;
}

sqrt(): Felt {
return new Felt(CURVE.Fp.sqrt(this.inner));
}
Expand Down

0 comments on commit 80e05ca

Please sign in to comment.