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> = Vec<T::SelfType<'a>>
36    where
37        Self: 'a;
38    type AsBytes<'a> = Vec<u8>
39    where
40        Self: 'a;
41
42    fn fixed_width() -> Option<usize> {
43        None
44    }
45
46    fn from_bytes<'a>(data: &'a [u8]) -> Vec<T::SelfType<'a>>
47    where
48        Self: 'a,
49    {
50        let (elements, mut offset) = decode_varint_len(data);
51        let mut result = Vec::with_capacity(elements);
52        for _ in 0..elements {
53            let element_len = if let Some(len) = T::fixed_width() {
54                len
55            } else {
56                let (len, consumed) = decode_varint_len(&data[offset..]);
57                offset += consumed;
58                len
59            };
60            result.push(T::from_bytes(&data[offset..(offset + element_len)]));
61            offset += element_len;
62        }
63        assert_eq!(offset, data.len());
64        result
65    }
66
67    fn as_bytes<'a, 'b: 'a>(value: &'a Vec<T::SelfType<'b>>) -> Vec<u8>
68    where
69        Self: 'b,
70    {
71        let mut result = if let Some(width) = T::fixed_width() {
72            Vec::with_capacity(value.len() * width + 5)
73        } else {
74            Vec::with_capacity(value.len() * 2 + 5)
75        };
76        encode_varint_len(value.len(), &mut result);
77
78        for element in value {
79            let serialized = T::as_bytes(element);
80            if T::fixed_width().is_none() {
81                encode_varint_len(serialized.as_ref().len(), &mut result);
82            }
83            result.extend_from_slice(serialized.as_ref());
84        }
85        result
86    }
87
88    fn type_name() -> TypeName {
89        TypeName::internal(&format!("Vec<{}>", T::type_name().name()))
90    }
91}