Debian Codegraph @

crt/s2n/bindings/rust/aws-kms-tls-auth/src/prefixed_list.rs

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 use crate::codec::{DecodeByteSource, DecodeValue, EncodeBytesSink, EncodeValue};
5 use std::{any::type_name, fmt::Debug, io::ErrorKind, mem::size_of};
6
7 /// An opaque list of bytes, where the size of the list is prefixed on the wire as `L`.
8 ///
9 /// This is just a convenience wrapper for `PrefixedList<u8, L>`.
10 #[derive(Clone, Hash, PartialEq, Eq)]
11 pub struct PrefixedBlob<L>(pub PrefixedList<u8, L>);
12
13 impl<L: TryFrom<usize>> PrefixedBlob<L> {
14 pub fn new(inner_blob: Vec<u8>) -> anyhow::Result<Self> {
15 let length_usize = inner_blob.len();
16 let length = match length_usize.try_into() {
17 Ok(length) => length,
18 _ => anyhow::bail!(
19 "failed to convert list length of {} into {}",
20 length_usize,
21 type_name::<L>()
22 ),
23 };
24
25 let list = PrefixedList::<u8, L> {
26 length,
27 items: inner_blob,
28 };
29 Ok(Self(list))
30 }
31 }
32
33 impl<L> PrefixedBlob<L> {
34 pub fn blob(&self) -> &[u8] {
35 &self.0.items
36 }
37
38 pub fn take_blob(self) -> Vec<u8> {
39 self.0.items
40 }
41 }
42
43 impl<L> Debug for PrefixedBlob<L> {
44 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45 f.debug_tuple("PrefixedBlob")
46 .field(&self.blob().len())
47 .finish()
48 }
49 }
50
51 impl<L> DecodeValue for PrefixedBlob<L>
52 where
53 L: Copy + TryInto<usize> + DecodeValue,
54 {
55 fn decode_from(buffer: &[u8]) -> std::io::Result<(Self, &[u8])> {
56 let (inner, remaining) = buffer.decode_value()?;
57 Ok((Self(inner), remaining))
58 }
59 }
60
61 impl<L> EncodeValue for PrefixedBlob<L>
62 where
63 L: EncodeValue,
64 {
65 fn encode_to(&self, buffer: &mut Vec<u8>) -> std::io::Result<()> {
66 buffer.encode_value(&self.0)?;
67 Ok(())
68 }
69 }
70
71 /// A list of `T`, where the byte length of the list is prefixed on the wire as `L`.
72 ///
73 /// NOTE: length != count. A list of 100 u16's, has count 100 and size 200.
74 ///
75 /// This unfortunately conflicts with the `.len()` function on rust `std` collections,
76 /// which will return the count of elements, and not their serialized length.
77 #[derive(Debug, Clone, Hash, PartialEq, Eq)]
78 pub struct PrefixedList<T, L> {
79 // We could remove the length since it's implicit in the items and their
80 // encode implementation, but it makes the writing much uglier because you need
81 // to use a "skip write" pattern.
82 /// The length of the list in bytes
83 length: L,
84 items: Vec<T>,
85 }
86
87 impl<T, L> PrefixedList<T, L>
88 where
89 L: Copy + Into<usize>,
90 {
91 pub fn list(&self) -> &[T] {
92 &self.items
93 }
94 }
95
96 impl<T, L> DecodeValue for PrefixedList<T, L>
97 where
98 L: Copy + TryInto<usize> + DecodeValue,
99 T: DecodeValue,
100 {
101 fn decode_from(buffer: &[u8]) -> std::io::Result<(Self, &[u8])> {
102 let (length, mut buffer): (L, &[u8]) = buffer.decode_value()?;
103 let length_usize: usize = match length.try_into() {
104 Ok(length) => length,
105 // this error should never happen except on 16 bit platforms. And we
106 // don't ever expect to run on 16 bit platforms.
107 Err(_) => {
108 return Err(std::io::Error::new(
109 ErrorKind::FileTooLarge,
110 "failed to convert to usize",
111 ))
112 }
113 };
114
115 let current_buffer_size = buffer.len();
116 if current_buffer_size < length_usize {
117 return Err(std::io::Error::new(
118 ErrorKind::UnexpectedEof,
119 "not enough data available".to_owned(),
120 ));
121 }
122 let target_buffer_size = current_buffer_size - length_usize;
123
124 // Estimate how many elements we expect to decode to avoid reallocation.
125 let element_count = if size_of::<T>() == 0 {
126 0
127 } else {
128 length_usize / size_of::<T>()
129 };
130
131 let mut list: Vec<T> = Vec::with_capacity(element_count);
132 while buffer.len() > target_buffer_size {
133 let (item, remaining_buffer) = buffer.decode_value()?;
134 list.push(item);
135 buffer = remaining_buffer;
136 }
137
138 // this case might occur if the list was of length e.g. 21,
139 // but each element was 2 bytes so we read 22,
140 if buffer.len() != target_buffer_size {
141 return Err(std::io::Error::new(
142 ErrorKind::InvalidData,
143 "overread data, length field likely corrupt",
144 ));
145 }
146
147 Ok((
148 Self {
149 length,
150 items: list,
151 },
152 buffer,
153 ))
154 }
155 }
156
157 impl<T, L> EncodeValue for PrefixedList<T, L>
158 where
159 T: EncodeValue,
160 L: EncodeValue,
161 {
162 fn encode_to(&self, buffer: &mut Vec<u8>) -> std::io::Result<()> {
163 buffer.encode_value(&self.length)?;
164 for item in &self.items {
165 buffer.encode_value(item)?;
166 }
167 Ok(())
168 }
169 }
170
171 #[cfg(test)]
172 mod tests {
173 use crate::codec::{DecodeValue, EncodeValue};
174 use crate::prefixed_list::PrefixedBlob;
175 use crate::prefixed_list::PrefixedList;
176 use std::mem::size_of;
177
178 #[test]
179 fn list_too_long() {
180 let error = PrefixedBlob::<u8>::new(vec![0; 257]).unwrap_err();
181 assert_eq!(
182 error.to_string(),
183 "failed to convert list length of 257 into u8"
184 );
185 }
186
187 /// Ensure allocation based on the number of items when each element is a single byte
188 #[test]
189 fn prefixed_list_decodes_correct_element_count() {
190 let items: Vec<u8> = vec![0u8; 1024];
191
192 let list = PrefixedList::<u8, u16> {
193 // length, in this case, equals total bytes (u8 => 1 byte each)
194 length: items.len() as u16,
195 items: items.clone(),
196 };
197 let mut encoded = Vec::new();
198 list.encode_to(&mut encoded).unwrap();
199
200 let (decoded, remaining) = PrefixedList::<u8, u16>::decode_from(&encoded).unwrap();
201 assert!(remaining.is_empty());
202 assert_eq!(decoded.items.capacity(), items.len());
203 }
204
205 /// Ensure allocation based on the number of items when each element is large
206 #[test]
207 fn prefixed_list_large_bytes_few_elements() {
208 // 1024 chosen to create a large "wire size" for a single element
209 let items = vec![[0u8; 1024]];
210 let items_length = (items.len() * size_of::<[u8; 1024]>()) as u16;
211
212 let list = PrefixedList::<[u8; 1024], u16> {
213 length: items_length,
214 items,
215 };
216 let mut encoded = Vec::new();
217 list.encode_to(&mut encoded).unwrap();
218
219 let (decoded, remaining) = PrefixedList::<[u8; 1024], u16>::decode_from(&encoded).unwrap();
220 assert!(remaining.is_empty());
221 assert_eq!(decoded.items.capacity(), decoded.items.len());
222 assert_eq!(decoded.items.len(), 1);
223 }
224 }