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
use core::num::{NonZeroU16, NonZeroU32, NonZeroU8, NonZeroUsize};

/// Types implementing this trait can be used as keys for all Rodeos
///
/// # Safety
///
/// into/from must be perfectly symmetrical, any key that goes on must be perfectly reproduced with the other
///
/// [`ReadOnlyLasso`]: crate::ReadOnlyLasso
pub unsafe trait Key: Copy + Eq {
    /// Returns the `usize` that represents the current key
    fn into_usize(self) -> usize;

    /// Attempts to create a key from a `usize`, returning `None` if it fails
    fn try_from_usize(int: usize) -> Option<Self>;
}

/// A key type taking up `size_of::<usize>()` bytes of space (generally 4 or 8 bytes)
///
/// Internally is a `NonZeroUsize` to allow for space optimizations when stored inside of an [`Option`]
///
/// [`ReadOnlyLasso`]: crate::ReadOnlyLasso
/// [`Option`]: https://doc.rust-lang.org/std/option/enum.Option.html
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct LargeSpur {
    key: NonZeroUsize,
}

unsafe impl Key for LargeSpur {
    #[cfg_attr(feature = "inline-more", inline)]
    fn into_usize(self) -> usize {
        self.key.get() - 1
    }

    /// Returns `None` if `int` is greater than `usize::MAX - 1`
    #[cfg_attr(feature = "inline-more", inline)]
    fn try_from_usize(int: usize) -> Option<Self> {
        if int < usize::max_value() {
            // Safety: The integer is less than the max value and then incremented by one, meaning that
            // is is impossible for a zero to inhabit the NonZeroUsize
            unsafe {
                Some(Self {
                    key: NonZeroUsize::new_unchecked(int + 1),
                })
            }
        } else {
            None
        }
    }
}

impl Default for LargeSpur {
    #[cfg_attr(feature = "inline-more", inline)]
    fn default() -> Self {
        Self::try_from_usize(0).unwrap()
    }
}

/// The default key for every Rodeo, uses only 32 bits of space
///
/// Internally is a `NonZeroU32` to allow for space optimizations when stored inside of an [`Option`]
///
/// [`ReadOnlyLasso`]: crate::ReadOnlyLasso
/// [`Option`]: https://doc.rust-lang.org/std/option/enum.Option.html
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct Spur {
    key: NonZeroU32,
}

unsafe impl Key for Spur {
    #[cfg_attr(feature = "inline-more", inline)]
    fn into_usize(self) -> usize {
        self.key.get() as usize - 1
    }

    /// Returns `None` if `int` is greater than `u32::MAX - 1`
    #[cfg_attr(feature = "inline-more", inline)]
    fn try_from_usize(int: usize) -> Option<Self> {
        if int < u32::max_value() as usize {
            // Safety: The integer is less than the max value and then incremented by one, meaning that
            // is is impossible for a zero to inhabit the NonZeroU32
            unsafe {
                Some(Self {
                    key: NonZeroU32::new_unchecked(int as u32 + 1),
                })
            }
        } else {
            None
        }
    }
}

impl Default for Spur {
    #[cfg_attr(feature = "inline-more", inline)]
    fn default() -> Self {
        Self::try_from_usize(0).unwrap()
    }
}

/// A miniature Key utilizing only 16 bits of space
///
/// Internally is a `NonZeroU16` to allow for space optimizations when stored inside of an [`Option`]
///
/// [`ReadOnlyLasso`]: crate::ReadOnlyLasso
/// [`Option`]: https://doc.rust-lang.org/std/option/enum.Option.html
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct MiniSpur {
    key: NonZeroU16,
}

unsafe impl Key for MiniSpur {
    #[cfg_attr(feature = "inline-more", inline)]
    fn into_usize(self) -> usize {
        self.key.get() as usize - 1
    }

    /// Returns `None` if `int` is greater than `u16::MAX - 1`
    #[cfg_attr(feature = "inline-more", inline)]
    fn try_from_usize(int: usize) -> Option<Self> {
        if int < u16::max_value() as usize {
            // Safety: The integer is less than the max value and then incremented by one, meaning that
            // is is impossible for a zero to inhabit the NonZeroU16
            unsafe {
                Some(Self {
                    key: NonZeroU16::new_unchecked(int as u16 + 1),
                })
            }
        } else {
            None
        }
    }
}

