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
15pub trait Encodable {
17 fn encoded_size(&self) -> usize;
24
25 fn encode<B: BufMut>(&self, encoder: &mut Encoder<B>);
27
28 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#[derive(Debug, Error)]
56pub enum DecodeErr {
57 #[error("not enough bytes")]
62 Length,
63
64 #[error("invalid encoding")]
70 Validity,
71
72 #[error("unknown magic value")]
78 Magic,
79
80 #[error("invalid checksum")]
85 Checksum,
86
87 #[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 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 assert_eq!(buf.as_ref(), &[0x01, 0x02, 0x03, 0x02, 0x03]);
266
267 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 assert_eq!(buf.as_ref(), &[0x01, 0x03, 0x00, 0x04]);
279
280 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 0x01, 0x02, 0x01, 0x03,
296 0x00, 0x00, 0x00, 0x00, 0x05
299 ]
300 );
301
302 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, 0x02, 0x00, 0x00, 0x01, 0x03, ]
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, 0x02, 0x00, 0x02, 0x00, 0x00, 0x01, 0x04, ]
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}