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
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
//! Symbol Codes (mainly provided for teaching purpose; typically inferior to stream codes)
//!
//! # TODO
//!
//! - implement `Pos` and `Seek` for `SymbolCoder` and for `QueueDecoder`.

#![allow(clippy::type_complexity)]

pub mod exp_golomb;
pub mod huffman;

use alloc::vec::Vec;
use core::{
    borrow::Borrow,
    convert::Infallible,
    fmt::{Debug, Display},
    iter::{Repeat, Take},
    marker::PhantomData,
    ops::Deref,
};

use smallvec::SmallVec;

use crate::{
    backends::{AsReadWords, BoundedReadWords, Cursor, IntoReadWords, ReadWords, WriteWords},
    BitArray, CoderError, DefaultEncoderError, Queue, Semantics, Stack, UnwrapInfallible,
};

// TRAITS FOR READING AND WRITNIG STREAMS OF BITS =============================

pub trait ReadBitStream<S: Semantics> {
    type ReadError;

    fn read_bit(&mut self) -> Result<Option<bool>, Self::ReadError>;

    fn decode_symbol<C: DecoderCodebook>(
        &mut self,
        codebook: C,
    ) -> Result<C::Symbol, CoderError<SymbolCodeError<C::InvalidCodeword>, Self::ReadError>>;

    fn decode_symbols<'s, I, C>(&'s mut self, codebooks: I) -> DecodeSymbols<'s, Self, I, S>
    where
        I: IntoIterator<Item = C> + 's,
        C: DecoderCodebook,
    {
        DecodeSymbols {
            bit_stream: self,
            codebooks,
            semantics: PhantomData,
        }
    }

    fn decode_iid_symbols<'a, C>(
        &'a mut self,
        amt: usize,
        codebook: &'a C,
    ) -> DecodeSymbols<'a, Self, Take<Repeat<&'a C>>, S>
    where
        C: DecoderCodebook,
    {
        self.decode_symbols(core::iter::repeat(codebook).take(amt))
    }
}

pub trait WriteBitStream<S: Semantics> {
    type WriteError;

    fn write_bit(&mut self, bit: bool) -> Result<(), Self::WriteError>;

    fn encode_symbol<Symbol, C>(
        &mut self,
        symbol: Symbol,
        codebook: C,
    ) -> Result<(), DefaultEncoderError<Self::WriteError>>
    where
        C: EncoderCodebook,
        Symbol: Borrow<C::Symbol>;

    fn encode_symbols<Symbol, C>(
        &mut self,
        symbols_and_codebooks: impl IntoIterator<Item = (Symbol, C)>,
    ) -> Result<(), DefaultEncoderError<Self::WriteError>>
    where
        C: EncoderCodebook,
        Symbol: Borrow<C::Symbol>,
    {
        for (symbol, codebook) in symbols_and_codebooks.into_iter() {
            self.encode_symbol(symbol, codebook)?;
        }

        Ok(())
    }

    fn encode_iid_symbols<Symbol, C>(
        &mut self,
        symbols: impl IntoIterator<Item = Symbol>,
        codebook: &C,
    ) -> Result<(), DefaultEncoderError<Self::WriteError>>
    where
        C: EncoderCodebook,
        Symbol: Borrow<C::Symbol>,
    {
        self.encode_symbols(symbols.into_iter().map(|symbol| (symbol, codebook)))
    }
}

#[derive(Debug)]
pub struct DecodeSymbols<'a, Stream: ?Sized, I, S: Semantics> {
    bit_stream: &'a mut Stream,
    codebooks: I,
    semantics: PhantomData<S>,
}

impl<'a, Stream, I, C, S> Iterator for DecodeSymbols<'a, Stream, I, S>
where
    S: Semantics,
    Stream: ReadBitStream<S>,
    C: DecoderCodebook,
    I: Iterator<Item = C>,
{
    type Item =
        Result<C::Symbol, CoderError<SymbolCodeError<C::InvalidCodeword>, Stream::ReadError>>;

    #[inline(always)]
    fn next(&mut self) -> Option<Self::Item> {
        Some(self.bit_stream.decode_symbol(self.codebooks.next()?))
    }

    #[inline(always)]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.codebooks.size_hint()
    }
}

