compression_codecs/bzip2/encoder.rs
1use crate::{bzip2::params::Bzip2EncoderParams, EncodeV2};
2use bzip2::{Action, Compress, Compression, Status};
3use compression_core::util::{PartialBuffer, WriteBuffer};
4use std::{fmt, io};
5
6pub struct BzEncoder {
7 compress: Compress,
8}
9
10impl fmt::Debug for BzEncoder {
11 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
12 write!(
13 f,
14 "BzEncoder {{total_in: {}, total_out: {}}}",
15 self.compress.total_in(),
16 self.compress.total_out()
17 )
18 }
19}
20
21impl BzEncoder {
22 /// Creates a new stream prepared for compression.
23 ///
24 /// The `work_factor` parameter controls how the compression phase behaves
25 /// when presented with worst case, highly repetitive, input data. If
26 /// compression runs into difficulties caused by repetitive data, the
27 /// library switches from the standard sorting algorithm to a fallback
28 /// algorithm. The fallback is slower than the standard algorithm by perhaps
29 /// a factor of three, but always behaves reasonably, no matter how bad the
30 /// input.
31 ///
32 /// Lower values of `work_factor` reduce the amount of effort the standard
33 /// algorithm will expend before resorting to the fallback. You should set
34 /// this parameter carefully; too low, and many inputs will be handled by
35 /// the fallback algorithm and so compress rather slowly, too high, and your
36 /// average-to-worst case compression times can become very large. The
37 /// default value of 30 gives reasonable behaviour over a wide range of
38 /// circumstances.
39 ///
40 /// Allowable values range from 0 to 250 inclusive. 0 is a special case,
41 /// equivalent to using the default value of 30.
42 pub fn new(params: Bzip2EncoderParams, work_factor: u32) -> Self {
43 let params = Compression::from(params);
44 Self {
45 compress: Compress::new(params, work_factor),
46 }
47 }
48
49 fn encode(
50 &mut self,
51 input: &mut PartialBuffer<&[u8]>,
52 output: &mut WriteBuffer<'_>,
53 action: Action,
54 ) -> io::Result<Status> {
55 let prior_in = self.compress.total_in();
56 let prior_out = self.compress.total_out();
57
58 let result = self
59 .compress
60 // Safety: We **trust** bzip2 to only write initialized bytes into it
61 .compress_uninit(input.unwritten(), unsafe { output.unwritten_mut() }, action)
62 .map_err(io::Error::other);
63
64 input.advance((self.compress.total_in() - prior_in) as usize);
65 // Safety: We **trust** bzip2 to properly write bytes into it
66 unsafe { output.assume_init_and_advance((self.compress.total_out() - prior_out) as usize) };
67
68 result
69 }
70}
71
72impl EncodeV2 for BzEncoder {
73 fn encode(
74 &mut self,
75 input: &mut PartialBuffer<&[u8]>,
76 output: &mut WriteBuffer<'_>,
77 ) -> io::Result<()> {
78 match self.encode(input, output, Action::Run)? {
79 // Decompression went fine, nothing much to report.
80 Status::Ok => Ok(()),
81
82 // The Flush action on a compression went ok.
83 Status::FlushOk => unreachable!(),
84
85 // The Run action on compression went ok.
86 Status::RunOk => Ok(()),
87
88 // The Finish action on compression went ok.
89 Status::FinishOk => unreachable!(),
90
91 // The stream's end has been met, meaning that no more data can be input.
92 Status::StreamEnd => unreachable!(),
93
94 // There was insufficient memory in the input or output buffer to complete
95 // the request, but otherwise everything went normally.
96 Status::MemNeeded => Err(io::ErrorKind::OutOfMemory.into()),
97 }
98 }
99
100 fn flush(&mut self, output: &mut WriteBuffer<'_>) -> io::Result<bool> {
101 match self.encode(&mut PartialBuffer::new(&[][..]), output, Action::Flush)? {
102 // Decompression went fine, nothing much to report.
103 Status::Ok => unreachable!(),
104
105 // The Flush action on a compression went ok.
106 Status::FlushOk => Ok(false),
107
108 // The Run action on compression went ok.
109 Status::RunOk => Ok(true),
110
111 // The Finish action on compression went ok.
112 Status::FinishOk => unreachable!(),
113
114 // The stream's end has been met, meaning that no more data can be input.
115 Status::StreamEnd => unreachable!(),
116
117 // There was insufficient memory in the input or output buffer to complete
118 // the request, but otherwise everything went normally.
119 Status::MemNeeded => Err(io::ErrorKind::OutOfMemory.into()),
120 }
121 }
122
123 fn finish(&mut self, output: &mut WriteBuffer<'_>) -> io::Result<bool> {
124 match self.encode(&mut PartialBuffer::new(&[][..]), output, Action::Finish)? {
125 // Decompression went fine, nothing much to report.
126 Status::Ok => Ok(false),
127
128 // The Flush action on a compression went ok.
129 Status::FlushOk => unreachable!(),
130
131 // The Run action on compression went ok.
132 Status::RunOk => unreachable!(),
133
134 // The Finish action on compression went ok.
135 Status::FinishOk => Ok(false),
136
137 // The stream's end has been met, meaning that no more data can be input.
138 Status::StreamEnd => Ok(true),
139
140 // There was insufficient memory in the input or output buffer to complete
141 // the request, but otherwise everything went normally.
142 Status::MemNeeded => Err(io::ErrorKind::OutOfMemory.into()),
143 }
144 }
145}