use super::{
error::{BufferTooShort, DecodeError, ReadingType, UnsortedArray},
schema::Schema,
};
pub trait Decode: Sized {
const MIN_SIZE: usize;
fn try_decode(buf: &[u8]) -> Result<Self, DecodeError>;
}
pub trait DecodeFields: Schema + Sized {
const MIN_SIGNED_SIZE: usize;
fn try_decode_fields(buf: &[u8]) -> Result<(Self, usize), DecodeError>;
}
#[inline]
pub fn u8(buf: &[u8], offset: usize) -> Result<u8, BufferTooShort> {
buf.get(offset).copied().ok_or(BufferTooShort {
reading: ReadingType::U8,
offset,
need: 1,
have: buf.len().saturating_sub(offset),
})
}
#[inline]
pub fn u16(buf: &[u8], offset: usize) -> Result<u16, BufferTooShort> {
let bytes: [u8; 2] = buf
.get(offset..offset + 2)
.and_then(|s| s.try_into().ok())
.ok_or(BufferTooShort {
reading: ReadingType::U16,
offset,
need: 2,
have: buf.len().saturating_sub(offset),
})?;
Ok(u16::from_be_bytes(bytes))
}
#[inline]
pub fn u32(buf: &[u8], offset: usize) -> Result<u32, BufferTooShort> {
let bytes: [u8; 4] = buf
.get(offset..offset + 4)
.and_then(|s| s.try_into().ok())
.ok_or(BufferTooShort {
reading: ReadingType::U32,
offset,
need: 4,
have: buf.len().saturating_sub(offset),
})?;
Ok(u32::from_be_bytes(bytes))
}
#[inline]
pub fn u64(buf: &[u8], offset: usize) -> Result<u64, BufferTooShort> {
let bytes: [u8; 8] = buf
.get(offset..offset + 8)
.and_then(|s| s.try_into().ok())
.ok_or(BufferTooShort {
reading: ReadingType::U64,
offset,
need: 8,
have: buf.len().saturating_sub(offset),
})?;
Ok(u64::from_be_bytes(bytes))
}
#[inline]
pub fn array<const N: usize>(buf: &[u8], offset: usize) -> Result<[u8; N], BufferTooShort> {
buf.get(offset..offset + N)
.and_then(|s| s.try_into().ok())
.ok_or(BufferTooShort {
reading: ReadingType::Array { size: N },
offset,
need: N,
have: buf.len().saturating_sub(offset),
})
}
#[inline]
pub fn slice(buf: &[u8], offset: usize, len: usize) -> Result<&[u8], BufferTooShort> {
let end = offset.checked_add(len).ok_or(BufferTooShort {
reading: ReadingType::Slice { len },
offset,
need: len,
have: buf.len().saturating_sub(offset),
})?;
buf.get(offset..end).ok_or(BufferTooShort {
reading: ReadingType::Slice { len },
offset,
need: len,
have: buf.len().saturating_sub(offset),
})
}
pub fn verify_sorted<const N: usize>(elements: &[[u8; N]]) -> Result<(), UnsortedArray> {
for (i, window) in elements.windows(2).enumerate() {
let [prev, curr] = window else {
continue;
};
if prev >= curr {
return Err(UnsortedArray { index: i + 1 });
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn verify_sorted_empty() {
let elements: &[[u8; 32]] = &[];
assert!(verify_sorted(elements).is_ok());
}
#[test]
fn verify_sorted_single() {
let elements: &[[u8; 32]] = &[[0x42; 32]];
assert!(verify_sorted(elements).is_ok());
}
#[test]
fn verify_sorted_descending_rejected() {
let elements: &[[u8; 32]] = &[[0x30; 32], [0x20; 32], [0x10; 32]];
assert!(matches!(
verify_sorted(elements),
Err(UnsortedArray { index: 1 })
));
}
#[test]
fn verify_sorted_duplicates_rejected() {
let elements: &[[u8; 32]] = &[[0x10; 32], [0x20; 32], [0x20; 32]];
assert!(matches!(
verify_sorted(elements),
Err(UnsortedArray { index: 2 })
));
}
}
#[cfg(all(test, feature = "bolero"))]
mod proptests {
use super::*;
use crate::codec::encode;
use alloc::vec::Vec;
#[test]
fn u8_does_not_panic() {
bolero::check!()
.with_arbitrary::<(Vec<u8>, usize)>()
.for_each(|(bytes, offset)| {
let _result = u8(bytes, *offset);
});
}
#[test]
fn u16_does_not_panic() {
bolero::check!()
.with_arbitrary::<(Vec<u8>, usize)>()
.for_each(|(bytes, offset)| {
let _result = u16(bytes, *offset);
});
}
#[test]
fn u32_does_not_panic() {
bolero::check!()
.with_arbitrary::<(Vec<u8>, usize)>()
.for_each(|(bytes, offset)| {
let _result = u32(bytes, *offset);
});
}
#[test]
fn u64_does_not_panic() {
bolero::check!()
.with_arbitrary::<(Vec<u8>, usize)>()
.for_each(|(bytes, offset)| {
let _result = u64(bytes, *offset);
});
}
#[test]
fn array_does_not_panic() {
bolero::check!()
.with_arbitrary::<(Vec<u8>, usize)>()
.for_each(|(bytes, offset)| {
let _result = array::<32>(bytes, *offset);
});
}
#[test]
fn slice_does_not_panic() {
bolero::check!()
.with_arbitrary::<(Vec<u8>, usize, usize)>()
.for_each(|(bytes, offset, len)| {
let _result = slice(bytes, *offset, *len);
});
}
#[test]
#[allow(clippy::panic)]
fn u8_round_trip() {
bolero::check!()
.with_arbitrary::<core::primitive::u8>()
.for_each(|value| {
let mut buf = Vec::new();
encode::u8(*value, &mut buf);
match u8(&buf, 0) {
Ok(decoded) => assert_eq!(decoded, *value),
Err(e) => panic!("decode should succeed: {e}"),
}
});
}
#[test]
#[allow(clippy::panic)]
fn u16_round_trip() {
bolero::check!()
.with_arbitrary::<core::primitive::u16>()
.for_each(|value| {
let mut buf = Vec::new();
encode::u16(*value, &mut buf);
match u16(&buf, 0) {
Ok(decoded) => assert_eq!(decoded, *value),
Err(e) => panic!("decode should succeed: {e}"),
}
});
}
#[test]
#[allow(clippy::panic)]
fn u32_round_trip() {
bolero::check!()
.with_arbitrary::<core::primitive::u32>()
.for_each(|value| {
let mut buf = Vec::new();
encode::u32(*value, &mut buf);
match u32(&buf, 0) {
Ok(decoded) => assert_eq!(decoded, *value),
Err(e) => panic!("decode should succeed: {e}"),
}
});
}
#[test]
#[allow(clippy::panic)]
fn u64_round_trip() {
bolero::check!()
.with_arbitrary::<core::primitive::u64>()
.for_each(|value| {
let mut buf = Vec::new();
encode::u64(*value, &mut buf);
match u64(&buf, 0) {
Ok(decoded) => assert_eq!(decoded, *value),
Err(e) => panic!("decode should succeed: {e}"),
}
});
}
#[test]
#[allow(clippy::panic)]
fn array_round_trip() {
bolero::check!()
.with_arbitrary::<[u8; 32]>()
.for_each(|value| {
let mut buf = Vec::new();
encode::array(value, &mut buf);
match array::<32>(&buf, 0) {
Ok(decoded) => assert_eq!(&decoded, value),
Err(e) => panic!("decode should succeed: {e}"),
}
});
}
#[test]
fn verify_sorted_accepts_sorted() {
bolero::check!()
.with_arbitrary::<Vec<[u8; 32]>>()
.for_each(|elements| {
let mut sorted = elements.clone();
sorted.sort_unstable();
sorted.dedup();
assert!(verify_sorted(&sorted).is_ok());
});
}
}