// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use crate::codec::{DecodeByteSource, DecodeValue, EncodeBytesSink, EncodeValue}; use std::{any::type_name, fmt::Debug, io::ErrorKind, mem::size_of}; /// An opaque list of bytes, where the size of the list is prefixed on the wire as `L`. /// /// This is just a convenience wrapper for `PrefixedList`. #[derive(Clone, Hash, PartialEq, Eq)] pub struct PrefixedBlob(pub PrefixedList); impl> PrefixedBlob { pub fn new(inner_blob: Vec) -> anyhow::Result { let length_usize = inner_blob.len(); let length = match length_usize.try_into() { Ok(length) => length, _ => anyhow::bail!( "failed to convert list length of {} into {}", length_usize, type_name::() ), }; let list = PrefixedList:: { length, items: inner_blob, }; Ok(Self(list)) } } impl PrefixedBlob { pub fn blob(&self) -> &[u8] { &self.0.items } pub fn take_blob(self) -> Vec { self.0.items } } impl Debug for PrefixedBlob { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_tuple("PrefixedBlob") .field(&self.blob().len()) .finish() } } impl DecodeValue for PrefixedBlob where L: Copy + TryInto + DecodeValue, { fn decode_from(buffer: &[u8]) -> std::io::Result<(Self, &[u8])> { let (inner, remaining) = buffer.decode_value()?; Ok((Self(inner), remaining)) } } impl EncodeValue for PrefixedBlob where L: EncodeValue, { fn encode_to(&self, buffer: &mut Vec) -> std::io::Result<()> { buffer.encode_value(&self.0)?; Ok(()) } } /// A list of `T`, where the byte length of the list is prefixed on the wire as `L`. /// /// NOTE: length != count. A list of 100 u16's, has count 100 and size 200. /// /// This unfortunately conflicts with the `.len()` function on rust `std` collections, /// which will return the count of elements, and not their serialized length. #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct PrefixedList { // We could remove the length since it's implicit in the items and their // encode implementation, but it makes the writing much uglier because you need // to use a "skip write" pattern. /// The length of the list in bytes length: L, items: Vec, } impl PrefixedList where L: Copy + Into, { pub fn list(&self) -> &[T] { &self.items } } impl DecodeValue for PrefixedList where L: Copy + TryInto + DecodeValue, T: DecodeValue, { fn decode_from(buffer: &[u8]) -> std::io::Result<(Self, &[u8])> { let (length, mut buffer): (L, &[u8]) = buffer.decode_value()?; let length_usize: usize = match length.try_into() { Ok(length) => length, // this error should never happen except on 16 bit platforms. And we // don't ever expect to run on 16 bit platforms. Err(_) => { return Err(std::io::Error::new( ErrorKind::FileTooLarge, "failed to convert to usize", )) } }; let current_buffer_size = buffer.len(); if current_buffer_size < length_usize { return Err(std::io::Error::new( ErrorKind::UnexpectedEof, "not enough data available".to_owned(), )); } let target_buffer_size = current_buffer_size - length_usize; // Estimate how many elements we expect to decode to avoid reallocation. let element_count = if size_of::() == 0 { 0 } else { length_usize / size_of::() }; let mut list: Vec = Vec::with_capacity(element_count); while buffer.len() > target_buffer_size { let (item, remaining_buffer) = buffer.decode_value()?; list.push(item); buffer = remaining_buffer; } // this case might occur if the list was of length e.g. 21, // but each element was 2 bytes so we read 22, if buffer.len() != target_buffer_size { return Err(std::io::Error::new( ErrorKind::InvalidData, "overread data, length field likely corrupt", )); } Ok(( Self { length, items: list, }, buffer, )) } } impl EncodeValue for PrefixedList where T: EncodeValue, L: EncodeValue, { fn encode_to(&self, buffer: &mut Vec) -> std::io::Result<()> { buffer.encode_value(&self.length)?; for item in &self.items { buffer.encode_value(item)?; } Ok(()) } } #[cfg(test)] mod tests { use crate::codec::{DecodeValue, EncodeValue}; use crate::prefixed_list::PrefixedBlob; use crate::prefixed_list::PrefixedList; use std::mem::size_of; #[test] fn list_too_long() { let error = PrefixedBlob::::new(vec![0; 257]).unwrap_err(); assert_eq!( error.to_string(), "failed to convert list length of 257 into u8" ); } /// Ensure allocation based on the number of items when each element is a single byte #[test] fn prefixed_list_decodes_correct_element_count() { let items: Vec = vec![0u8; 1024]; let list = PrefixedList:: { // length, in this case, equals total bytes (u8 => 1 byte each) length: items.len() as u16, items: items.clone(), }; let mut encoded = Vec::new(); list.encode_to(&mut encoded).unwrap(); let (decoded, remaining) = PrefixedList::::decode_from(&encoded).unwrap(); assert!(remaining.is_empty()); assert_eq!(decoded.items.capacity(), items.len()); } /// Ensure allocation based on the number of items when each element is large #[test] fn prefixed_list_large_bytes_few_elements() { // 1024 chosen to create a large "wire size" for a single element let items = vec![[0u8; 1024]]; let items_length = (items.len() * size_of::<[u8; 1024]>()) as u16; let list = PrefixedList::<[u8; 1024], u16> { length: items_length, items, }; let mut encoded = Vec::new(); list.encode_to(&mut encoded).unwrap(); let (decoded, remaining) = PrefixedList::<[u8; 1024], u16>::decode_from(&encoded).unwrap(); assert!(remaining.is_empty()); assert_eq!(decoded.items.capacity(), decoded.items.len()); assert_eq!(decoded.items.len(), 1); } }