redb/
complex_types.rs

1use crate::types::{TypeName, Value};
2
3// Encode len as a varint and store it at the end of output
4fn encode_varint_len(len: usize, output: &mut Vec<u8>) {
5    if len < 254 {
6        output.push(len.try_into().unwrap());
7    } else if len <= u16::MAX.into() {
8        let u16_len: u16 = len.try_into().unwrap();
9        output.push(254);
10        output.extend_from_slice(&u16_len.to_le_bytes());
11    } else {
12        let u32_len: u32 = len.try_into().unwrap();
13        output.push(255);
14        output.extend_from_slice(&u32_len.to_le_bytes());
15    }
16}
17
18// Decode a variable length int starting at the beginning of data
19// Returns (decoded length, length consumed of `data`)
20fn decode_varint_len(data: &[u8]) -> (usize, usize) {
21    match data[0] {
22        0..=253 => (data[0] as usize, 1),
23        254 => (
24            u16::from_le_bytes(data[1..3].try_into().unwrap()) as usize,
25            3,
26        ),
27        255 => (
28            u32::from_le_bytes(data[1..5].try_into().unwrap()) as usize,
29            5,
30        ),
31    }
32}
33
34impl<T: Value> Value for Vec<T> {
35    type SelfType<'a>
36        = Vec<T::SelfType<'a>>
37    where
38        Self: 'a;
39    type AsBytes<'a>
40        = Vec<u8>
41    where
42        Self: 'a;
43
44    fn fixed_width() -> Option<usize> {
45        None
46    }
47
48    fn from_bytes<'a>(data: &'a [u8]) -> Vec<T::SelfType<'a>>
49    where
50        Self: 'a,
51    {
52        let (elements, mut offset) = decode_varint_len(data);
53        let mut result = Vec::with_capacity(elements);
54        for _ in 0..elements {
55            let element_len = if let Some(len) = T::fixed_width() {
56                len
57            } else {
58                let (len, consumed) = decode_varint_len(&data[offset..]);
59                offset += consumed;
60                len
61            };
62            result.push(T::from_bytes(&data[offset..(offset + element_len)]));
63            offset += element_len;
64        }
65        assert_eq!(offset, data.len());
66        result
67    }
68
69    fn as_bytes<'a, 'b: 'a>(value: &'a Vec<T::SelfType<'b>>) -> Vec<u8>
70    where
71        Self: 'b,
72    {
73        let mut result = if let Some(width) = T::fixed_width() {
74            Vec::with_capacity(value.len() * width + 5)
75        } else {
76            Vec::with_capacity(value.len() * 2 + 5)
77        };
78        encode_varint_len(value.len(), &mut result);
79
80        for element in value {
81            let serialized = T::as_bytes(element);
82            if T::fixed_width().is_none() {
83                encode_varint_len(serialized.as_ref().len(), &mut result);
84            }
85            result.extend_from_slice(serialized.as_ref());
86        }
87        result
88    }
89
90    fn type_name() -> TypeName {
91        TypeName::internal(&format!("Vec<{}>", T::type_name().name()))
92    }
93}