constriction 0.4.2

Entropy coders for research and production (Rust and Python).
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
use std::prelude::v1::*;

use numpy::{PyArray1, PyReadonlyArray1};
use pyo3::{prelude::*, types::PyTuple};

use crate::{
    pybindings::array1_to_vec,
    stream::{
        queue::{DecoderFrontendError, RangeCoderState},
        Decode, Encode,
    },
    Pos, Seek, UnwrapInfallible,
};

use super::model::{internals::EncoderDecoderModel, Model};

/// Range Coding: a stream code with queue semantics (i.e., "first in first out") [1, 2].
///
/// The Range Coding algorithm is a variation on Arithmetic Coding [1, 3] that runs more efficiently
/// on standard computing hardware.
///
/// ## Example
///
/// The following example shows a full round trip that encodes a message, prints its compressed
/// representation, and then decodes the message again. The message is a sequence of 11 integers
/// (referred to as "symbols") and comprised of two parts: the first 7 symbols are encoded with an
/// i.i.d. entropy model, i.e., using the same distribution for each symbol, which happens to be a
/// [`Categorical`](model.html#constriction.stream.model.Categorical) distribution; and the remaining
/// 4 symbols are each encoded with a different entropy model, but all of these 4 models are from
/// the same family of [`QuantizedGaussian`](model.html#constriction.stream.model.QuantizedGaussian)s,
/// just with different model parameters (means and standard deviations) for each of the 4 symbols.
///
/// ```python
/// import constriction
/// import numpy as np
///
/// # Define the two parts of the message and their respective entropy models:
/// message_part1       = np.array([1, 2, 0, 3, 2, 3, 0], dtype=np.int32)
/// probabilities_part1 = np.array([0.2, 0.4, 0.1, 0.3], dtype=np.float32)
/// model_part1       = constriction.stream.model.Categorical(probabilities_part1, perfect=False)
/// # `model_part1` is a categorical distribution over the (implied) alphabet
/// # {0,1,2,3} with P(X=0) = 0.2, P(X=1) = 0.4, P(X=2) = 0.1, and P(X=3) = 0.3;
/// # we will use it below to encode each of the 7 symbols in `message_part1`.
///
/// message_part2       = np.array([6,   10,   -4,    2  ], dtype=np.int32)
/// means_part2         = np.array([2.5, 13.1, -1.1, -3.0], dtype=np.float32)
/// stds_part2          = np.array([4.1,  8.7,  6.2,  5.4], dtype=np.float32)
/// model_family_part2  = constriction.stream.model.QuantizedGaussian(-100, 100)
/// # `model_family_part2` is a *family* of Gaussian distributions, quantized to
/// # bins of width 1 centered at the integers -100, -99, ..., 100. We could
/// # have provided a fixed mean and standard deviation to the constructor of
/// # `QuantizedGaussian` but we'll instead provide individual means and standard
/// # deviations for each symbol when we encode and decode `message_part2` below.
///
/// print(f"Original message: {np.concatenate([message_part1, message_part2])}")
///
/// # Encode both parts of the message in sequence:
/// encoder = constriction.stream.queue.RangeEncoder()
/// encoder.encode(message_part1, model_part1)
/// encoder.encode(message_part2, model_family_part2, means_part2, stds_part2)
///
/// # Get and print the compressed representation:
/// compressed = encoder.get_compressed()
/// print(f"compressed representation: {compressed}")
/// print(f"(in binary: {[bin(word) for word in compressed]})")
///
/// # You could save `compressed` to a file using `compressed.tofile("filename")`
/// # and read it back in: `compressed = np.fromfile("filename", dtype=np.uint32).
///
/// # Decode the message:
/// decoder = constriction.stream.queue.RangeDecoder(compressed)
/// decoded_part1 = decoder.decode(model_part1, 7) # (decodes 7 symbols)
/// decoded_part2 = decoder.decode(model_family_part2, means_part2, stds_part2)
/// print(f"Decoded message: {np.concatenate([decoded_part1, decoded_part2])}")
/// assert np.all(decoded_part1 == message_part1)
/// assert np.all(decoded_part2 == message_part2)
/// ```
///
/// ## References
///
/// [1] Pasco, Richard Clark. Source coding algorithms for fast data compression. Diss.
/// Stanford University, 1976.
///
/// [2] Martin, G. Nigel N. "Range encoding: an algorithm for removing redundancy from a
/// digitised message." Proc. Institution of Electronic and Radio Engineers International
/// Conference on Video and Data Recording. 1979.
///
/// [3] Rissanen, Jorma, and Glen G. Langdon. "Arithmetic coding." IBM Journal of research
/// and development 23.2 (1979): 149-162.
#[pymodule]
#[pyo3(name = "queue")]
pub fn init_module(module: &Bound<'_, PyModule>) -> PyResult<()> {
    module.add_class::<RangeEncoder>()?;
    module.add_class::<RangeDecoder>()?;
    Ok(())
}