impl<'a, Stream, I, C, S> ExactSizeIterator for DecodeSymbols<'a, Stream, I, S>
where
    S: Semantics,
    Stream: ReadBitStream<S>,
    C: DecoderCodebook,
    I: ExactSizeIterator<Item = C>,
{
}

// ADAPTER THAT TURNS A BACKEND INTO A BIT STREAM =============================

/// Generic symbol coder for 3 out of 4 possible cases
///
/// You likely won't spell out this type explicitly. It's more convenient to use one of the
/// type aliases [`QueueEncoder`] or [`StackCoder`] (or the more opinionated aliases
/// [`DefaultQueueEncoder`] and [`DefaultStackCoder`]).
///
/// Depending on the type parameter `S`, this type supports:
/// - encoding on a queue (i.e., writing prefix codes); this is type aliased as
///   [`QueueEncoder`].
/// - encoding and decoding on a stack (i.e., writing suffix codes and reading them back in
///   reoverse order). This is type aliased as [`StackCoder`].
///
/// This type does not support decoding from a queue. Use a [`QueueDecoder`] for this
/// purpose.
#[derive(Clone, PartialEq, Eq, Debug, Default)]
pub struct SymbolCoder<Word: BitArray, S: Semantics, B = Vec<Word>> {
    backend: B,
    current_word: Word,

    /// A `BitArray` with at most one set bit:
    /// - `mask_last_written == 0` if all bits written so far have already been flushed to
    ///   the backend (in case of a write backend) and/or if reading the next bit would
    ///   require obtaining a new word from the backend (in case of a read backend); This
    ///   includes the case of an empty `QueueEncoder`. In all of these cases, `current_word`
    ///  as to be zero.
    /// - otherwise, `mask_last_written` has a single set bit which marks the position in
    ///   `current_word` where the next bit should be written if any.
    mask_last_written: Word,

    semantics: PhantomData<S>,
}

pub type QueueEncoder<Word, B = Vec<Word>> = SymbolCoder<Word, Queue, B>;
pub type StackCoder<Word, B = Vec<Word>> = SymbolCoder<Word, Stack, B>;

#[derive(Clone, PartialEq, Eq, Debug, Default)]
pub struct QueueDecoder<Word: BitArray, B> {
    backend: B,
    current_word: Word,

    /// If zero then `current_word` is meaningless and has to be read in from `backend`.
    mask_next_to_read: Word,
}

pub type DefaultQueueEncoder = QueueEncoder<u32, Vec<u32>>;
pub type DefaultQueueDecoder = QueueDecoder<u32, Cursor<u32, Vec<u32>>>;
pub type DefaultStackCoder = StackCoder<u32, Vec<u32>>;

// GENERIC IMPLEMENTATIONS ====================================================

impl<Word: BitArray, S: Semantics, B> SymbolCoder<Word, S, B> {
    pub fn new() -> Self
    where
        B: Default,
    {
        Default::default()
    }

    /// Returns the correct len for, e.g., `B = Vec<Word>` regardless of whether `S = Queue`
    /// or `S = Stack`.
    pub fn len(&self) -> usize
    where
        B: BoundedReadWords<Word, Stack>,
    {
        self.backend
            .remaining()
            .checked_mul(Word::BITS)
            .expect("len overflows addressable space")
            .checked_add(if self.mask_last_written == Word::zero() {
                0
            } else {
                (self.mask_last_written.trailing_zeros() + 1) as usize
            })
            .expect("len overflows addressable space")
    }

    /// Returns `true` if no bits are on the `SymbolCoder`.
    pub fn is_empty(&self) -> bool
    where
        B: BoundedReadWords<Word, Stack>,
    {
        self.mask_last_written == Word::zero() && self.backend.is_exhausted()
    }
}

// SPECIAL IMPLEMENTATIONS FOR VEC ============================================

impl<Word: BitArray> StackCoder<Word, Vec<Word>> {
    pub fn with_bit_capacity(bit_capacity: usize) -> Self {
        Self {
            // Reserve capacity for one additional bit for sealing.
            backend: Vec::with_capacity(bit_capacity / Word::BITS + 1),
            ..Default::default()
        }
    }

