1use bytes::{BufMut, Bytes, BytesMut};
2use thiserror::Error;
3use zerocopy::{ConvertError, SizeError};
4
5use crate::codec::encoder::Encoder;
6
7pub mod encoder;
8
9pub(crate) mod footer;
10pub(crate) mod partition_ref;
11pub(crate) mod runs_ref;
12pub(crate) mod tree_ref;
13
14pub trait Encodable {
16 fn encoded_size(&self) -> usize;
23
24 fn encode<B: BufMut>(&self, encoder: &mut Encoder<B>);
26
27 fn encode_to_bytes(&self) -> Bytes {
43 let size = self.encoded_size();
44 let mut encoder = Encoder::new(BytesMut::with_capacity(size));
45 self.encode(&mut encoder);
46 encoder.into_inner().freeze()
47 }
48}
49
50#[derive(Debug, Error)]
55pub enum DecodeErr {
56 #[error("not enough bytes")]
61 Length,
62
63 #[error("invalid encoding")]
69 Validity,
70
71 #[error("unknown magic value")]
77 Magic,
78
79 #[error("invalid checksum")]
84 Checksum,
85
86 #[error("buffer contains serialized Splinter V1, decode using splinter-rs:v0.3.3")]
91 SplinterV1,
92}
93
94impl DecodeErr {
95 #[inline]
96 fn ensure_bytes_available(data: &[u8], len: usize) -> Result<(), DecodeErr> {
97 if data.len() < len {
98 Err(Self::Length)
99 } else {
100 Ok(())
101 }
102 }
103}
104
105impl<S, D> From<SizeError<S, D>> for DecodeErr {
106 #[track_caller]
107 fn from(_: SizeError<S, D>) -> Self {
108 DecodeErr::Length
109 }
110}
111
112impl<A, S, V> From<ConvertError<A, S, V>> for DecodeErr {
113 #[track_caller]
114 fn from(err: ConvertError<A, S, V>) -> Self {
115 match err {
116 ConvertError::Alignment(_) => panic!("All zerocopy transmutations must be unaligned"),
117 ConvertError::Size(_) => DecodeErr::Length,
118 ConvertError::Validity(_) => DecodeErr::Validity,
119 }
120 }
121}
122
123#[cfg(test)]
124mod tests {
125 use itertools::Itertools;
126 use proptest::proptest;
127
128 use crate::{
129 Encodable, Splinter, SplinterRef, assert_error,
130 codec::{
131 DecodeErr,
132 footer::{Footer, SPLINTER_V2_MAGIC},
133 partition_ref::PartitionRef,
134 },
135 level::{Block, Level, Low},
136 partition_kind::PartitionKind,
137 testutil::{
138 LevelSetGen, mkpartition, mkpartition_buf, mksplinter_buf, mksplinter_manual,
139 test_partition_read,
140 },
141 traits::{Optimizable, TruncateFrom},
142 };
143
144 #[test]
145 fn test_encode_decode_direct() {
146 let mut setgen = LevelSetGen::<Low>::new(0xDEADBEEF);
147 let kinds = [
148 PartitionKind::Bitmap,
149 PartitionKind::Vec,
150 PartitionKind::Run,
151 PartitionKind::Tree,
152 ];
153 let sets = &[
154 vec![0],
155 vec![0, 1],
156 vec![0, u16::MAX],
157 vec![u16::MAX],
158 setgen.random(8),
159 setgen.random(4096),
160 setgen.runs(4096, 0.01),
161 setgen.runs(4096, 0.2),
162 setgen.runs(4096, 0.5),
163 setgen.runs(4096, 0.9),
164 (0..Low::MAX_LEN)
165 .map(|v| <Low as Level>::Value::truncate_from(v))
166 .collect_vec(),
167 ];
168
169 for kind in kinds {
170 for (i, set) in sets.iter().enumerate() {
171 println!("Testing partition kind: {kind:?} with set {i}");
172
173 let partition = mkpartition::<Low>(kind, &set);
174 let buf = partition.encode_to_bytes();
175 assert_eq!(
176 partition.encoded_size(),
177 buf.len(),
178 "encoded_size doesn't match actual size"
179 );
180
181 let partition_ref = PartitionRef::<'_, Low>::from_suffix(&buf).unwrap();
182
183 assert_eq!(partition_ref.kind(), kind);
184 test_partition_read(&partition_ref, &set);
185 }
186 }
187 }
188
189 proptest! {
190 #[test]
191 fn test_encode_decode_proptest(
192 values in proptest::collection::vec(0u32..16384, 0..1024),
193 ) {
194 let expected = values.iter().copied().sorted().dedup().collect_vec();
195 let mut splinter = Splinter::from_iter(values);
196 splinter.optimize();
197 let buf = splinter.encode_to_bytes();
198 assert_eq!(
199 buf.len(),
200 splinter.encoded_size(),
201 "encoded_size doesn't match actual size"
202 );
203 let splinter_ref = SplinterRef::from_bytes(buf).unwrap();
204
205 test_partition_read(&splinter_ref, &expected);
206 }
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}