/// An encoder that uses the range coding algorithm.
///
/// To encode data with a `RangeEncoder`, call its method
/// [`encode`](#constriction.stream.queue.RangeEncoder.encode) one or more times. A `RangeEncoder`
/// has an internal buffer of compressed data, and each `encode` operation appends to this internal
/// buffer. You can copy out the contents of the internal buffer by calling the method
/// [`get_compressed`](#constriction.stream.queue.RangeEncoder.get_compressed). This will return a
/// rank-1 numpy array with `dtype=np.uint32` that you can pass to the constructor of a
/// `RangeDecoder` or write to a file for decoding at some later time (see example in the
/// documentation of the method
/// [`get_compressed`](#constriction.stream.queue.RangeEncoder.get_compressed)).
///
/// ## Example
///
/// See [module level example](#example).
#[pyclass]
#[derive(Debug, Default, Clone)]
pub struct RangeEncoder {
    inner: crate::stream::queue::DefaultRangeEncoder,
}

#[pymethods]
impl RangeEncoder {
    /// Constructs a new (empty) range encoder.
    #[new]
    #[pyo3(signature = ())]
    pub fn new() -> Self {
        let inner = crate::stream::queue::DefaultRangeEncoder::new();
        Self { inner }
    }

    /// Resets the encoder to an empty state.
    ///
    /// This removes any existing compressed data on the coder. It is equivalent to replacing the
    /// coder with a new one but slightly more efficient.
    #[pyo3(signature = ())]
    pub fn clear(&mut self) {
        self.inner.clear();
    }

    /// Records a checkpoint to which you can jump during decoding using
    /// [`seek`](#constriction.stream.queue.RangeDecoder.seek).
    ///
    /// Returns a tuple `(position, state)` where `position` is an integer that specifies how many
    /// 32-bit words of compressed data have been produced so far, and `state` is a tuple of two
    /// integers that define the `RangeEncoder`'s internal state (so that it can be restored upon
    /// [`seek`ing](#constriction.stream.queue.RangeDecoder.seek).
    ///
    /// **Note:** Don't call `pos` if you just want to find out how much compressed data has been
    /// produced so far. Call [`num_words`](#constriction.stream.queue.RangeEncoder.num_words)
    /// instead.
    ///
    /// ## Example
    ///
    /// See [`seek`](#constriction.stream.queue.RangeDecoder.seek).
    #[pyo3(signature = ())]
    pub fn pos(&mut self) -> (usize, (u64, u64)) {
        let (pos, state) = self.inner.pos();
        (pos, (state.lower(), state.range().get()))
    }

    /// Returns the current size of the encapsulated compressed data, in `np.uint32` words.
    ///
    /// Thus, the number returned by this method is the length of the array that you would get if
    /// you called [`get_compressed`](#constriction.stream.queue.RangeEncoder.get_compressed).
    #[pyo3(signature = ())]
    pub fn num_words(&self) -> usize {
        self.inner.num_words()
    }

    /// Returns the current size of the compressed data, in bits, rounded up to full words.
    ///
    /// This is 32 times the result of what [`num_words`](#constriction.stream.queue.RangeEncoder.num_words)
    /// would return.
    #[pyo3(signature = ())]
    pub fn num_bits(&self) -> usize {
        self.inner.num_bits()
    }