    pub fn get_compressed(&mut self) -> StackCoderGuard<'_, Word> {
        StackCoderGuard::new(self)
    }
}

impl<Word: BitArray> QueueEncoder<Word, Vec<Word>> {
    pub fn with_bit_capacity(bit_capacity: usize) -> Self {
        Self {
            backend: Vec::with_capacity((bit_capacity + Word::BITS - 1) / Word::BITS),
            ..Default::default()
        }
    }

    pub fn get_compressed(&mut self) -> QueueEncoderGuard<'_, Word> {
        QueueEncoderGuard::new(self)
    }
}

#[derive(Debug)]
pub struct StackCoderGuard<'a, Word: BitArray> {
    inner: &'a mut StackCoder<Word, Vec<Word>>,
}

impl<'a, Word: BitArray> StackCoderGuard<'a, Word> {
    fn new(stack_coder: &'a mut StackCoder<Word, Vec<Word>>) -> Self {
        // Stacks need to be sealed by one additional bit so that the end can be discovered.
        stack_coder.write_bit(true).unwrap_infallible();
        if stack_coder.mask_last_written != Word::zero() {
            stack_coder.backend.push(stack_coder.current_word);
        }
        Self { inner: stack_coder }
    }
}

impl<'a, Word: BitArray> Drop for StackCoderGuard<'a, Word> {
    fn drop(&mut self) {
        if self.inner.mask_last_written != Word::zero() {
            self.inner.backend.pop();
        }
        self.inner.read_bit().expect("The constructor wrote a bit.");
    }
}

impl<'a, Word: BitArray> Deref for StackCoderGuard<'a, Word> {
    type Target = [Word];

    fn deref(&self) -> &Self::Target {
        &self.inner.backend
    }
}

#[derive(Debug)]
pub struct QueueEncoderGuard<'a, Word: BitArray> {
    inner: &'a mut QueueEncoder<Word, Vec<Word>>,
}

impl<'a, Word: BitArray> QueueEncoderGuard<'a, Word> {
    fn new(queue_encoder: &'a mut QueueEncoder<Word, Vec<Word>>) -> Self {
        // Queues don't need to be sealed, so just flush the remaining word if any.
        if queue_encoder.mask_last_written != Word::zero() {
            queue_encoder.backend.push(queue_encoder.current_word);
        }
        Self {
            inner: queue_encoder,
        }
    }
}

impl<'a, Word: BitArray> Drop for QueueEncoderGuard<'a, Word> {
    fn drop(&mut self) {
        if self.inner.mask_last_written != Word::zero() {
            self.inner.backend.pop();
        }
    }
}

impl<'a, Word: BitArray> Deref for QueueEncoderGuard<'a, Word> {
    type Target = [Word];

    fn deref(&self) -> &Self::Target {
        &self.inner.backend
    }
}

// IMPLEMENTATIONS FOR A QUEUE ================================================

impl<Word: BitArray, B> QueueEncoder<Word, B> {
    pub fn from_compressed(compressed: B) -> Self
    where
        B: Default,
    {
        Self {
            backend: compressed,
            ..Default::default()
        }
    }

    pub fn into_decoder(self) -> Result<QueueDecoder<Word, B::IntoReadWords>, B::WriteError>
    where
        B: WriteWords<Word> + IntoReadWords<Word, Queue>,
    {
        Ok(QueueDecoder::from_compressed(
            self.into_compressed()?.into_read_words(),
        ))
    }

    pub fn into_compressed(mut self) -> Result<B, B::WriteError>
    where
        B: WriteWords<Word>,
    {
        // Queues don't need to be sealed, so just flush the remaining word if any.
        if self.mask_last_written != Word::zero() {
            self.backend.write(self.current_word)?;
        }
        Ok(self.backend)
    }

    pub fn into_overshooting_iter(
        self,
    ) -> Result<
        impl Iterator<Item = Result<bool, <B::IntoReadWords as ReadWords<Word, Queue>>::ReadError>>,
        B::WriteError,
    >
    where
        B: WriteWords<Word> + IntoReadWords<Word, Queue>,
    {
        // TODO: return `impl ExactSizeIterator` for `B: BoundedReadWords` once
        // specialization is stable
        self.into_decoder()
    }
}

