splinter_rs/
codec.rs

1use bytes::{BufMut, Bytes, BytesMut};
2use culprit::Culprit;
3use thiserror::Error;
4use zerocopy::{ConvertError, SizeError};
5
6use crate::codec::encoder::Encoder;
7
8pub mod encoder;
9
10pub(crate) mod footer;
11pub(crate) mod partition_ref;
12pub(crate) mod runs_ref;
13pub(crate) mod tree_ref;
14
15/// Trait for types that can be encoded into a binary format.
16pub trait Encodable {
17    /// Returns the number of bytes required to encode this value.
18    ///
19    /// This should return the exact number of bytes that [`encode`](Self::encode)
20    /// will write, allowing for efficient buffer pre-allocation.
21    ///
22    /// Note: This function traverses the entire datastructure which scales with cardinality.
23    fn encoded_size(&self) -> usize;
24
25    /// Encodes this value into the provided encoder.
26    fn encode<B: BufMut>(&self, encoder: &mut Encoder<B>);
27
28    /// Convenience method that encodes this value to a [`Bytes`] buffer.
29    ///
30    /// This is the easiest way to serialize splinter data. It allocates
31    /// a buffer of the exact required size and encodes the value into it.
32    ///
33    /// # Examples
34    ///
35    /// ```
36    /// use splinter_rs::{Splinter, Encodable, PartitionWrite};
37    ///
38    /// let splinter = Splinter::from_iter([8, 42, 16]);
39    /// let bytes = splinter.encode_to_bytes();
40    /// assert!(!bytes.is_empty());
41    /// assert_eq!(bytes.len(), splinter.encoded_size());
42    /// ```
43    fn encode_to_bytes(&self) -> Bytes {
44        let size = self.encoded_size();
45        let mut encoder = Encoder::new(BytesMut::with_capacity(size));
46        self.encode(&mut encoder);
47        encoder.into_inner().freeze()
48    }
49}
50
51/// Errors that can occur when deserializing splinter data from bytes.
52///
53/// These errors indicate various types of corruption or invalid data that can
54/// be encountered when attempting to decode serialized splinter data.
55#[derive(Debug, Error)]
56pub enum DecodeErr {
57    /// The buffer does not contain enough bytes to decode the expected data.
58    ///
59    /// This error occurs when the buffer is truncated or smaller than the
60    /// minimum required size for a valid splinter.
61    #[error("not enough bytes")]
62    Length,
63
64    /// The data contains invalid or corrupted encoding structures.
65    ///
66    /// This error indicates that while the buffer has sufficient length and
67    /// correct magic bytes, the internal data structures are malformed or
68    /// contain invalid values.
69    #[error("invalid encoding")]
70    Validity,
71
72    /// The buffer does not end with the expected magic bytes.
73    ///
74    /// Splinter data ends with specific magic bytes to identify the format.
75    /// This error indicates the buffer does not contain valid splinter data
76    /// or has been corrupted at the end.
77    #[error("unknown magic value")]
78    Magic,
79
80    /// The calculated checksum does not match the stored checksum.
81    ///
82    /// This error indicates data corruption has occurred somewhere in the
83    /// buffer, as the integrity check has failed.
84    #[error("invalid checksum")]
85    Checksum,
86
87    /// The buffer contains data from the incompatible Splinter V1 format.
88    ///
89    /// This version of splinter-rs can only decode V2 format data. To decode
90    /// V1 data, use splinter-rs version 0.3.3 or earlier.
91    #[error("buffer contains serialized Splinter V1, decode using splinter-rs:v0.3.3")]
92    SplinterV1,
93}
94
95impl DecodeErr {
96    #[inline]
97    fn ensure_bytes_available(data: &[u8], len: usize) -> culprit::Result<(), DecodeErr> {
98        if data.len() < len {
99            Err(Culprit::new(Self::Length))
100        } else {
101            Ok(())
102        }
103    }
104}
105
106impl<S, D> From<SizeError<S, D>> for DecodeErr {
107    #[track_caller]
108    fn from(_: SizeError<S, D>) -> Self {
109        DecodeErr::Length
110    }
111}
112
113impl<A, S, V> From<ConvertError<A, S, V>> for DecodeErr {
114    #[track_caller]
115    fn from(err: ConvertError<A, S, V>) -> Self {
116        match err {
117            ConvertError::Alignment(_) => panic!("All zerocopy transmutations must be unaligned"),
118            ConvertError::Size(_) => DecodeErr::Length,
119            ConvertError::Validity(_) => DecodeErr::Validity,
120        }
121    }
122}
123
124#[cfg(test)]
125mod tests {
126    use itertools::Itertools;
127    use quickcheck::TestResult;
128    use quickcheck_macros::quickcheck;
129
130    use crate::{
131        Encodable, Splinter, SplinterRef, assert_error,
132        codec::{
133            DecodeErr,
134            footer::{Footer, SPLINTER_V2_MAGIC},
135            partition_ref::PartitionRef,
136        },
137        level::{Block, Level, Low},
138        partition_kind::PartitionKind,
139        testutil::{
140            LevelSetGen, mkpartition, mkpartition_buf, mksplinter_buf, mksplinter_manual,
141            test_partition_read,
142        },
143        traits::{Optimizable, TruncateFrom},
144    };
145
146    #[test]
147    fn test_encode_decode_direct() {
148        let mut setgen = LevelSetGen::<Low>::new(0xDEADBEEF);
149        let kinds = [
150            PartitionKind::Bitmap,
151            PartitionKind::Vec,
152            PartitionKind::Run,
153            PartitionKind::Tree,
154        ];
155        let sets = &[
156            vec![0],
157            vec![0, 1],
158            vec![0, u16::MAX],
159            vec![u16::MAX],
160            setgen.random(8),
161            setgen.random(4096),
162            setgen.runs(4096, 0.01),
163            setgen.runs(4096, 0.2),
164            setgen.runs(4096, 0.5),
165            setgen.runs(4096, 0.9),
166            (0..Low::MAX_LEN)
167                .map(|v| <Low as Level>::Value::truncate_from(v))
168                .collect_vec(),
169        ];
170
171        for kind in kinds {
172            for (i, set) in sets.iter().enumerate() {
173                println!("Testing partition kind: {kind:?} with set {i}");
174
175                let partition = mkpartition::<Low>(kind, &set);
176                let buf = partition.encode_to_bytes();
177                assert_eq!(
178                    partition.encoded_size(),
179                    buf.len(),
180                    "encoded_size doesn't match actual size"
181                );
182
183                let partition_ref = PartitionRef::<'_, Low>::from_suffix(&buf).unwrap();
184
185                assert_eq!(partition_ref.kind(), kind);
186                test_partition_read(&partition_ref, &set);
187            }
188        }
189    }
190
191    #[quickcheck]
192    fn test_encode_decode_quickcheck(values: Vec<u32>) -> TestResult {
193        let expected = values.iter().copied().sorted().dedup().collect_vec();
194        let mut splinter = Splinter::from_iter(values);
195        splinter.optimize();
196        let buf = splinter.encode_to_bytes();
197        assert_eq!(
198            buf.len(),
199            splinter.encoded_size(),
200            "encoded_size doesn't match actual size"
201        );
202        let splinter_ref = SplinterRef::from_bytes(buf).unwrap();
203
204        test_partition_read(&splinter_ref, &expected);
205
206        TestResult::passed()
207    }
208
209    #[test]
210    fn test_length_corruption() {
211        for i in 0..Footer::SIZE {
212            let truncated = [0].repeat(i);
213            assert_error!(
214                SplinterRef::from_bytes(truncated),
215                DecodeErr::Length,
216                "Failed for truncated buffer of size {}",
217                i
218            );
219        }
220    }
221
222    #[test]
223    fn test_corrupted_root_partition_kind() {
224        let mut buf = mksplinter_buf(&[1, 2, 3]);
225
226        // Buffer with just footer size but corrupted partition kind
227        let footer_offset = buf.len() - Footer::SIZE;
228        let partitions = &mut buf[0..footer_offset];
229        partitions[partitions.len() - 1] = 10;
230        let corrupted = mksplinter_manual(partitions);
231
232        assert_error!(SplinterRef::from_bytes(corrupted), DecodeErr::Validity);
233    }
234
235    #[test]
236    fn test_corrupted_magic() {
237        let mut buf = mksplinter_buf(&[1, 2, 3]);
238
239        let magic_offset = buf.len() - SPLINTER_V2_MAGIC.len();
240        buf[magic_offset..].copy_from_slice(&[0].repeat(4));
241
242        assert_error!(SplinterRef::from_bytes(buf), DecodeErr::Magic);
243    }
244
245    #[test]
246    fn test_corrupted_data() {
247        let mut buf = mksplinter_buf(&[1, 2, 3]);
248        buf[0] = 123;
249        assert_error!(SplinterRef::from_bytes(buf), DecodeErr::Checksum);
250    }
251
252    #[test]
253    fn test_corrupted_checksum() {
254        let mut buf = mksplinter_buf(&[1, 2, 3]);
255        let checksum_offset = buf.len() - Footer::SIZE;
256        buf[checksum_offset] = 123;
257        assert_error!(SplinterRef::from_bytes(buf), DecodeErr::Checksum);
258    }
259
260    #[test]
261    fn test_corrupted_vec_partition() {
262        let mut buf = mkpartition_buf::<Block>(PartitionKind::Vec, &[1, 2, 3]);
263
264        //                            1     2     3   len  kind
265        assert_eq!(buf.as_ref(), &[0x01, 0x02, 0x03, 0x02, 0x03]);
266
267        // corrupt the length
268        buf[3] = 5;
269
270        assert_error!(PartitionRef::<Block>::from_suffix(&buf), DecodeErr::Length);
271    }
272
273    #[test]
274    fn test_corrupted_run_partition() {
275        let mut buf = mkpartition_buf::<Block>(PartitionKind::Run, &[1, 2, 3]);
276
277        //                            1     3   len  kind
278        assert_eq!(buf.as_ref(), &[0x01, 0x03, 0x00, 0x04]);
279
280        // corrupt the length
281        buf[2] = 5;
282
283        assert_error!(PartitionRef::<Block>::from_suffix(&buf), DecodeErr::Length);
284    }
285
286    #[test]
287    fn test_corrupted_tree_partition() {
288        let mut buf = mkpartition_buf::<Low>(PartitionKind::Tree, &[1, 2]);
289
290        assert_eq!(
291            buf.as_ref(),
292            &[
293                // Vec partition
294                // 1     2   len  kind
295                0x01, 0x02, 0x01, 0x03,
296                // Tree partition
297                // offsets (u16), segments, len, kind
298                0x00, 0x00, 0x00, 0x00, 0x05
299            ]
300        );
301
302        // corrupt the tree len
303        buf[7] = 5;
304
305        assert_error!(PartitionRef::<Block>::from_suffix(&buf), DecodeErr::Length);
306    }
307
308    #[test]
309    fn test_vec_byteorder() {
310        let buf = mkpartition_buf::<Low>(PartitionKind::Vec, &[0x01_00, 0x02_00]);
311        assert_eq!(
312            buf.as_ref(),
313            &[
314                0x01, 0x00, // first value
315                0x02, 0x00, // second value
316                0x00, 0x01, // length
317                0x03, // kind
318            ]
319        );
320    }
321
322    #[test]
323    fn test_run_byteorder() {
324        let buf = mkpartition_buf::<Low>(PartitionKind::Run, &[0x01_00, 0x02_00]);
325        assert_eq!(
326            buf.as_ref(),
327            &[
328                0x01, 0x00, 0x01, 0x00, // first run
329                0x02, 0x00, 0x02, 0x00, // second run
330                0x00, 0x01, // length
331                0x04, // kind
332            ]
333        );
334    }
335
336    #[test]
337    fn test_detect_splinter_v1() {
338        let empty_splinter_v1 = b"\xda\xae\x12\xdf\0\0\0\0";
339        assert_error!(
340            SplinterRef::from_bytes(empty_splinter_v1.as_slice()),
341            DecodeErr::SplinterV1
342        );
343    }
344}