51 lines
1.4 KiB
TypeScript
51 lines
1.4 KiB
TypeScript
export default class Snowflake {
|
|
static current_increment = 0n;
|
|
|
|
public static increment() {
|
|
this.current_increment = BigInt.asUintN(12, this.current_increment + 1n);
|
|
return this.current_increment;
|
|
}
|
|
|
|
state = 0n;
|
|
public set_timestamp(value: number | bigint) {
|
|
value = BigInt.asUintN(64 - 22, BigInt(value));
|
|
const state = BigInt.asUintN(22, this.state);
|
|
this.state = state + (value << 22n);
|
|
}
|
|
|
|
public set_machineid(value: number | bigint) {
|
|
value = BigInt.asUintN(12 - 17, BigInt(value));
|
|
const state = BigInt.asUintN(17, this.state) + (this.state >> 22n) << 22n;
|
|
this.state = state + (value << 12n);
|
|
}
|
|
|
|
public set_processid(value: number | bigint) {
|
|
value = BigInt.asUintN(17 - 12, BigInt(value));
|
|
const state = BigInt.asUintN(12, this.state) + (this.state >> 17n) << 17n;
|
|
this.state = state + (value << 12n);
|
|
}
|
|
|
|
public set_increment(value: number | bigint) {
|
|
value = BigInt.asUintN(12 - 0, BigInt(value));
|
|
const state = (this.state >> 12n) << 12n;
|
|
this.state = state + (value << 0n);
|
|
}
|
|
|
|
constructor(value?: bigint) {
|
|
if (value) {
|
|
this.state = BigInt.asUintN(64, value);
|
|
return;
|
|
}
|
|
this.set_timestamp(Date.now());
|
|
this.set_processid(1);
|
|
this.set_increment(Snowflake.increment());
|
|
}
|
|
|
|
public toString() {
|
|
return this.state.toString();
|
|
}
|
|
|
|
public get timestamp() {
|
|
return BigInt.asUintN(64 - 22, this.state >> 22n);
|
|
}
|
|
}
|