impl<Word: BitArray, B: WriteWords<Word>> WriteBitStream<Queue> for QueueEncoder<Word, B> {
    type WriteError = B::WriteError;

    fn write_bit(&mut self, bit: bool) -> Result<(), Self::WriteError> {
        let write_mask = self.mask_last_written << 1;
        self.mask_last_written = if write_mask != Word::zero() {
            let new_bit = if bit { write_mask } else { Word::zero() };
            self.current_word = self.current_word | new_bit;
            write_mask
        } else {
            if self.mask_last_written != Word::zero() {
                self.backend.write(self.current_word)?;
            }
            self.current_word = if bit { Word::one() } else { Word::zero() };
            Word::one()
        };

        Ok(())
    }

    #[inline(always)]
    fn encode_symbol<Symbol, C>(
        &mut self,
        symbol: Symbol,
        codebook: C,
    ) -> Result<(), DefaultEncoderError<Self::WriteError>>
    where
        C: EncoderCodebook,
        Symbol: Borrow<C::Symbol>,
    {
        codebook.encode_symbol_prefix(symbol, |bit| self.write_bit(bit))
    }
}

impl<Word: BitArray, B> QueueDecoder<Word, B> {
    pub fn from_compressed(compressed: B) -> Self {
        Self {
            backend: compressed,
            current_word: Word::zero(),
            mask_next_to_read: Word::zero(),
        }
    }

    /// We don't keep track of the exact length of a queue, so we can only say with
    /// certainty if we can detect that there's something left.
    pub fn maybe_exhausted(&self) -> bool
    where
        B: BoundedReadWords<Word, Queue>,
    {
        let mask_remaining_bits = !self.mask_next_to_read.wrapping_sub(&Word::one());
        self.current_word & mask_remaining_bits == Word::zero() && self.backend.is_exhausted()
    }
}

impl<Word: BitArray, B: ReadWords<Word, Queue>> ReadBitStream<Queue> for QueueDecoder<Word, B> {
    type ReadError = B::ReadError;

    #[inline(always)]
    fn decode_symbol<C: DecoderCodebook>(
        &mut self,
        codebook: C,
    ) -> Result<C::Symbol, CoderError<SymbolCodeError<C::InvalidCodeword>, Self::ReadError>> {
        codebook.decode_symbol(self)
    }

    fn read_bit(&mut self) -> Result<Option<bool>, Self::ReadError> {
        if self.mask_next_to_read == Word::zero() {
            match self.backend.read() {
                Ok(Some(next_word)) => {
                    self.current_word = next_word;
                    self.mask_next_to_read = Word::one();
                }
                Ok(None) => return Ok(None),
                Err(err) => return Err(err),
            }
        }

        let bit = self.current_word & self.mask_next_to_read != Word::zero();
        // No need to unset the bit in `current_word` since we're only reading, never writing.
        self.mask_next_to_read = self.mask_next_to_read << 1;
        Ok(Some(bit))
    }
}

impl<Word: BitArray, B: ReadWords<Word, Queue>> Iterator for QueueDecoder<Word, B> {
    type Item = Result<bool, B::ReadError>;

    fn next(&mut self) -> Option<Self::Item> {
        self.read_bit().transpose()
    }
}

// IMPLEMENTATIONS FOR A STACK ================================================

impl<Word: BitArray, B: WriteWords<Word>> StackCoder<Word, B> {
    /// # Errors
    ///
    /// - Returns `Err(CoderError::FrontendError(compressed))` if `compressed` ends in a
    ///   zero which is not allowed for stacks (because we need a terminal "one" bit to
    ///   identify the head position). Note that "EOF" is not considered an error, and the
    ///   method will return with a success if called with an empty backend.
    /// - Returns `Err(CoderError::BackendError(err))` if reading the last word from the
    ///   backend resulted in `Err(err)`.
    /// - Returns `Ok(stack_coder)` in all other cases, including the case where the backend
    ///   is empty.
    pub fn from_compressed(mut compressed: B) -> Result<Self, CoderError<B, B::ReadError>>
    where
        B: ReadWords<Word, Stack>,
    {
        let (current_word, mask_last_written) = if let Some(last_word) = compressed.read()? {
            if last_word == Word::zero() {
                // A stack of compressed data must not end in a zero word.
                return Err(CoderError::Frontend(compressed));
            }
            let mask_end_bit = Word::one() << last_word.trailing_zeros() as usize;
            (last_word ^ mask_end_bit, mask_end_bit >> 1)
        } else {
            (Word::zero(), Word::zero())
        };

        Ok(Self {
            backend: compressed,
            current_word,
            mask_last_written,
            semantics: PhantomData,
        })
    }

