-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathsmall_vec.rs
282 lines (234 loc) · 7.91 KB
/
small_vec.rs
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
use std::io::{Read, Write};
use std::marker::PhantomData;
use anchor_lang::prelude::*;
/// Concise serialization schema for vectors where the length can be represented
/// by any type `L` (typically unsigned integer like `u8` or `u16`)
/// that implements AnchorDeserialize and can be converted to `u32`.
#[derive(Clone, Debug, Default)]
pub struct SmallVec<L, T>(Vec<T>, PhantomData<L>);
impl<L, T> SmallVec<L, T> {
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl<L, T> From<SmallVec<L, T>> for Vec<T> {
fn from(val: SmallVec<L, T>) -> Self {
val.0
}
}
impl<L, T> From<Vec<T>> for SmallVec<L, T> {
fn from(val: Vec<T>) -> Self {
Self(val, PhantomData)
}
}
impl<T: AnchorSerialize> AnchorSerialize for SmallVec<u8, T> {
fn serialize<W: Write>(&self, writer: &mut W) -> std::io::Result<()> {
let len = u8::try_from(self.len()).map_err(|_| std::io::ErrorKind::InvalidInput)?;
// Write the length of the vector as u8.
writer.write_all(&len.to_le_bytes())?;
// Write the vector elements.
serialize_slice(&self.0, writer)
}
}
impl<T: AnchorSerialize> AnchorSerialize for SmallVec<u16, T> {
fn serialize<W: Write>(&self, writer: &mut W) -> std::io::Result<()> {
let len = u16::try_from(self.len()).map_err(|_| std::io::ErrorKind::InvalidInput)?;
// Write the length of the vector as u16.
writer.write_all(&len.to_le_bytes())?;
// Write the vector elements.
serialize_slice(&self.0, writer)
}
}
impl<L, T> AnchorDeserialize for SmallVec<L, T>
where
L: AnchorDeserialize + Into<u32>,
T: AnchorDeserialize,
{
/// This implementation almost exactly matches standard implementation of
/// `Vec<T>::deserialize` except that it uses `L` instead of `u32` for the length,
/// and doesn't include `unsafe` code.
fn deserialize_reader<R: Read>(reader: &mut R) -> std::io::Result<Self> {
let len: u32 = L::deserialize_reader(reader)?.into();
let vec = if len == 0 {
Vec::new()
} else if let Some(vec_bytes) = T::vec_from_reader(len, reader)? {
vec_bytes
} else {
let mut result = Vec::with_capacity(hint::cautious::<T>(len));
for _ in 0..len {
result.push(T::deserialize_reader(reader)?);
}
result
};
Ok(SmallVec(vec, PhantomData))
}
}
// This is copy-pasted from borsh::de::hint;
mod hint {
#[inline]
pub fn cautious<T>(hint: u32) -> usize {
let el_size = core::mem::size_of::<T>() as u32;
core::cmp::max(core::cmp::min(hint, 4096 / el_size), 1) as usize
}
}
/// Helper method that is used to serialize a slice of data (without the length marker).
/// Copied from borsh::ser::serialize_slice.
#[inline]
fn serialize_slice<T: AnchorSerialize, W: Write>(
data: &[T],
writer: &mut W,
) -> std::io::Result<()> {
if let Some(u8_slice) = T::u8_slice(data) {
writer.write_all(u8_slice)?;
} else {
for item in data {
item.serialize(writer)?;
}
}
Ok(())
}
#[cfg(test)]
mod test {
use super::*;
mod deserialize {
use super::*;
#[test]
fn test_length_u8_type_u8() {
let mut input = &[
0x02, // len (2)
0x05, // vec[0]
0x09, // vec[1]
][..];
let small_vec: SmallVec<u8, u8> = SmallVec::deserialize(&mut input).unwrap();
assert_eq!(small_vec.0, vec![5, 9]);
}
#[test]
fn test_length_u8_type_u32() {
let mut input = &[
0x02, // len (2)
0x05, 0x00, 0x00, 0x00, // vec[0]
0x09, 0x00, 0x00, 0x00, // vec[1]
][..];
let small_vec: SmallVec<u8, u32> = SmallVec::deserialize(&mut input).unwrap();
assert_eq!(small_vec.0, vec![5, 9]);
}
#[test]
fn test_length_u8_type_pubkey() {
let pubkey1 = Pubkey::new_unique();
let pubkey2 = Pubkey::new_unique();
let mut input = &[
&[0x02], // len (2)
&pubkey1.try_to_vec().unwrap()[..],
&pubkey2.try_to_vec().unwrap()[..],
]
.concat()[..];
let small_vec: SmallVec<u8, Pubkey> = SmallVec::deserialize(&mut input).unwrap();
assert_eq!(small_vec.0, vec![pubkey1, pubkey2]);
}
#[test]
fn test_length_u16_type_u8() {
let mut input = &[
0x02, 0x00, // len (2)
0x05, // vec[0]
0x09, // vec[1]
][..];
let small_vec: SmallVec<u16, u8> = SmallVec::deserialize(&mut input).unwrap();
assert_eq!(small_vec.0, vec![5, 9]);
}
#[test]
fn test_length_u16_type_pubkey() {
let pubkey1 = Pubkey::new_unique();
let pubkey2 = Pubkey::new_unique();
let mut input = &[
&[0x02, 0x00], // len (2)
&pubkey1.try_to_vec().unwrap()[..],
&pubkey2.try_to_vec().unwrap()[..],
]
.concat()[..];
let small_vec: SmallVec<u16, Pubkey> = SmallVec::deserialize(&mut input).unwrap();
assert_eq!(small_vec.0, vec![pubkey1, pubkey2]);
}
}
mod serialize {
use super::*;
#[test]
fn test_length_u8_type_u8() {
let small_vec = SmallVec::<u8, u8>::from(vec![3, 5]);
let mut output = vec![];
small_vec.serialize(&mut output).unwrap();
assert_eq!(
output,
vec![
0x02, // len (2)
0x03, // vec[0]
0x05, // vec[1]
]
);
}
#[test]
fn test_length_u8_type_u32() {
let small_vec = SmallVec::<u8, u32>::from(vec![3, 5]);
let mut output = vec![];
small_vec.serialize(&mut output).unwrap();
assert_eq!(
output,
vec![
0x02, // len (2)
0x03, 0x00, 0x00, 0x00, // vec[0]
0x05, 0x00, 0x00, 0x00, // vec[1]
]
);
}
#[test]
fn test_length_u8_type_pubkey() {
let pubkey1 = Pubkey::new_unique();
let pubkey2 = Pubkey::new_unique();
let small_vec = SmallVec::<u8, Pubkey>::from(vec![pubkey1, pubkey2]);
let mut output = vec![];
small_vec.serialize(&mut output).unwrap();
assert_eq!(
output,
[
&[0x02], // len (2)
&pubkey1.to_bytes()[..],
&pubkey2.to_bytes()[..],
]
.concat()[..]
);
}
#[test]
fn test_length_u16_type_u8() {
let small_vec = SmallVec::<u16, u8>::from(vec![3, 5]);
let mut output = vec![];
small_vec.serialize(&mut output).unwrap();
assert_eq!(
output,
vec![
0x02, 0x00, // len (2)
0x03, // vec[0]
0x05, // vec[1]
]
);
}
#[test]
fn test_length_u16_type_pubkey() {
let pubkey1 = Pubkey::new_unique();
let pubkey2 = Pubkey::new_unique();
let small_vec = SmallVec::<u16, Pubkey>::from(vec![pubkey1, pubkey2]);
let mut output = vec![];
small_vec.serialize(&mut output).unwrap();
assert_eq!(
output,
[
&[0x02, 0x00], // len (2)
&pubkey1.to_bytes()[..],
&pubkey2.to_bytes()[..],
]
.concat()[..]
);
}
}
}