1use std::{
6 io::{Read, Write},
7 marker::PhantomData,
8};
9
10use anyhow::{Result, anyhow, bail};
11use byteorder::ReadBytesExt;
12use integer_encoding::{VarInt, VarIntReader};
13use num_enum::{IntoPrimitive, TryFromPrimitive};
14use serde::{Serialize, de::DeserializeOwned};
15use tracing::error;
16
17pub const MAX_VARINT_LENGTH: usize = 10;
18pub const BLOB_ENCODING_BYTES: usize = 1;
19const MAX_PREALLOCATION: usize = 1 << 20;
20const MAX_BLOB_LENGTH: u64 = 1 << 32;
24
25#[derive(Copy, Clone, Debug, Eq, PartialEq, TryFromPrimitive, IntoPrimitive)]
26#[repr(u8)]
27pub enum BlobEncoding {
28 Bcs = 1,
29}
30
31pub struct Blob {
32 pub data: Vec<u8>,
33 pub encoding: BlobEncoding,
34}
35
36impl Blob {
37 pub fn encode<T: Serialize>(value: &T, encoding: BlobEncoding) -> Result<Self> {
38 let value_buf = bcs::to_bytes(value)?;
39 let (data, encoding) = match encoding {
40 BlobEncoding::Bcs => (value_buf, encoding),
41 };
42 Ok(Blob { data, encoding })
43 }
44 pub fn decode<T: DeserializeOwned>(self) -> Result<T> {
45 let data = match &self.encoding {
46 BlobEncoding::Bcs => self.data,
47 };
48 let res = bcs::from_bytes(&data)?;
49 Ok(res)
50 }
51 pub fn read<R: Read>(rbuf: &mut R) -> Result<Blob> {
63 let len = rbuf.read_varint::<u64>()?;
64 if len == 0 {
65 bail!("Invalid object length of 0 in file");
66 }
67 if len > MAX_BLOB_LENGTH {
68 bail!("blob length {len} is above the maximum of {MAX_BLOB_LENGTH} bytes");
69 }
70 let encoding = rbuf.read_u8()?;
71 let mut data = Vec::with_capacity(len.min(MAX_PREALLOCATION as u64) as usize);
74 rbuf.take(len).read_to_end(&mut data)?;
75 if data.len() as u64 != len {
76 bail!(
77 "blob length {len} is beyond the remaining input of {} bytes",
78 data.len()
79 );
80 }
81 let blob = Blob {
82 data,
83 encoding: BlobEncoding::try_from(encoding)?,
84 };
85 Ok(blob)
86 }
87 pub fn write<W: Write>(&self, wbuf: &mut W) -> Result<usize> {
88 let mut buf = [0u8; MAX_VARINT_LENGTH];
89 let mut counter = 0;
90 let n = (self.data.len() as u64).encode_var(&mut buf);
91 wbuf.write_all(&buf[0..n])?;
92 counter += n;
93 buf[0] = self.encoding.into();
94 wbuf.write_all(&buf[0..BLOB_ENCODING_BYTES])?;
95 counter += 1;
96 wbuf.write_all(&self.data)?;
97 counter += self.data.len();
98 Ok(counter)
99 }
100 pub fn size(&self) -> usize {
101 let mut blob_size = self.data.len().required_space();
102 blob_size += BLOB_ENCODING_BYTES;
103 blob_size += self.data.len();
104 blob_size
105 }
106 pub fn to_bytes(&self) -> Vec<u8> {
107 [vec![self.encoding.into()], self.data.clone()].concat()
108 }
109 pub fn from_bytes<T: DeserializeOwned>(bytes: &[u8]) -> Result<T> {
110 let (encoding, data) = bytes.split_first().ok_or(anyhow!("empty bytes"))?;
111 Blob {
112 data: data.to_vec(),
113 encoding: BlobEncoding::try_from(*encoding)?,
114 }
115 .decode()
116 }
117}
118
119pub struct BlobIter<T> {
122 reader: Box<dyn Read + Send>,
123 _phantom: PhantomData<fn() -> T>,
124}
125
126impl<T: DeserializeOwned> BlobIter<T> {
127 pub fn new(reader: Box<dyn Read + Send>) -> Self {
128 Self {
129 reader,
130 _phantom: PhantomData,
131 }
132 }
133 fn next_blob(&mut self) -> Result<Option<T>> {
135 let mut first = [0u8; 1];
138 if self.reader.read(&mut first)? == 0 {
139 return Ok(None);
140 }
141 let blob = Blob::read(&mut first.as_slice().chain(&mut self.reader))?;
142 blob.decode().map(Some)
143 }
144}
145
146impl<T: DeserializeOwned> Iterator for BlobIter<T> {
147 type Item = T;
148 fn next(&mut self) -> Option<Self::Item> {
149 self.next_blob().unwrap_or_else(|err| {
150 error!("failed to read a blob, ignoring the rest of the file: {err:#}");
151 None
152 })
153 }
154}
155
156#[cfg(test)]
157mod tests {
158 use std::io::Cursor;
159
160 use super::*;
161 use crate::{FileCompression, StorageFormat, make_iterator};
162
163 const MAGIC: u32 = 0x0000BEEF;
164
165 fn header(len: u64) -> Vec<u8> {
168 let mut bytes = len.encode_var_vec();
169 bytes.push(BlobEncoding::Bcs.into());
170 bytes
171 }
172
173 fn encode_blobs(values: &[u64]) -> Vec<u8> {
175 let mut blobs = Vec::new();
176 for value in values {
177 Blob::encode(value, BlobEncoding::Bcs)
178 .unwrap()
179 .write(&mut blobs)
180 .unwrap();
181 }
182 blobs
183 }
184
185 fn blob_file(compression: FileCompression, blobs: Vec<u8>) -> Vec<u8> {
187 let mut file = MAGIC.to_be_bytes().to_vec();
188 file.push(StorageFormat::Blob.into());
189 file.push(compression.into());
190 match compression {
191 FileCompression::None => file.extend(blobs),
192 FileCompression::Zstd => {
193 FileCompression::zstd_compress(&mut Cursor::new(blobs), &mut file).unwrap()
194 }
195 }
196 file
197 }
198
199 #[test]
200 fn write_read() {
201 for value in [vec![1u8, 2, 3], vec![7u8; 3 * MAX_PREALLOCATION]] {
203 let blob = Blob::encode(&value, BlobEncoding::Bcs).unwrap();
204 let mut bytes = Vec::new();
205 blob.write(&mut bytes).unwrap();
206 let read = Blob::read(&mut Cursor::new(bytes)).unwrap();
207 assert_eq!(read.data, blob.data);
208 assert_eq!(read.decode::<Vec<u8>>().unwrap(), value);
209 }
210 }
211
212 #[test]
213 fn rejects_length_beyond_input() {
214 for len in [MAX_BLOB_LENGTH, 2_313_050_709, 4] {
216 let mut bytes = header(len);
217 bytes.extend_from_slice(&[0u8; 3]);
218 let err = Blob::read(&mut Cursor::new(bytes)).err().unwrap();
219 assert!(
220 err.to_string()
221 .contains("is beyond the remaining input of 3 bytes"),
222 "{err}"
223 );
224 }
225 }
226
227 #[test]
230 fn rejects_length_above_maximum() {
231 for compression in [FileCompression::None, FileCompression::Zstd] {
232 for len in [MAX_BLOB_LENGTH + 1, u64::MAX] {
233 let mut blob = header(len);
234 blob.extend_from_slice(&[0u8; 3]);
235 let file = blob_file(compression, blob);
236
237 let (mut reader, _) = crate::read(MAGIC, Cursor::new(file)).unwrap();
238 let err = Blob::read(&mut reader).err().unwrap();
239 assert!(
240 err.to_string().contains(&format!(
241 "blob length {len} is above the maximum of {MAX_BLOB_LENGTH} bytes"
242 )),
243 "{err}"
244 );
245 }
246 }
247 }
248
249 #[test]
250 fn blob_iter_reads_until_end_of_input() {
251 for count in [0u64, 1, 3] {
252 let expected: Vec<u64> = (0..count).collect();
253 let file = blob_file(FileCompression::None, encode_blobs(&expected));
254
255 let values: Vec<u64> = make_iterator(MAGIC, Cursor::new(file)).unwrap().collect();
256 assert_eq!(values, expected);
257 }
258 }
259
260 #[test]
261 fn blob_iter_stops_at_length_beyond_input() {
262 for compression in [FileCompression::None, FileCompression::Zstd] {
263 let mut blobs = encode_blobs(&[7]);
264 blobs.extend(header(4));
265 blobs.extend_from_slice(&[0u8; 3]);
266 let file = blob_file(compression, blobs);
267
268 let values: Vec<u64> = make_iterator(MAGIC, Cursor::new(file)).unwrap().collect();
269 assert_eq!(values, vec![7]);
270 }
271 }
272
273 #[tokio::test]
277 async fn blob_iter_can_be_held_across_await_in_spawned_task() {
278 let file = blob_file(FileCompression::None, encode_blobs(&[0, 1, 2]));
279 let iter = make_iterator::<u64, _>(MAGIC, Cursor::new(file)).unwrap();
280 let values = tokio::spawn(async move {
281 let mut values = Vec::new();
282 for value in iter {
283 tokio::task::yield_now().await;
284 values.push(value);
285 }
286 values
287 })
288 .await
289 .unwrap();
290 assert_eq!(values, vec![0, 1, 2]);
291 }
292}