brotlic 0.2.1

Bindings to the brotli library featuring a low-overhead encoder and decoder, `Write`rs and `Read`ers for compression and decompression at customizable compression qualities and window sizes.
Documentation
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
//! # Brotlic
//!
//! Brotlic (or BrotlyC) is a thin wrapper around [brotli](https://github.com/google/brotli). It
//! provides Rust bindings to all compression and decompression APIs. On the fly compression and
//! decompression is supported for both `BufRead` and `Write` via [`CompressorReader<R>`,
//! `CompressorWriter<W>`, `DecompressorReader<R>` and `DecompressorWriter<W>`. For low-level
//! instances, see `BrotliEncoder` and `BrotliDecoder`. These can be configured via
//! `BrotliEncoderOptions` and `BrotliDecoderOptions` respectively.
//!
//! ## High level abstractions
//!
//! When dealing with [`BufRead`]:
//!
//! * [`DecompressorReader<R>`] - Reads a brotli compressed input stream and decompresses it.
//! * [`CompressorReader<R>`] - Reads a stream and compresses it while reading.
//!
//! When dealing with [`Write`]:
//!
//! * [`CompressorWriter<W>`] - Writes brotli compressed data to the underlying writer.
//! * [`DecompressorWriter<W>`] - Writes brotli decompressed data to the underlying writer.
//!
//! To simplify this decision, the following table outlines all the differences:
//!
//! |                           | Input        | Output       | Wraps       |
//! |---------------------------|--------------|--------------|-------------|
//! | [`CompressorReader<R>`]   | Uncompressed | Compressed   | [`BufRead`] |
//! | [`DecompressorReader<R>`] | Compressed   | Uncompressed | [`BufRead`] |
//! | [`CompressorWriter<W>`]   | Uncompressed | Compressed   | [`Write`]   |
//! | [`DecompressorWriter<W>`] | Compressed   | Uncompressed | [`Write`]   |
//!
//! [`BufRead`]: https://doc.rust-lang.org/std/io/trait.BufRead.html
//! [`Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
//!
//! To compress a file with brotli:
//!
//! ```no_run
//! use std::fs::File;
//! use std::io::{self, Write};
//! use brotlic::CompressorWriter;
//!
//! let mut input = File::open("test.txt")?; // uncompressed text file
//! let mut output = File::create("test.brotli")?; // compressed text output file
//! let mut output_compressed = CompressorWriter::new(output);
//!
//! output_compressed.write_all(b"test")?;
//!
//! # Ok::<(), io::Error>(())
//! ```
//!
//! To decompress that same file:
//!
//! ```no_run
//! use std::fs::File;
//! use std::io::{self, BufReader, Read};
//! use brotlic::DecompressorReader;
//!
//! let mut input = BufReader::new(File::open("test.brotli")?); // uncompressed text file
//! let mut input_decompressed = DecompressorReader::new(input); // requires BufRead
//!
//! let mut text = String::new();
//! input_decompressed.read_to_string(&mut text)?;
//!
//! assert_eq!(text, "test");
//!
//! # Ok::<(), io::Error>(())
//! ```
//!
//! To compress and decompress in memory:
//!
//! ```
//! use std::io::{self, Read, Write};
//! use brotlic::{CompressorWriter, DecompressorReader};
//!
//! let input = vec![0; 1024];
//!
//! // create a wrapper around Write that supports on the fly brotli compression.
//! let mut compressor = CompressorWriter::new(Vec::new()); // Vec implements Write
//! compressor.write_all(input.as_slice());
//! let compressed_input = compressor.into_inner()?; // read to vec
//!
//! // create a wrapper around BufRead that supports on the fly brotli decompression.
//! let mut decompressor = DecompressorReader::new(compressed_input.as_slice()); // slice is BufRead
//! let mut decompressed_input = Vec::new();
//!
//! decompressor.read_to_end(&mut decompressed_input)?;
//!
//! assert_eq!(input, decompressed_input);
//!
//! # Ok::<(), io::Error>(())
//! ```
//!
//! ## Customizing compression quality
//!
//! Sometimes it can be desirable to trade run-time costs for an even better compression ratio:
//!
//! ```
//! use brotlic::{BlockSize, BrotliEncoderOptions, CompressorWriter, Quality, WindowSize};
//! # use brotlic::ParameterError;
//!
//! let encoder = BrotliEncoderOptions::new()
//!     .quality(Quality::best())
//!     .window_size(WindowSize::best())
//!     .block_size(BlockSize::best())
//!     .build()?;
//!
//! let compressed_writer = CompressorWriter::with_encoder(encoder, Vec::new());
//!
//! # Ok::<(), ParameterError>(())
//! ```
//!
//! It is recommended to not use the encoder directly but instead pass it onto the higher level
//! abstractions like `CompressorWriter<W>` or `DecompressorReader<R>`.

