rust_distributed_id/
bits_allocator.rs

1
2pub const TOTAL_BITS: i32 = 1 << 6;
3
4//bits 分配器
5#[derive(Clone, Debug, Copy)]
6pub struct BitsAllocator {
7    pub sign_bits:     i32,
8    pub timestamp_bits: i32,
9    pub worker_id_bits:  i32,
10    pub sequence_bits: i32,
11    pub allocate_total_bits: i32,
12
13    // Max value for workId & sequence
14    pub max_delta_seconds: i64,
15    pub max_worker_id:  i64,
16    pub max_sequence:   i64,
17
18    //Shift for timestamp & workerId
19    pub timestamp_shift: i32,
20    pub worker_id_shift:  i32,
21}
22
23
24impl BitsAllocator {
25    //构建一个bits管理器实例
26    pub fn new(timestamp_bits: i32, worker_id_bits: i32, sequence_bits: i32) -> Self {
27        let sign_bits: i32 = 1;
28        let allocate_total_bits = sign_bits + timestamp_bits + worker_id_bits + sequence_bits;
29
30        if allocate_total_bits > TOTAL_BITS {
31            panic!("allocate larger than 64 bits");
32        }
33
34        BitsAllocator {
35            sign_bits,
36            timestamp_bits,
37            worker_id_bits,
38            sequence_bits,
39            max_delta_seconds: -1 ^ (-1 << timestamp_bits),
40            max_worker_id: -1 ^ (-1 << worker_id_bits),
41            max_sequence: -1 ^ (-1 << sequence_bits),
42            timestamp_shift: worker_id_bits + sequence_bits,
43            worker_id_shift: sequence_bits,
44            allocate_total_bits
45        }
46    }
47
48    pub fn allocate(&self, delta_seconds: i64, worker_id: i64, sequence: i64) -> i64 {
49        (delta_seconds << self.timestamp_shift) | (worker_id << self.worker_id_shift) | sequence
50    }
51}
52