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
use std::cmp::Ordering;
use std::convert::TryInto;
use std::fmt::Debug;
pub trait Key<'a>:
AsRef<[u8]> + From<Vec<u8>> + From<&'a [u8]> + Debug + Clone + Send + Sync + Ord + Default
{
const LEN: u16;
type Ref: RefKey<'a>;
fn to_vec(&self) -> Vec<u8> {
self.as_ref().to_vec()
}
fn as_ref_key(&'a self) -> Self::Ref {
Self::Ref::from(self.as_ref())
}
}
pub trait RefKey<'a>: Ord + From<&'a [u8]> {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ArrayKey<const N: usize>([u8; N]);
impl<const N: usize> AsRef<ArrayKey<N>> for ArrayKey<N> {
fn as_ref(&self) -> &ArrayKey<N> {
self
}
}
impl<const N: usize> Default for ArrayKey<N> {
fn default() -> Self {
Self([0; N])
}
}
impl<const N: usize> AsRef<[u8]> for ArrayKey<N> {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl<const N: usize> From<Vec<u8>> for ArrayKey<N> {
fn from(v: Vec<u8>) -> Self {
Self(v.try_into().expect("size mismatch"))
}
}
impl<const N: usize> From<&[u8]> for ArrayKey<N> {
fn from(a: &[u8]) -> Self {
Self(a.try_into().expect("size mismatch"))
}
}
impl<const N: usize> From<[u8; N]> for ArrayKey<N> {
fn from(a: [u8; N]) -> Self {
Self(a)
}
}
impl<const N: usize> PartialOrd for ArrayKey<N> {
fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
self.0.partial_cmp(&rhs.0)
}
}
impl<const N: usize> Ord for ArrayKey<N> {
fn cmp(&self, rhs: &Self) -> Ordering {
self.0.cmp(&rhs.0)
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct SliceKey<'a>(&'a [u8]);
impl<'a> From<&'a [u8]> for SliceKey<'a> {
fn from(v: &'a [u8]) -> Self {
Self(v)
}
}
impl<'a> PartialOrd for SliceKey<'a> {
fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
self.0.partial_cmp(rhs.0)
}
}
impl<'a> Ord for SliceKey<'a> {
fn cmp(&self, rhs: &Self) -> Ordering {
self.0.cmp(rhs.0)
}
}
impl<'a> RefKey<'a> for SliceKey<'a> {}
impl<'a, const N: usize> Key<'a> for ArrayKey<N> {
const LEN: u16 = N as u16;
type Ref = SliceKey<'a>;
}