#![warn(missing_docs)]

pub mod decode;
pub mod encode;

pub use encode::BrotliEncoder;
pub use encode::BrotliEncoderOptions;
pub use encode::CompressorWriter;
pub use encode::CompressorReader;

pub use decode::BrotliDecoder;
pub use decode::BrotliDecoderOptions;
pub use decode::DecompressorReader;
pub use decode::DecompressorWriter;

use brotlic_sys::*;
use std::os::raw::c_int;
use std::{error, fmt, io};

/// Quality level of the brotli compression
///
/// [`Quality::best()`] represents the best available quality that maximizes the compression ratio
/// at the cost of run-time speed. [`Quality::worst()`] represents the worst available quality that
/// maximizes speed at the expense of compression ratio.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct Quality(u8);

impl Quality {
    /// Attempts to create a new brotli compression quality.
    ///
    /// The range of valid qualities is from 0 to 11 inclusive, where 0 is the worst possible
    /// quality and 11 is the best possible quality.
    ///
    /// # Errors
    ///
    /// An [`Err`] will be returned if the `value` is out of the range of valid qualities.
    ///
    /// # Examples
    ///
    /// ```
    /// use brotlic::Quality;
    ///
    /// let worst_quality = Quality::new(0).unwrap();
    /// let best_quality = Quality::new(11).unwrap();
    ///
    /// assert_eq!(worst_quality, Quality::worst());
    /// assert_eq!(best_quality, Quality::best());
    /// ```
    pub fn new(value: u8) -> Result<Quality, QualityError> {
        match value {
            BROTLI_MIN_QUALITY..=BROTLI_MAX_QUALITY => Ok(Quality(value)),
            _ => Err(QualityError),
        }
    }

    /// The highest quality for brotli compression.
    ///
    /// This quality yields maximum compression ratio at the expense of run-time speed.
    pub fn best() -> Quality {
        Quality(BROTLI_MAX_QUALITY)
    }

    /// The default quality to use for brotli compression.
    ///
    /// This is current set to the best possible quality.
    pub fn default() -> Quality {
        Quality(BROTLI_DEFAULT_QUALITY)
    }

    /// The worst quality to use for brotli compression.
    ///
    /// This quality yields the worst compression ratio while offering the highest run-time speed.
    pub fn worst() -> Quality {
        Quality(BROTLI_MIN_QUALITY)
    }
}

impl Default for Quality {
    /// Creates a new `Quality` using [`default`].
    /// See its documentation for more.
    ///
    /// [`default`]: Quality::default
    fn default() -> Self {
        Quality::default()
    }
}

/// An error returned by [`Quality::new`].
#[derive(Debug)]
pub struct QualityError;

impl fmt::Display for QualityError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "quality out of range (must be between {} and {} inclusive)",
            BROTLI_MIN_QUALITY, BROTLI_MAX_QUALITY
        )
    }
}

impl error::Error for QualityError {}

