basecoin_store/avl/
as_bytes.rs

1//! # AsBytes trait definition
2//!
3//! This module hosts the `AsBytes` trait, which is used by the AVL Tree to convert value to raw
4//! bytes. This is helpful for making the AVL Tree generic over a wide range of data types for its
5//! keys (the values still need to implement `Borrow<[u8]>), as long as they can be interpreted as
6//! a slice of bytes.
7//!
8//! To add support for a new type in the AVL Tree, simply implement the `AsByte` trait for that type.
9
10pub enum ByteSlice<'a> {
11    Slice(&'a [u8]),
12    Vector(Vec<u8>),
13}
14
15impl AsRef<[u8]> for ByteSlice<'_> {
16    fn as_ref(&self) -> &[u8] {
17        match self {
18            ByteSlice::Slice(s) => s,
19            ByteSlice::Vector(v) => v.as_slice(),
20        }
21    }
22}
23
24/// A trait for objects that can be interpreted as a slice of bytes.
25pub trait AsBytes {
26    fn as_bytes(&self) -> ByteSlice<'_>;
27}
28
29impl AsBytes for Vec<u8> {
30    fn as_bytes(&self) -> ByteSlice<'_> {
31        ByteSlice::Slice(self)
32    }
33}
34
35impl AsBytes for [u8] {
36    fn as_bytes(&self) -> ByteSlice<'_> {
37        ByteSlice::Slice(self)
38    }
39}
40
41impl AsBytes for str {
42    fn as_bytes(&self) -> ByteSlice<'_> {
43        ByteSlice::Slice(self.as_bytes())
44    }
45}
46
47impl AsBytes for &str {
48    fn as_bytes(&self) -> ByteSlice<'_> {
49        ByteSlice::Slice((*self).as_bytes())
50    }
51}
52
53impl AsBytes for String {
54    fn as_bytes(&self) -> ByteSlice<'_> {
55        ByteSlice::Slice(self.as_bytes())
56    }
57}
58
59impl AsBytes for [u8; 1] {
60    fn as_bytes(&self) -> ByteSlice<'_> {
61        ByteSlice::Slice(self)
62    }
63}