Repository navigation
Expand file tree
/
Copy pathborsh.rs
More file actions
68 lines (63 loc) · 1.92 KB
/
Copy pathborsh.rs
File metadata and controls
68 lines (63 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use {
super::SmallVec,
alloc::{
collections::BTreeMap as Map,
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() as u64).serialize(writer)?;
for element in self {
element.serialize(writer)?;
}
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)?;
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 {
format!("Vec<{}>", Type::declaration())
}
fn add_definitions_recursively(definitions: &mut Map<Declaration, Definition>) {
let declaration = Self::declaration();
if definitions.contains_key(&declaration) {
return;
}
Type::add_definitions_recursively(definitions);
definitions.insert(
declaration,
Definition::Sequence {
length_width: 8,
length_range: 0..=u64::MAX,
elements: Type::declaration()
}
);
}
}