Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ criterion = "0.8"
name = "arbitrary"
required-features = ["arbitrary"]

[[test]]
name = "borsh"
required-features = ["borsh"]

[[test]]
name = "bytes"
required-features = ["bytes"]
Expand Down
24 changes: 20 additions & 4 deletions src/borsh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,45 @@ use {
format
},
borsh::{
BorshDeserialize,
BorshSchema,
BorshSerialize,
io::{
Error,
ErrorKind,
Result as Serial,
Write
},
schema::{
Declaration,
Definition
}
}
},
core::iter::repeat_with
};

impl<Type: BorshSerialize, const INLINE: usize> BorshSerialize for SmallVec<Type, INLINE> {
fn serialize<Writer: Write>(&self, writer: &mut Writer) -> Serial<()> {
self.len.value().serialize(writer)?;
(self.len.value() as u64).serialize(writer)?;
for element in self {
element.serialize(writer)?;
}
return Ok(());
}
}

impl<Type: BorshDeserialize, const INLINE: usize> BorshDeserialize for SmallVec<Type, INLINE> {
fn deserialize_reader<R: borsh::io::Read>(reader: &mut R) -> Serial<Self> {
let length = u64::deserialize_reader(reader)?;
return repeat_with(|| Type::deserialize_reader(reader))
.take(length.try_into().map_err(|_| Error::new(
ErrorKind::OutOfMemory,
"Cannot deserialize a sequence with more than usize::MAX elements in this machine"
))?)
.collect();
}
}

impl<Type: BorshSchema, const INLINE: usize> BorshSchema for SmallVec<Type, INLINE> {
fn declaration() -> Declaration {
return format!("Vec<{}>", Type::declaration());
Expand All @@ -42,8 +58,8 @@ impl<Type: BorshSchema, const INLINE: usize> BorshSchema for SmallVec<Type, INLI
definitions.insert(
declaration,
Definition::Sequence {
length_width: usize::BITS as u8 / 8,
length_range: 0..=(usize::MAX as u64),
length_width: 8,
length_range: 0..=u64::MAX,
elements: Type::declaration()
}
);
Expand Down
25 changes: 25 additions & 0 deletions tests/borsh.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
use {
borsh::{
BorshDeserialize,
to_vec
},
smallvec::SmallVec
};

#[test]
fn round_trip() -> () {
let smallvec = SmallVec::<u8, 6>::from([1, 2, 3]);
let bytes = to_vec(&smallvec).unwrap();
assert_eq!(bytes, [3, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3]);
let new = SmallVec::<u8, 6>::deserialize(&mut bytes.as_ref()).unwrap();
assert_eq!(new, smallvec);
}

#[test]
fn round_trip_zst() -> () {
let smallvec = SmallVec::<(), 5>::from([(); 0x100000]);
let bytes = to_vec(&smallvec).unwrap();
assert_eq!(bytes, [0, 0, 16, 0, 0, 0, 0, 0]);
let new = SmallVec::<(), 100>::deserialize(&mut bytes.as_ref()).unwrap();
assert_eq!(new, smallvec);
}
Loading