impl Default for MiniSpur {
    #[cfg_attr(feature = "inline-more", inline)]
    fn default() -> Self {
        Self::try_from_usize(0).unwrap()
    }
}

/// A miniature Key utilizing only 8 bits of space
///
/// Internally is a `NonZeroU8` to allow for space optimizations when stored inside of an [`Option`]
///
/// [`ReadOnlyLasso`]: crate::ReadOnlyLasso
/// [`Option`]: https://doc.rust-lang.org/std/option/enum.Option.html
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct MicroSpur {
    key: NonZeroU8,
}

unsafe impl Key for MicroSpur {
    #[cfg_attr(feature = "inline-more", inline)]
    fn into_usize(self) -> usize {
        self.key.get() as usize - 1
    }

    /// Returns `None` if `int` is greater than `u8::MAX - 1`
    #[cfg_attr(feature = "inline-more", inline)]
    fn try_from_usize(int: usize) -> Option<Self> {
        if int < u8::max_value() as usize {
            // Safety: The integer is less than the max value and then incremented by one, meaning that
            // is is impossible for a zero to inhabit the NonZeroU8
            unsafe {
                Some(Self {
                    key: NonZeroU8::new_unchecked(int as u8 + 1),
                })
            }
        } else {
            None
        }
    }
}

impl Default for MicroSpur {
    #[cfg_attr(feature = "inline-more", inline)]
    fn default() -> Self {
        Self::try_from_usize(0).unwrap()
    }
}

macro_rules! impl_serde {
    ($($key:ident => $ty:ident),* $(,)?) => {
        #[cfg(feature = "serialize")]
        mod __serde {
            use super::{$($key),*};
            use serde::{
                de::{Deserialize, Deserializer},
                ser::{Serialize, Serializer},
            };
            use core::num::{$($ty),*};

            $(
                impl Serialize for $key {
                    #[cfg_attr(feature = "inline-more", inline)]
                    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
                    where
                        S: Serializer,
                    {
                        self.key.serialize(serializer)
                    }
                }

                impl<'de> Deserialize<'de> for $key {
                    #[cfg_attr(feature = "inline-more", inline)]
                    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
                    where
                        D: Deserializer<'de>,
                    {
                        let key = <$ty>::deserialize(deserializer)?;
                        Ok(Self { key })
                    }
                }
            )*
        }
    };
}

// Implement `Serialize` and `Deserialize` when the `serde` feature is enabled
impl_serde! {
    Spur => NonZeroU32,
    MiniSpur => NonZeroU16,
    MicroSpur => NonZeroU8,
    LargeSpur => NonZeroUsize,
}

macro_rules! impl_deepsize {
    ($($type:ident),* $(,)?) => {
        #[cfg(feature = "deepsize")]
        mod __deepsize {
            use super::{$($type),*};
            #[cfg(test)]
            use super::Key;
            use deepsize::{DeepSizeOf, Context};
            use core::mem;

            $(
                impl DeepSizeOf for $type {
                    fn deep_size_of_children(&self, _context: &mut Context) -> usize {
                        0
                    }

                    fn deep_size_of(&self) -> usize {
                        mem::size_of::<$type>()
                    }
                }
            )*

            #[test]
            fn deepsize_implementations() {
                $(
                    assert_eq!(
                        mem::size_of::<$type>(),
                        $type::try_from_usize(0).unwrap().deep_size_of(),
                    );
                )*
            }
        }
    };
}

// Implement `DeepSizeOf` when the `deepsize` feature is enabled
impl_deepsize! {
    Spur,
    MiniSpur,
    MicroSpur,
    LargeSpur,
}

macro_rules! impl_abomonation {
    ($($type:ident),* $(,)?) => {
        #[cfg(all(feature = "abomonation", not(feature = "no-std")))]
        mod __abomonation {
            use super::{$($type),*};
            #[cfg(test)]
            use super::Key;
            use abomonation::Abomonation;
            use std::io::{self, Write};

            $(
                impl Abomonation for $type {
                    unsafe fn entomb<W: Write>(&self, write: &mut W) -> io::Result<()> {
                        self.key.entomb(write)
                    }

                    unsafe fn exhume<'a, 'b>(&'a mut self, bytes: &'b mut [u8]) -> Option<&'b mut [u8]> {
                        self.key.exhume(bytes)
                    }

                    fn extent(&self) -> usize {
                        self.key.extent()
                    }
                }
            )*

            #[test]
            fn abomonation_implementations() {
                let mut buf = Vec::new();

                $(
                    unsafe {
                        let base = $type::try_from_usize(0).unwrap();

                        abomonation::encode(&base, &mut buf).unwrap();
                        assert_eq!(base, *abomonation::decode(&mut buf [..]).unwrap().0);
                    }

                    buf.clear();
                )*
            }
        }
    };
}