    /// Returns `True` iff the coder is in its default initial state.
    ///
    /// The default initial state is the state returned by the constructor when
    /// called without arguments, or the state to which the coder is set when
    /// calling `clear`.
    #[pyo3(signature = ())]
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Returns a copy of the compressed data accumulated so far, as a rank-1 numpy array of
    /// `dtype=np.uint32`.
    ///
    /// You will typically only want to call this method at the very end of your encoding task,
    /// i.e., once you've encoded the *entire* message. There is usually no need to call this method
    /// after encoding each symbol or other portion of your message. The encoders in `constriction`
    /// *accumulate* compressed data in an internal buffer, and encoding (semantically) *appends* to
    /// this buffer.
    ///
    /// That said, calling `get_compressed` has no side effects, so you *can* call `get_compressed`,
    /// then continue to encode more symbols, and then call `get_compressed` again. The first call
    /// of `get_compressed` will have no effect on the return value of the second call of
    /// `get_compressed`.
    ///
    /// The return value is a rank-1 numpy array of `dtype=np.uint32`. You can write it to a file by
    /// calling `to_file` on it, but we recommend to convert it into an architecture-independent
    /// byte order first:
    ///
    /// ```python
    /// import sys
    ///
    /// encoder = constriction.stream.queue.RangeEncoder()
    /// # ... encode some message (skipped here) ...
    /// compressed = encoder.get_compressed() # returns a numpy array.
    /// if sys.byteorder != 'little':
    ///     # Let's save data in little-endian byte order by convention.
    ///     compressed.byteswap(inplace=True)
    /// compressed.tofile('compressed-file.bin')
    ///
    /// # At a later point, you might want to read and decode the file:
    /// compressed = np.fromfile('compressed-file.bin', dtype=np.uint32)
    /// if sys.byteorder != 'little':
    ///     # Restore native byte order before passing it to `constriction`.
    ///     compressed.byteswap(inplace=True)
    /// decoder = constriction.stream.queue.RangeDecoder(compressed)
    /// # ... decode the message (skipped here) ...
    /// ```
    #[pyo3(signature = ())]
    pub fn get_compressed<'py>(&mut self, py: Python<'py>) -> Bound<'py, PyArray1<u32>> {
        PyArray1::from_slice(py, &self.inner.get_compressed())
    }

    /// Returns a `RangeDecoder` that is initialized with a copy of the compressed data currently on
    /// this `RangeEncoder`.
    ///
    /// If `encoder` is a `RangeEncoder`, then
    ///
    /// ```python
    /// decoder = encoder.get_decoder()
    /// ```
    ///
    /// is equivalent to:
    ///
    /// ```python
    /// compressed = encoder.get_compressed()
    /// decoder = constriction.stream.stack.RangeDecoder(compressed)
    /// ```
    ///
    /// Calling `get_decoder` is more efficient since it copies the compressed data only once
    /// whereas the longhand version copies the data twice.
    #[pyo3(signature = ())]
    pub fn get_decoder(&mut self) -> RangeDecoder {
        let compressed = self.inner.get_compressed().to_vec();
        RangeDecoder::from_vec(compressed)
    }

    /// Encodes one or more symbols, appending them to the encapsulated compressed data.
    ///
    /// This method can be called in 3 different ways:
    ///
    /// ## Option 1: encode(symbol, model)
    ///
    /// Encodes a *single* symbol with a concrete (i.e., fully parameterized) entropy model; (for
    /// optimal computational efficiency, don't use this option in a loop if you can instead use one
    /// of the two alternative options below.)
    ///
    /// For example:
    ///
    /// ```python
    /// # Define a concrete categorical entropy model over the (implied)
    /// # alphabet {0, 1, 2}:
    /// probabilities = np.array([0.1, 0.6, 0.3], dtype=np.float32)
    /// model = constriction.stream.model.Categorical(probabilities, perfect=False)
    ///
    /// # Encode a single symbol with this entropy model:
    /// encoder = constriction.stream.queue.RangeEncoder()
    /// encoder.encode(2, model) # Encodes the symbol `2`.
    /// # ... then encode some more symbols ...
    /// ```
    ///
    /// ## Option 2: encode(symbols, model)
    ///
    /// Encodes multiple i.i.d. symbols, i.e., all symbols in the rank-1 array `symbols` will be
    /// encoded with the same concrete (i.e., fully parameterized) entropy model.
    ///
    /// For example:
    ///
    /// ```python
    /// # Use the same concrete entropy model as in the previous example:
    /// probabilities = np.array([0.1, 0.6, 0.3], dtype=np.float32)
    /// model = constriction.stream.model.Categorical(probabilities, perfect=False)
    ///
    /// # Encode an example message using the above `model` for all symbols:
    /// symbols = np.array([0, 2, 1, 2, 0, 2, 0, 2, 1], dtype=np.int32)
    /// encoder = constriction.stream.queue.RangeEncoder()
    /// encoder.encode(symbols, model)
    /// print(encoder.get_compressed()) # (prints: [369323576])
    /// ```
    ///
    /// ## Option 3: encode(symbols, model_family, params1, params2, ...)
    ///
    /// Encodes multiple symbols, using the same *family* of entropy models (e.g., categorical or
    /// quantized Gaussian) for all symbols, but with different model parameters for each symbol;
    /// here, each `paramsX` argument is an array of the same length as `symbols`. The number of
    /// required `paramsX` arguments and their shapes and `dtype`s depend on the model family.
    ///
    /// For example, the
    /// [`QuantizedGaussian`](model.html#constriction.stream.model.QuantizedGaussian) model family
    /// expects two rank-1 model parameters with float `dtype`, which specify the mean and
    /// standard deviation for each entropy model:
    ///
    /// ```python
    /// # Define a generic quantized Gaussian distribution for all integers
    /// # in the range from -100 to 100 (both ends inclusive):
    /// model_family = constriction.stream.model.QuantizedGaussian(-100, 100)
    ///    
    /// # Specify the model parameters for each symbol:
    /// means = np.array([10.3, -4.7, 20.5], dtype=np.float32)
    /// stds  = np.array([ 5.2, 24.2,  3.1], dtype=np.float32)
    ///    
    /// # Encode an example message:
    /// # (needs `len(symbols) == len(means) == len(stds)`)
    /// symbols = np.array([12, -13, 25], dtype=np.int32)
    /// encoder = constriction.stream.queue.RangeEncoder()
    /// encoder.encode(symbols, model_family, means, stds)
    /// print(encoder.get_compressed()) # (prints: [2655472005])
    /// ```
    ///
    /// By contrast, the [`Categorical`](model.html#constriction.stream.model.Categorical) model
    /// family expects a single rank-2 model parameter where the i'th row lists the
    /// probabilities for each possible value of the i'th symbol:
    ///
    /// ```python
    /// # Define 2 categorical models over the alphabet {0, 1, 2, 3, 4}:
    /// probabilities = np.array(
    ///     [[0.1, 0.2, 0.3, 0.1, 0.3],  # (for first encoded symbol)
    ///      [0.3, 0.2, 0.2, 0.2, 0.1]], # (for second encoded symbol)
    ///     dtype=np.float32)
    /// model_family = constriction.stream.model.Categorical(perfect=False)
    ///
    /// # Encode 2 symbols (needs `len(symbols) == probabilities.shape[0]`):
    /// symbols = np.array([3, 1], dtype=np.int32)
    /// encoder = constriction.stream.queue.RangeEncoder()
    /// encoder.encode(symbols, model_family, probabilities)
    /// print(encoder.get_compressed()) # (prints: [2705829510])
    /// ```
    #[pyo3(signature = (symbols, model, *optional_model_params))]
    pub fn encode(
        &mut self,
        py: Python<'_>,
        symbols: &Bound<'_, PyAny>,
        model: &Model,
        optional_model_params: &Bound<'_, PyTuple>,
    ) -> PyResult<()> {
        // TODO: also allow encoding and decoding with model type instead of instance for
        // models that take no range.
        if let Ok(symbol) = symbols.extract::<i32>() {
            if !optional_model_params.is_empty() {
                return Err(pyo3::exceptions::PyValueError::new_err(
                    "To encode a single symbol, use a concrete model, i.e., pass the\n\
                    model parameters directly to the constructor of the model and not to the\n\
                    `encode` method of the entropy coder. Delaying the specification of model\n\
                    parameters until calling `encode` is only useful if you want to encode several\n\
                    symbols in a row with individual model parameters for each symbol. If this is\n\
                    what you're trying to do then the `symbols` argument should be a numpy array,\n\
                    not a scalar.",
                ));
            }
            return model.0.as_parameterized(py, &mut |model| {
                self.inner
                    .encode_symbol(symbol, EncoderDecoderModel(model))?;
                Ok(())
            });
        }

        // Don't use an `else` branch here because, if the following `extract` fails, the returned
        // error message is actually pretty user friendly.
        let symbols = symbols.extract::<PyReadonlyArray1<'_, i32>>()?;
        let symbols = symbols.as_array();

        if optional_model_params.is_empty() {
            model.0.as_parameterized(py, &mut |model| {
                self.inner
                    .encode_iid_symbols(symbols, EncoderDecoderModel(model))?;
                Ok(())
            })?;
        } else {
            if symbols.len()
                != model.0.len(
                    optional_model_params
                        .get_borrowed_item(0)
                        .expect("len checked above"),
                )?
            {
                return Err(pyo3::exceptions::PyValueError::new_err(
                    "`symbols` argument has wrong length.",
                ));
            }
            let mut symbol_iter = symbols.iter();
            model
                .0
                .parameterize(py, optional_model_params, false, &mut |model| {
                    let symbol = symbol_iter.next().expect("TODO");
                    self.inner
                        .encode_symbol(*symbol, EncoderDecoderModel(model))?;
                    Ok(())
                })?;
        }

        Ok(())
    }

    /// Creates a deep copy of the coder and returns it.
    ///
    /// The returned copy will initially encapsulate the identical compressed data as the
    /// original coder, but the two coders can be used independently without influencing
    /// other.
    #[pyo3(signature = ())]
    pub fn clone(&self) -> Self {
        Clone::clone(self)
    }
}

