1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
use super::*;
use crate::dictionary::PreparedDictionary;
use crate::{Operation, StreamConfig};
use alloc::boxed::Box;
use std::io::{self, Write};
/// Container writer owning its sink and borrowing one reusable framed encoder.
#[derive(Debug)]
pub struct FramedWriter<'c, W> {
session: FramedEncoderSession<'c>,
transport: Transport<W>,
}
/// Fixed inline transport storage; no framing allocation is moved outside its budget.
#[derive(Debug)]
struct Transport<W> {
sink: W,
bytes: [u8; 8192],
cursor: usize,
length: usize,
deferred: Option<FramedEncodeError>,
}
impl<W: Write> Transport<W> {
fn drain(&mut self) -> Result<(), FramedEncodeError> {
while self.cursor < self.length {
match self.sink.write(&self.bytes[self.cursor..self.length]) {
Ok(0) => return Err(io::Error::from(io::ErrorKind::WriteZero).into()),
Ok(n) if n <= self.length - self.cursor => self.cursor += n,
Ok(_) => return Err(io::Error::other("sink reported an oversized write").into()),
Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
Err(e) => return Err(e.into()),
}
}
self.cursor = 0;
self.length = 0;
if let Some(e) = self.deferred.take() {
return Err(e);
}
Ok(())
}
}
impl FramedCompressor {
/// Starts a container writer without I/O, using this owner's framing policy.
/// # Errors
/// Rejects forgotten sessions or header allocation failure.
/// # Examples
/// ```
/// use mbrotli::framing::*;
/// use std::io::Write;
/// let mut owner = FramedCompressor::new(Default::default())?;
/// let mut writer = owner.framed_writer(Vec::new(), Default::default())?;
/// let mut resource = writer.resource(Default::default(), Default::default())?;
/// resource.write_all(b"streaming payload")?;
/// resource.try_finish()?;
/// drop(resource);
/// let bytes = writer.finish().map_err(|e| e.error)?;
/// assert_eq!(&bytes[..4], &[0x91, 10, 66, 82]);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn framed_writer<W: Write>(
&mut self,
writer: W,
stream: FramedEncodeStreamConfig,
) -> Result<FramedWriter<'_, W>, FramedEncodeError> {
Ok(FramedWriter {
session: self.start(stream)?,
transport: Transport {
sink: writer,
bytes: [0; 8192],
cursor: 0,
length: 0,
deferred: None,
},
})
}
}
impl<W: Write> FramedWriter<'_, W> {
fn drain(&mut self, operation: FramedEncodeOperation) -> Result<(), FramedEncodeError> {
loop {
self.transport.drain()?;
let p = match self.session.process(&mut self.transport.bytes, operation) {
Ok(p) => p,
Err(e) => {
self.transport.length = e.produced;
self.transport.deferred = Some(e.error);
self.transport.drain()?;
return Err(FramedEncodeError::InvalidState);
}
};
self.transport.length = p.produced;
self.transport.drain()?;
if p.status != FramedEncoderStatus::NeedsOutput {
return Ok(());
}
}
}
/// Starts a compressed payload resource after draining earlier output.
/// # Errors
/// Reports transport failure, invalid settings/order or exhausted budgets.
pub fn resource(
&mut self,
options: ResourceOptions,
stream: StreamConfig,
) -> Result<ResourceWriter<'_, 'static, W>, FramedEncodeError> {
self.drain(FramedEncodeOperation::Process)?;
Ok(ResourceWriter {
session: self.session.resource(options, stream)?,
transport: &mut self.transport,
})
}
/// Starts a resource with a borrowed dictionary and explicit wire references.
/// # Errors
/// As `resource`, plus invalid references or unsupported dictionary settings.
pub fn resource_with_dictionary<'s, 'dict>(
&'s mut self,
options: ResourceOptions,
stream: StreamConfig,
dictionary: &'dict PreparedDictionary,
references: &[DictionaryReference],
) -> Result<ResourceWriter<'s, 'dict, W>, FramedEncodeError> {
self.drain(FramedEncodeOperation::Process)?;
Ok(ResourceWriter {
session: self
.session
.resource_with_dictionary(options, stream, dictionary, references)?,
transport: &mut self.transport,
})
}
/// Starts a verbatim payload resource after draining earlier output.
/// # Errors
/// Reports transport failure, invalid ordering or exhausted budgets.
pub fn uncompressed_resource(
&mut self,
options: ResourceOptions,
) -> Result<ResourceWriter<'_, 'static, W>, FramedEncodeError> {
self.drain(FramedEncodeOperation::Process)?;
Ok(ResourceWriter {
session: self.session.uncompressed_resource(options)?,
transport: &mut self.transport,
})
}
/// Queues uncompressed metadata after delivering earlier output.
/// # Errors
/// Reports transport, ordering, field validation or budget errors.
pub fn metadata(
&mut self,
kind: MetadataKind,
fields: &[MetadataField<'_>],
) -> Result<(), FramedEncodeError> {
self.metadata_with_options(kind, fields, Default::default())
}
/// Queues metadata with independent original and repeated encodings.
/// # Errors
/// Invalid commands remain uncommitted; earlier pending output can be retried.
pub fn metadata_with_options(
&mut self,
kind: MetadataKind,
fields: &[MetadataField<'_>],
options: MetadataOptions<'_>,
) -> Result<(), FramedEncodeError> {
self.drain(FramedEncodeOperation::Process)?;
self.session.metadata_with_options(kind, fields, options)
}
/// Selects repeated fields before the first metadata command.
/// # Errors
/// Reports invalid codes/order, disabled repetition, transport or budget errors.
pub fn repeat_metadata_fields(&mut self, codes: &[[u8; 2]]) -> Result<(), FramedEncodeError> {
self.drain(FramedEncodeOperation::Process)?;
self.session.repeat_metadata_fields(codes)
}
/// Queues a padding chunk after delivering previous output.
/// # Errors
/// Reports ordering, budget or transport errors.
pub fn padding(&mut self, bytes: usize) -> Result<(), FramedEncodeError> {
self.drain(FramedEncodeOperation::Process)?;
self.session.padding(bytes)
}
/// Delivers pending container bytes and flushes the sink.
/// # Errors
/// Retains the cursor on transport errors so callers can repair and retry.
pub fn flush(&mut self) -> Result<(), FramedEncodeError> {
self.drain(FramedEncodeOperation::Process)?;
self.transport.sink.flush()?;
Ok(())
}
/// Generates the suffix once, delivers it, and flushes the sink.
/// # Errors
/// Transport failures preserve all progress for retry; codec errors are terminal.
pub fn try_finish(&mut self) -> Result<(), FramedEncodeError> {
self.drain(FramedEncodeOperation::Finish)?;
self.transport.sink.flush()?;
Ok(())
}
/// Finalizes and returns the sink, retaining the whole writer on failure.
/// # Errors
/// As `try_finish`; recover the writer from the owning error to retry.
pub fn finish(mut self) -> Result<W, Box<FramingFinishError<Self>>> {
match self.try_finish() {
Ok(()) => Ok(self.transport.sink),
Err(error) => Err(Box::new(FramingFinishError {
writer: self,
error,
})),
}
}
/// Borrows the sink for inspection.
pub const fn get_ref(&self) -> &W {
&self.transport.sink
}
/// Repairs the sink. Inserting/removing bytes through this borrow invalidates offsets.
pub fn get_mut(&mut self) -> &mut W {
&mut self.transport.sink
}
/// Container-relative queued offset for subsequent internal references.
pub const fn next_chunk_offset(&self) -> u64 {
self.session.next_chunk_offset()
}
/// Cancels without I/O and returns the sink; this does not finalize output.
pub fn into_inner(self) -> W {
self.transport.sink
}
}
/// Borrowing Write adapter for one resource. Drop never writes or finalizes.
#[derive(Debug)]
pub struct ResourceWriter<'s, 'dict, W> {
session: FramedResourceSession<'s, 'dict>,
transport: &'s mut Transport<W>,
}
impl<W: Write> ResourceWriter<'_, '_, W> {
fn complete(&mut self, operation: Operation) -> Result<(), FramedEncodeError> {
loop {
self.transport.drain()?;
let p = match self
.session
.process(&[], &mut self.transport.bytes, operation)
{
Ok(p) => p,
Err(e) => {
self.transport.length = e.produced;
self.transport.deferred = Some(e.error);
self.transport.drain()?;
return Err(FramedEncodeError::InvalidState);
}
};
self.transport.length = p.produced;
self.transport.drain()?;
if p.status != FramedEncoderStatus::NeedsOutput {
return Ok(());
}
}
}
/// Completes and delivers the resource, retrying transport without re-encoding.
/// # Errors
/// Codec failures are terminal; sink errors preserve the unwritten suffix.
pub fn try_finish(&mut self) -> Result<(), FramedEncodeError> {
self.complete(Operation::Finish)
}
/// Repairs the sink; writing container bytes through this borrow is forbidden.
pub fn get_mut(&mut self) -> &mut W {
&mut self.transport.sink
}
}
impl<W: Write> Write for ResourceWriter<'_, '_, W> {
fn write(&mut self, input: &[u8]) -> io::Result<usize> {
if input.is_empty() {
return Ok(0);
}
self.transport.drain().map_err(io::Error::from)?;
if self.session.is_finished() {
return Err(FramedEncodeError::InvalidState.into());
}
loop {
match self
.session
.process(input, &mut self.transport.bytes, Operation::Process)
{
Ok(p) => {
self.transport.length = p.produced;
if p.consumed != 0 {
return Ok(p.consumed);
}
self.transport.drain().map_err(io::Error::from)?;
}
Err(e) => {
self.transport.length = e.produced;
if e.consumed != 0 {
self.transport.deferred = Some(e.error);
return Ok(e.consumed);
}
return Err(e.error.into());
}
}
}
}
fn flush(&mut self) -> io::Result<()> {
self.complete(Operation::Flush).map_err(io::Error::from)?;
self.transport.sink.flush()
}
}