Skip to content

Commit 287dcd9

Browse files
authored
common: share the bzip2 stream engine (#8638)
Move the VM-independent bzip2 stream owner into a `bz2`-gated `rustpython-common` module beside the zlib and lzma engines, and keep `rustpython-stdlib` as the Python object and exception adapter. The adapter no longer names the `bzip2` crate; the `bz2` feature carries it. `_bz2` was the last user of the generic `DecompressState` / `DecompressStatus` / `Decompressor` machinery in `stdlib/src/compression.rs`, so that goes with it; `DecompressArgs` stays for zlib and lzma. The decompressor feeds the stream through the existing `Chunker`, so buffered and freshly supplied input are no longer joined into a new allocation first. `test_decompress_after_data_error` passes on the ported engine, so its `expectedFailure` marker goes. Assisted-by: Grok
1 parent 9c518bf commit 287dcd9

9 files changed

Lines changed: 390 additions & 287 deletions

File tree

‎Cargo.lock‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Lib/test/test_bz2.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1032,7 +1032,6 @@ def test_failure(self):
10321032
# Previously, a second call could crash due to internal inconsistency
10331033
self.assertRaises(Exception, bzd.decompress, self.BAD_DATA * 30)
10341034

1035-
@unittest.expectedFailure # TODO: RUSTPYTHON; Wrong error message
10361035
def test_decompress_after_data_error(self):
10371036
data = bytes.fromhex(
10381037
"425a6839314159265359000000000000007fffff000000000000000000000000"

‎crates/common/Cargo.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ license.workspace = true
1111
[features]
1212
default = ["std"]
1313
binascii = ["dep:base64", "dep:crc32fast"]
14+
bz2 = ["std", "dep:bzip2"]
1415
cjk-codecs = []
1516
inet = ["std"]
1617
json = ["dep:memchr", "std"]
@@ -28,6 +29,7 @@ rustpython-wtf8 = { workspace = true }
2829
ascii = { workspace = true }
2930
base64 = { workspace = true, optional = true }
3031
bitflags = { workspace = true }
32+
bzip2 = { workspace = true, optional = true }
3133
crc32fast = { workspace = true, optional = true }
3234
getrandom = { workspace = true }
3335
itertools = { workspace = true }
Lines changed: 324 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,324 @@
1+
// spell-checker:ignore chunker libbz
2+
//! VM-independent bzip2 stream engine.
3+
//!
4+
//! The engine owns its native stream state and reports plain Rust errors so
5+
//! interpreter and embedding layers can provide their own object and exception
6+
//! adapters.
7+
8+
use bzip2::{Action, Compress, Compression, Decompress, Error, Status};
9+
10+
use super::Chunker;
11+
12+
const INITIAL_BUFFER_SIZE: usize = 8192;
13+
const BIGCHUNK: usize = 512 * 1024;
14+
15+
/// Double the output block until `BIGCHUNK`, then keep the size fixed.
16+
const fn new_buffer_size(current_size: usize) -> usize {
17+
if current_size < BIGCHUNK {
18+
current_size + current_size
19+
} else {
20+
current_size
21+
}
22+
}
23+
24+
/// Stream errors reported by the bzip2 engine. Exception mapping belongs to
25+
/// the interpreter adapter.
26+
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
27+
pub enum Bz2Error {
28+
/// `BZ_PARAM_ERROR`
29+
Param,
30+
/// `BZ_DATA_ERROR` / `BZ_DATA_ERROR_MAGIC`
31+
Data,
32+
/// `BZ_SEQUENCE_ERROR`
33+
Sequence,
34+
/// `BZ_MEM_ERROR`
35+
Mem,
36+
}
37+
38+
impl From<Error> for Bz2Error {
39+
fn from(error: Error) -> Self {
40+
match error {
41+
Error::Param => Self::Param,
42+
Error::Data | Error::DataMagic => Self::Data,
43+
Error::Sequence => Self::Sequence,
44+
}
45+
}
46+
}
47+
48+
/// Incremental compressor. After `flush`, the stream is finished and must
49+
/// not be used again.
50+
pub struct Compressor {
51+
compress: Compress,
52+
flushed: bool,
53+
}
54+
55+
impl Compressor {
56+
/// Create a compressor. Returns `None` when `compresslevel` is outside
57+
/// `1..=9`. A zero work factor selects libbz2's default of 30.
58+
pub fn new(compresslevel: i64) -> Option<Self> {
59+
let level = u32::try_from(compresslevel)
60+
.ok()
61+
.and_then(Compression::try_new)?;
62+
Some(Self {
63+
compress: Compress::new(level, 0),
64+
flushed: false,
65+
})
66+
}
67+
68+
#[must_use]
69+
pub fn is_flushed(&self) -> bool {
70+
self.flushed
71+
}
72+
73+
/// Compress `data` without finishing the stream.
74+
pub fn compress(&mut self, data: &[u8]) -> Result<Vec<u8>, Bz2Error> {
75+
self.run(data, Action::Run)
76+
}
77+
78+
/// Finish the stream. The compressor must not be used again.
79+
pub fn flush(&mut self) -> Result<Vec<u8>, Bz2Error> {
80+
self.flushed = true;
81+
self.run(&[], Action::Finish)
82+
}
83+
84+
/// One pass over the input with the requested action, growing the output
85+
/// block whenever libbz2 fills it.
86+
fn run(&mut self, mut input: &[u8], action: Action) -> Result<Vec<u8>, Bz2Error> {
87+
let mut out = Vec::new();
88+
let mut block = vec![0u8; INITIAL_BUFFER_SIZE];
89+
loop {
90+
// In regular compression mode, stop when input data is exhausted.
91+
if action == Action::Run && input.is_empty() {
92+
break;
93+
}
94+
let previous_in = self.compress.total_in();
95+
let previous_out = self.compress.total_out();
96+
let status = self.compress.compress(input, &mut block, action)?;
97+
let consumed = (self.compress.total_in() - previous_in) as usize;
98+
let produced = (self.compress.total_out() - previous_out) as usize;
99+
out.extend_from_slice(&block[..produced]);
100+
input = &input[consumed..];
101+
// In flushing mode, stop when all buffered data has been flushed.
102+
if action == Action::Finish && status == Status::StreamEnd {
103+
break;
104+
}
105+
if produced == block.len() {
106+
block = vec![0u8; new_buffer_size(block.len())];
107+
}
108+
}
109+
out.shrink_to_fit();
110+
Ok(out)
111+
}
112+
}
113+
114+
/// Incremental decompressor. The first failure is latched so later calls
115+
/// can be refused by the caller; re-entering the native stream after a
116+
/// failure can write out of bounds.
117+
pub struct Decompressor {
118+
decompress: Decompress,
119+
eof: bool,
120+
failed: bool,
121+
needs_input: bool,
122+
unused_data: Vec<u8>,
123+
/// Input handed to `decompress` that libbz2 has not consumed yet.
124+
input_buffer: Vec<u8>,
125+
}
126+
127+
impl Decompressor {
128+
/// Create a decompressor using the fast (non-`small`) algorithm.
129+
#[must_use]
130+
pub fn new() -> Self {
131+
Self {
132+
decompress: Decompress::new(false),
133+
eof: false,
134+
failed: false,
135+
needs_input: true,
136+
unused_data: Vec::new(),
137+
input_buffer: Vec::new(),
138+
}
139+
}
140+
141+
#[must_use]
142+
pub fn eof(&self) -> bool {
143+
self.eof
144+
}
145+
146+
#[must_use]
147+
pub fn failed(&self) -> bool {
148+
self.failed
149+
}
150+
151+
#[must_use]
152+
pub fn needs_input(&self) -> bool {
153+
self.needs_input
154+
}
155+
156+
#[must_use]
157+
pub fn unused_data(&self) -> &[u8] {
158+
&self.unused_data
159+
}
160+
161+
/// Decompress from new input and any bytes buffered by an earlier call.
162+
/// `max_length` of `None` means unlimited output.
163+
pub fn decompress(
164+
&mut self,
165+
data: &[u8],
166+
max_length: Option<usize>,
167+
) -> Result<Vec<u8>, Bz2Error> {
168+
let max_length = max_length.unwrap_or(usize::MAX);
169+
let mut out = Vec::new();
170+
let mut block = vec![0u8; INITIAL_BUFFER_SIZE.min(max_length)];
171+
172+
let mut failed = None;
173+
let mut stream_end = false;
174+
let leftover = {
175+
let mut chunks = Chunker::chain(&self.input_buffer, data);
176+
loop {
177+
let chunk = chunks.chunk();
178+
let previous_in = self.decompress.total_in();
179+
let previous_out = self.decompress.total_out();
180+
let status = self.decompress.decompress(chunk, &mut block);
181+
let consumed = (self.decompress.total_in() - previous_in) as usize;
182+
let produced = (self.decompress.total_out() - previous_out) as usize;
183+
chunks.advance(consumed);
184+
out.extend_from_slice(&block[..produced]);
185+
match status {
186+
Err(error) => {
187+
failed = Some(error.into());
188+
break;
189+
}
190+
Ok(Status::MemNeeded) => {
191+
failed = Some(Bz2Error::Mem);
192+
break;
193+
}
194+
Ok(Status::StreamEnd) => {
195+
stream_end = true;
196+
break;
197+
}
198+
Ok(_) => {}
199+
}
200+
if chunks.is_empty() {
201+
break;
202+
}
203+
if produced == block.len() {
204+
// The output block is full: grow it unless `max_length`
205+
// has already been reached.
206+
if out.len() == max_length {
207+
break;
208+
}
209+
block = vec![0u8; new_buffer_size(block.len()).min(max_length - out.len())];
210+
}
211+
}
212+
if chunks.is_empty() {
213+
None
214+
} else {
215+
Some(chunks.to_vec())
216+
}
217+
};
218+
219+
if let Some(error) = failed {
220+
return Err(self.fail(error));
221+
}
222+
223+
if stream_end {
224+
self.eof = true;
225+
self.needs_input = false;
226+
self.input_buffer.clear();
227+
if let Some(unused) = leftover {
228+
self.unused_data = unused;
229+
}
230+
} else if let Some(remaining) = leftover {
231+
self.needs_input = false;
232+
self.input_buffer = remaining;
233+
} else {
234+
self.needs_input = true;
235+
self.input_buffer.clear();
236+
}
237+
out.shrink_to_fit();
238+
Ok(out)
239+
}
240+
241+
/// Latch the first failure and drop the pending input with it.
242+
fn fail(&mut self, error: Bz2Error) -> Bz2Error {
243+
self.failed = true;
244+
self.needs_input = false;
245+
self.input_buffer = Vec::new();
246+
error
247+
}
248+
}
249+
250+
impl Default for Decompressor {
251+
fn default() -> Self {
252+
Self::new()
253+
}
254+
}
255+
256+
#[cfg(test)]
257+
mod tests {
258+
use super::*;
259+
260+
fn roundtrip(data: &[u8], level: i64) -> Vec<u8> {
261+
let mut compressor = Compressor::new(level).unwrap();
262+
let mut encoded = compressor.compress(data).unwrap();
263+
encoded.extend(compressor.flush().unwrap());
264+
let mut decompressor = Decompressor::new();
265+
let out = decompressor.decompress(&encoded, None).unwrap();
266+
assert!(decompressor.eof());
267+
out
268+
}
269+
270+
#[test]
271+
fn invalid_level_is_rejected() {
272+
assert!(Compressor::new(0).is_none());
273+
assert!(Compressor::new(10).is_none());
274+
assert!(Compressor::new(-1).is_none());
275+
}
276+
277+
#[test]
278+
fn streaming_roundtrip() {
279+
let data = b"the quick brown fox jumps over the lazy dog".repeat(50);
280+
assert_eq!(roundtrip(&data, 9), data);
281+
}
282+
283+
#[test]
284+
fn unused_data_after_stream_end() {
285+
let mut compressor = Compressor::new(9).unwrap();
286+
let mut encoded = compressor.compress(b"hello").unwrap();
287+
encoded.extend(compressor.flush().unwrap());
288+
encoded.extend_from_slice(b"trailing");
289+
290+
let mut decompressor = Decompressor::new();
291+
let out = decompressor.decompress(&encoded, None).unwrap();
292+
assert_eq!(out, b"hello");
293+
assert!(decompressor.eof());
294+
assert!(!decompressor.needs_input());
295+
assert_eq!(decompressor.unused_data(), b"trailing");
296+
}
297+
298+
#[test]
299+
fn max_length_leaves_unconsumed_input() {
300+
let data = b"abcdefghij".repeat(20);
301+
let mut compressor = Compressor::new(9).unwrap();
302+
let mut encoded = compressor.compress(&data).unwrap();
303+
encoded.extend(compressor.flush().unwrap());
304+
305+
let mut decompressor = Decompressor::new();
306+
let first = decompressor.decompress(&encoded, Some(5)).unwrap();
307+
assert_eq!(first.len(), 5);
308+
assert!(!decompressor.eof());
309+
assert!(!decompressor.needs_input());
310+
let rest = decompressor.decompress(&[], None).unwrap();
311+
assert_eq!([first, rest].concat(), data);
312+
assert!(decompressor.eof());
313+
}
314+
315+
#[test]
316+
fn bad_data_latches_failure() {
317+
let mut decompressor = Decompressor::new();
318+
let err = decompressor.decompress(b"not a bz2 stream", None);
319+
assert_eq!(err, Err(Bz2Error::Data));
320+
assert!(decompressor.failed());
321+
assert!(!decompressor.needs_input());
322+
assert!(!decompressor.eof());
323+
}
324+
}

‎crates/common/src/compression/mod.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,8 @@ impl<'a> Chunker<'a> {
6969
}
7070
}
7171

72+
#[cfg(feature = "bz2")]
73+
pub mod bz2;
7274
#[cfg(all(
7375
feature = "lzma",
7476
not(any(target_os = "android", target_arch = "wasm32"))

‎crates/common/src/lib.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ pub mod binascii;
1111
pub mod borrow;
1212
pub mod boxvec;
1313
pub mod cformat;
14-
#[cfg(any(feature = "lzma", feature = "zlib"))]
14+
#[cfg(any(feature = "bz2", feature = "lzma", feature = "zlib"))]
1515
pub mod compression;
1616
pub mod encodings;
1717
pub mod float_ops;

‎crates/stdlib/Cargo.toml‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ __ssl-rustls = ["ssl", "rustls", "rustls-native-certs", "rustls-pemfile", "rustl
3030
# rustpython crates
3131
rustpython-derive = { workspace = true }
3232
rustpython-vm = { workspace = true, default-features = false, features = ["compiler"]}
33-
rustpython-common = { workspace = true, features = ["binascii", "cjk-codecs", "inet", "json", "lzma", "zlib"] }
33+
rustpython-common = { workspace = true, features = ["binascii", "bz2", "cjk-codecs", "inet", "json", "lzma", "zlib"] }
3434
rustpython-host_env = { workspace = true }
3535
rustpython-unicode = { workspace = true }
3636

@@ -79,7 +79,6 @@ constant_time_eq = { workspace = true }
7979

8080
# compression
8181
adler32 = { workspace = true }
82-
bzip2 = { workspace = true }
8382

8483
# tkinter
8584
jiff = { workspace = true }

0 commit comments

Comments
 (0)