/// The sliding window size (in bits) to use for compression.
///
/// Its maximum size is currently limited to 16 MiB, as specified in RFC7932 (Brotli proper).
/// Larger window sizes are supported via [`LargeWindowSize`], however note that decompression
/// support for these have to be explicitly enabled. This can be configured via
/// [`non_std_window_size_support`] for the matching [`BrotliDecoder`].
///
/// [`non_std_window_size_support`]: decode::BrotliDecoderOptions::non_std_window_size_support()
/// [`BrotliDecoder`]: decode::BrotliDecoder
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct WindowSize(u8);

impl WindowSize {
    /// Consturcts a new sliding window size to use for brotli compression.
    ///
    /// Valid `bits` range from 10 (1 KiB) to 24 (16 MiB) inclusive.
    ///
    /// # Errors
    ///
    /// An [`Err`] will be returned if the `bits` are out of the range of valid window sizes.
    ///
    /// # Examples
    ///
    /// ```
    /// use brotlic::WindowSize;
    ///
    /// let worst_size = WindowSize::new(10).unwrap();
    /// let best_size = WindowSize::new(24).unwrap();
    ///
    /// assert_eq!(worst_size, WindowSize::worst());
    /// assert_eq!(best_size, WindowSize::best());
    /// ```
    pub fn new(bits: u8) -> Result<WindowSize, WindowSizeError> {
        match bits {
            BROTLI_MIN_WINDOW_BITS..=BROTLI_MAX_WINDOW_BITS => Ok(WindowSize(bits)),
            _ => Err(WindowSizeError),
        }
    }

    /// Constructs the best sliding window size to use for brotli compression.
    ///
    /// This is currently limited to 24 bits (16 MiB) due to RFC7932 (Brotli proper). To use larger
    /// sliding window sizes, please refer to [`LargeWindowSize`]. Note however that explicit
    /// support has to be enabled by the decoder. This is supported by enabling
    /// [`non_std_window_size_support`] when constructing a [`BrotliDecoder`].
    ///
    /// [`non_std_window_size_support`]: decode::BrotliDecoderOptions::non_std_window_size_support()
    /// [`BrotliDecoder`]: decode::BrotliDecoder
    ///
    /// # Examples
    ///
    /// ```
    /// use brotlic::WindowSize;
    ///
    /// let best_size = WindowSize::new(24).unwrap();
    ///
    /// assert_eq!(best_size, WindowSize::best());
    /// ```
    pub fn best() -> WindowSize {
        WindowSize(BROTLI_MAX_WINDOW_BITS)
    }

    /// Constructs the default sliding window size to use for brotli compression.
    ///
    /// This is currently set to 22 bits (4 MiB).
    ///
    /// # Examples
    ///
    /// ```
    /// use brotlic::WindowSize;
    ///
    /// let default_size = WindowSize::new(22).unwrap();
    ///
    /// assert_eq!(default_size, WindowSize::default());
    /// ```
    pub fn default() -> WindowSize {
        WindowSize(BROTLI_DEFAULT_WINDOW)
    }

    /// Constructs the worst sliding window size to use for brotli compression
    ///
    /// This is currently set to 10 bits (1 KiB).
    ///
    /// # Examples
    ///
    /// ```
    /// use brotlic::WindowSize;
    ///
    /// let worst_size = WindowSize::new(10).unwrap();
    ///
    /// assert_eq!(worst_size, WindowSize::worst());
    /// ```
    pub fn worst() -> WindowSize {
        WindowSize(BROTLI_MIN_WINDOW_BITS)
    }
}

impl Default for WindowSize {
    /// Creates a new `WindowSize` using [`default`].
    /// See its documentation for more.
    ///
    /// [`default`]: WindowSize::default()
    fn default() -> Self {
        WindowSize::default()
    }
}

impl TryFrom<LargeWindowSize> for WindowSize {
    type Error = WindowSizeError;

    /// Attempts to construct a [`WindowSize`] from a [`LargeWindowSize`].
    ///
    /// This only works if the large window size is currently set to a value lower or equal to
    /// [`WindowSize::best()`].
    ///
    /// # Errors
    ///
    /// Large window size does not fit into a window size.
    fn try_from(large_window_size: LargeWindowSize) -> Result<Self, Self::Error> {
        WindowSize::new(large_window_size.0)
    }
}

