WorkshopTasker/server/utils/snowflake.ts

44 lines
1.2 KiB
TypeScript
Raw Normal View History

2023-05-11 06:03:22 +02:00
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() {
this.set_timestamp(Date.now());
this.set_processid(1);
this.set_increment(Snowflake.increment());
}
public toString() {
return this.state.toString();
}
}