qubit_id/snowflake/timestamp_precision.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2026 Haixing Hu.
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 *
7 * Licensed under the Apache License, Version 2.0.
8 *
9 ******************************************************************************/
10//! Timestamp precision for Qubit snowflake IDs.
11
12use super::constants::{
13 SEQUENCE_BITS_IN_MILLISECOND,
14 SEQUENCE_BITS_IN_SECOND,
15 TIMESTAMP_BITS_IN_MILLISECOND,
16 TIMESTAMP_BITS_IN_SECOND,
17 WAIT_DURATION_IN_MILLISECOND,
18 WAIT_DURATION_IN_SECOND,
19};
20
21/// Timestamp precision encoded in a Qubit snowflake ID.
22#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
23pub enum TimestampPrecision {
24 /// Millisecond precision with 41 timestamp bits and 12 sequence bits.
25 Millisecond,
26 /// Second precision with 31 timestamp bits and 22 sequence bits.
27 Second,
28}
29
30impl TimestampPrecision {
31 /// Returns the one-bit ordinal used by the Qubit layout.
32 ///
33 /// # Returns
34 /// `0` for millisecond precision and `1` for second precision.
35 pub const fn ordinal(self) -> u64 {
36 match self {
37 Self::Millisecond => 0,
38 Self::Second => 1,
39 }
40 }
41
42 /// Decodes timestamp precision from a one-bit value.
43 ///
44 /// # Parameters
45 /// - `bit`: Encoded one-bit precision value.
46 ///
47 /// # Returns
48 /// [`TimestampPrecision::Millisecond`] for `0`; [`TimestampPrecision::Second`]
49 /// for every non-zero value after masking by callers.
50 pub const fn from_bit(bit: u64) -> Self {
51 if bit == 0 { Self::Millisecond } else { Self::Second }
52 }
53
54 /// Returns the number of timestamp bits for this precision.
55 ///
56 /// # Returns
57 /// Timestamp bit length.
58 pub const fn timestamp_bits(self) -> u8 {
59 match self {
60 Self::Millisecond => TIMESTAMP_BITS_IN_MILLISECOND,
61 Self::Second => TIMESTAMP_BITS_IN_SECOND,
62 }
63 }
64
65 /// Returns the number of sequence bits for this precision.
66 ///
67 /// # Returns
68 /// Sequence bit length.
69 pub const fn sequence_bits(self) -> u8 {
70 match self {
71 Self::Millisecond => SEQUENCE_BITS_IN_MILLISECOND,
72 Self::Second => SEQUENCE_BITS_IN_SECOND,
73 }
74 }
75
76 /// Returns the time unit divisor in milliseconds.
77 ///
78 /// # Returns
79 /// `1` for millisecond precision and `1000` for second precision.
80 pub const fn divisor_millis(self) -> u64 {
81 match self {
82 Self::Millisecond => 1,
83 Self::Second => 1_000,
84 }
85 }
86
87 /// Returns the sleep duration used while waiting for a new time slice.
88 ///
89 /// # Returns
90 /// Wait duration in milliseconds.
91 pub const fn wait_duration_millis(self) -> u64 {
92 match self {
93 Self::Millisecond => WAIT_DURATION_IN_MILLISECOND,
94 Self::Second => WAIT_DURATION_IN_SECOND,
95 }
96 }
97}