/// An error returned by [`WindowSize::new`].
#[derive(Debug)]
pub struct WindowSizeError;

impl fmt::Display for WindowSizeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "window size out of range (must be between {} and {} inclusive)",
            BROTLI_MIN_WINDOW_BITS, BROTLI_MAX_WINDOW_BITS
        )
    }
}

impl error::Error for WindowSizeError {}

/// The large sliding window size (in bits) to use for compression.
///
/// Note that using a large sliding window size for a particular compressor requires explicit
/// support by the decompressor. This is supported by enabling [`non_std_window_size_support`] when
/// constructing a [`BrotliDecoder`].
///
/// [`non_std_window_size_support`]: decode::BrotliDecoderOptions::non_std_window_size_support()
/// [`BrotliDecoder`]: decode::BrotliDecoder
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct LargeWindowSize(u8);

impl LargeWindowSize {
    /// Consturcts a new large sliding window size (in bits) to use for brotli compression.
    ///
    /// Valid `bits` range from 10 (1 KiB) to 30 (1 GiB) inclusive.
    ///
    /// # Errors
    ///
    /// An [`Err`] will be returned if the `bits` are out of the range of valid large window sizes.
    ///
    /// # Examples
    ///
    /// ```
    /// use brotlic::LargeWindowSize;
    ///
    /// let worst_size = LargeWindowSize::new(10).unwrap();
    /// let best_size = LargeWindowSize::new(30).unwrap();
    ///
    /// assert_eq!(worst_size, LargeWindowSize::worst());
    /// assert_eq!(best_size, LargeWindowSize::best());
    /// ```
    pub fn new(bits: u8) -> Result<LargeWindowSize, LargeWindowSizeError> {
        match bits {
            BROTLI_MIN_WINDOW_BITS..=BROTLI_LARGE_MAX_WINDOW_BITS => Ok(LargeWindowSize(bits)),
            _ => Err(LargeWindowSizeError),
        }
    }

    /// Constructs the best large sliding window size to use for brotli compression.
    ///
    /// This is currently set to 30 bits (1 GiB). Note that this requires explicit support by the
    /// decompressor. For more information see [`LargeWindowSize`].
    ///
    /// # Examples
    ///
    /// ```
    /// use brotlic::LargeWindowSize;
    ///
    /// let best_size = LargeWindowSize::new(30).unwrap();
    ///
    /// assert_eq!(best_size, LargeWindowSize::best());
    /// ```
    pub fn best() -> LargeWindowSize {
        LargeWindowSize(BROTLI_LARGE_MAX_WINDOW_BITS)
    }

    /// Constructs the default large sliding window size to use for brotli compression.
    ///
    /// This is currently set to 22 bits (4 MiB).
    ///
    /// # Examples
    ///
    /// ```
    /// use brotlic::LargeWindowSize;
    ///
    /// let default_size = LargeWindowSize::new(22).unwrap();
    ///
    /// assert_eq!(default_size, LargeWindowSize::default());
    /// ```
    pub fn default() -> LargeWindowSize {
        LargeWindowSize(BROTLI_DEFAULT_WINDOW)
    }

    /// Constructs the worst large sliding window size to use for brotli compression
    ///
    /// This is currently set to 10 bits (1 KiB).
    ///
    /// # Examples
    ///
    /// ```
    /// use brotlic::LargeWindowSize;
    ///
    /// let worst_size = LargeWindowSize::new(10).unwrap();
    ///
    /// assert_eq!(worst_size, LargeWindowSize::worst());
    /// ```
    pub fn worst() -> LargeWindowSize {
        LargeWindowSize(BROTLI_MIN_WINDOW_BITS)
    }
}