    pub fn into_compressed(mut self) -> Result<B, B::WriteError> {
        // Stacks need to be sealed by one additional bit so that the end can be discovered.
        self.write_bit(true)?;
        if self.mask_last_written != Word::zero() {
            self.backend.write(self.current_word)?;
        }
        Ok(self.backend)
    }

    #[inline(always)]
    pub fn encode_symbols_reverse<Symbol, C, I>(
        &mut self,
        symbols_and_codebooks: I,
    ) -> Result<(), DefaultEncoderError<B::WriteError>>
    where
        Symbol: Borrow<C::Symbol>,
        C: EncoderCodebook,
        I: IntoIterator<Item = (Symbol, C)>,
        I::IntoIter: DoubleEndedIterator,
    {
        self.encode_symbols(symbols_and_codebooks.into_iter().rev())
    }

    #[inline(always)]
    pub fn encode_iid_symbols_reverse<Symbol, C, I>(
        &mut self,
        symbols: I,
        codebook: &C,
    ) -> Result<(), DefaultEncoderError<B::WriteError>>
    where
        Symbol: Borrow<C::Symbol>,
        C: EncoderCodebook,
        I: IntoIterator<Item = Symbol>,
        I::IntoIter: DoubleEndedIterator,
    {
        self.encode_iid_symbols(symbols.into_iter().rev(), codebook)
    }

    pub fn into_decoder(self) -> SymbolCoder<Word, Stack, B::IntoReadWords>
    where
        B: IntoReadWords<Word, Stack>,
    {
        SymbolCoder {
            backend: self.backend.into_read_words(),
            current_word: self.current_word,
            mask_last_written: self.mask_last_written,
            semantics: PhantomData,
        }
    }

    pub fn as_decoder<'a>(&'a self) -> SymbolCoder<Word, Stack, B::AsReadWords>
    where
        B: AsReadWords<'a, Word, Stack>,
    {
        SymbolCoder {
            backend: self.backend.as_read_words(),
            current_word: self.current_word,
            mask_last_written: self.mask_last_written,
            semantics: PhantomData,
        }
    }

    /// Consumes the coder and returns an iterator over bits (in reverse direction)
    ///
    /// You often don't need to call this method since a `StackCoder` is already an iterator
    /// if the backend implements `ReadWords<Word, Stack>` (as the default backend
    /// `Vec<Word>` does).
    pub fn into_iterator(
        self,
    ) -> impl Iterator<Item = Result<bool, <B::IntoReadWords as ReadWords<Word, Stack>>::ReadError>>
    where
        B: IntoReadWords<Word, Stack>,
    {
        self.into_decoder()
    }

    /// Returns an iterator over bits (in reverse direction) that leaves the current coder untouched.
    ///
    /// You often don't need to call this method since a `StackCoder` is already an iterator
    /// if the backend implements `ReadWords<Word, Stack>` (as the default backend
    /// `Vec<Word>` does).
    pub fn iter<'a>(
        &'a self,
    ) -> impl Iterator<
        Item = Result<
            bool,
            <<B as AsReadWords<'a, Word, Stack>>::AsReadWords as ReadWords<Word, Stack>>::ReadError,
        >,
    > + 'a
    where
        B: AsReadWords<'a, Word, Stack>,
    {
        self.as_decoder()
    }
}

impl<Word: BitArray, B: WriteWords<Word>> WriteBitStream<Stack> for StackCoder<Word, B> {
    type WriteError = B::WriteError;

