powerio_archive/
stream.rs1use std::io::Read;
4
5#[derive(Debug)]
7#[non_exhaustive]
8pub enum DeclaredSizeFailure {
9 Read(std::io::Error),
11 Allocation,
13 Short(u64),
15 Long,
17}
18
19impl DeclaredSizeFailure {
20 fn from_read_error(error: std::io::Error) -> Self {
21 if error
26 .to_string()
27 .contains("larger than its declared uncompressed size")
28 {
29 Self::Long
30 } else {
31 Self::Read(error)
32 }
33 }
34}
35
36pub fn read_declared_size(
43 entry: &mut impl Read,
44 prefix: &[u8],
45 size: u64,
46) -> std::result::Result<Vec<u8>, DeclaredSizeFailure> {
47 if prefix.len() as u64 > size {
48 return Err(DeclaredSizeFailure::Long);
49 }
50 let capacity = usize::try_from(size).map_err(|_| DeclaredSizeFailure::Allocation)?;
51 let mut content = Vec::new();
52 content
53 .try_reserve_exact(capacity)
54 .map_err(|_| DeclaredSizeFailure::Allocation)?;
55 content.extend_from_slice(prefix);
56 entry
57 .by_ref()
58 .take(size - prefix.len() as u64)
59 .read_to_end(&mut content)
60 .map_err(DeclaredSizeFailure::from_read_error)?;
61 let produced = content.len() as u64;
62 if produced != size {
63 return Err(DeclaredSizeFailure::Short(produced));
64 }
65 if entry
66 .read(&mut [0_u8; 1])
67 .map_err(DeclaredSizeFailure::from_read_error)?
68 != 0
69 {
70 return Err(DeclaredSizeFailure::Long);
71 }
72 Ok(content)
73}
74
75pub fn read_bounded(
78 reader: &mut impl Read,
79 max_bytes: u64,
80) -> Result<Vec<u8>, DeclaredSizeFailure> {
81 let mut bytes = Vec::new();
82 reader
83 .take(max_bytes.saturating_add(1))
84 .read_to_end(&mut bytes)
85 .map_err(DeclaredSizeFailure::Read)?;
86 if bytes.len() as u64 > max_bytes {
87 return Err(DeclaredSizeFailure::Long);
88 }
89 Ok(bytes)
90}