impl Default for LargeWindowSize {
    /// Creates a new `LargeWindowSize` using [`default`].
    /// See its documentation for more.
    ///
    /// [`default`]: LargeWindowSize::default()
    fn default() -> Self {
        LargeWindowSize::default()
    }
}

impl From<WindowSize> for LargeWindowSize {
    /// Constructs a [`LargeWindowSize`] from a [`WindowSize`].
    ///
    /// This always works because a `LargeWindowSize` covers a larger range than the regular
    /// `WindowSize`. The inverse is not true, however.
    fn from(window_size: WindowSize) -> Self {
        LargeWindowSize(window_size.0)
    }
}

/// An error returned by [`LargeWindowSize::new`].
#[derive(Debug)]
pub struct LargeWindowSizeError;

impl fmt::Display for LargeWindowSizeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "large window size out of range (must be between {} and {} inclusive)",
            BROTLI_MIN_WINDOW_BITS, BROTLI_LARGE_MAX_WINDOW_BITS
        )
    }
}

impl error::Error for LargeWindowSizeError {}

/// The recommended input block size (in bits) to use for compression.
///
/// The compressor may reduce this value at its leisure, for example when the input size is small.
/// Larger block sizes allow better compression at the expense of using more memory. Rough formula
/// for memory required is `3 << bits` bytes.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct BlockSize(u8);

impl BlockSize {
    /// Constructs a new block size (in bits) to use for brotli compression.
    ///
    /// Valid `bits` range from 16 to 24 inclusive.
    ///
    /// # Errors
    ///
    /// An [`Err`] will be returned if the `bits` are out of the range of valid block sizes.
    ///
    /// # Examples
    ///
    /// ```
    /// use brotlic::BlockSize;
    ///
    /// let worst_size = BlockSize::new(16).unwrap();
    /// let best_size = BlockSize::new(24).unwrap();
    ///
    /// assert_eq!(worst_size, BlockSize::worst());
    /// assert_eq!(best_size, BlockSize::best());
    /// ```
    pub fn new(bits: u8) -> Result<BlockSize, BlockSizeError> {
        match bits {
            BROTLI_MIN_INPUT_BLOCK_BITS..=BROTLI_MAX_INPUT_BLOCK_BITS => Ok(BlockSize(bits)),
            _ => Err(BlockSizeError),
        }
    }

    /// Constructs the best block size (in bits) to use for brotli compression.
    ///
    /// This will allow better compression at the expense of memory usage. Currently it is set to
    /// 24 bits.
    ///
    /// # Examples
    ///
    /// ```
    /// use brotlic::BlockSize;
    ///
    /// let best_size = BlockSize::new(24).unwrap();
    ///
    /// assert_eq!(best_size, BlockSize::best());
    /// ```
    pub fn best() -> BlockSize {
        BlockSize(BROTLI_MAX_INPUT_BLOCK_BITS)
    }

    /// Constructs the worst block size (in bits) to use for brotli compression.
    ///
    /// This will consume the least amount of memory at the expense of compression ratio. Currently
    /// it is set to 16 bits.
    ///
    /// # Examples
    ///
    /// ```
    /// use brotlic::BlockSize;
    ///
    /// let worst_size = BlockSize::new(16).unwrap();
    ///
    /// assert_eq!(worst_size, BlockSize::worst());
    /// ```
    pub fn worst() -> BlockSize {
        BlockSize(BROTLI_MIN_INPUT_BLOCK_BITS)
    }
}

/// An error returned by [`BlockSize::new`].
#[derive(Debug)]
pub struct BlockSizeError;

impl fmt::Display for BlockSizeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "block size out of range (must be between {} and {} inclusive)",
            BROTLI_MIN_INPUT_BLOCK_BITS, BROTLI_MAX_INPUT_BLOCK_BITS
        )
    }
}

impl error::Error for BlockSizeError {}