    fn write_bit(&mut self, bit: bool) -> Result<(), Self::WriteError> {
        let write_mask = self.mask_last_written << 1;
        self.mask_last_written = if write_mask != Word::zero() {
            let new_bit = if bit { write_mask } else { Word::zero() };
            self.current_word = self.current_word | new_bit;
            write_mask
        } else {
            if self.mask_last_written != Word::zero() {
                self.backend.write(self.current_word)?;
            }
            self.current_word = if bit { Word::one() } else { Word::zero() };
            Word::one()
        };

        Ok(())
    }

    #[inline(always)]
    fn encode_symbol<Symbol, C>(
        &mut self,
        symbol: Symbol,
        codebook: C,
    ) -> Result<(), DefaultEncoderError<Self::WriteError>>
    where
        Symbol: Borrow<C::Symbol>,
        C: EncoderCodebook,
    {
        codebook.encode_symbol_suffix(symbol, |bit| self.write_bit(bit))
    }
}

impl<Word: BitArray, B: ReadWords<Word, Stack>> ReadBitStream<Stack> for StackCoder<Word, B> {
    type ReadError = B::ReadError;

    #[inline(always)]
    fn decode_symbol<C: DecoderCodebook>(
        &mut self,
        codebook: C,
    ) -> Result<C::Symbol, CoderError<SymbolCodeError<C::InvalidCodeword>, Self::ReadError>> {
        codebook.decode_symbol(self)
    }

    fn read_bit(&mut self) -> Result<Option<bool>, Self::ReadError> {
        if self.mask_last_written == Word::zero() {
            self.current_word = if let Some(next_word) = self.backend.read()? {
                next_word
            } else {
                // Reached end of stream (this is considered `Ok`).
                return Ok(None);
            };
            self.mask_last_written = Word::one() << (Word::BITS - 1);
        }

        let bit = self.current_word & self.mask_last_written;
        self.current_word = self.current_word ^ bit;
        self.mask_last_written = self.mask_last_written >> 1;
        Ok(Some(bit != Word::zero()))
    }
}

impl<Word: BitArray, B: ReadWords<Word, Stack>> Iterator for StackCoder<Word, B> {
    type Item = Result<bool, B::ReadError>;

    fn next(&mut self) -> Option<Self::Item> {
        self.read_bit().transpose()
    }

    // TODO: override `size_hint` for `B: BoundedReadWords` when specialization is stable.
}

impl<Word: BitArray, B: BoundedReadWords<Word, Stack>> ExactSizeIterator for StackCoder<Word, B> {
    fn len(&self) -> usize {
        StackCoder::len(self)
    }
}

type SmallBitStack = StackCoder<usize, SmallVec<[usize; 1]>>;

#[derive(Debug)]
pub enum SymbolCodeError<InvalidCodeword = Infallible> {
    /// The compressed data ended before the current codeword was complete.
    OutOfCompressedData,

    /// Found a code word that does not map to any symbol.
    InvalidCodeword(InvalidCodeword),
}

impl<InvalidCodeword> SymbolCodeError<InvalidCodeword> {
    pub fn into_coder_error<BackendError>(self) -> CoderError<Self, BackendError> {
        CoderError::Frontend(self)
    }
}

impl<InvalidCodeword: Display> Display for SymbolCodeError<InvalidCodeword> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::OutOfCompressedData => write!(
                f,
                "The compressed data ended before the current codeword was complete."
            ),
            Self::InvalidCodeword(err) => write!(f, "Invalid codeword for this codebook: {}", err),
        }
    }
}

#[cfg(feature = "std")]
impl<InvalidCodeword: std::error::Error + 'static> std::error::Error
    for SymbolCodeError<InvalidCodeword>
{
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::OutOfCompressedData => None,
            Self::InvalidCodeword(source) => Some(source),
        }
    }
}

pub trait Codebook {
    type Symbol;
}

pub trait EncoderCodebook: Codebook {
    fn encode_symbol_prefix<BackendError>(
        &self,
        symbol: impl Borrow<Self::Symbol>,
        mut emit: impl FnMut(bool) -> Result<(), BackendError>,
    ) -> Result<(), DefaultEncoderError<BackendError>> {
        let mut reverse_codeword = SmallBitStack::new();
        self.encode_symbol_suffix(symbol, |bit| reverse_codeword.write_bit(bit))
            .map_err(|err| CoderError::Frontend(err.into_frontend_error()))?;

        for bit in reverse_codeword {
            emit(bit.unwrap_infallible())?;
        }
        Ok(())
    }