/// A decoder of data that was previously encoded with a `RangeEncoder`.
///
/// The constructor expects a single argument `compressed`, which has to be a rank-1 numpy array
/// with `dtype=np.uint32` that contains the compressed data (as returned by the method
/// [`get_compressed`](#constriction.stream.queue.RangeEncoder.get_compressed) of a `RangeEncoder`).
/// The provided compressed data gets *copied* into an internal buffer of the `RangeDecoder`.
///
/// To decode data with a `RangeDecoder`, call its method
/// [`decode`](#constriction.stream.queue.RangeDecoder.decode) one or more times. Each decoding
/// operation consumes some portion of the compressed data from the `RangeDecoder`'s internal
/// buffer.
///
/// ## Example
///
/// See [module level example](#example).
#[pyclass]
#[derive(Debug, Clone)]
pub struct RangeDecoder {
    inner: crate::stream::queue::DefaultRangeDecoder,
}

#[pymethods]
impl RangeDecoder {
    #[new]
    #[pyo3(signature = (compressed))]
    pub fn new(compressed: PyReadonlyArray1<'_, u32>) -> PyResult<Self> {
        Ok(Self::from_vec(array1_to_vec(compressed)))
    }

    /// Jumps to a checkpoint recorded with method
    /// [`pos`](#constriction.stream.queue.RangeEncoder.pos) during encoding.
    ///
    /// This allows random-access decoding. The arguments `position` and `state` are the two values
    /// returned by the `RangeEncoder`'s method [`pos`](#constriction.stream.queue.RangeEncoder.pos).
    ///
    /// ## Example
    ///
    /// ```python
    /// probabilities = np.array([0.2, 0.4, 0.1, 0.3], dtype=np.float32)
    /// model         = constriction.stream.model.Categorical(probabilities, perfect=False)
    /// message_part1 = np.array([1, 2, 0, 3, 2, 3, 0], dtype=np.int32)
    /// message_part2 = np.array([2, 2, 0, 1, 3], dtype=np.int32)
    ///
    /// # Encode both parts of the message and record a checkpoint in-between:
    /// encoder = constriction.stream.queue.RangeEncoder()
    /// encoder.encode(message_part1, model)
    /// (position, state) = encoder.pos() # Records a checkpoint.
    /// encoder.encode(message_part2, model)
    ///
    /// compressed = encoder.get_compressed()
    /// decoder = constriction.stream.queue.RangeDecoder(compressed)
    ///
    /// # Decode first symbol:
    /// print(decoder.decode(model)) # (prints: 1)
    ///
    /// # Jump to part 2 and decode it:
    /// decoder.seek(position, state)
    /// decoded_part2 = decoder.decode(model, 5)
    /// assert np.all(decoded_part2 == message_part2)
    /// ```
    #[pyo3(signature = (position, state))]
    pub fn seek(&mut self, position: usize, state: (u64, u64)) -> PyResult<()> {
        let (lower, range) = state;
        let state = RangeCoderState::new(lower, range)
            .map_err(|()| pyo3::exceptions::PyValueError::new_err("Invalid coder state."))?;
        self.inner.seek((position, state)).map_err(|()| {
            pyo3::exceptions::PyValueError::new_err("Tried to seek past end of stream.")
        })
    }