/// Allows to tune a brotli compressor for a specific type of input.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum CompressionMode {
    /// No known attributes about the input data.
    Generic = BrotliEncoderMode_BROTLI_MODE_GENERIC as isize,

    /// Tune compression for UTF-8 formatted text input.
    Text = BrotliEncoderMode_BROTLI_MODE_TEXT as isize,

    /// Tune compression for WOFF 2.0 fonts
    Font = BrotliEncoderMode_BROTLI_MODE_FONT as isize,
}

impl Default for CompressionMode {
    /// Creates a `CompressionMode` using [`Generic`].
    /// See its documentation for more.
    ///
    /// [`Generic`]: CompressionMode::Generic
    fn default() -> Self {
        CompressionMode::Generic
    }
}

/// An error returned by [`compress`].
#[derive(Debug)]
pub struct CompressionError;

impl fmt::Display for CompressionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("buffer was too small or compression error occurred")
    }
}

impl error::Error for CompressionError {}

/// a specialized [`Result`] type returned by [`compress`].
pub type CompressionResult<T> = Result<T, CompressionError>;

/// An error returned by [`decompress`].
#[derive(Debug)]
pub struct DecompressionError;

impl fmt::Display for DecompressionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("buffer was too small or decompression error occurred")
    }
}

impl error::Error for DecompressionError {}

/// a specialized [`Result`] type returned by [`decompress`].
pub type DecompressionResult<T> = Result<T, DecompressionError>;

/// An error returned by [`BrotliEncoderOptions::build`] and [`BrotliDecoderOptions::build`]
///
/// [`BrotliEncoderOptions::build`]: encode::BrotliEncoderOptions::build
/// [`BrotliDecoderOptions::build`]: decode::BrotliDecoderOptions::build
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum ParameterError {
    /// The encoder or decoder returned an error.
    ///
    /// This error originates from `BrotliEncoderSetParameter` or `BrotliDecoderSetParameter` being
    /// unsuccessful.
    Generic,

    /// Postfix bits were out of range.
    InvalidPostfix,

    /// Direct distance codes were out of range or were given in invalid increments.
    InvalidDirectDistanceCodes,

    /// The stream offset was beyond its maximum offset.
    InvalidStreamOffset,
}

impl fmt::Display for ParameterError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ParameterError::Generic =>
                f.write_str("invalid parameter"),
            ParameterError::InvalidPostfix =>
                f.write_str("invalid number of postfix bits"),
            ParameterError::InvalidDirectDistanceCodes =>
                f.write_str("invalid number of direct distance codes"),
            ParameterError::InvalidStreamOffset =>
                f.write_str("stream offset was out of range"),
        }
    }
}

impl error::Error for ParameterError {}

/// Read all bytes from `input` and compress them into `output`, returning how many bytes were
/// written.
///
/// The compression will use the specified `quality` (see [`Quality`] for more information),
/// `window_size` (see [`WindowSize`] for more information) and `mode` (see [`CompressionMode`] for
/// more information). The compressed `input` using the specified compression settings must fit into
/// `output`, otherwise an error is returned and the compression will be aborted. To get an upper
/// bound when `quality` is 2 or higher, use [`compress_bound`].
///
/// # Errors
///
/// An [`Err`] will be returned if:
///
/// * `output` is not large enough to contain the compressed data
/// * A generic compression error occurs
/// * memory allocation failed
///
/// # Examples
///
/// ```
/// use brotlic::{compress, CompressionMode, Quality, WindowSize};
///
/// let input = vec![0; 1024];
/// let mut output = vec![0; 1024];
///
/// let bytes_written = compress(
///      input.as_slice(),
///      output.as_mut_slice(),
///      Quality::default(),
///      WindowSize::default(),
///      CompressionMode::Generic
/// ).unwrap();
///
/// assert!(bytes_written < input.len());
/// ```
#[doc(alias = "BrotliEncoderCompress")]
pub fn compress(
    input: &[u8],
    output: &mut [u8],
    quality: Quality,
    window_size: WindowSize,
    mode: CompressionMode,
) -> CompressionResult<usize> {
    let mut output_size = output.len();

    let res = unsafe {
        BrotliEncoderCompress(
            quality.0 as c_int,
            window_size.0 as c_int,
            mode as BrotliEncoderMode,
            input.len(),
            input.as_ptr(),
            &mut output_size as *mut usize,
            output.as_mut_ptr(),
        )
    };

    if res != 0 {
        Ok(output_size)
    } else {
        Err(CompressionError)
    }
}