    fn encode_symbol_suffix<BackendError>(
        &self,
        symbol: impl Borrow<Self::Symbol>,
        mut emit: impl FnMut(bool) -> Result<(), BackendError>,
    ) -> Result<(), DefaultEncoderError<BackendError>> {
        let mut reverse_codeword = SmallBitStack::new();
        self.encode_symbol_prefix(symbol, |bit| reverse_codeword.write_bit(bit))
            .map_err(|err| CoderError::Frontend(err.into_frontend_error()))?;

        for bit in reverse_codeword {
            emit(bit.unwrap_infallible())?;
        }
        Ok(())
    }
}

pub trait DecoderCodebook: Codebook {
    type InvalidCodeword;

    fn decode_symbol<BackendError>(
        &self,
        source: impl Iterator<Item = Result<bool, BackendError>>,
    ) -> Result<Self::Symbol, CoderError<SymbolCodeError<Self::InvalidCodeword>, BackendError>>;
}

impl<C: Codebook> Codebook for &C {
    type Symbol = C::Symbol;
}

impl<C: EncoderCodebook> EncoderCodebook for &C {
    #[inline(always)]
    fn encode_symbol_prefix<BackendError>(
        &self,
        symbol: impl Borrow<Self::Symbol>,
        emit: impl FnMut(bool) -> Result<(), BackendError>,
    ) -> Result<(), DefaultEncoderError<BackendError>> {
        (*self).encode_symbol_prefix(symbol, emit)
    }

    #[inline(always)]
    fn encode_symbol_suffix<BackendError>(
        &self,
        symbol: impl Borrow<Self::Symbol>,
        emit: impl FnMut(bool) -> Result<(), BackendError>,
    ) -> Result<(), DefaultEncoderError<BackendError>> {
        (*self).encode_symbol_suffix(symbol, emit)
    }
}

impl<C: DecoderCodebook> DecoderCodebook for &C {
    type InvalidCodeword = C::InvalidCodeword;

    fn decode_symbol<BackendError>(
        &self,
        source: impl Iterator<Item = Result<bool, BackendError>>,
    ) -> Result<Self::Symbol, CoderError<SymbolCodeError<Self::InvalidCodeword>, BackendError>>
    {
        (*self).decode_symbol(source)
    }
}

#[cfg(test)]
mod tests {
    use super::{
        huffman::{DecoderHuffmanTree, EncoderHuffmanTree},
        *,
    };

    use crate::UnwrapInfallible;

    use rand_xoshiro::{
        rand_core::{RngCore, SeedableRng},
        Xoshiro256StarStar,
    };

    #[test]
    fn bit_queue() {
        let mut bit_queue = DefaultQueueEncoder::new();
        assert_eq!(bit_queue.len(), 0);
        assert!(bit_queue.is_empty());

        let amt = 150;
        let mut bool_vec = Vec::with_capacity(amt);
        let mut rng = Xoshiro256StarStar::seed_from_u64(123);
        for _ in 0..amt {
            let bit = rng.next_u32() % 2 != 0;
            bit_queue.write_bit(bit).unwrap();
            bool_vec.push(bit);
        }

        assert_eq!(bit_queue.len(), amt);
        assert!(!bit_queue.is_empty());

        let mut queue_iter = bit_queue.into_overshooting_iter().unwrap_infallible();
        for expected in bool_vec {
            assert_eq!(queue_iter.next().unwrap().unwrap_infallible(), expected);
        }

        for remaining in queue_iter {
            assert!(!remaining.unwrap_infallible());
        }
    }

    #[test]
    fn bit_stack() {
        let mut bit_stack = DefaultStackCoder::new();
        assert_eq!(bit_stack.len(), 0);
        assert!(bit_stack.is_empty());

        let amt = 150;
        let mut bool_vec = Vec::with_capacity(amt);
        let mut rng = Xoshiro256StarStar::seed_from_u64(123);
        for _ in 0..amt {
            let bit = rng.next_u32() % 2 != 0;
            bit_stack.write_bit(bit).unwrap();
            bool_vec.push(bit);
        }

        assert_eq!(bit_stack.len(), amt);
        assert!(!bit_stack.is_empty());
        assert!(bool_vec.into_iter().rev().eq(bit_stack.map(Result::unwrap)));
    }

