Skip to content

Instantly share code, notes, and snippets.

@goya

goya/long.ts Secret

Created December 1, 2021 15:59
Show Gist options
  • Save goya/8185996e60725371bb30971bd641aad4 to your computer and use it in GitHub Desktop.
Save goya/8185996e60725371bb30971bd641aad4 to your computer and use it in GitHub Desktop.
const thirtyTwo = BigInt(32);
const mask = BigInt(0xffffffff);
class Long implements Long.Long {
public low = 0;
public high = 0;
public readonly unsigned = true;
constructor(low: number | bigint | string, high = 0, unsigned = true) {
if (!unsigned) throw new Error('signed longs unsupported');
try {
if (typeof low === 'string') {
low = BigInt(low);
}
if (typeof low === 'number') {
this.low = low;
this.high = high;
} else if (typeof low === 'bigint') {
this.high = Number(low >> thirtyTwo);
this.low = Number(low & ~(mask << thirtyTwo));
if (this.low > 0) this.low = -(~this.low + 1);
if (this.high > 0) this.high = -(~this.high + 1);
}
} catch {}
}
get bigint(): bigint {
const low = this.low >>> 0;
const high = this.high >>> 0;
return (BigInt(high) << thirtyTwo) + BigInt(low);
}
static get ZERO(): Long {
return new Long(0);
}
toString(): string {
return this.bigint.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment