armour-core 0.1.0

Core types for armour ecosystem
Documentation
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
use core::{hash::Hash, str::FromStr};
use std::{fmt::Debug, marker::PhantomData};

#[cfg(feature = "bytemuck")]
use bytemuck::{Pod, TransparentWrapper, Zeroable};
use rapira::{Rapira, RapiraError};
use rend::u64_be;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};

use crate::{
    IdStr, Typ,
    enc::IdHasher,
    error::ArmourError,
    get_type::GetType,
    key_part::{KeyPart, SEQ64_BITS},
    key_type::KeyType,
    num_ops::g8bits,
};

type Result<T, E = ArmourError> = core::result::Result<T, E>;

/// - 64bit sequence id
/// - Blowfish for encryption (64bit block)
/// - ZBASE32 for encoding into 13 length string
#[derive(IntoBytes, FromBytes, Immutable, KnownLayout)]
#[cfg_attr(
    feature = "rkyv",
    derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
#[cfg_attr(feature = "bytemuck", derive(TransparentWrapper))]
#[cfg_attr(feature = "bytemuck", transparent(u64_be))]
#[cfg_attr(feature = "bitcode", derive(bitcode::Encode, bitcode::Decode))]
#[repr(transparent)]
pub struct Id64<T>(pub u64_be, PhantomData<T>);

#[cfg(feature = "bytemuck")]
unsafe impl<T> Zeroable for Id64<T> {}
#[cfg(feature = "bytemuck")]
unsafe impl<T: 'static> Pod for Id64<T> {}

impl<T> Clone for Id64<T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T> Copy for Id64<T> {}

impl<T> PartialOrd for Id64<T> {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl<T> Ord for Id64<T> {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        self.0.cmp(&other.0)
    }
}

impl<T> PartialEq for Id64<T> {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<T> Eq for Id64<T> {}

impl<T> PartialEq<[u8; 8]> for Id64<T> {
    fn eq(&self, other: &[u8; 8]) -> bool {
        let bytes: &[u8; 8] = zerocopy::transmute_ref!(self);
        bytes == other
    }
}

impl<T> PartialEq<Id64<T>> for [u8; 8] {
    fn eq(&self, other: &Id64<T>) -> bool {
        let bytes: &[u8; 8] = zerocopy::transmute_ref!(other);
        bytes == self
    }
}

impl<T> PartialEq<Id64<T>> for Option<Id64<T>> {
    fn eq(&self, other: &Id64<T>) -> bool {
        match self {
            Some(id) => id == other,
            None => false,
        }
    }
}

impl<T> PartialEq<Option<Id64<T>>> for Id64<T> {
    fn eq(&self, other: &Option<Id64<T>>) -> bool {
        match other {
            Some(id) => id == self,
            None => false,
        }
    }
}

impl<T> AsRef<Self> for Id64<T> {
    fn as_ref(&self) -> &Self {
        self
    }
}

impl<T> AsRef<[u8; 8]> for Id64<T> {
    fn as_ref(&self) -> &[u8; 8] {
        zerocopy::transmute_ref!(self)
    }
}

impl<T> Id64<T> {
    /// get LE u64
    #[inline]
    pub fn get(self) -> u64 {
        self.0.to_native()
    }

    /// Create a new ID64 from a native (LE) u64.
    #[inline]
    pub fn new(id: u64) -> Self {
        Id64(u64_be::from_native(id), PhantomData)
    }

    #[inline]
    pub fn to_le_bytes(self) -> [u8; 8] {
        self.0.to_native().to_le_bytes()
    }

    #[inline]
    pub fn to_be_bytes(self) -> [u8; 8] {
        zerocopy::transmute!(self)
    }

    #[inline]
    pub fn from_be_bytes(bytes: [u8; 8]) -> Self {
        zerocopy::transmute!(bytes)
    }

    /// to BE bytes
    #[inline]
    pub fn to_bytes(self) -> [u8; 8] {
        zerocopy::transmute!(self)
    }

    /// from BE bytes
    #[inline]
    pub fn from_bytes(bytes: [u8; 8]) -> Self {
        zerocopy::transmute!(bytes)
    }

