1use std::{fmt::Debug, ops::Add};
2
3use zerocopy::{Immutable, IntoBytes, KnownLayout, TryFromBytes};
4
5use crate::{Error, Printable, Result};
6
7pub trait StoredIndex
8where
9 Self: Debug
10 + Default
11 + Copy
12 + Clone
13 + PartialEq
14 + Eq
15 + PartialOrd
16 + Ord
17 + From<usize>
18 + TryInto<usize>
19 + Add<usize, Output = Self>
20 + TryFromBytes
21 + IntoBytes
22 + Immutable
23 + KnownLayout
24 + Send
25 + Sync
26 + Printable,
27{
28 fn unwrap_to_usize(self) -> usize;
29 fn to_usize(self) -> Result<usize>;
30 fn decremented(self) -> Option<Self>;
31}
32
33impl<I> StoredIndex for I
34where
35 I: Debug
36 + Default
37 + Copy
38 + Clone
39 + PartialEq
40 + Eq
41 + PartialOrd
42 + Ord
43 + From<usize>
44 + TryInto<usize>
45 + Add<usize, Output = Self>
46 + TryFromBytes
47 + IntoBytes
48 + Immutable
49 + KnownLayout
50 + Send
51 + Sync
52 + Printable,
53{
54 #[inline]
55 fn unwrap_to_usize(self) -> usize {
56 self.to_usize().unwrap()
57 }
58
59 #[inline]
60 fn to_usize(self) -> Result<usize> {
61 self.try_into().map_err(|_| Error::FailedKeyTryIntoUsize)
62 }
63
64 #[inline]
65 fn decremented(self) -> Option<Self> {
66 self.unwrap_to_usize().checked_sub(1).map(Self::from)
67 }
68}