// Implement `Abomonation` when the `abomonation` feature is enabled
impl_abomonation! {
    Spur,
    MiniSpur,
    MicroSpur,
    LargeSpur,
}

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

    #[test]
    fn large() {
        let zero = LargeSpur::try_from_usize(0).unwrap();
        let max = LargeSpur::try_from_usize(usize::max_value() - 1).unwrap();
        let default = LargeSpur::default();

        assert_eq!(zero.into_usize(), 0);
        assert_eq!(max.into_usize(), usize::max_value() - 1);
        assert_eq!(default.into_usize(), 0);
    }

    #[test]
    fn large_max_returns_none() {
        assert_eq!(None, LargeSpur::try_from_usize(usize::max_value()));
    }

    #[test]
    #[should_panic]
    #[cfg(not(miri))]
    fn large_max_panics() {
        LargeSpur::try_from_usize(usize::max_value()).unwrap();
    }

    #[test]
    fn spur() {
        let zero = Spur::try_from_usize(0).unwrap();
        let max = Spur::try_from_usize(u32::max_value() as usize - 1).unwrap();
        let default = Spur::default();

        assert_eq!(zero.into_usize(), 0);
        assert_eq!(max.into_usize(), u32::max_value() as usize - 1);
        assert_eq!(default.into_usize(), 0);
    }

    #[test]
    fn spur_returns_none() {
        assert_eq!(None, Spur::try_from_usize(u32::max_value() as usize));
    }

    #[test]
    #[should_panic]
    #[cfg(not(miri))]
    fn spur_panics() {
        Spur::try_from_usize(u32::max_value() as usize).unwrap();
    }

    #[test]
    fn mini() {
        let zero = MiniSpur::try_from_usize(0).unwrap();
        let max = MiniSpur::try_from_usize(u16::max_value() as usize - 1).unwrap();
        let default = MiniSpur::default();

        assert_eq!(zero.into_usize(), 0);
        assert_eq!(max.into_usize(), u16::max_value() as usize - 1);
        assert_eq!(default.into_usize(), 0);
    }

    #[test]
    fn mini_returns_none() {
        assert_eq!(None, MiniSpur::try_from_usize(u16::max_value() as usize));
    }

    #[test]
    #[should_panic]
    #[cfg(not(miri))]
    fn mini_panics() {
        MiniSpur::try_from_usize(u16::max_value() as usize).unwrap();
    }

    #[test]
    fn micro() {
        let zero = MicroSpur::try_from_usize(0).unwrap();
        let max = MicroSpur::try_from_usize(u8::max_value() as usize - 1).unwrap();
        let default = MicroSpur::default();

        assert_eq!(zero.into_usize(), 0);
        assert_eq!(max.into_usize(), u8::max_value() as usize - 1);
        assert_eq!(default.into_usize(), 0);
    }

    #[test]
    fn micro_returns_none() {
        assert_eq!(None, MicroSpur::try_from_usize(u8::max_value() as usize));
    }

    #[test]
    #[should_panic]
    #[cfg(not(miri))]
    fn micro_panics() {
        MicroSpur::try_from_usize(u8::max_value() as usize).unwrap();
    }

    #[test]
    #[cfg(feature = "serialize")]
    fn all_serialize() {
        let large = LargeSpur::try_from_usize(0).unwrap();
        let _ = serde_json::to_string(&large).unwrap();

        let normal = Spur::try_from_usize(0).unwrap();
        let _ = serde_json::to_string(&normal).unwrap();

        let mini = MiniSpur::try_from_usize(0).unwrap();
        let _ = serde_json::to_string(&mini).unwrap();

        let micro = MicroSpur::try_from_usize(0).unwrap();
        let _ = serde_json::to_string(&micro).unwrap();
    }
}