    /// Returns `True` if all compressed data *may* have already been decoded and `False` if there
    /// is definitely still some more data available to decode.
    ///
    /// A return value of `True` does not necessarily mean that there is no data left on the
    /// decoder because `constriction`'s range coding implementation--by design--cannot detect end-
    /// of-stream in all cases. If you need ot be able to decode variable-length messages then you
    /// can introduce an "end of stream" sentinel symbol, which you append to all messages before
    /// encoding them.
    #[pyo3(signature = ())]
    pub fn maybe_exhausted(&self) -> bool {
        self.inner.maybe_exhausted()
    }

    /// Decodes one or more symbols, consuming them from the encapsulated compressed data.
    ///
    /// This method can be called in 3 different ways:
    ///
    /// ## Option 1: decode(model)
    ///
    /// Decodes a *single* symbol with a concrete (i.e., fully parameterized) entropy model and
    /// returns the decoded symbol; (for optimal computational efficiency, don't use this option in
    /// a loop if you can instead use one of the two alternative options below.)
    ///
    /// For example:
    ///
    /// ```python
    /// # Define a concrete categorical entropy model over the (implied)
    /// # alphabet {0, 1, 2}:
    /// probabilities = np.array([0.1, 0.6, 0.3], dtype=np.float32)
    /// model = constriction.stream.model.Categorical(probabilities, perfect=False)
    ///
    /// # Decode a single symbol from some example compressed data:
    /// compressed = np.array([3089773345, 1894195597], dtype=np.uint32)
    /// decoder = constriction.stream.queue.RangeDecoder(compressed)
    /// symbol = decoder.decode(model)
    /// print(symbol) # (prints: 2)
    /// # ... then decode some more symbols ...
    /// ```
    ///
    /// ## Option 2: decode(model, amt) [where `amt` is an integer]
    ///
    /// Decodes `amt` i.i.d. symbols using the same concrete (i.e., fully parametrized) entropy
    /// model for each symbol, and returns the decoded symbols as a rank-1 numpy array with
    /// `dtype=np.int32` and length `amt`;
    ///
    /// For example:
    ///
    /// ```python
    /// # Use the same concrete entropy model as in the previous example:
    /// probabilities = np.array([0.1, 0.6, 0.3], dtype=np.float32)
    /// model = constriction.stream.model.Categorical(probabilities, perfect=False)
    ///
    /// # Decode 9 symbols from some example compressed data, using the
    /// # same (fixed) entropy model defined above for all symbols:
    /// compressed = np.array([369323598], dtype=np.uint32)
    /// decoder = constriction.stream.queue.RangeDecoder(compressed)
    /// symbols = decoder.decode(model, 9)
    /// print(symbols) # (prints: [0, 2, 1, 2, 0, 2, 0, 2, 1])
    /// ```
    ///
    /// ## Option 3: decode(model_family, params1, params2, ...)
    ///
    /// Decodes multiple symbols, using the same *family* of entropy models (e.g., categorical or
    /// quantized Gaussian) for all symbols, but with different model parameters for each symbol,
    /// and returns the decoded symbols as a rank-1 numpy array with `dtype=np.int32`; here, all
    /// `paramsX` arguments are arrays of equal length (the number of symbols to be decoded). The
    /// number of required `paramsX` arguments and their shapes and `dtype`s depend on the model
    /// family.
    ///
    /// For example, the
    /// [`QuantizedGaussian`](model.html#constriction.stream.model.QuantizedGaussian) model family
    /// expects two rank-1 model parameters with a float `dtype`, which specify the mean and
    /// standard deviation for each entropy model:
    ///
    /// ```python
    /// # Define a generic quantized Gaussian distribution for all integers
    /// # in the range from -100 to 100 (both ends inclusive):
    /// model_family = constriction.stream.model.QuantizedGaussian(-100, 100)
    ///
    /// # Specify the model parameters for each symbol:
    /// means = np.array([10.3, -4.7, 20.5], dtype=np.float32)
    /// stds  = np.array([ 5.2, 24.2,  3.1], dtype=np.float32)
    ///
    /// # Decode a message from some example compressed data:
    /// compressed = np.array([2655472005], dtype=np.uint32)
    /// decoder = constriction.stream.queue.RangeDecoder(compressed)
    /// symbols = decoder.decode(model_family, means, stds)
    /// print(symbols) # (prints: [12, -13, 25])
    /// ```
    ///
    /// By contrast, the [`Categorical`](model.html#constriction.stream.model.Categorical) model
    /// family expects a single rank-2 model parameter where the i'th row lists the
    /// probabilities for each possible value of the i'th symbol:
    ///
    /// ```python
    /// # Define 2 categorical models over the alphabet {0, 1, 2, 3, 4}:
    /// probabilities = np.array(
    ///     [[0.1, 0.2, 0.3, 0.1, 0.3],  # (for first decoded symbol)
    ///      [0.3, 0.2, 0.2, 0.2, 0.1]], # (for second decoded symbol)
    ///     dtype=np.float32)
    /// model_family = constriction.stream.model.Categorical(perfect=False)
    ///
    /// # Decode 2 symbols:
    /// compressed = np.array([2705829535], dtype=np.uint32)
    /// decoder = constriction.stream.queue.RangeDecoder(compressed)
    /// symbols = decoder.decode(model_family, probabilities)
    /// print(symbols) # (prints: [3, 1])
    /// ```
    #[pyo3(signature = (model, *optional_amt_or_model_params))]
    pub fn decode(
        &mut self,
        py: Python<'_>,
        model: &Model,
        optional_amt_or_model_params: &Bound<'_, PyTuple>,
    ) -> PyResult<Py<PyAny>> {
        match optional_amt_or_model_params.len() {
            0 => {
                let mut symbol = 0;
                model.0.as_parameterized(py, &mut |model| {
                    symbol = self.inner.decode_symbol(EncoderDecoderModel(model))?;
                    Ok(())
                })?;
                return Ok(symbol
                    .into_pyobject(py)
                    .unwrap_infallible()
                    .into_any()
                    .unbind());
            }
            1 => {
                if let Ok(amt) = optional_amt_or_model_params
                    .get_borrowed_item(0)
                    .expect("len checked above")
                    .extract::<usize>()
                {
                    let mut symbols = Vec::with_capacity(amt);
                    model.0.as_parameterized(py, &mut |model| {
                        for symbol in self
                            .inner
                            .decode_iid_symbols(amt, EncoderDecoderModel(model))
                        {
                            symbols.push(symbol?);
                        }
                        Ok(())
                    })?;
                    return Ok(PyArray1::from_iter(py, symbols).into_any().unbind());
                }
            }
            _ => {} // Fall through to code below.
        };

        let mut symbols = Vec::with_capacity(
            model.0.len(
                optional_amt_or_model_params
                    .get_borrowed_item(0)
                    .expect("len checked above"),
            )?,
        );
        model
            .0
            .parameterize(py, optional_amt_or_model_params, false, &mut |model| {
                let symbol = self.inner.decode_symbol(EncoderDecoderModel(model))?;
                symbols.push(symbol);
                Ok(())
            })?;

        Ok(PyArray1::from_vec(py, symbols).into_any().unbind())
    }

    /// Creates a deep copy of the coder and returns it.
    ///
    /// The returned copy will initially encapsulate the identical compressed data as the
    /// original coder, but the two coders can be used independently without influencing
    /// other.
    #[pyo3(signature = ())]
    pub fn clone(&self) -> Self {
        Clone::clone(self)
    }
}

impl RangeDecoder {
    pub fn from_vec(compressed: Vec<u32>) -> Self {
        let inner = crate::stream::queue::DefaultRangeDecoder::from_compressed(compressed)
            .unwrap_infallible();
        Self { inner }
    }
}

impl From<DecoderFrontendError> for pyo3::PyErr {
    fn from(err: DecoderFrontendError) -> Self {
        match err {
            DecoderFrontendError::InvalidData => {
                pyo3::exceptions::PyAssertionError::new_err(err.to_string())
            }
        }
    }
}