    #[test]
    fn encode_decode_iid_queue() {
        let amt = 1000;
        let mut rng = Xoshiro256StarStar::seed_from_u64(12345);
        let symbols = (0..amt)
            .map(|_| (rng.next_u32() % 5) as usize)
            .collect::<Vec<_>>();

        let probabilities = [2, 2, 4, 1, 1];
        let encoder_codebook = EncoderHuffmanTree::from_probabilities::<u32, _>(&probabilities);
        let decoder_codebook = DecoderHuffmanTree::from_probabilities::<u32, _>(&probabilities);

        let mut encoder = DefaultQueueEncoder::new();

        assert_eq!(encoder.len(), 0);
        encoder
            .encode_iid_symbols(&symbols, &encoder_codebook)
            .unwrap();
        assert!(encoder.len() > amt);

        let mut decoder = encoder.into_decoder().unwrap_infallible();
        let reconstructed = decoder
            .decode_iid_symbols(amt, &decoder_codebook)
            .collect::<Result<Vec<_>, _>>()
            .unwrap();

        assert_eq!(reconstructed, symbols);
        assert!(decoder.maybe_exhausted());
    }

    #[test]
    fn encode_decode_iid_stack() {
        let amt = 1000;
        let mut rng = Xoshiro256StarStar::seed_from_u64(12345);
        let symbols = (0..amt)
            .map(|_| (rng.next_u32() % 5) as usize)
            .collect::<Vec<_>>();

        let probabilities = [2, 2, 4, 1, 1];
        let encoder_codebook = EncoderHuffmanTree::from_probabilities::<u32, _>(&probabilities);
        let decoder_codebook = DecoderHuffmanTree::from_probabilities::<u32, _>(&probabilities);

        let mut coder = DefaultStackCoder::new();

        assert_eq!(coder.len(), 0);
        coder
            .encode_iid_symbols_reverse(&symbols, &encoder_codebook)
            .unwrap();
        assert!(coder.len() > amt);

        let reconstructed = coder
            .decode_iid_symbols(amt, &decoder_codebook)
            .collect::<Result<Vec<_>, _>>()
            .unwrap();

        assert_eq!(reconstructed, symbols);
        assert!(coder.is_empty());
    }

    #[test]
    fn encode_decode_non_iid() {
        fn iter_probs_and_symbols(amt: usize) -> impl Iterator<Item = (Vec<u32>, usize)> {
            let mut rng = Xoshiro256StarStar::seed_from_u64(123456);
            (0..amt).map(move |_| {
                let num_symbols = 1 + rng.next_u32() % 10;
                let probs = (0..num_symbols).map(|_| rng.next_u32() >> 16).collect();
                let symbol = rng.next_u32() % num_symbols;
                (probs, symbol as usize)
            })
        }

        let amt;
        #[cfg(not(miri))]
        {
            amt = 1000;
        }
        #[cfg(miri)]
        {
            amt = 100; // miri would take forever if we used `amt = 1000` here.
        }

        let mut compressed = DefaultQueueEncoder::new();

        assert_eq!(compressed.len(), 0);
        compressed
            .encode_symbols(iter_probs_and_symbols(amt).map(|(probs, symbol)| {
                (
                    symbol,
                    EncoderHuffmanTree::from_probabilities::<u32, _>(&probs),
                )
            }))
            .unwrap();
        assert!(compressed.len() > amt);

        let mut decoder = compressed.into_decoder().unwrap_infallible();
        let reconstructed = decoder
            .decode_symbols(
                iter_probs_and_symbols(amt)
                    .map(|(probs, _)| DecoderHuffmanTree::from_probabilities::<u32, _>(&probs)),
            )
            .map(Result::unwrap);

        assert!(reconstructed.eq(iter_probs_and_symbols(amt).map(|(_, symbol)| symbol)));
        assert!(decoder.maybe_exhausted());
    }
}