art_tree/
keys.rs

1use std::borrow::Borrow;
2use std::cmp::Ordering;
3use std::mem;
4
5/// Trait represent [Art] key.
6/// Trait define method which convert key into byte comparable sequence. This sequence will be
7/// used to order keys inside tree.
8pub trait Key {
9    /// Converts key to byte comparable sequence. This sequence used to represent key inside
10    /// [Art] tree.
11    ///
12    /// ## Warning
13    /// Implementation must ensure that returned bytes vector have consistent order of bytes. E.g.
14    /// key type must have same ordering guarantees as returned byte sequence.  
15    /// For instance, if `"abc" < "def"`, then `"abc".to_bytes() < "def".to_bytes()`.
16    /// **Violation** of this rule is **undefined behaviour** and can cause `panic`.
17    fn to_bytes(&self) -> Vec<u8>;
18}
19
20/// Implementation of [Key] which wraps bytes slice. It can be used to represent strings as
21/// comparable byte sequence.
22#[derive(Clone, PartialOrd, Ord, Debug)]
23#[repr(transparent)]
24pub struct ByteString {
25    bytes: Vec<u8>,
26}
27
28impl ByteString {
29    pub fn new(bytes: &[u8]) -> Self {
30        Self {
31            bytes: bytes.to_vec(),
32        }
33    }
34}
35
36impl Borrow<[u8]> for ByteString {
37    fn borrow(&self) -> &[u8] {
38        &self.bytes
39    }
40}
41
42impl Key for ByteString {
43    fn to_bytes(&self) -> Vec<u8> {
44        self.bytes.clone()
45    }
46}
47
48impl Eq for ByteString {}
49
50impl PartialEq for ByteString {
51    fn eq(&self, other: &Self) -> bool {
52        self.bytes == other.bytes
53    }
54}
55
56impl Key for usize {
57    fn to_bytes(&self) -> Vec<u8> {
58        self.to_be_bytes().to_vec()
59    }
60}
61
62impl Key for u8 {
63    fn to_bytes(&self) -> Vec<u8> {
64        self.to_be_bytes().to_vec()
65    }
66}
67
68impl Key for u16 {
69    fn to_bytes(&self) -> Vec<u8> {
70        self.to_be_bytes().to_vec()
71    }
72}
73
74impl Key for u32 {
75    fn to_bytes(&self) -> Vec<u8> {
76        self.to_be_bytes().to_vec()
77    }
78}
79
80impl Key for u64 {
81    fn to_bytes(&self) -> Vec<u8> {
82        self.to_be_bytes().to_vec()
83    }
84}
85
86impl Key for u128 {
87    fn to_bytes(&self) -> Vec<u8> {
88        self.to_be_bytes().to_vec()
89    }
90}
91
92impl Key for i8 {
93    fn to_bytes(&self) -> Vec<u8> {
94        // flip upper bit of signed value to get comparable byte sequence:
95        // -128 => 0
96        // -127 => 1
97        // 0 => 128
98        // 1 => 129
99        // 127 => 255
100        let v: u8 = unsafe { mem::transmute(*self) };
101        // flip upper bit and set to 0 other bits:
102        // (0000_1100 ^ 1000_0000) & 1000_0000 = 1000_0000
103        // (1000_1100 ^ 1000_0000) & 1000_0000 = 0000_0000
104        let i = (v ^ 0x80) & 0x80;
105        // repair bits(except upper bit) of value:
106        // self = -127
107        // i = 0 (0b0000_0000)
108        // v = 129 (0b1000_0001)
109        // j = 0b0000_0000 | (0b1000_0001 & 0b0111_1111) = 0b0000_0000 | 0b0000_0001 = 0b0000_0001 = 1
110        let j = i | (v & 0x7F);
111        j.to_be_bytes().to_vec()
112    }
113}
114
115impl Key for i16 {
116    fn to_bytes(&self) -> Vec<u8> {
117        let v: u16 = unsafe { mem::transmute(*self) };
118        let xor = 1 << 15;
119        let i = (v ^ xor) & xor;
120        let j = i | (v & (u16::MAX >> 1));
121        j.to_be_bytes().to_vec()
122    }
123}
124
125impl Key for i32 {
126    fn to_bytes(&self) -> Vec<u8> {
127        let v: u32 = unsafe { mem::transmute(*self) };
128        let xor = 1 << 31;
129        let i = (v ^ xor) & xor;
130        let j = i | (v & (u32::MAX >> 1));
131        j.to_be_bytes().to_vec()
132    }
133}
134
135impl Key for i64 {
136    fn to_bytes(&self) -> Vec<u8> {
137        let v: u64 = unsafe { mem::transmute(*self) };
138        let xor = 1 << 63;
139        let i = (v ^ xor) & xor;
140        let j = i | (v & (u64::MAX >> 1));
141        j.to_be_bytes().to_vec()
142    }
143}
144
145impl Key for i128 {
146    fn to_bytes(&self) -> Vec<u8> {
147        let v: u128 = unsafe { mem::transmute(*self) };
148        let xor = 1 << 127;
149        let i = (v ^ xor) & xor;
150        let j = i | (v & (u128::MAX >> 1));
151        j.to_be_bytes().to_vec()
152    }
153}
154
155#[derive(Clone, Debug)]
156#[repr(transparent)]
157pub struct Float32 {
158    key: [u8; 4],
159}
160
161impl Borrow<[u8]> for Float32 {
162    fn borrow(&self) -> &[u8] {
163        &self.key
164    }
165}
166
167impl Eq for Float32 {}
168
169impl PartialEq<Float32> for Float32 {
170    fn eq(&self, other: &Self) -> bool {
171        self.key == other.key
172    }
173}
174
175impl Ord for Float32 {
176    fn cmp(&self, other: &Self) -> Ordering {
177        self.partial_cmp(other).unwrap()
178    }
179}
180
181impl PartialOrd<Float32> for Float32 {
182    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
183        Some(self.key.cmp(&other.key))
184    }
185}
186
187impl From<f32> for Float32 {
188    fn from(v: f32) -> Self {
189        let v: u32 = v.to_bits();
190        let xor = 1 << 31;
191        let i = (v ^ xor) & xor;
192        let j = i | (v & (u32::MAX >> 1));
193        Self {
194            key: j.to_be_bytes(),
195        }
196    }
197}
198
199#[derive(Clone, Debug)]
200#[repr(transparent)]
201pub struct Float64 {
202    key: [u8; 8],
203}
204
205impl Borrow<[u8]> for Float64 {
206    fn borrow(&self) -> &[u8] {
207        &self.key
208    }
209}
210
211impl Eq for Float64 {}
212
213impl PartialEq<Float64> for Float64 {
214    fn eq(&self, other: &Self) -> bool {
215        self.key == other.key
216    }
217}
218
219impl Ord for Float64 {
220    fn cmp(&self, other: &Self) -> Ordering {
221        self.partial_cmp(other).unwrap()
222    }
223}
224
225impl PartialOrd<Float64> for Float64 {
226    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
227        Some(self.key.cmp(&other.key))
228    }
229}
230
231impl From<f64> for Float64 {
232    fn from(v: f64) -> Self {
233        let v: u64 = v.to_bits();
234        let xor = 1 << 63;
235        let i = (v ^ xor) & xor;
236        let j = i | (v & (u64::MAX >> 1));
237        Self {
238            key: j.to_be_bytes(),
239        }
240    }
241}
242
243impl Key for Float32 {
244    fn to_bytes(&self) -> Vec<u8> {
245        self.key.to_vec()
246    }
247}
248
249impl Key for Float64 {
250    fn to_bytes(&self) -> Vec<u8> {
251        self.key.to_vec()
252    }
253}
254
255/// Builder to create keys based on several other keys.
256/// For instance, we have a structure:
257/// ```
258/// struct MyStruct(u8, String, u32, Box<f64>);
259/// ```
260/// and we want to store this structure inside [Art](crate::Art) tree. This structure can identified
261/// by first 2 fields: `(u8, String)`. We can create compound key based on them and use it as
262/// tree key.
263/// ```
264/// use art_tree::Art;
265/// use art_tree::KeyBuilder;
266/// use art_tree::ByteString;
267///
268/// struct MyStruct(u8, String, u32, Box<f64>);
269///
270/// let mut art = Art::new();
271/// let key = KeyBuilder::new().append(1).append(ByteString::new("abc".to_string().as_bytes())).build();
272/// let val = MyStruct(1, "abc".to_string(), 200, Box::new(0.1));
273/// assert!(art.insert(key.clone(), val));
274/// assert!(art.get(&key).is_some());
275/// ```
276#[repr(transparent)]
277pub struct KeyBuilder {
278    key: ByteString,
279}
280
281impl Default for KeyBuilder {
282    fn default() -> Self {
283        Self::new()
284    }
285}
286
287impl KeyBuilder {
288    pub fn new() -> Self {
289        Self {
290            key: ByteString { bytes: Vec::new() },
291        }
292    }
293
294    pub fn with_capacity(cap: usize) -> Self {
295        Self {
296            key: ByteString {
297                bytes: Vec::with_capacity(cap),
298            },
299        }
300    }
301
302    pub fn append(mut self, key_part: impl Key) -> Self {
303        self.key.bytes.append(&mut key_part.to_bytes());
304        self
305    }
306
307    pub fn build(self) -> ByteString {
308        self.key
309    }
310}