    /// to BE u64
    #[inline]
    pub fn to_u64(self) -> u64 {
        zerocopy::transmute!(self)
    }

    /// from BE u64
    #[inline]
    pub fn from_u64(bytes: u64) -> Self {
        zerocopy::transmute!(bytes)
    }

    /// get native (LE) u32
    #[inline]
    pub fn get_u32(self) -> Option<u32> {
        let native = self.0.to_native();
        if native > u32::MAX as u64 {
            None
        } else {
            Some(native as u32)
        }
    }

    #[inline]
    pub fn increment(mut self) -> Self {
        self.0 += 1;
        self
    }

    /// group_id for this Id64
    #[inline]
    pub fn group_id(&self) -> u32 {
        let id = self.get();
        g8bits(id, SEQ64_BITS)
    }
}

impl<T: IdHasher> Id64<T> {
    #[inline]
    pub fn deser(s: &str) -> Result<Id64<T>> {
        let v = T::deser(s)?;
        Ok(zerocopy::transmute!(v))
    }

    #[inline]
    pub fn ser(self) -> IdStr {
        let u: u64 = zerocopy::transmute!(self);
        T::ser(u)
    }
}

impl<T: IdHasher> TryFrom<&str> for Id64<T> {
    type Error = ArmourError;
    fn try_from(val: &str) -> Result<Id64<T>> {
        Self::deser(val)
    }
}

impl TryFrom<&str> for Id64<()> {
    type Error = ArmourError;
    fn try_from(val: &str) -> Result<Self> {
        let val = u64::from_str(val)?;
        Ok(Self(u64_be::from_native(val), PhantomData))
    }
}

impl<T: IdHasher> FromStr for Id64<T> {
    type Err = ArmourError;
    fn from_str(s: &str) -> Result<Self> {
        Self::deser(s)
    }
}

impl FromStr for Id64<()> {
    type Err = ArmourError;
    fn from_str(s: &str) -> Result<Self> {
        let val = u64::from_str(s)?;
        Ok(Self(u64_be::from_native(val), PhantomData))
    }
}

impl<T> From<Id64<T>> for u64 {
    #[inline(always)]
    fn from(id: Id64<T>) -> Self {
        id.get()
    }
}

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

impl<T> Debug for Id64<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("ID").field(&self.0).finish()
    }
}

impl<T> Hash for Id64<T> {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.0.hash(state);
    }
}

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

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

#[cfg(feature = "std")]
impl Serialize for Id64<()> {
    fn serialize<S: Serializer>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error> {
        let s = self.get();
        serializer.serialize_u64(s)
    }
}

#[cfg(feature = "std")]
impl<'de> Deserialize<'de> for Id64<()> {
    fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s: u64 = Deserialize::deserialize(deserializer)?;
        Ok(Id64(u64_be::from_native(s), PhantomData))
    }
}

impl<T> Rapira for Id64<T> {
    const STATIC_SIZE: Option<usize> = Some(8);
    const MIN_SIZE: usize = 8;

    #[inline]
    fn size(&self) -> usize {
        8
    }

