1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
use core::{cell::Cell, fmt::Debug, marker::PhantomData, num::NonZeroU64};

#[cfg(feature = "std")]
use rand::{thread_rng, Rng};
use rapira::{Rapira, RapiraError};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[cfg(feature = "std")]
use time::{Instant, OffsetDateTime};

use super::{enc::IdHasher, ArmourError, IdStr};
use crate::{Cid, GetType, KeyScheme, KeyType, Typ};

/// different from the unix timestamp epoch
///
/// 2023-04-09 0:00:00 UTC
const TS_DIFF: u64 = 0x0187_6300_0000;

const TS_BITS: u32 = 40;
const TS_SHIFT: u32 = u64::BITS - TS_BITS;

// 2^4 = 16
const APP_BITS: u32 = 4;
const APP_SHIFT: u32 = TS_SHIFT - APP_BITS;
const APP_ID_MAX: u64 = (1 << APP_BITS) - 1;

// 2^5 = 32
const THREAD_BITS: u32 = 5;
const THREAD_SHIFT: u32 = APP_SHIFT - THREAD_BITS;
const THREAD_ID_MAX: u64 = (1 << THREAD_BITS) - 1;

/// 15 bits
const SEQ_BITS: u32 = u64::BITS - TS_BITS - APP_BITS - THREAD_BITS;
/// 32_767 max sequence
const SEQ_MAX: u64 = (1 << SEQ_BITS) - 1;

#[derive(Debug, Clone, Copy, Default)]
struct SeqForMs {
    ms: u16,
    seq: u64,
    count: u64,
}

impl SeqForMs {
    #[cfg(feature = "std")]
    #[inline]
    fn new(ms: u16) -> Self {
        let seq = thread_rng().gen_range(0..=SEQ_MAX);

        SeqForMs { ms, seq, count: 0 }
    }
}

thread_local! {
    static SEQ_CHECK: Cell<SeqForMs> = Cell::new(SeqForMs::default());
}

/// - 64bit id
/// - ZBASE32 for encoding into 13 length string
/// - Blowfish for encryption
/// - first 40 bit - timestamp (in milliseconds) started from 2023-04-09 0:00:00 UTC
/// - 2-8 bit - instance id (datacenter id / shard id)
/// - 4-8 bit - thread id
/// - 8-18 bit - sequence id
/// - create ~50ns (~21k in 1ms)
#[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct Fuid<H>(NonZeroU64, PhantomData<H>);

impl<H> Fuid<H> {
    #[cfg(feature = "std")]
    pub fn new(instance_id: u64, thread_id: u64) -> Self {
        debug_assert!(instance_id <= APP_ID_MAX);
        debug_assert!(thread_id <= THREAD_ID_MAX);

        let now = OffsetDateTime::now_utc();
        let ts = (now.unix_timestamp() as u64) * 1000;
        let nanos = now.nanosecond();
        let ms = (nanos / 1_000_000) as u16;

        // in ms
        let ts = ts + (ms as u64);
        // log::debug!("now in ms: {ts:#} {ts:#x}");

        let ts = ts - TS_DIFF;
        // log::debug!("now from custom epoch in ms: {ts:#} {ts:#x}");

        let ts = ts << TS_SHIFT;
        // log::debug!("bits: {ts:b}");

        let ts = ts | (instance_id << APP_SHIFT);
        // log::debug!("bits: {ts:b}");

        let ts = ts | (thread_id << THREAD_SHIFT);
        // log::debug!("bits: {ts:b}");

        let mut seq_check = SEQ_CHECK.get();

        if seq_check.ms == ms {
            if seq_check.count == SEQ_MAX {
                let instant = Instant::now();
                let nanos = now.nanosecond();
                let nanos = nanos % 1_000_000;
                let wait_nanos = (1_000_000 - nanos) as i128;

                loop {
                    let duration = instant.elapsed();
                    let elapsed_nanos = duration.whole_nanoseconds();
                    if elapsed_nanos >= wait_nanos {
                        break;
                    }
                    core::hint::spin_loop();
                }

                seq_check = SeqForMs::new(ms);
                SEQ_CHECK.set(seq_check);
            } else {
                seq_check.seq = seq_check.seq.wrapping_add(1);
                seq_check.count += 1;
                SEQ_CHECK.set(seq_check);
            }
        } else {
            seq_check = SeqForMs::new(ms);
            SEQ_CHECK.set(seq_check);
        }

        let ts = ts | seq_check.seq;
        // log::debug!("bits: {ts:b}");

        Self(NonZeroU64::new(ts).unwrap(), PhantomData)
    }

