zstd/stream/write/mod.rs
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 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
//! Implement push-based [`Write`] trait for both compressing and decompressing.
use std::io::{self, Write};
use zstd_safe;
use crate::dict::{DecoderDictionary, EncoderDictionary};
use crate::stream::{raw, zio};
#[cfg(test)]
mod tests;
/// An encoder that compress and forward data to another writer.
///
/// This allows to compress a stream of data
/// (good for files or heavy network stream).
///
/// Don't forget to call [`finish()`] before dropping it!
///
/// Alternatively, you can call [`auto_finish()`] to use an
/// [`AutoFinishEncoder`] that will finish on drop.
///
/// Note: The zstd library has its own internal input buffer (~128kb).
///
/// [`finish()`]: #method.finish
/// [`auto_finish()`]: #method.auto_finish
/// [`AutoFinishEncoder`]: AutoFinishEncoder
pub struct Encoder<'a, W: Write> {
// output writer (compressed data)
writer: zio::Writer<W, raw::Encoder<'a>>,
}
/// A decoder that decompress and forward data to another writer.
///
/// Note that you probably want to `flush()` after writing your stream content.
/// You can use [`auto_flush()`] to automatically flush the writer on drop.
///
/// [`auto_flush()`]: Decoder::auto_flush
pub struct Decoder<'a, W: Write> {
// output writer (decompressed data)
writer: zio::Writer<W, raw::Decoder<'a>>,
}
/// A wrapper around an `Encoder<W>` that finishes the stream on drop.
///
/// This can be created by the [`auto_finish()`] method on the [`Encoder`].
///
/// [`auto_finish()`]: Encoder::auto_finish
/// [`Encoder`]: Encoder
pub struct AutoFinishEncoder<
'a,
W: Write,
F: FnMut(io::Result<W>) = Box<dyn Send + FnMut(io::Result<W>)>,
> {
// We wrap this in an option to take it during drop.
encoder: Option<Encoder<'a, W>>,
on_finish: Option<F>,
}
/// A wrapper around a `Decoder<W>` that flushes the stream on drop.
///
/// This can be created by the [`auto_flush()`] method on the [`Decoder`].
///
/// [`auto_flush()`]: Decoder::auto_flush
/// [`Decoder`]: Decoder
pub struct AutoFlushDecoder<
'a,
W: Write,
F: FnMut(io::Result<()>) = Box<dyn Send + FnMut(io::Result<()>)>,
> {
// We wrap this in an option to take it during drop.
decoder: Option<Decoder<'a, W>>,
on_flush: Option<F>,
}
impl<'a, W: Write, F: FnMut(io::Result<()>)> AutoFlushDecoder<'a, W, F> {
fn new(decoder: Decoder<'a, W>, on_flush: F) -> Self {
AutoFlushDecoder {
decoder: Some(decoder),
on_flush: Some(on_flush),
}
}
/// Acquires a reference to the underlying writer.
pub fn get_ref(&self) -> &W {
self.decoder.as_ref().unwrap().get_ref()
}
/// Acquires a mutable reference to the underlying writer.
///
/// Note that mutation of the writer may result in surprising results if
/// this decoder is continued to be used.
///
/// Mostly used for testing purposes.
pub fn get_mut(&mut self) -> &mut W {
self.decoder.as_mut().unwrap().get_mut()
}
}
impl<W, F> Drop for AutoFlushDecoder<'_, W, F>
where
W: Write,
F: FnMut(io::Result<()>),
{
fn drop(&mut self) {
let mut decoder = self.decoder.take().unwrap();
let result = decoder.flush();
if let Some(mut on_finish) = self.on_flush.take() {
on_finish(result);
}
}
}
impl<W: Write, F: FnMut(io::Result<()>)> Write for AutoFlushDecoder<'_, W, F> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.decoder.as_mut().unwrap().write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.decoder.as_mut().unwrap().flush()
}
}
impl<'a, W: Write, F: FnMut(io::Result<W>)> AutoFinishEncoder<'a, W, F> {
fn new(encoder: Encoder<'a, W>, on_finish: F) -> Self {
AutoFinishEncoder {
encoder: Some(encoder),
on_finish: Some(on_finish),
}
}
/// Acquires a reference to the underlying writer.
pub fn get_ref(&self) -> &W {
self.encoder.as_ref().unwrap().get_ref()
}
/// Acquires a mutable reference to the underlying writer.
///
/// Note that mutation of the writer may result in surprising results if
/// this encoder is continued to be used.
///
/// Mostly used for testing purposes.
pub fn get_mut(&mut self) -> &mut W {
self.encoder.as_mut().unwrap().get_mut()
}
}
impl<W: Write, F: FnMut(io::Result<W>)> Drop for AutoFinishEncoder<'_, W, F> {
fn drop(&mut self) {
let result = self.encoder.take().unwrap().finish();
if let Some(mut on_finish) = self.on_finish.take() {
on_finish(result);
}
}
}
impl<W: Write, F: FnMut(io::Result<W>)> Write for AutoFinishEncoder<'_, W, F> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.encoder.as_mut().unwrap().write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.encoder.as_mut().unwrap().flush()
}
}
impl<W: Write> Encoder<'static, W> {
/// Creates a new encoder.
///
/// `level`: compression level (1-22).
///
/// A level of `0` uses zstd's default (currently `3`).
pub fn new(writer: W, level: i32) -> io::Result<Self> {
Self::with_dictionary(writer, level, &[])
}
/// Creates a new encoder, using an existing dictionary.
///
/// (Provides better compression ratio for small files,
/// but requires the dictionary to be present during decompression.)
///
/// A level of `0` uses zstd's default (currently `3`).
pub fn with_dictionary(
writer: W,
level: i32,
dictionary: &[u8],
) -> io::Result<Self> {
let encoder = raw::Encoder::with_dictionary(level, dictionary)?;
let writer = zio::Writer::new(writer, encoder);
Ok(Encoder { writer })
}
}
impl<'a, W: Write> Encoder<'a, W> {
/// Creates an encoder that uses the provided context to compress a stream.
pub fn with_context(
writer: W,
context: &'a mut zstd_safe::CCtx<'static>,
) -> Self {
Self {
writer: zio::Writer::new(
writer,
raw::Encoder::with_context(context),
),
}
}
/// Creates a new encoder, using an existing prepared `EncoderDictionary`.
///
/// (Provides better compression ratio for small files,
/// but requires the dictionary to be present during decompression.)
pub fn with_prepared_dictionary<'b>(
writer: W,
dictionary: &EncoderDictionary<'b>,
) -> io::Result<Self>
where
'b: 'a,
{
let encoder = raw::Encoder::with_prepared_dictionary(dictionary)?;
let writer = zio::Writer::new(writer, encoder);
Ok(Encoder { writer })
}
/// Creates a new encoder, using a ref prefix
pub fn with_ref_prefix<'b>(
writer: W,
level: i32,
ref_prefix: &'b [u8],
) -> io::Result<Self>
where
'b: 'a,
{
let encoder = raw::Encoder::with_ref_prefix(level, ref_prefix)?;
let writer = zio::Writer::new(writer, encoder);
Ok(Encoder { writer })
}
/// Returns a wrapper around `self` that will finish the stream on drop.
pub fn auto_finish(self) -> AutoFinishEncoder<'a, W> {
AutoFinishEncoder {
encoder: Some(self),
on_finish: None,
}
}
/// Returns an encoder that will finish the stream on drop.
///
/// Calls the given callback with the result from `finish()`. This runs during drop so it's
/// important that the provided callback doesn't panic.
pub fn on_finish<F: FnMut(io::Result<W>)>(
self,
f: F,
) -> AutoFinishEncoder<'a, W, F> {
AutoFinishEncoder::new(self, f)
}
/// Acquires a reference to the underlying writer.
pub fn get_ref(&self) -> &W {
self.writer.writer()
}
/// Acquires a mutable reference to the underlying writer.
///
/// Note that mutation of the writer may result in surprising results if
/// this encoder is continued to be used.
pub fn get_mut(&mut self) -> &mut W {
self.writer.writer_mut()
}
/// **Required**: Finishes the stream.
///
/// You *need* to finish the stream when you're done writing, either with
/// this method or with [`try_finish(self)`](#method.try_finish).
///
/// This returns the inner writer in case you need it.
///
/// To get back `self` in case an error happened, use `try_finish`.
///
/// **Note**: If you don't want (or can't) call `finish()` manually after
/// writing your data, consider using `auto_finish()` to get an
/// `AutoFinishEncoder`.
pub fn finish(self) -> io::Result<W> {
self.try_finish().map_err(|(_, err)| err)
}
/// **Required**: Attempts to finish the stream.
///
/// You *need* to finish the stream when you're done writing, either with
/// this method or with [`finish(self)`](#method.finish).
///
/// This returns the inner writer if the finish was successful, or the
/// object plus an error if it wasn't.
///
/// `write` on this object will panic after `try_finish` has been called,
/// even if it fails.
pub fn try_finish(mut self) -> Result<W, (Self, io::Error)> {
match self.writer.finish() {
// Return the writer, because why not
Ok(()) => Ok(self.writer.into_inner().0),
Err(e) => Err((self, e)),
}
}
/// Attempts to finish the stream.
///
/// You *need* to finish the stream when you're done writing, either with
/// this method or with [`finish(self)`](#method.finish).
pub fn do_finish(&mut self) -> io::Result<()> {
self.writer.finish()
}
/// Return a recommendation for the size of data to write at once.
pub fn recommended_input_size() -> usize {
zstd_safe::CCtx::in_size()
}
crate::encoder_common!(writer);
}
impl<'a, W: Write> Write for Encoder<'a, W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.writer.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.writer.flush()
}
}
impl<W: Write> Decoder<'static, W> {
/// Creates a new decoder.
pub fn new(writer: W) -> io::Result<Self> {
Self::with_dictionary(writer, &[])
}
/// Creates a new decoder, using an existing dictionary.
///
/// (Provides better compression ratio for small files,
/// but requires the dictionary to be present during decompression.)
pub fn with_dictionary(writer: W, dictionary: &[u8]) -> io::Result<Self> {
let decoder = raw::Decoder::with_dictionary(dictionary)?;
let writer = zio::Writer::new(writer, decoder);
Ok(Decoder { writer })
}
}
impl<'a, W: Write> Decoder<'a, W> {
/// Creates a new decoder, using an existing prepared `DecoderDictionary`.
///
/// (Provides better compression ratio for small files,
/// but requires the dictionary to be present during decompression.)
pub fn with_prepared_dictionary<'b>(
writer: W,
dictionary: &DecoderDictionary<'b>,
) -> io::Result<Self>
where
'b: 'a,
{
let decoder = raw::Decoder::with_prepared_dictionary(dictionary)?;
let writer = zio::Writer::new(writer, decoder);
Ok(Decoder { writer })
}
/// Acquires a reference to the underlying writer.
pub fn get_ref(&self) -> &W {
self.writer.writer()
}
/// Acquires a mutable reference to the underlying writer.
///
/// Note that mutation of the writer may result in surprising results if
/// this decoder is continued to be used.
pub fn get_mut(&mut self) -> &mut W {
self.writer.writer_mut()
}
/// Returns the inner `Write`.
pub fn into_inner(self) -> W {
self.writer.into_inner().0
}
/// Return a recommendation for the size of data to write at once.
pub fn recommended_input_size() -> usize {
zstd_safe::DCtx::in_size()
}
/// Returns a wrapper around `self` that will flush the stream on drop.
pub fn auto_flush(self) -> AutoFlushDecoder<'a, W> {
AutoFlushDecoder {
decoder: Some(self),
on_flush: None,
}
}
/// Returns a decoder that will flush the stream on drop.
///
/// Calls the given callback with the result from `flush()`. This runs during drop so it's
/// important that the provided callback doesn't panic.
pub fn on_flush<F: FnMut(io::Result<()>)>(
self,
f: F,
) -> AutoFlushDecoder<'a, W, F> {
AutoFlushDecoder::new(self, f)
}
crate::decoder_common!(writer);
}
impl<W: Write> Write for Decoder<'_, W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.writer.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.writer.flush()
}
}
fn _assert_traits() {
fn _assert_send<T: Send>(_: T) {}
_assert_send(Decoder::new(Vec::new()));
_assert_send(Encoder::new(Vec::new(), 1));
_assert_send(Decoder::new(Vec::new()).unwrap().auto_flush());
_assert_send(Encoder::new(Vec::new(), 1).unwrap().auto_finish());
}