    #[inline]
    fn check_bytes(slice: &mut &[u8]) -> core::result::Result<(), rapira::RapiraError>
    where
        Self: Sized,
    {
        let bytes: &[u8] = slice.get(..8).ok_or(RapiraError::SliceLen)?;

        if bytes == [0u8; 8] {
            return Err(RapiraError::NonZero);
        }

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

    #[inline]
    fn from_slice(slice: &mut &[u8]) -> core::result::Result<Self, rapira::RapiraError>
    where
        Self: Sized,
    {
        let bytes = <[u8; 8]>::from_slice(slice)?;
        let id = Self::from_bytes(bytes);
        Ok(id)
    }

    #[inline]
    fn convert_to_bytes(&self, slice: &mut [u8], cursor: &mut usize) {
        let bytes: &[u8; 8] = zerocopy::transmute_ref!(self);
        bytes.convert_to_bytes(slice, cursor);
    }
}

impl<T> GetType for Id64<T> {
    const TYPE: Typ = Typ::Id64;
}

impl<H> KeyPart for Id64<H> {
    const TY: KeyType = KeyType::Fuid;
    const PREFIX_BITS: u32 = SEQ64_BITS;
}

#[cfg(feature = "ts-rs")]
impl<T> ts_rs::TS for Id64<T> {
    type WithoutGenerics = Id64<()>;
    type OptionInnerType = Self;
    fn name(_: &ts_rs::Config) -> String {
        "Id64".to_owned()
    }
    fn decl_concrete(c: &ts_rs::Config) -> String {
        format!("type {} = {};", Self::name(c), Self::inline(c))
    }
    fn decl(c: &ts_rs::Config) -> String {
        let inline = <Id64<()> as ::ts_rs::TS>::inline(c);
        format!("type {} = {};", Self::name(c), inline)
    }
    fn inline(_: &ts_rs::Config) -> String {
        "string".to_owned()
    }
    fn inline_flattened(c: &ts_rs::Config) -> String {
        panic!("{} cannot be flattened", Self::name(c))
    }
    fn output_path() -> Option<std::path::PathBuf> {
        Some(std::path::PathBuf::from("id64.ts"))
    }
}

#[cfg(feature = "facet")]
unsafe impl<'facet, T: 'static> facet::Facet<'facet> for Id64<T> {
    const SHAPE: &'static facet::Shape = &const {
        const VTABLE: facet::VTableDirect = facet::vtable_direct!(Id64<()> =>
            Debug,
            Hash,
            PartialEq,
            PartialOrd,
            Ord,
        );

        facet::ShapeBuilder::for_sized::<Id64<T>>("Id64")
            .ty(facet::Type::User(facet::UserType::Struct(facet::StructType {
                repr: facet::Repr::transparent(),
                kind: facet::StructKind::TupleStruct,
                fields: &const {
                    [facet::FieldBuilder::new("0", facet::shape_of::<u64>, 0).build()]
                },
            })))
            .inner(<u64 as facet::Facet>::SHAPE)
            .def(facet::Def::Scalar)
            .vtable_direct(&VTABLE)
            .eq()
            .copy()
            .send()
            .sync()
            .build()
    };
}

#[cfg(feature = "fake")]
impl<H, T> fake::Dummy<T> for Id64<H> {
    fn dummy_with_rng<R: rand::Rng + ?Sized>(_: &T, _: &mut R) -> Self {
        use fake::Fake;

        let u = (0..100_000_000).fake::<u64>();
        Self::new(u)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_increment_basic() {
        let id = Id64::<()>::new(42);
        let incremented = id.increment();
        assert_eq!(incremented.get(), 43);
    }

    #[test]
    fn test_increment_multiple() {
        let id = Id64::<()>::new(100);
        let id = id.increment();
        assert_eq!(id.get(), 101);
        let id = id.increment();
        assert_eq!(id.get(), 102);
        let id = id.increment();
        assert_eq!(id.get(), 103);
    }

    #[test]
    fn test_increment_zero() {
        let id = Id64::<()>::new(0);
        let incremented = id.increment();
        assert_eq!(incremented.get(), 1);
    }

    #[test]
    fn test_increment_large_value() {
        let id = Id64::<()>::new(u64::MAX - 1);
        let incremented = id.increment();
        assert_eq!(incremented.get(), u64::MAX);
    }

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "attempt to add with overflow")]
    fn test_increment_overflow_debug() {
        let id = Id64::<()>::new(u64::MAX);
        let _ = id.increment(); // This will panic in debug mode
    }

    #[test]
    #[cfg(not(debug_assertions))]
    fn test_increment_overflow_release() {
        let id = Id64::<()>::new(u64::MAX);
        let incremented = id.increment();
        // In release mode, this will wrap around to 0
        assert_eq!(incremented.get(), 0);
    }

    #[test]
    fn test_increment_endianness() {
        // Test that increment works correctly with big-endian representation
        let id = Id64::<()>::new(255); // 0xFF
        let incremented = id.increment();
        assert_eq!(incremented.get(), 256); // 0x100

        // Verify the big-endian bytes are correct
        let bytes = incremented.to_be_bytes();
        assert_eq!(bytes, [0, 0, 0, 0, 0, 0, 1, 0]);
    }
}