    pub fn date(&self) -> OffsetDateTime {
        let ts = self.0.get() >> TS_SHIFT;
        // ms
        let ts = ts + TS_DIFF;
        let ts = ts as i128;
        let ts = ts * 1_000_000;
        let dt = OffsetDateTime::from_unix_timestamp_nanos(ts);
        dt.unwrap()
    }
}

impl<H: IdHasher> Fuid<H> {
    pub fn ser(&self) -> IdStr {
        H::ser(self.0.get())
    }

    pub fn deser(id: &str) -> Result<Self, ArmourError> {
        H::deser(id).and_then(|id| {
            let id = NonZeroU64::new(id).ok_or(ArmourError::NonZeroError)?;
            Ok(Self(id, PhantomData))
        })
    }
}

impl<H> Rapira for Fuid<H> {
    const STATIC_SIZE: Option<usize> = Some(8);

    fn size(&self) -> usize {
        8
    }

    fn check_bytes(slice: &mut &[u8]) -> rapira::Result<()> {
        let bytes: &[u8] = slice.get(..8).ok_or(RapiraError::SliceLenError)?;

        if bytes == u64::MIN.to_le_bytes() {
            return Err(RapiraError::NonZeroError);
        }

        *slice = unsafe { slice.get_unchecked(8..) };
        Ok(())
    }

    fn from_slice(slice: &mut &[u8]) -> rapira::Result<Self>
    where
        Self: Sized,
    {
        let u = u64::from_slice(slice)?;
        let id = NonZeroU64::new(u).ok_or(RapiraError::NonZeroError)?;
        Ok(Self(id, PhantomData))
    }

    fn convert_to_bytes(&self, slice: &mut [u8], cursor: &mut usize) {
        self.0.get().convert_to_bytes(slice, cursor);
    }
}

impl<H> GetType for Fuid<H> {
    const TYPE: Typ = Typ::U64;
}

impl<H: Ord> Cid for Fuid<H> {
    type B = [u8; 8];
    const TY: KeyScheme = KeyScheme::Typed(&[KeyType::U64]);
    // 30 bit timestamp in ms represent 12 days
    const GROUP_BITS: u32 = TS_BITS - 30;

    fn encode(&self) -> Self::B {
        self.0.get().to_be_bytes()
    }

    fn decode(bytes: &Self::B) -> super::Result<Self> {
        let u = u64::from_be_bytes(*bytes);
        let u = NonZeroU64::new(u).ok_or(ArmourError::NonZeroError)?;
        let id = Self(u, PhantomData);
        Ok(id)
    }

    fn group_id(&self) -> u32 {
        (self.0.get() >> (u64::BITS - Self::GROUP_BITS)) as u32
    }
}

impl<H: IdHasher> std::fmt::Display for Fuid<H> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.ser())
    }
}

impl<H> Debug for Fuid<H> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let id = self.0.get();
        let id = format!("{id:#X}");
        f.debug_tuple("Fuid").field(&id).finish()
    }
}

#[cfg(feature = "std")]
impl<T: IdHasher> Serialize for Fuid<T> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let s = self.ser();
        serializer.serialize_str(&s)
    }
}

#[cfg(feature = "std")]
impl<'de, T: IdHasher> Deserialize<'de> for Fuid<T> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        use serde::de::Error;
        let s: &str = Deserialize::deserialize(deserializer)?;
        let a = Fuid::<T>::deser(s).map_err(|_| D::Error::custom("id value error"))?;
        Ok(a)
    }
}