/// Returns an upper bound for compression.
///
/// Given an input of `input_size` bytes in size and a `quality`, determine an upper bound for
/// compression. This may be larger than `input_size`. The result is only valid for a quality of at
/// least `2`, as per documentation of `BrotliEncoderMaxCompressedSize`. For qualities lower than
/// `2`, `None` will be returned.
#[doc(alias = "BrotliEncoderMaxCompressedSize")]
pub fn compress_bound(input_size: usize, quality: Quality) -> Option<usize> {
    if quality.0 >= 2 {
        Some(unsafe { BrotliEncoderMaxCompressedSize(input_size) })
    } else {
        None
    }
}

/// Read all bytes from `input` and decompress them into `output`, returning how many bytes were
/// written.
///
/// The uncompressed `input` must fit into `output`, otherwise an error is returned and the
/// decompression will be aborted.
///
/// # Errors
///
/// An [`Err`] will be returned if:
///
/// * `input` is corrupted
/// * memory allocation failed
/// * `output` is not large enough to hold uncompressed `input`
///
/// # Examples
///
/// ```
/// use brotlic::{compress, CompressionMode, decompress, Quality, WindowSize};
///
/// let input = vec![0; 1024];
/// let mut encoded = vec![1; 1024];
/// let mut decoded = vec![2; 1024];
///
/// let bytes_written = compress(
///      input.as_slice(),
///      encoded.as_mut_slice(),
///      Quality::default(),
///      WindowSize::default(),
///      CompressionMode::Generic
/// ).unwrap();
///
/// let encoded = &encoded[..bytes_written];
/// let bytes_written = decompress(encoded, decoded.as_mut_slice()).unwrap();
/// let decoded = &decoded[..bytes_written];
///
/// assert_eq!(input, decoded);
/// ```
#[doc(alias = "BrotliDecoderDecompress")]
pub fn decompress(input: &[u8], output: &mut [u8]) -> DecompressionResult<usize> {
    let mut output_size = output.len();

    let res = unsafe {
        BrotliDecoderDecompress(
            input.len(),
            input.as_ptr(),
            &mut output_size as *mut usize,
            output.as_mut_ptr(),
        )
    };

    if res == BrotliDecoderResult_BROTLI_DECODER_RESULT_SUCCESS {
        Ok(output_size)
    } else {
        Err(DecompressionError)
    }
}

/// An error returned by `into_inner`.
///
/// This error combines an error that happened while processing data, and the instance
/// object which may be used to recover from the condition.
#[derive(Debug)]
pub struct IntoInnerError<I>(I, io::Error);

impl<I> IntoInnerError<I> {
    fn new(instance: I, error: io::Error) -> Self {
        Self(instance, error)
    }

    /// Returns the error which caused the call to `into_inner()` to fail.
    pub fn error(&self) -> &io::Error {
        &self.1
    }

    /// Returns the instance which generated the error
    pub fn into_inner(self) -> I {
        self.0
    }

    /// Returns the error which caused the `into_inner` call to fail. This is used to obtain
    /// ownership of the error in contrast to [`error`].
    pub fn into_error(self) -> io::Error {
        self.1
    }

    /// Returns both the error and the instance that generated it. This is used to obtain ownership
    /// of both of them.
    pub fn into_parts(self) -> (io::Error, I) {
        (self.1, self.0)
    }
}

impl<I> From<IntoInnerError<I>> for io::Error {
    fn from(iie: IntoInnerError<I>) -> io::Error {
        iie.1
    }
}

impl<I: fmt::Debug> error::Error for IntoInnerError<I> {}

impl<I> fmt::Display for IntoInnerError<I> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.error().fmt(f)
    }
}