• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

agronholm / cbor2 / 23518655450

25 Mar 2026 12:19AM UTC coverage: 93.306% (-1.3%) from 94.565%
23518655450

Pull #278

github

web-flow
Merge cd482bb0d into 93c598838
Pull Request #278: Rust conversion

2175 of 2338 new or added lines in 7 files covered. (93.03%)

2272 of 2435 relevant lines covered (93.31%)

1556.06 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

91.22
/rust/decoder.rs
1
use crate::_cbor2::{BREAK_MARKER, SYS_MAXSIZE, UNDEFINED};
2
use crate::decoder::DecoderResult::{
3
    BeginFrame, CompleteFrame, ContinueFrame, Shareable, SharedReference, StringNamespace,
4
    StringReference, StringValue, Value,
5
};
6
#[cfg(not(Py_3_15))]
7
use crate::types::FrozenDict;
8
use crate::types::{
9
    BreakMarkerType, CBORDecodeEOF, CBORDecodeError, CBORSimpleValue, CBORTag, DECIMAL_TYPE,
10
    FRACTION_TYPE, IPV4ADDRESS_TYPE, IPV4INTERFACE_TYPE, IPV4NETWORK_TYPE, IPV6ADDRESS_TYPE,
11
    IPV6INTERFACE_TYPE, IPV6NETWORK_TYPE, UUID_TYPE,
12
};
13
use crate::utils::{PyImportable, create_exc_from, raise_exc_from};
14
use half::f16;
15
use pyo3::exceptions::{PyException, PyLookupError, PyTypeError, PyValueError};
16
use pyo3::prelude::*;
17
use pyo3::sync::PyOnceLock;
18
use pyo3::types::{
19
    PyBytes, PyCFunction, PyComplex, PyDict, PyFrozenSet, PyInt, PyList, PyListMethods, PyMapping,
20
    PySet, PyString, PyTuple,
21
};
22
use pyo3::{IntoPyObjectExt, Py, PyAny, PyErrArguments, intern, pyclass};
23
use std::fmt::{Display, Formatter};
24
use std::mem::{replace, take};
25

26
const IMMUTABLE_ATTR: &str = "_cbor2_immutable";
27
const NAME_ATTR: &str = "_cbor2_name";
28
const SEEK_CUR: u8 = 1;
29

30
static DATE_FROMISOFORMAT: PyImportable = PyImportable::new("datetime", "date.fromisoformat");
31
static DATE_FROMORDINAL: PyImportable = PyImportable::new("datetime", "date.fromordinal");
32
static DATETIME_FROMISOFORMAT: PyImportable =
33
    PyImportable::new("datetime", "datetime.fromisoformat");
34
static DATETIME_FROMTIMESTAMP: PyImportable =
35
    PyImportable::new("datetime", "datetime.fromtimestamp");
36
static EMAIL_PARSER: PyImportable = PyImportable::new("email.parser", "Parser");
37
static INCREMENTAL_UTF8_DECODER: PyOnceLock<Py<PyAny>> = PyOnceLock::new();
38
static INT_FROMBYTES: PyImportable = PyImportable::new("builtins", "int.from_bytes");
39
static IPADDRESS_FUNC: PyImportable = PyImportable::new("ipaddress", "ip_address");
40
static IPNETWORK_FUNC: PyImportable = PyImportable::new("ipaddress", "ip_network");
41
static IPINTERFACE_FUNC: PyImportable = PyImportable::new("ipaddress", "ip_interface");
42
static RE_COMPILE: PyImportable = PyImportable::new("re", "compile");
43
static UTC: PyImportable = PyImportable::new("datetime", "timezone.utc");
44
#[cfg(Py_3_15)]
45
static FROZEN_DICT: PyImportable = PyImportable::new("builtins", "frozendict");
46

47
enum DecoderResult<'a> {
48
    BeginFrame(
49
        Box<DecoderCallback<'a>>,
50
        bool,
51
        Option<Bound<'a, PyAny>>,
52
        DisplayName<'a>,
53
    ),
54
    ContinueFrame(bool),
55
    CompleteFrame(Bound<'a, PyAny>),
56
    Value(Bound<'a, PyAny>),
57
    StringValue(Bound<'a, PyAny>, usize),
58
    StringNamespace,
59
    StringReference(usize),
60
    Shareable,
61
    SharedReference(usize),
62
}
63

64
enum DisplayName<'a> {
65
    String(&'static str),
66
    SemanticTag(usize),
67
    PythonName(Bound<'a, PyAny>),
68
}
69

70
impl<'a> Display for DisplayName<'a> {
71
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
468✔
72
        match self {
468✔
73
            DisplayName::String(s) => f.write_str(s),
444✔
74
            DisplayName::SemanticTag(tagnum) => write!(f, "semantic tag {}", tagnum),
12✔
75
            DisplayName::PythonName(obj) => write!(f, "{}", obj),
12✔
76
        }
77
    }
468✔
78
}
79

80
type DecoderCallback<'py> =
81
    dyn 'py + FnMut(Bound<'py, PyAny>, bool) -> PyResult<DecoderResult<'py>>;
82

83
struct StackFrame<'py> {
84
    immutable: bool,
85
    decoder_callback: Option<Box<DecoderCallback<'py>>>,
86
    shareable_index: Option<usize>,
87
    typename: DisplayName<'py>,
88
    contains_string_namespace: bool,
89
}
90

91
/// Decorates a function to be a two-stage decoder.
92
///
93
/// :param name: the name displayed in a :exc:`CBORDecodeError` raised by the decoder
94
///     (e.g. "error decoding thingamajig") where name='thingamajig`)
95
/// :param immutable: :data:`True` if the item sent to the decoder should be decoded as immutable
96
#[pyfunction]
97
#[pyo3(signature = (func=None, /, *, name=None, immutable=false))]
98
pub fn shareable_decoder<'py>(
120✔
99
    py: Python<'py>,
120✔
100
    func: Option<Py<PyAny>>,
120✔
101
    name: Option<Py<PyString>>,
120✔
102
    immutable: bool,
120✔
103
) -> PyResult<Bound<'py, PyAny>> {
120✔
104
    match func {
120✔
105
        None => PyCFunction::new_closure(
60✔
106
            py,
60✔
107
            None,
60✔
108
            None,
60✔
109
            move |args: &Bound<'_, PyTuple>,
110
                  _kwargs: Option<&Bound<'_, PyDict>>|
111
                  -> PyResult<Py<PyAny>> {
60✔
112
                let py = args.py();
60✔
113
                let func = args.get_item(0)?;
60✔
114
                let name = name.as_ref().map(|x| x.clone_ref(py));
60✔
115
                shareable_decoder(py, Some(func.unbind()), name, immutable).map(Bound::unbind)
60✔
116
            },
60✔
117
        )
118
        .map(|f| f.into_any()),
60✔
119
        Some(func) => {
60✔
120
            let bound_func = func.bind(py);
60✔
121
            if !bound_func.is_callable() {
60✔
NEW
122
                return Err(PyTypeError::new_err(format!("{func} is not callable")));
×
123
            }
60✔
124
            bound_func.setattr(intern!(py, NAME_ATTR), name)?;
60✔
125
            bound_func.setattr(intern!(py, IMMUTABLE_ATTR), immutable)?;
60✔
126
            Ok(bound_func.clone().into_any())
60✔
127
        }
128
    }
129
}
120✔
130

131
fn require_tuple<'py>(value: Bound<'py, PyAny>, length: usize) -> PyResult<Bound<'py, PyTuple>> {
792✔
132
    let array: Bound<'py, PyTuple> = value
792✔
133
        .cast_into()
792✔
134
        .map_err(|_| PyTypeError::new_err("input value must be an array"))?;
792✔
135
    if array.len() != length {
756✔
NEW
136
        return Err(PyValueError::new_err(format!(
×
NEW
137
            "expected an array with exactly {length} elements"
×
NEW
138
        )));
×
139
    }
756✔
140
    Ok(array)
756✔
141
}
792✔
142

143
/// The CBORDecoder class implements a fully featured `CBOR`_ decoder with
144
/// several extensions for handling shared references, big integers, rational
145
/// numbers and so on. Typically, the class is not used directly, but the
146
/// :func:`load` and :func:`loads` functions are called to indirectly construct
147
/// and use the class.
148
///
149
/// When the class is constructed manually, the main entry point is :meth:`decode`.
150
///
151
/// :param fp: the file to read from (any file-like object opened for reading in binary mode)
152
/// :param tag_hook:
153
///     callable that takes 2 arguments: the decoder instance, and the :class:`.CBORTag`
154
///     to be decoded. This callback is invoked for any tags for which there is no
155
///     built-in decoder. The return value is substituted for the :class:`.CBORTag`
156
///     object in the deserialized output
157
/// :param object_hook:
158
///     callable that takes 2 arguments: the decoder instance, and a dictionary. This
159
///     callback is invoked for each deserialized :class:`dict` object. The return value
160
///     is substituted for the dict in the deserialized output.
161
/// :param semantic_decoders:
162
///     An optional mapping for overriding the decoding for select semantic tags.
163
///     The value is a mapping of semantic tags (integers) to callables that take
164
///     the decoder instance as the sole argument.
165
/// :param str_errors:
166
///     determines how to handle Unicode decoding errors (see the `Error Handlers`_
167
///     section in the standard library documentation for details)
168
/// :param read_size: minimum number of bytes to read at once
169
///     (ignored if ``fp`` is not seekable)
170
/// :param max_depth:
171
///     maximum allowed depth for nested containers
172
/// :param allow_indefinite:
173
///     if :data:`False`, raise a :exc:`CBORDecodeError` when encountering an indefinite-length
174
///     string or container in the input stream
175
///
176
/// .. _CBOR: https://cbor.io/
177
#[pyclass(module = "cbor2")]
178
pub struct CBORDecoder {
179
    fp: Option<Py<PyAny>>,
180
    tag_hook: Option<Py<PyAny>>,
181
    object_hook: Option<Py<PyAny>>,
182
    semantic_decoders: Option<Py<PyMapping>>,
183
    str_errors: Option<Py<PyString>>,
184
    #[pyo3(get)]
185
    read_size: usize,
186
    #[pyo3(get)]
187
    max_depth: usize,
188
    #[pyo3(get)]
189
    allow_indefinite: bool,
190

191
    read_method: Option<Py<PyAny>>,
192
    buffer: Option<Py<PyBytes>>,
193
    read_position: usize,
194
    available_bytes: usize,
195
    fp_is_seekable: bool,
196
}
197

198
impl CBORDecoder {
199
    pub fn new_internal(
4,440✔
200
        py: Python<'_>,
4,440✔
201
        fp: Option<&Bound<'_, PyAny>>,
4,440✔
202
        buffer: Option<Bound<PyBytes>>,
4,440✔
203
        tag_hook: Option<&Bound<'_, PyAny>>,
4,440✔
204
        object_hook: Option<&Bound<'_, PyAny>>,
4,440✔
205
        semantic_decoders: Option<&Bound<'_, PyMapping>>,
4,440✔
206
        str_errors: &str,
4,440✔
207
        read_size: usize,
4,440✔
208
        max_depth: usize,
4,440✔
209
        allow_indefinite: bool,
4,440✔
210
    ) -> PyResult<Self> {
4,440✔
211
        let available_bytes = if let Some(buffer) = buffer.as_ref() {
4,440✔
212
            buffer.len()?
4,056✔
213
        } else {
214
            0
384✔
215
        };
216
        let bound_str_errors = PyString::new(py, str_errors);
4,440✔
217
        let mut this = Self {
4,440✔
218
            fp: None,
4,440✔
219
            tag_hook: None,
4,440✔
220
            object_hook: None,
4,440✔
221
            str_errors: None,
4,440✔
222
            read_size,
4,440✔
223
            max_depth,
4,440✔
224
            allow_indefinite,
4,440✔
225
            semantic_decoders: semantic_decoders.map(|d| d.clone().unbind()),
4,440✔
226
            read_method: None,
4,440✔
227
            buffer: buffer.map(Bound::unbind),
4,440✔
228
            read_position: 0,
229
            available_bytes,
4,440✔
230
            fp_is_seekable: false,
231
        };
232
        if let Some(fp) = fp {
4,440✔
233
            this.set_fp(fp)?
384✔
234
        };
4,056✔
235
        this.set_tag_hook(tag_hook)?;
4,416✔
236
        this.set_object_hook(object_hook)?;
4,404✔
237
        this.set_str_errors(&bound_str_errors)?;
4,392✔
238
        Ok(this)
4,380✔
239
    }
4,440✔
240

241
    fn read_from_fp<'py>(
384✔
242
        &mut self,
384✔
243
        py: Python<'py>,
384✔
244
        minimum_amount: usize,
384✔
245
    ) -> PyResult<(Bound<'py, PyBytes>, usize)> {
384✔
246
        let read_size: usize = if self.fp_is_seekable {
384✔
247
            self.read_size
252✔
248
        } else {
249
            1
132✔
250
        };
251
        let bytes_to_read = minimum_amount.max(read_size);
384✔
252
        let num_read_bytes = if let Some(read) = self.read_method.as_ref() {
384✔
253
            let bytes_from_fp: Bound<PyBytes> =
276✔
254
                read.bind(py).call1((&bytes_to_read,))?.cast_into()?;
276✔
255
            let num_read_bytes = bytes_from_fp.len()?;
276✔
256
            if num_read_bytes >= minimum_amount {
276✔
257
                return Ok((bytes_from_fp, num_read_bytes));
228✔
258
            }
48✔
259
            num_read_bytes
48✔
260
        } else {
261
            0
108✔
262
        };
263
        Err(CBORDecodeEOF::new_err(format!(
156✔
264
            "premature end of stream (expected to read at least {minimum_amount} \
156✔
265
                 bytes, got {num_read_bytes} instead)"
156✔
266
        )))
156✔
267
    }
384✔
268

269
    fn read_exact<const N: usize>(&mut self, py: Python<'_>) -> PyResult<[u8; N]> {
35,508✔
270
        if self.available_bytes == 0 {
35,508✔
271
            // No buffer
272
            let (new_bytes, amount_read) = self.read_from_fp(py, N)?;
240✔
273
            self.read_position = N;
216✔
274
            self.available_bytes = amount_read - N;
216✔
275
            self.buffer = Some(new_bytes.unbind());
216✔
276
            Ok(self.buffer.as_ref().unwrap().as_bytes(py)[..N].try_into()?)
216✔
277
        } else if self.available_bytes < N {
35,268✔
278
            // Combine the remnants of the partial buffer with new data read from the file
NEW
279
            let needed_bytes = N - self.available_bytes;
×
NEW
280
            let mut concatenated_buffer: Vec<u8> = self.buffer.take().unwrap().extract(py)?;
×
NEW
281
            let (new_bytes, amount_read) = self.read_from_fp(py, needed_bytes)?;
×
NEW
282
            concatenated_buffer.extend_from_slice(&new_bytes[..needed_bytes]);
×
NEW
283
            self.buffer = Some(new_bytes.unbind());
×
NEW
284
            self.available_bytes = amount_read - needed_bytes;
×
NEW
285
            self.read_position = needed_bytes;
×
NEW
286
            Ok(concatenated_buffer.try_into().unwrap())
×
287
        } else {
288
            // Return a slice from the existing bytes object
289
            let slice: [u8; N] = self.buffer.as_ref().unwrap().bind(py).as_bytes()
35,268✔
290
                [self.read_position..self.read_position + N]
35,268✔
291
                .try_into()?;
35,268✔
292
            self.available_bytes -= N;
35,268✔
293
            self.read_position += N;
35,268✔
294
            Ok(slice)
35,268✔
295
        }
296
    }
35,508✔
297

298
    fn read_major_and_subtype(&mut self, py: Python<'_>) -> PyResult<(u8, u8)> {
29,856✔
299
        let initial_byte = self.read_exact::<1>(py)?[0];
29,856✔
300
        let major_type = initial_byte >> 5;
29,832✔
301
        let subtype = initial_byte & 31;
29,832✔
302
        Ok((major_type, subtype))
29,832✔
303
    }
29,856✔
304

305
    fn decode_length_finite(&mut self, py: Python<'_>, subtype: u8) -> PyResult<usize> {
7,680✔
306
        match self.decode_length(py, subtype)? {
7,680✔
307
            Some(length) => Ok(length),
7,644✔
308
            None => Err(CBORDecodeError::new_err(
24✔
309
                "indefinite length not allowed here",
24✔
310
            )),
24✔
311
        }
312
    }
7,680✔
313
    //
314
    // Decoders for major tags (0-7)
315
    //
316

317
    /// Decode the length of the next item.
318
    ///
319
    /// This is a low-level operation that may be needed by custom decoder callbacks.
320
    ///
321
    /// :param subtype:
322
    /// :return: the length of the item, or :data:`None` to indicate an indefinite-length item
323
    fn decode_length(&mut self, py: Python<'_>, subtype: u8) -> PyResult<Option<usize>> {
27,360✔
324
        let length = match subtype {
27,360✔
325
            ..24 => Some(subtype as usize),
27,360✔
326
            24 => Some(self.read_exact::<1>(py)?[0] as usize),
2,112✔
327
            25 => Some(u16::from_be_bytes(self.read_exact(py)?) as usize),
1,572✔
328
            26 => Some(u32::from_be_bytes(self.read_exact(py)?) as usize),
420✔
329
            27 => Some(u64::from_be_bytes(self.read_exact(py)?) as usize),
228✔
330
            31 => {
331
                if !self.allow_indefinite {
360✔
332
                    return Err(CBORDecodeError::new_err(
12✔
333
                        "encountered indefinite length but it has been disabled",
12✔
334
                    ));
12✔
335
                }
348✔
336
                None
348✔
337
            }
338
            _ => {
339
                return Err(CBORDecodeError::new_err(format!(
12✔
340
                    "unknown unsigned integer subtype 0x{subtype:x}"
12✔
341
                )));
12✔
342
            }
343
        };
344
        Ok(length)
27,336✔
345
    }
27,360✔
346

347
    fn decode_uint<'py>(&mut self, py: Python<'py>, subtype: u8) -> PyResult<DecoderResult<'py>> {
3,300✔
348
        // Major tag 0
349
        let uint = self.decode_length_finite(py, subtype)?;
3,300✔
350
        Ok(Value(uint.into_bound_py_any(py)?))
3,288✔
351
    }
3,300✔
352

353
    fn decode_negint<'py>(&mut self, py: Python<'py>, subtype: u8) -> PyResult<DecoderResult<'py>> {
768✔
354
        // Major tag 1
355
        let uint = self.decode_length_finite(py, subtype)?;
768✔
356
        let signed_int = -(uint as i128) - 1;
768✔
357
        Ok(Value(signed_int.into_bound_py_any(py)?))
768✔
358
    }
768✔
359

360
    fn decode_bytestring<'py>(
1,128✔
361
        &mut self,
1,128✔
362
        py: Python<'py>,
1,128✔
363
        subtype: u8,
1,128✔
364
    ) -> PyResult<DecoderResult<'py>> {
1,128✔
365
        // Major tag 2
366
        match self.decode_length(py, subtype)? {
1,128✔
367
            None => {
368
                // Indefinite length
369
                let mut bytes = PyBytes::new(py, b"");
72✔
370
                let sys_maxsize = *SYS_MAXSIZE.get(py).unwrap();
72✔
371
                loop {
372
                    let (major_type, subtype) = self.read_major_and_subtype(py)?;
120✔
373
                    match (major_type, subtype) {
120✔
374
                        (2, _) => {
375
                            let length = self.decode_length_finite(py, subtype)?;
84✔
376
                            if length > sys_maxsize {
72✔
377
                                return Err(CBORDecodeError::new_err(format!(
12✔
378
                                    "chunk too long in an indefinite bytestring chunk: {length}"
12✔
379
                                )));
12✔
380
                            }
60✔
381
                            let chunk = self.read(py, length)?;
60✔
382
                            bytes = bytes.add(chunk)?.cast_into()?;
48✔
383
                        }
384
                        (7, 31) => break Ok(Value(bytes.into_any())), // break marker
12✔
385
                        _ => {
386
                            return Err(CBORDecodeError::new_err(format!(
24✔
387
                                "non-byte string (major type {major_type}) found in indefinite \
24✔
388
                                    length byte string"
24✔
389
                            )));
24✔
390
                        }
391
                    }
392
                }
393
            }
394
            Some(length) if length <= 65536 => {
1,056✔
395
                let bytes = self.read(py, length)?;
1,032✔
396
                Ok(StringValue(PyBytes::new(py, &bytes).into_any(), length))
996✔
397
            }
398
            Some(length) => {
24✔
399
                // Incrementally read the bytestring, in chunks of 65536 bytes
400
                let mut bytes = PyBytes::new(py, b"");
24✔
401
                let mut remaining_length = length;
24✔
402
                while remaining_length > 0 {
48✔
403
                    let chunk_size = remaining_length.min(65536);
36✔
404
                    let chunk = self.read(py, chunk_size)?;
36✔
405
                    remaining_length -= chunk_size;
24✔
406
                    bytes = bytes.add(chunk)?.cast_into()?;
24✔
407
                }
408
                Ok(StringValue(bytes.into_any(), length))
12✔
409
            }
410
        }
411
    }
1,128✔
412

413
    fn decode_string<'py>(&mut self, py: Python<'py>, subtype: u8) -> PyResult<DecoderResult<'py>> {
2,232✔
414
        // Major tag 3
415
        match self.decode_length(py, subtype)? {
2,232✔
416
            None => {
417
                // Indefinite length
418
                let mut string = PyString::new(py, "");
96✔
419
                loop {
420
                    let (major_type, subtype) = self.read_major_and_subtype(py)?;
168✔
421
                    let sys_maxsize = *SYS_MAXSIZE.get(py).unwrap();
168✔
422
                    match (major_type, subtype) {
168✔
423
                        (3, _) => {
424
                            let length = self.decode_length_finite(py, subtype)?;
120✔
425
                            if length > sys_maxsize {
108✔
426
                                return Err(CBORDecodeError::new_err(format!(
12✔
427
                                    "chunk too long in an indefinite text string chunk: {length}"
12✔
428
                                )));
12✔
429
                            }
96✔
430
                            let bytes = self.read(py, length)?;
96✔
431
                            let decoded = match self.str_errors.as_ref() {
84✔
432
                                None => PyString::from_bytes(py, bytes.as_slice()),
84✔
NEW
433
                                Some(str_errors) => bytes
×
NEW
434
                                    .into_bound_py_any(py)?
×
NEW
435
                                    .call_method1(
×
NEW
436
                                        intern!(py, "decode"),
×
NEW
437
                                        (intern!(py, "utf-8"), str_errors),
×
438
                                    )
NEW
439
                                    .and_then(|string| {
×
NEW
440
                                        string.cast_into().map_err(|e| PyErr::from(e))
×
NEW
441
                                    }),
×
442
                            }?;
12✔
443
                            string = string.add(decoded)?.cast_into()?;
72✔
444
                        }
445
                        (7, 31) => break Ok(Value(string.into_any())), // break marker
24✔
446
                        _ => {
447
                            return Err(CBORDecodeError::new_err(format!(
24✔
448
                                "non-text string (major type {major_type}) found in indefinite \
24✔
449
                                    length text string"
24✔
450
                            )));
24✔
451
                        }
452
                    }
453
                }
454
            }
455
            Some(length) if length <= 65536 => {
2,124✔
456
                let bytes = self.read(py, length)?;
2,076✔
457
                let decoded_string: Bound<'_, PyAny> = match self.str_errors.as_ref() {
2,028✔
458
                    None => PyString::from_bytes(py, bytes.as_slice())?.into_any(),
2,004✔
459
                    Some(str_errors) => bytes.into_bound_py_any(py)?.call_method1(
24✔
460
                        intern!(py, "decode"),
24✔
461
                        (intern!(py, "utf-8"), str_errors.bind(py)),
24✔
NEW
462
                    )?,
×
463
                };
464
                Ok(StringValue(decoded_string, length))
1,992✔
465
            }
466
            Some(mut length) => {
48✔
467
                // Incrementally decode the string, in chunks of 65536 bytes
468
                let decoder_class = INCREMENTAL_UTF8_DECODER
48✔
469
                    .get_or_try_init(py, || -> PyResult<Py<PyAny>> {
48✔
470
                        let decoder = py
12✔
471
                            .import("codecs")?
12✔
472
                            .getattr("lookup")?
12✔
473
                            .call1(("utf-8",))?
12✔
474
                            .getattr("incrementaldecoder")?;
12✔
475
                        Ok(decoder.unbind())
12✔
476
                    })?
12✔
477
                    .bind(py);
48✔
478
                let decoder = match self.str_errors.as_ref() {
48✔
479
                    None => decoder_class.call0()?,
24✔
480
                    Some(str_errors) => decoder_class.call1((str_errors,))?,
24✔
481
                };
482
                let mut string = PyString::new(py, "").into_any();
48✔
483
                while length > 0 {
168✔
484
                    let chunk_size = length.min(65536);
120✔
485
                    let chunk = self.read(py, chunk_size)?;
120✔
486
                    length -= chunk_size;
120✔
487
                    let is_final_chunk = length == 0;
120✔
488
                    let decoded_chunk =
120✔
489
                        decoder.call_method1(intern!(py, "decode"), (chunk, is_final_chunk))?;
120✔
490
                    string = string.add(decoded_chunk)?;
120✔
491
                }
492
                Ok(StringValue(string.into_any(), length))
48✔
493
            }
494
        }
495
    }
2,232✔
496

497
    fn decode_array<'py>(
14,580✔
498
        &mut self,
14,580✔
499
        py: Python<'py>,
14,580✔
500
        subtype: u8,
14,580✔
501
        immutable: bool,
14,580✔
502
    ) -> PyResult<DecoderResult<'py>> {
14,580✔
503
        // Major tag 4
504
        let optional_length = self.decode_length(py, subtype)?;
14,580✔
505
        if immutable {
14,580✔
506
            let mut items: Vec<Bound<'py, PyAny>> = Vec::new();
1,500✔
507
            let callback: Box<DecoderCallback<'py>> = if let Some(length) = optional_length {
1,500✔
508
                if length == 0 {
1,476✔
509
                    return Ok(Value(PyTuple::empty(py).into_any()));
36✔
510
                }
1,440✔
511

512
                Box::new(move |item: Bound<'py, PyAny>, _immutable: bool| {
3,048✔
513
                    items.push(item);
3,048✔
514
                    if items.len() == length {
3,048✔
515
                        Ok(CompleteFrame(
516
                            PyTuple::new(py, take(&mut items))?.into_any(),
1,392✔
517
                        ))
518
                    } else {
519
                        Ok(ContinueFrame(false))
1,656✔
520
                    }
521
                })
3,048✔
522
            } else {
523
                Box::new(move |item: Bound<'py, PyAny>, _immutable: bool| {
72✔
524
                    if item.is_exact_instance_of::<BreakMarkerType>() {
72✔
525
                        Ok(CompleteFrame(
526
                            PyTuple::new(py, take(&mut items))?.into_any(),
12✔
527
                        ))
528
                    } else {
529
                        items.push(item);
60✔
530
                        Ok(ContinueFrame(false))
60✔
531
                    }
532
                })
72✔
533
            };
534
            Ok(BeginFrame(
1,464✔
535
                callback,
1,464✔
536
                false,
1,464✔
537
                None,
1,464✔
538
                DisplayName::String("array"),
1,464✔
539
            ))
1,464✔
540
        } else {
541
            let mut list = PyList::empty(py);
13,080✔
542
            let container = list.clone().into_any();
13,080✔
543
            let callback: Box<DecoderCallback<'py>> = if let Some(length) = optional_length {
13,080✔
544
                if length == 0 {
12,984✔
545
                    return Ok(Value(PyList::empty(py).into_any()));
36✔
546
                }
12,948✔
547

548
                Box::new(move |item, _immutable: bool| {
12,948✔
549
                    list.append(item)?;
2,208✔
550
                    if list.len() == length {
2,208✔
551
                        Ok(CompleteFrame(
780✔
552
                            replace(&mut list, PyList::empty(py)).into_any(),
780✔
553
                        ))
780✔
554
                    } else {
555
                        Ok(ContinueFrame(false))
1,428✔
556
                    }
557
                })
2,208✔
558
            } else {
559
                Box::new(move |item: Bound<'py, PyAny>, _immutable: bool| {
564✔
560
                    if item.is_exact_instance_of::<BreakMarkerType>() {
564✔
561
                        Ok(CompleteFrame(
96✔
562
                            replace(&mut list, PyList::empty(py)).into_any(),
96✔
563
                        ))
96✔
564
                    } else {
565
                        list.append(item)?;
468✔
566
                        Ok(ContinueFrame(false))
468✔
567
                    }
568
                })
564✔
569
            };
570
            Ok(BeginFrame(
13,044✔
571
                callback,
13,044✔
572
                false,
13,044✔
573
                Some(container),
13,044✔
574
                DisplayName::String("array"),
13,044✔
575
            ))
13,044✔
576
        }
577
    }
14,580✔
578

579
    fn decode_map<'py>(
1,740✔
580
        &mut self,
1,740✔
581
        py: Python<'py>,
1,740✔
582
        subtype: u8,
1,740✔
583
        immutable: bool,
1,740✔
584
    ) -> PyResult<DecoderResult<'py>> {
1,740✔
585
        // Major tag 5
586

587
        #[cfg(Py_3_15)]
588
        fn create_frozen_dict<'py>(
12✔
589
            py: Python<'py>,
12✔
590
            items: Vec<(Bound<'py, PyAny>, Bound<'py, PyAny>)>,
12✔
591
        ) -> PyResult<Bound<'py, PyAny>> {
12✔
592
            FROZEN_DICT
12✔
593
                .get(py)?
12✔
594
                .call1((items,))?
12✔
595
                .cast_into()
12✔
596
                .map_err(|e| PyErr::from(e))
12✔
597
        }
12✔
598
        #[cfg(not(Py_3_15))]
599
        fn create_frozen_dict<'py>(
132✔
600
            py: Python<'py>,
132✔
601
            items: Vec<(Bound<'py, PyAny>, Bound<'py, PyAny>)>,
132✔
602
        ) -> PyResult<Bound<'py, PyAny>> {
132✔
603
            FrozenDict::from_items(py, items).map(|dict| dict.into_any())
132✔
604
        }
132✔
605

606
        #[inline]
607
        fn maybe_call_object_hook<'py>(
1,584✔
608
            py: Python<'py>,
1,584✔
609
            dict: Bound<'py, PyAny>,
1,584✔
610
            object_hook: Option<&Py<PyAny>>,
1,584✔
611
            immutable: bool,
1,584✔
612
        ) -> PyResult<Bound<'py, PyAny>> {
1,584✔
613
            if let Some(object_hook) = object_hook {
1,584✔
614
                object_hook.bind(py).call1((dict, immutable))
24✔
615
            } else {
616
                Ok(dict)
1,560✔
617
            }
618
        }
1,584✔
619

620
        let object_hook = self.object_hook.as_ref().map(|hook| hook.clone_ref(py));
1,740✔
621
        let length_or_none = self.decode_length(py, subtype)?;
1,740✔
622

623
        // Return immediately if this is an empty dict
624
        if let Some(length) = length_or_none
1,740✔
625
            && length == 0
1,704✔
626
        {
627
            let container: Bound<'py, PyAny> = if immutable {
396✔
NEW
628
                create_frozen_dict(py, Vec::new())?
×
629
            } else {
630
                PyDict::new(py).into_any()
396✔
631
            };
632
            let transformed =
396✔
633
                maybe_call_object_hook(py, container, object_hook.as_ref(), immutable)?;
396✔
634
            return Ok(Value(transformed));
396✔
635
        };
1,344✔
636

637
        let mut key: Option<Bound<'py, PyAny>> = None;
1,344✔
638
        if immutable {
1,344✔
639
            let mut items: Vec<(Bound<'py, PyAny>, Bound<'py, PyAny>)> = Vec::new();
276✔
640
            let callback: Box<DecoderCallback<'py>> = if let Some(length) = length_or_none {
276✔
641
                Box::new(move |item: Bound<'py, PyAny>, _immutable: bool| {
348✔
642
                    if let Some(key) = key.take() {
348✔
643
                        items.push((key, item));
168✔
644
                        if items.len() == length {
168✔
645
                            let transformed = maybe_call_object_hook(
144✔
646
                                py,
144✔
647
                                create_frozen_dict(py, take(&mut items))?,
144✔
648
                                object_hook.as_ref(),
144✔
649
                                immutable,
144✔
NEW
650
                            )?;
×
651
                            return Ok(CompleteFrame(transformed));
144✔
652
                        }
24✔
653
                        Ok(ContinueFrame(true))
24✔
654
                    } else {
655
                        key = Some(item);
180✔
656
                        Ok(ContinueFrame(false))
180✔
657
                    }
658
                })
348✔
659
            } else {
NEW
660
                Box::new(move |item: Bound<'py, PyAny>, _immutable: bool| {
×
NEW
661
                    if item.is_exact_instance_of::<BreakMarkerType>() {
×
NEW
662
                        let container = create_frozen_dict(py, take(&mut items))?;
×
NEW
663
                        let transformed = maybe_call_object_hook(
×
NEW
664
                            py,
×
NEW
665
                            container.into_any(),
×
NEW
666
                            object_hook.as_ref(),
×
NEW
667
                            immutable,
×
NEW
668
                        )?;
×
NEW
669
                        return Ok(CompleteFrame(transformed));
×
NEW
670
                    } else if let Some(key) = key.take() {
×
NEW
671
                        items.push((key, item));
×
NEW
672
                        Ok(ContinueFrame(true))
×
673
                    } else {
NEW
674
                        key = Some(item);
×
NEW
675
                        Ok(ContinueFrame(false))
×
676
                    }
NEW
677
                })
×
678
            };
679
            Ok(BeginFrame(callback, true, None, DisplayName::String("map")))
276✔
680
        } else {
681
            let mut dict = PyDict::new(py);
1,068✔
682
            let container = dict.clone().into_any();
1,068✔
683
            let callback: Box<DecoderCallback<'py>> = if let Some(length) = length_or_none {
1,068✔
684
                Box::new(move |item: Bound<'py, PyAny>, _immutable: bool| {
3,120✔
685
                    if let Some(key) = key.take() {
3,120✔
686
                        dict.set_item(key, item)?;
1,560✔
687
                        if dict.len() == length {
1,560✔
688
                            let dict = replace(&mut dict, PyDict::new(py));
1,008✔
689
                            let transformed = maybe_call_object_hook(
1,008✔
690
                                py,
1,008✔
691
                                dict.into_any(),
1,008✔
692
                                object_hook.as_ref(),
1,008✔
693
                                immutable,
1,008✔
694
                            )?;
12✔
695
                            return Ok(CompleteFrame(transformed));
996✔
696
                        }
552✔
697
                        Ok(ContinueFrame(true))
552✔
698
                    } else {
699
                        key = Some(item);
1,560✔
700
                        Ok(ContinueFrame(false))
1,560✔
701
                    }
702
                })
3,120✔
703
            } else {
704
                Box::new(move |item: Bound<'py, PyAny>, _immutable: bool| {
156✔
705
                    if item.is_exact_instance_of::<BreakMarkerType>() {
156✔
706
                        let dict = replace(&mut dict, PyDict::new(py));
36✔
707
                        let transformed = maybe_call_object_hook(
36✔
708
                            py,
36✔
709
                            dict.into_any(),
36✔
710
                            object_hook.as_ref(),
36✔
711
                            immutable,
36✔
NEW
712
                        )?;
×
713
                        return Ok(CompleteFrame(transformed));
36✔
714
                    } else if let Some(key) = key.take() {
120✔
715
                        dict.set_item(key, item)?;
60✔
716
                        Ok(ContinueFrame(true))
60✔
717
                    } else {
718
                        key = Some(item);
60✔
719
                        Ok(ContinueFrame(false))
60✔
720
                    }
721
                })
156✔
722
            };
723
            Ok(BeginFrame(
1,068✔
724
                callback,
1,068✔
725
                true,
1,068✔
726
                Some(container),
1,068✔
727
                DisplayName::String("map"),
1,068✔
728
            ))
1,068✔
729
        }
730
    }
1,740✔
731

732
    fn decode_semantic<'py>(
3,408✔
733
        &mut self,
3,408✔
734
        py: Python<'py>,
3,408✔
735
        subtype: u8,
3,408✔
736
        immutable: bool,
3,408✔
737
    ) -> PyResult<DecoderResult<'py>> {
3,408✔
738
        let tagnum = self.decode_length_finite(py, subtype)?;
3,408✔
739
        if let Some(semantic_decoders) = &self.semantic_decoders {
3,408✔
740
            match semantic_decoders.bind(py).get_item(&tagnum) {
120✔
741
                Ok(decoder) => {
96✔
742
                    let name = decoder.getattr_opt(intern!(py, NAME_ATTR))?;
96✔
743

744
                    // If these attributes are present, this callable was decorated with
745
                    // @shareable_decoder
746
                    return if let Some(name) = name {
96✔
747
                        let require_immutable: bool = decoder
60✔
748
                            .getattr_opt(intern!(py, IMMUTABLE_ATTR))?
60✔
749
                            .map(|x| x.is_truthy())
60✔
750
                            .transpose()?
60✔
751
                            .unwrap_or(false);
60✔
752
                        let retval = decoder.call1((immutable,))?;
60✔
753
                        let tuple: Bound<'_, PyTuple> = retval.cast_into()?;
60✔
754
                        if tuple.len() != 2 {
60✔
NEW
755
                            return Err(CBORDecodeError::new_err(format!(
×
NEW
756
                                "{decoder} returned a tuple of {} items, expected 2",
×
NEW
757
                                tuple.len()
×
NEW
758
                            )));
×
759
                        }
60✔
760
                        let container: Bound<'_, PyAny> = tuple.get_item(0)?.cast_into()?;
60✔
761
                        let callback: Bound<'_, PyAny> = tuple.get_item(1)?.cast_into()?;
60✔
762
                        Ok(BeginFrame(
763
                            Box::new(
60✔
764
                                move |item, _immutable: bool| -> PyResult<DecoderResult<'py>> {
60✔
765
                                    callback.call1((item,)).map(CompleteFrame)
60✔
766
                                },
60✔
767
                            ),
768
                            require_immutable,
60✔
769
                            if container.is_none() {
60✔
770
                                None
48✔
771
                            } else {
772
                                Some(container)
12✔
773
                            },
774
                            if name.is_none() {
60✔
775
                                DisplayName::SemanticTag(tagnum)
12✔
776
                            } else {
777
                                DisplayName::PythonName(name.clone())
48✔
778
                            },
779
                        ))
780
                    } else {
781
                        let callback =
36✔
782
                            move |item, new_immutable: bool| -> PyResult<DecoderResult<'py>> {
36✔
783
                                decoder.call1((item, new_immutable)).map(CompleteFrame)
36✔
784
                            };
36✔
785
                        Ok(BeginFrame(
36✔
786
                            Box::new(callback),
36✔
787
                            immutable,
36✔
788
                            None,
36✔
789
                            DisplayName::SemanticTag(tagnum),
36✔
790
                        ))
36✔
791
                    };
792
                }
793
                Err(e) if e.is_instance_of::<PyLookupError>(py) => {}
24✔
NEW
794
                Err(e) => return Err(e),
×
795
            }
796
        };
3,288✔
797

798
        // No semantic decoder lookup map – fall back to the hard coded switchboard
799
        let (callback, typename): (Box<DecoderCallback<'py>>, &str) = match tagnum {
3,312✔
800
            0 => (
456✔
801
                Box::new(Self::decode_datetime_string),
456✔
802
                "string-form datetime",
456✔
803
            ),
456✔
804
            1 => (Box::new(Self::decode_epoch_datetime), "epoch-form datetime"),
60✔
805
            2 => (Box::new(Self::decode_positive_bignum), "positive bignum"),
132✔
806
            3 => (Box::new(Self::decode_negative_bignum), "negative bignum"),
36✔
807
            4 => (Box::new(Self::decode_fraction), "decimal fraction"),
264✔
808
            5 => (Box::new(Self::decode_bigfloat), "bigfloat"),
24✔
809
            25 => (Box::new(Self::decode_stringref), "string reference"),
96✔
810
            28 => return Ok(Shareable),
240✔
811
            29 => (Box::new(Self::decode_sharedref), "shared reference"),
180✔
812
            30 => (Box::new(Self::decode_rational), "rational"),
252✔
813
            35 => (Box::new(Self::decode_regexp), "regular expression"),
36✔
814
            36 => (Box::new(Self::decode_mime), "MIME message"),
36✔
815
            37 => (Box::new(Self::decode_uuid), "UUID"),
300✔
816
            52 => (Box::new(Self::decode_ipv4), "IPv4 address"),
120✔
817
            54 => (Box::new(Self::decode_ipv6), "IPv6 address"),
72✔
818
            100 => (Box::new(Self::decode_epoch_date), "epoch-form date"),
12✔
819
            256 => return Ok(StringNamespace),
36✔
820
            258 => return self.decode_set(py, immutable),
408✔
821
            260 => (Box::new(Self::decode_ipaddress), "IP address"),
84✔
822
            261 => (Box::new(Self::decode_ipnetwork), "IP network"),
84✔
823
            1004 => (Box::new(Self::decode_date_string), "string-form date"),
12✔
824
            43000 => (Box::new(Self::decode_complex), "complex number"),
252✔
825
            55799 => (
24✔
826
                Box::new(Self::decode_self_describe_cbor),
24✔
827
                "self-described CBOR value",
24✔
828
            ),
24✔
829
            _ => {
830
                // For a tag with no designated decoder, check if we have a tag hook, and call
831
                // that with the tag object, using its return value as the decoded value.
832
                let tag = CBORTag::new(tagnum.into_bound_py_any(py)?, py.None().into_bound(py))?;
96✔
833
                let bound_tag = Bound::new(py, tag)?.into_any();
96✔
834
                let container = bound_tag.clone();
96✔
835
                let mut tag_hook = self
96✔
836
                    .tag_hook
96✔
837
                    .as_ref()
96✔
838
                    .map(|hook| hook.clone_ref(py).into_bound(py));
96✔
839
                let callback = Box::new(move |item: Bound<'py, PyAny>, _immutable: bool| {
96✔
840
                    let tag: &Bound<'py, CBORTag> = bound_tag.cast()?;
84✔
841
                    tag.borrow_mut().value = item.unbind();
84✔
842
                    if let Some(tag_hook) = tag_hook.take() {
84✔
843
                        tag_hook.call1((&bound_tag, immutable)).map(CompleteFrame)
60✔
844
                    } else {
845
                        Ok(CompleteFrame(bound_tag.clone()))
24✔
846
                    }
847
                });
84✔
848
                return Ok(BeginFrame(
96✔
849
                    callback,
96✔
850
                    true,
96✔
851
                    Some(container),
96✔
852
                    DisplayName::SemanticTag(tagnum),
96✔
853
                ));
96✔
854
            }
855
        };
856
        Ok(BeginFrame(
2,532✔
857
            callback,
2,532✔
858
            true,
2,532✔
859
            None,
2,532✔
860
            DisplayName::String(typename),
2,532✔
861
        ))
2,532✔
862
    }
3,408✔
863

864
    fn decode_special<'py>(
2,388✔
865
        &mut self,
2,388✔
866
        py: Python<'py>,
2,388✔
867
        subtype: u8,
2,388✔
868
    ) -> PyResult<DecoderResult<'py>> {
2,388✔
869
        // Major tag 7
870
        match subtype {
2,388✔
871
            0..20 => {
2,388✔
872
                let value = subtype.into_pyobject(py)?;
72✔
873
                CBORSimpleValue::new(value)?.into_bound_py_any(py)
72✔
874
            }
875
            20 => Ok(false.into_bound_py_any(py)?),
132✔
876
            21 => Ok(true.into_bound_py_any(py)?),
144✔
877
            22 => Ok(py.None().into_bound_py_any(py)?),
504✔
878
            23 => Ok(UNDEFINED.get(py).unwrap().into_bound_py_any(py)?),
24✔
879
            24 => {
880
                let value = self.read_exact::<1>(py)?[0];
84✔
881
                if value < 0x20 {
84✔
882
                    return Err(CBORDecodeError::new_err(
36✔
883
                        "invalid two-byte sequence for simple value",
36✔
884
                    ));
36✔
885
                }
48✔
886
                CBORSimpleValue::new(value.into_pyobject(py)?)?.into_bound_py_any(py)
48✔
887
            }
888
            25 => {
889
                let bytes = self.read_exact::<2>(py)?;
684✔
890
                f16::from_be_bytes(bytes).to_f32().into_bound_py_any(py)
684✔
891
            }
892
            26 => {
893
                let bytes = self.read_exact::<4>(py)?;
108✔
894
                f32::from_be_bytes(bytes).into_bound_py_any(py)
108✔
895
            }
896
            27 => {
897
                let bytes = self.read_exact::<8>(py)?;
444✔
898
                f64::from_be_bytes(bytes).into_bound_py_any(py)
444✔
899
            }
900
            31 => Ok(BREAK_MARKER.get(py).unwrap().into_bound_py_any(py)?),
156✔
901
            _ => Err(CBORDecodeError::new_err(format!(
36✔
902
                "undefined reserved major type 7 subtype 0x{subtype:x}"
36✔
903
            ))),
36✔
904
        }
905
        .map(Value)
2,352✔
906
    }
2,388✔
907

908
    //
909
    // Decoders for semantic tags (major tag 6)
910
    //
911

912
    fn decode_datetime_string<'py>(
456✔
913
        value: Bound<'py, PyAny>,
456✔
914
        _immutable: bool,
456✔
915
    ) -> PyResult<DecoderResult<'py>> {
456✔
916
        // Semantic tag 0
917
        let py = value.py();
456✔
918
        let value_type = value.get_type();
456✔
919
        let mut datetime_str: Bound<'py, PyString> = value.cast_into().map_err(|e| {
456✔
NEW
920
            create_exc_from(
×
NEW
921
                py,
×
NEW
922
                CBORDecodeError::new_err(format!(
×
923
                    "expected string for tag, got {} instead",
NEW
924
                    value_type.to_string()
×
925
                )),
NEW
926
                Some(PyErr::from(e)),
×
927
            )
NEW
928
        })?;
×
929

930
        // Python 3.10 has impaired parsing of the ISO format:
931
        // * It doesn't handle the standard "Z" suffix
932
        // * It doesn't handle the fractional seconds part having fewer than 6 digits
933
        if py.version_info() <= (3, 10) {
456✔
934
            // Convert Z to +00:00
935
            let mut temp_str = datetime_str.to_string().replacen("Z", "+00:00", 1);
114✔
936

937
            // Pad any microseconds part with zeros
938
            if let Some((first, second)) = temp_str.split_once('.') {
114✔
939
                if let Some(index) = second.find(|c: char| !c.is_numeric()) {
576✔
940
                    let (mut micros, tz_part) = second.split_at(index);
78✔
941
                    // Cut off excess zeroes from the start of the microseconds part
942
                    if micros.len() >= 6 {
78✔
943
                        micros = &micros[..6];
63✔
944
                    }
63✔
945

946
                    // Reconstitute the datetime string, right-padding the microseconds part
947
                    // with zeroes
948
                    temp_str = format!("{first}.{micros:0<6}{tz_part}");
78✔
NEW
949
                }
×
950
            }
36✔
951

952
            datetime_str = temp_str.into_pyobject(py)?;
114✔
953
        }
342✔
954

955
        DATETIME_FROMISOFORMAT
456✔
956
            .get(py)?
456✔
957
            .call1((&datetime_str,))
456✔
958
            .map(CompleteFrame)
456✔
959
    }
456✔
960

961
    fn decode_epoch_datetime(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
60✔
962
        // Semantic tag 1
963
        let py = value.py();
60✔
964
        let utc = UTC.get(py)?;
60✔
965
        DATETIME_FROMTIMESTAMP
60✔
966
            .get(py)?
60✔
967
            .call1((value, utc))
60✔
968
            .map(CompleteFrame)
60✔
969
    }
60✔
970

971
    fn decode_positive_bignum(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
108✔
972
        // Semantic tag 2
973
        let py = value.py();
108✔
974
        INT_FROMBYTES
108✔
975
            .get(py)?
108✔
976
            .call1((value, intern!(py, "big")))
108✔
977
            .map(CompleteFrame)
108✔
978
    }
108✔
979

980
    fn decode_negative_bignum(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
36✔
981
        // Semantic tag 3
982
        let py = value.py();
36✔
983
        let int = INT_FROMBYTES.get(py)?.call1((value, intern!(py, "big")))?;
36✔
984
        int.neg()?.add(-1).map(CompleteFrame)
36✔
985
    }
36✔
986

987
    fn decode_fraction(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
264✔
988
        // Semantic tag 4
989
        let py = value.py();
264✔
990
        let tuple = require_tuple(value, 2)?;
264✔
991
        let decimal_class = DECIMAL_TYPE.get(py)?;
252✔
992
        {
993
            let exp = tuple.get_item(0)?;
252✔
994
            let sig_tuple = decimal_class
252✔
995
                .call1((tuple.get_item(1)?,))?
252✔
996
                .call_method0(intern!(py, "as_tuple"))?
252✔
997
                .cast_into::<PyTuple>()?;
252✔
998
            let sign = sig_tuple.get_item(0)?;
252✔
999
            let digits = sig_tuple.get_item(1)?;
252✔
1000
            let args_tuple = PyTuple::new(py, [sign, digits, exp])?;
252✔
1001
            decimal_class.call1((args_tuple,)).map(CompleteFrame)
252✔
1002
        }
1003
    }
264✔
1004

1005
    fn decode_bigfloat(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
24✔
1006
        // Semantic tag 5
1007
        let py = value.py();
24✔
1008
        let tuple = require_tuple(value, 2)?;
24✔
1009
        let decimal_class = DECIMAL_TYPE.get(py)?;
12✔
1010
        {
1011
            let exp = decimal_class.call1((tuple.get_item(0)?,))?;
12✔
1012
            let sig = decimal_class.call1((tuple.get_item(1)?,))?;
12✔
1013
            let exp = PyInt::new(py, 2).pow(exp, py.None())?;
12✔
1014
            sig.mul(exp).map(CompleteFrame)
12✔
1015
        }
1016
    }
24✔
1017

1018
    fn decode_stringref(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
96✔
1019
        // Semantic tag 25
1020
        let index: usize = value.extract()?;
96✔
1021
        Ok(StringReference(index))
96✔
1022
    }
96✔
1023

1024
    fn decode_sharedref(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
180✔
1025
        // Semantic tag 29
1026
        let index: usize = value.extract()?;
180✔
1027
        Ok(SharedReference(index))
180✔
1028
    }
180✔
1029

1030
    fn decode_rational(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
252✔
1031
        // Semantic tag 30
1032
        let py = value.py();
252✔
1033
        let tuple = require_tuple(value, 2)?;
252✔
1034
        FRACTION_TYPE.get(py)?.call1(tuple).map(CompleteFrame)
240✔
1035
    }
252✔
1036

1037
    fn decode_regexp(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
36✔
1038
        // Semantic tag 35
1039
        RE_COMPILE
36✔
1040
            .get(value.py())?
36✔
1041
            .call1((value,))
36✔
1042
            .map(CompleteFrame)
36✔
1043
    }
36✔
1044

1045
    fn decode_mime(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
24✔
1046
        // Semantic tag 36
1047
        let py = value.py();
24✔
1048
        let parser = EMAIL_PARSER.get(py)?.call0()?;
24✔
1049
        parser
24✔
1050
            .call_method1(intern!(py, "parsestr"), (value,))
24✔
1051
            .map(CompleteFrame)
24✔
1052
    }
24✔
1053

1054
    fn decode_uuid(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
300✔
1055
        // Semantic tag 37
1056
        let py = value.py();
300✔
1057
        let kwargs = PyDict::new(py);
300✔
1058
        kwargs.set_item(intern!(py, "bytes"), value)?;
300✔
1059
        UUID_TYPE
300✔
1060
            .get(py)?
300✔
1061
            .call((), Some(&kwargs))
300✔
1062
            .map(CompleteFrame)
300✔
1063
    }
300✔
1064

1065
    fn decode_ipv4(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
120✔
1066
        // Semantic tag 52
1067
        let py = value.py();
120✔
1068
        let addr = if let Ok(bytes) = value.cast::<PyBytes>() {
120✔
1069
            // The decoded value was a bytestring, so this is an IPv4 address
1070
            IPV4ADDRESS_TYPE.get(py)?.call1((bytes,))?
96✔
1071
        } else if let Ok(tuple) = value.cast_into::<PyTuple>()
24✔
1072
            && tuple.len() == 2
24✔
1073
        {
1074
            // The decoded value was a 2-item array. Check the types of the elements:
1075
            // (int, bytes) -> network
1076
            // (bytes, int) -> interface
1077
            let first_item = tuple.get_item(0)?;
24✔
1078
            let second_item = tuple.get_item(1)?;
24✔
1079
            if let Ok(prefix) = first_item.cast::<PyInt>()
24✔
1080
                && let Ok(address) = second_item.cast::<PyBytes>()
12✔
1081
            {
1082
                let mut address_vec: Vec<u8> = address.extract()?;
12✔
1083
                address_vec.resize(4, 0);
12✔
1084
                IPV4NETWORK_TYPE.get(py)?.call1(((address_vec, prefix),))?
12✔
1085
            } else if let Ok(address) = first_item.cast::<PyBytes>()
12✔
1086
                && let Ok(prefix) = second_item.cast::<PyInt>()
12✔
1087
            {
1088
                IPV4INTERFACE_TYPE.get(py)?.call1(((address, prefix),))?
12✔
1089
            } else {
NEW
1090
                return Err(CBORDecodeError::new_err("invalid types in input array"));
×
1091
            }
1092
        } else {
NEW
1093
            return Err(CBORDecodeError::new_err(
×
NEW
1094
                "input value must be a bytestring or an array of 2 elements",
×
NEW
1095
            ));
×
1096
        };
1097
        Ok(CompleteFrame(addr))
120✔
1098
    }
120✔
1099

1100
    fn decode_ipv6(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
72✔
1101
        // Semantic tag 54
1102
        let py = value.py();
72✔
1103
        let ipv6addr_class = IPV6ADDRESS_TYPE.get(py)?;
72✔
1104
        let addr = if let Ok(bytes) = value.cast::<PyBytes>() {
72✔
1105
            // The decoded value was a bytestring, so this is an IPv6 address
1106
            ipv6addr_class.call1((bytes,))?
36✔
1107
        } else if let Ok(tuple) = value.cast_into::<PyTuple>()
36✔
1108
            && (2..=3).contains(&tuple.len())
36✔
1109
        {
1110
            // The decoded value was a 2-item (or 3 with zone ID) array.
1111
            // Check the types of the elements:
1112
            // (int, bytes) -> network
1113
            // (bytes, int) -> interface
1114
            let first_item = tuple.get_item(0)?;
36✔
1115
            let second_item = tuple.get_item(1)?;
36✔
1116
            let zone_id = tuple.get_item(2).ok();
36✔
1117
            let (class, addr_bytes, prefix) = if let Ok(prefix) = first_item.cast::<PyInt>()
36✔
1118
                && let Ok(address) = second_item.cast::<PyBytes>()
12✔
1119
            {
1120
                let mut address_vec: Vec<u8> = address.extract()?;
12✔
1121
                address_vec.resize(16, 0);
12✔
1122
                Ok((
1123
                    IPV6NETWORK_TYPE.get(py)?,
12✔
1124
                    PyBytes::new(py, address_vec.as_slice()),
12✔
1125
                    prefix,
12✔
1126
                ))
1127
            } else if let Ok(address) = first_item.cast_into::<PyBytes>()
24✔
1128
                && let Ok(prefix) = second_item.cast::<PyInt>()
24✔
1129
            {
1130
                Ok((IPV6INTERFACE_TYPE.get(py)?, address, prefix))
24✔
1131
            } else {
NEW
1132
                Err(CBORDecodeError::new_err("invalid types in input array"))
×
NEW
1133
            }?;
×
1134
            let addr_obj = ipv6addr_class.call1((addr_bytes,))?;
36✔
1135

1136
            // Format the zone ID suffix if a zone ID was included
1137
            // (bytes or integer as the last item of a 3-tuple)
1138
            let zone_id_suffix = if let Some(zone_id) = zone_id {
36✔
1139
                if let Ok(zone_id_bytes) = zone_id.cast::<PyBytes>() {
24✔
1140
                    let zone_id_str = String::from_utf8(zone_id_bytes.as_bytes().to_vec())?;
12✔
1141
                    format!("%{zone_id_str}")
12✔
1142
                } else if let Ok(zone_id_int) = zone_id.cast::<PyInt>() {
12✔
1143
                    format!("%{zone_id_int}")
12✔
1144
                } else {
NEW
1145
                    return Err(CBORDecodeError::new_err(
×
NEW
1146
                        "zone ID must be an integer or a bytestring",
×
NEW
1147
                    ));
×
1148
                }
1149
            } else {
1150
                String::default()
12✔
1151
            };
1152

1153
            let formatted_addr = format!("{addr_obj}{zone_id_suffix}/{prefix}");
36✔
1154
            class.call1((formatted_addr,))?
36✔
1155
        } else {
NEW
1156
            return Err(CBORDecodeError::new_err(
×
NEW
1157
                "input value must be a bytestring or an array of 2 elements",
×
NEW
1158
            ));
×
1159
        };
1160
        Ok(CompleteFrame(addr))
72✔
1161
    }
72✔
1162

1163
    fn decode_epoch_date(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
12✔
1164
        // Semantic tag 100
1165
        let py = value.py();
12✔
1166
        let value = value.extract::<i32>()? + 719163;
12✔
1167
        DATE_FROMORDINAL.get(py)?.call1((value,)).map(CompleteFrame)
12✔
1168
    }
12✔
1169

1170
    fn decode_ipaddress(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
84✔
1171
        // Semantic tag 260 (deprecated)
1172
        let py = value.py();
84✔
1173
        let value = value.cast_into::<PyBytes>()?;
84✔
1174
        let addr_obj = match value.len()? {
72✔
1175
            4 | 16 => IPADDRESS_FUNC.get(py)?.call1((value,)),
48✔
1176
            6 => Ok(Bound::new(py, CBORTag::new_internal(260, value.into_any()))?.into_any()), // MAC address
12✔
1177
            length => Err(CBORDecodeError::new_err(format!(
12✔
1178
                "invalid IP address length ({length})"
12✔
1179
            ))),
12✔
1180
        }?;
12✔
1181
        Ok(CompleteFrame(addr_obj))
60✔
1182
    }
84✔
1183

1184
    fn decode_ipnetwork<'py>(
84✔
1185
        value: Bound<'py, PyAny>,
84✔
1186
        _immutable: bool,
84✔
1187
    ) -> PyResult<DecoderResult<'py>> {
84✔
1188
        // Semantic tag 261 (deprecated)
1189
        let py = value.py();
84✔
1190
        let value: Bound<'py, PyMapping> = value.cast_into()?;
84✔
1191
        let length = value.len()?;
84✔
1192
        if length != 1 {
84✔
1193
            return Err(CBORDecodeError::new_err(format!(
12✔
1194
                "invalid input map length for IP network: {}",
12✔
1195
                length
12✔
1196
            )));
12✔
1197
        }
72✔
1198
        let first_item = value.items()?.get_item(0)?;
72✔
1199
        let mask_length = first_item.get_item(1)?;
72✔
1200
        if !mask_length.is_exact_instance_of::<PyInt>() {
72✔
1201
            return Err(CBORDecodeError::new_err(format!(
12✔
1202
                "invalid mask length for IP network: {mask_length}"
12✔
1203
            )));
12✔
1204
        }
60✔
1205

1206
        let addr_obj = match IPNETWORK_FUNC.get(py)?.call1((&first_item,)) {
60✔
1207
            Ok(ip_network) => Ok(ip_network),
48✔
1208
            Err(e) => {
12✔
1209
                // A CompleteFrameError may indicate that the bytestring has host bits set, so try parsing
1210
                // it as an IP interface instead
1211
                if e.is_instance_of::<PyValueError>(py) {
12✔
1212
                    IPINTERFACE_FUNC.get(py)?.call1((first_item,))
12✔
1213
                } else {
NEW
1214
                    Err(e)
×
1215
                }
1216
            }
NEW
1217
        }?;
×
1218
        Ok(CompleteFrame(addr_obj))
60✔
1219
    }
84✔
1220

1221
    fn decode_date_string(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
12✔
1222
        // Semantic tag 1004
1223
        let py = value.py();
12✔
1224
        let date = DATE_FROMISOFORMAT.get(py)?.call1((value,))?;
12✔
1225
        Ok(CompleteFrame(date))
12✔
1226
    }
12✔
1227

1228
    fn decode_complex(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
252✔
1229
        // Semantic tag 43000
1230
        let py = value.py();
252✔
1231
        let tuple = require_tuple(value, 2)?;
252✔
1232
        let real: f64 = tuple.get_item(0)?.extract()?;
252✔
1233
        let imag: f64 = tuple.get_item(1)?.extract()?;
252✔
1234
        Ok(CompleteFrame(
252✔
1235
            PyComplex::from_doubles(py, real, imag).into_any(),
252✔
1236
        ))
252✔
1237
    }
252✔
1238

1239
    fn decode_self_describe_cbor(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
24✔
1240
        // Semantic tag 55799
1241
        Ok(CompleteFrame(value))
24✔
1242
    }
24✔
1243

1244
    fn decode_set<'py>(
408✔
1245
        &mut self,
408✔
1246
        py: Python<'py>,
408✔
1247
        immutable: bool,
408✔
1248
    ) -> PyResult<DecoderResult<'py>> {
408✔
1249
        // Semantic tag 258
1250
        let mut set_or_none = if immutable {
408✔
1251
            None
96✔
1252
        } else {
1253
            Some(PySet::empty(py)?.into_any())
312✔
1254
        };
1255
        let container = set_or_none.as_ref().map(|set| set.clone());
408✔
1256
        let callback = move |item: Bound<'py, PyAny>, _immutable: bool| {
408✔
1257
            let container: Bound<'py, PyAny> = if let Some(set) = set_or_none.take() {
396✔
1258
                set.call_method1(intern!(py, "update"), (item,))?;
300✔
1259
                set.into_any()
300✔
1260
            } else {
1261
                let tuple = item.cast_into::<PyTuple>()?;
96✔
1262
                PyFrozenSet::new(py, tuple)?.into_any()
96✔
1263
            };
1264
            Ok(CompleteFrame(container))
396✔
1265
        };
396✔
1266
        Ok(BeginFrame(
408✔
1267
            Box::new(callback),
408✔
1268
            true,
408✔
1269
            container,
408✔
1270
            DisplayName::String("set"),
408✔
1271
        ))
408✔
1272
    }
408✔
1273
}
1274

NEW
1275
#[pymethods]
×
1276
impl CBORDecoder {
1277
    #[new]
1278
    #[pyo3(signature = (
1279
        fp,
1280
        *,
1281
        tag_hook = None,
1282
        object_hook = None,
1283
        semantic_decoders = None,
1284
        str_errors = "strict",
1285
        read_size = 4096,
1286
        max_depth = 1000,
1287
        allow_indefinite = true,
1288
    ))]
1289
    pub fn new(
384✔
1290
        py: Python<'_>,
384✔
1291
        fp: &Bound<'_, PyAny>,
384✔
1292
        tag_hook: Option<&Bound<'_, PyAny>>,
384✔
1293
        object_hook: Option<&Bound<'_, PyAny>>,
384✔
1294
        semantic_decoders: Option<&Bound<'_, PyMapping>>,
384✔
1295
        str_errors: &str,
384✔
1296
        read_size: usize,
384✔
1297
        max_depth: usize,
384✔
1298
        allow_indefinite: bool,
384✔
1299
    ) -> PyResult<Self> {
384✔
1300
        Self::new_internal(
384✔
1301
            py,
384✔
1302
            Some(fp),
384✔
1303
            None,
384✔
1304
            tag_hook,
384✔
1305
            object_hook,
384✔
1306
            semantic_decoders,
384✔
1307
            str_errors,
384✔
1308
            read_size,
384✔
1309
            max_depth,
384✔
1310
            allow_indefinite,
384✔
1311
        )
1312
    }
384✔
1313

1314
    #[getter]
NEW
1315
    fn fp(&self, py: Python<'_>) -> Option<Py<PyAny>> {
×
NEW
1316
        self.fp.as_ref().map(|fp| fp.clone_ref(py))
×
NEW
1317
    }
×
1318

1319
    #[setter]
1320
    fn set_fp(&mut self, fp: &Bound<'_, PyAny>) -> PyResult<()> {
396✔
1321
        let result = fp.call_method0("readable");
396✔
1322
        if let Ok(readable) = &result
396✔
1323
            && readable.is_truthy()?
384✔
1324
        {
1325
            self.fp_is_seekable = fp.call_method0("seekable")?.is_truthy()?;
372✔
1326
            let fp = fp.clone();
372✔
1327
            self.read_method = Some(fp.getattr("read")?.unbind());
372✔
1328
            self.fp = Some(fp.unbind());
372✔
1329
            self.available_bytes = 0;
372✔
1330
            self.read_position = 0;
372✔
1331
            self.buffer = None;
372✔
1332
            Ok(())
372✔
1333
        } else {
1334
            raise_exc_from(
24✔
1335
                fp.py(),
24✔
1336
                PyValueError::new_err("fp must be a readable file-like object"),
24✔
1337
                result.err(),
24✔
1338
            )
1339
        }
1340
    }
396✔
1341

1342
    #[getter]
1343
    fn tag_hook(&self, py: Python<'_>) -> Option<Py<PyAny>> {
12✔
1344
        self.tag_hook
12✔
1345
            .as_ref()
12✔
1346
            .map(|tag_hook| tag_hook.clone_ref(py))
12✔
1347
    }
12✔
1348

1349
    #[setter]
1350
    fn set_tag_hook(&mut self, tag_hook: Option<&Bound<'_, PyAny>>) -> PyResult<()> {
4,416✔
1351
        if let Some(tag_hook) = tag_hook {
4,416✔
1352
            if !tag_hook.is_callable() {
132✔
1353
                return Err(PyErr::new::<PyTypeError, _>(
12✔
1354
                    "tag_hook must be callable or None",
12✔
1355
                ));
12✔
1356
            }
120✔
1357

1358
            self.tag_hook = Some(tag_hook.clone().unbind());
120✔
1359
        } else {
4,284✔
1360
            self.tag_hook = None;
4,284✔
1361
        }
4,284✔
1362
        Ok(())
4,404✔
1363
    }
4,416✔
1364

1365
    #[getter]
1366
    fn object_hook(&self, py: Python<'_>) -> Option<Py<PyAny>> {
12✔
1367
        self.object_hook
12✔
1368
            .as_ref()
12✔
1369
            .map(|object_hook| object_hook.clone_ref(py))
12✔
1370
    }
12✔
1371

1372
    #[setter]
1373
    fn set_object_hook(&mut self, object_hook: Option<&Bound<'_, PyAny>>) -> PyResult<()> {
4,404✔
1374
        if let Some(object_hook) = object_hook {
4,404✔
1375
            if !object_hook.is_callable() {
48✔
1376
                return Err(PyErr::new::<PyTypeError, _>(
12✔
1377
                    "object_hook must be callable or None",
12✔
1378
                ));
12✔
1379
            }
36✔
1380

1381
            self.object_hook = Some(object_hook.clone().unbind());
36✔
1382
        } else {
4,356✔
1383
            self.object_hook = None;
4,356✔
1384
        }
4,356✔
1385
        Ok(())
4,392✔
1386
    }
4,404✔
1387

1388
    #[getter]
1389
    fn str_errors(&self, py: Python<'_>) -> Py<PyString> {
60✔
1390
        if let Some(str_errors) = self.str_errors.as_ref() {
60✔
1391
            str_errors.clone_ref(py)
48✔
1392
        } else {
1393
            intern!(py, "strict").clone().unbind()
12✔
1394
        }
1395
    }
60✔
1396

1397
    #[setter]
1398
    fn set_str_errors(&mut self, str_errors: &Bound<'_, PyString>) -> PyResult<()> {
4,392✔
1399
        let as_string: &str = str_errors.extract()?;
4,392✔
1400
        self.str_errors = match as_string {
4,392✔
1401
            "strict" => None,
4,392✔
1402
            "ignore" | "replace" | "backslashreplace" | "surrogateescape" => {
108✔
1403
                Some(str_errors.clone().unbind())
96✔
1404
            }
1405
            _ => {
1406
                return Err(PyValueError::new_err(format!(
12✔
1407
                    "invalid str_errors value: '{str_errors}'"
12✔
1408
                )));
12✔
1409
            }
1410
        };
1411
        Ok(())
4,380✔
1412
    }
4,392✔
1413

1414
    /// Read bytes from the data stream.
1415
    ///
1416
    /// :param amount: the number of bytes to read
1417
    #[pyo3(signature = (amount, /))]
1418
    fn read(&mut self, py: Python<'_>, amount: usize) -> PyResult<Vec<u8>> {
3,456✔
1419
        if amount == 0 {
3,456✔
1420
            return Ok(Vec::default());
96✔
1421
        }
3,360✔
1422

1423
        if self.available_bytes == 0 {
3,360✔
1424
            // No buffer
1425
            let (new_bytes, amount_read) = self.read_from_fp(py, amount)?;
72✔
1426
            self.read_position = amount;
12✔
1427
            self.available_bytes = amount_read - amount;
12✔
1428
            let new_buffer = new_bytes.as_bytes()[..amount].to_vec();
12✔
1429
            self.buffer = Some(new_bytes.unbind());
12✔
1430
            Ok(new_buffer)
12✔
1431
        } else if self.available_bytes < amount {
3,288✔
1432
            // Combine the remnants of the partial buffer with new data read from the file
1433
            let needed_bytes = amount - self.available_bytes;
72✔
1434
            let mut concatenated_buffer: Vec<u8> =
72✔
1435
                self.buffer.take().unwrap().as_bytes(py).to_vec();
72✔
1436
            let (new_bytes, amount_read) = self.read_from_fp(py, needed_bytes)?;
72✔
NEW
1437
            concatenated_buffer.extend_from_slice(&new_bytes[..needed_bytes]);
×
NEW
1438
            self.buffer = Some(new_bytes.unbind());
×
NEW
1439
            self.available_bytes = amount_read - needed_bytes;
×
NEW
1440
            self.read_position = needed_bytes;
×
NEW
1441
            Ok(concatenated_buffer)
×
1442
        } else {
1443
            // Return a slice from the existing bytes object
1444
            let vec = self.buffer.as_ref().unwrap().as_bytes(py)
3,216✔
1445
                [self.read_position..self.read_position + amount]
3,216✔
1446
                .to_vec();
3,216✔
1447
            self.available_bytes -= amount;
3,216✔
1448
            self.read_position += amount;
3,216✔
1449
            Ok(vec)
3,216✔
1450
        }
1451
    }
3,456✔
1452

1453
    /// Decode the next value from the stream.
1454
    ///
1455
    /// :param immutable: if :data:`True`, decode the next item as an immutable type
1456
    ///     (e.g. :class:`tuple` instead of a :class:`list`), if possible
1457
    /// :return: the decoded object
1458
    /// :raises CBORDecodeError: if there is any problem decoding the stream
1459
    #[pyo3(signature = (*, immutable = false))]
1460
    pub fn decode<'py>(&mut self, py: Python<'py>, immutable: bool) -> PyResult<Bound<'py, PyAny>> {
4,284✔
1461
        let mut frames: Vec<StackFrame> = Vec::new();
4,284✔
1462

1463
        fn add_frame<'a>(
19,260✔
1464
            frames: &mut Vec<StackFrame<'a>>,
19,260✔
1465
            max_depth: usize,
19,260✔
1466
            frame: StackFrame<'a>,
19,260✔
1467
        ) -> PyResult<()> {
19,260✔
1468
            if frames.len() == max_depth {
19,260✔
1469
                return Err(CBORDecodeError::new_err(format!(
24✔
1470
                    "maximum container nesting depth ({max_depth}) exceeded",
24✔
1471
                )));
24✔
1472
            }
19,236✔
1473

1474
            frames.push(frame);
19,236✔
1475
            Ok(())
19,236✔
1476
        }
19,260✔
1477

1478
        fn wrap_exception(py: Python<'_>, err: PyErr, typename: &DisplayName) -> PyErr {
588✔
1479
            if err.is_instance_of::<CBORDecodeEOF>(py) {
588✔
1480
                err
120✔
1481
            } else if err.is_instance_of::<CBORDecodeError>(py) {
468✔
1482
                CBORDecodeError::new_err(format!(
228✔
1483
                    "error decoding {}: {}",
1484
                    typename,
1485
                    err.arguments(py)
228✔
1486
                ))
1487
            } else {
1488
                create_exc_from(
240✔
1489
                    py,
240✔
1490
                    CBORDecodeError::new_err(format!("error decoding {}", typename)),
240✔
1491
                    Some(err),
240✔
1492
                )
1493
            }
1494
        }
588✔
1495

1496
        let mut shareables: Vec<Option<Bound<'py, PyAny>>> = Vec::new();
4,284✔
1497
        let mut string_namespaces: Vec<Vec<Bound<'py, PyAny>>> = Vec::new();
4,284✔
1498
        let mut value: Option<Bound<'py, PyAny>> = None;
4,284✔
1499
        let mut current_immutable: bool = immutable;
4,284✔
1500
        loop {
1501
            let result: PyResult<DecoderResult<'py>> = if let Some(previous_value) = value.take() {
42,240✔
1502
                // Call the decoder callback of the last frame
1503
                let frame = frames.last_mut().unwrap();
12,672✔
1504
                if let Some(decoder_callback) = frame.decoder_callback.as_mut() {
12,672✔
1505
                    decoder_callback(previous_value, frame.immutable)
12,588✔
1506
                        .map_err(|e| wrap_exception(py, e, &frame.typename))
12,588✔
1507
                } else if frame.contains_string_namespace {
84✔
1508
                    string_namespaces
12✔
1509
                        .pop()
12✔
1510
                        .expect("no string namespaces to pop from");
12✔
1511
                    Ok(CompleteFrame(previous_value))
12✔
1512
                } else if let Some(shareable_index) = frame.shareable_index {
72✔
1513
                    shareables[shareable_index].get_or_insert_with(|| previous_value.clone());
72✔
1514
                    Ok(CompleteFrame(previous_value))
72✔
1515
                } else {
NEW
1516
                    panic!("no decoder callback, shareable index or string namespace");
×
1517
                }
1518
            } else {
1519
                let (major_type, subtype) = self.read_major_and_subtype(py)?;
29,568✔
1520
                match major_type {
29,544✔
1521
                    0 => self.decode_uint(py, subtype),
3,300✔
1522
                    1 => self.decode_negint(py, subtype),
768✔
1523
                    2 => self.decode_bytestring(py, subtype),
1,128✔
1524
                    3 => self.decode_string(py, subtype),
2,232✔
1525
                    4 => self.decode_array(py, subtype, current_immutable),
14,580✔
1526
                    5 => self.decode_map(py, subtype, current_immutable),
1,740✔
1527
                    6 => self.decode_semantic(py, subtype, current_immutable),
3,408✔
1528
                    7 => self.decode_special(py, subtype),
2,388✔
NEW
1529
                    _ => Err(CBORDecodeError::new_err(format!(
×
NEW
1530
                        "invalid major type: {major_type}"
×
NEW
1531
                    ))),
×
1532
                }
1533
                .map_err(|e| {
29,544✔
1534
                    let typename = match major_type {
360✔
1535
                        0 => "unsigned integer",
12✔
NEW
1536
                        1 => "negative integer",
×
1537
                        2 => "byte string",
108✔
1538
                        3 => "text string",
168✔
NEW
1539
                        4 => "array",
×
NEW
1540
                        5 => "map",
×
NEW
1541
                        6 => "semantic tag",
×
1542
                        7 => "special value",
72✔
NEW
1543
                        _ => unreachable!("invalid major types should have been handled earlier"),
×
1544
                    };
1545
                    wrap_exception(py, e, &DisplayName::String(typename))
360✔
1546
                })
360✔
1547
            };
1548

1549
            match result {
41,628✔
1550
                Ok(BeginFrame(callback, requested_immutable, container, typename)) => {
18,984✔
1551
                    if let Some(frame) = frames.last_mut()
18,984✔
1552
                        && let Some(container) = container
16,428✔
1553
                        && let Some(shareable_index) = frame.shareable_index
13,092✔
1554
                    {
156✔
1555
                        frames.pop();
156✔
1556
                        shareables[shareable_index] = Some(container.clone());
156✔
1557
                    }
18,828✔
1558
                    current_immutable = current_immutable || requested_immutable;
18,984✔
1559
                    add_frame(
18,984✔
1560
                        &mut frames,
18,984✔
1561
                        self.max_depth,
18,984✔
1562
                        StackFrame {
18,984✔
1563
                            immutable: current_immutable,
18,984✔
1564
                            decoder_callback: Some(callback),
18,984✔
1565
                            shareable_index: None,
18,984✔
1566
                            typename,
18,984✔
1567
                            contains_string_namespace: false,
18,984✔
1568
                        },
18,984✔
1569
                    )?;
24✔
1570
                }
1571
                Ok(ContinueFrame(require_immutable)) => {
6,048✔
1572
                    // If require_immutable is true, the next value must be immutable
1573
                    // Otherwise, restore the immutable flag to the previous value
1574
                    current_immutable = if frames.len() >= 2 {
6,048✔
1575
                        frames.get(frames.len() - 2).unwrap().immutable
3,120✔
1576
                    } else {
1577
                        immutable
2,928✔
1578
                    } || require_immutable;
3,384✔
1579
                }
1580
                Ok(CompleteFrame(new_value)) => {
6,120✔
1581
                    frames
6,120✔
1582
                        .pop()
6,120✔
1583
                        .expect("received frame completion but there are no frames on the stack");
6,120✔
1584
                    current_immutable = frames.last().map_or(immutable, |frame| frame.immutable);
6,120✔
1585
                    value = Some(new_value);
6,120✔
1586
                }
1587
                Ok(Value(new_value)) => {
6,876✔
1588
                    value = Some(new_value);
6,876✔
1589
                }
6,876✔
1590
                Ok(StringNamespace) => {
1591
                    add_frame(
36✔
1592
                        &mut frames,
36✔
1593
                        self.max_depth,
36✔
1594
                        StackFrame {
36✔
1595
                            immutable: current_immutable,
36✔
1596
                            decoder_callback: None,
36✔
1597
                            shareable_index: None,
36✔
1598
                            typename: DisplayName::String("string namespace"),
36✔
1599
                            contains_string_namespace: true,
36✔
1600
                        },
36✔
NEW
1601
                    )?;
×
1602
                    string_namespaces.push(Vec::new());
36✔
1603
                }
1604
                Ok(StringValue(string, length)) => {
3,048✔
1605
                    // Conditionally add the string to the innermost string namespace
1606
                    if let Some(namespace) = string_namespaces.last_mut() {
3,048✔
1607
                        if match namespace.len() {
48✔
1608
                            0..24 => length >= 3,
48✔
NEW
1609
                            24..256 => length >= 4,
×
NEW
1610
                            256..65536 => length >= 5,
×
NEW
1611
                            65536..4294967296 => length >= 6,
×
NEW
1612
                            _ => length >= 11,
×
1613
                        } {
48✔
1614
                            namespace.push(string.clone());
48✔
1615
                        }
48✔
1616
                    }
3,000✔
1617
                    value = Some(string);
3,048✔
1618
                }
1619
                Ok(StringReference(index)) => {
96✔
1620
                    frames
96✔
1621
                        .pop()
96✔
1622
                        .expect("  received string reference but there are no frames on the stack");
96✔
1623
                    if let Some(namespace) = string_namespaces.last() {
96✔
1624
                        if let Some(string) = namespace.get(index) {
84✔
1625
                            value = Some(string.clone());
72✔
1626
                        } else {
72✔
1627
                            return Err(CBORDecodeError::new_err(format!(
12✔
1628
                                "string reference {index} not found"
12✔
1629
                            )));
12✔
1630
                        }
1631
                    } else {
1632
                        return Err(CBORDecodeError::new_err(
12✔
1633
                            "string reference outside of namespace",
12✔
1634
                        ));
12✔
1635
                    }
1636
                    current_immutable = frames
72✔
1637
                        .last()
72✔
1638
                        .map_or(current_immutable, |frame| frame.immutable);
72✔
1639
                }
1640
                Ok(Shareable) => {
1641
                    add_frame(
240✔
1642
                        &mut frames,
240✔
1643
                        self.max_depth,
240✔
1644
                        StackFrame {
240✔
1645
                            immutable: current_immutable,
240✔
1646
                            decoder_callback: None,
240✔
1647
                            shareable_index: Some(shareables.len()),
240✔
1648
                            typename: DisplayName::String("shareable value"),
240✔
1649
                            contains_string_namespace: false,
240✔
1650
                        },
240✔
NEW
1651
                    )?;
×
1652
                    shareables.push(None);
240✔
1653
                }
1654
                Ok(SharedReference(index)) => {
180✔
1655
                    frames
180✔
1656
                        .pop()
180✔
1657
                        .expect("received shared reference but there are no frames on the stack");
180✔
1658
                    value = match shareables.get(index) {
180✔
1659
                        Some(Some(value)) => Some(value.clone()),
144✔
1660
                        Some(None) => {
1661
                            return Err(CBORDecodeError::new_err(format!(
12✔
1662
                                "shared value {index} has not been initialized"
12✔
1663
                            )));
12✔
1664
                        }
1665
                        None => {
1666
                            return Err(CBORDecodeError::new_err(format!(
24✔
1667
                                "shared reference {index} not found"
24✔
1668
                            )));
24✔
1669
                        }
1670
                    };
1671
                    current_immutable = frames
144✔
1672
                        .last()
144✔
1673
                        .map_or(current_immutable, |frame| frame.immutable);
144✔
1674
                }
1675
                Err(err) => {
588✔
1676
                    // If an Exception was raised, wrap it in a CBORDecodeError
1677
                    // If a ValueError was raised, wrap it in a CBORDecodeError
1678
                    return if err.is_instance_of::<CBORDecodeError>(py) {
588✔
1679
                        Err(err)
588✔
NEW
1680
                    } else if err.is_instance_of::<PyValueError>(py) {
×
NEW
1681
                        Err(create_exc_from(
×
NEW
1682
                            py,
×
NEW
1683
                            CBORDecodeError::new_err(err.to_string()),
×
NEW
1684
                            Some(err),
×
NEW
1685
                        ))
×
NEW
1686
                    } else if err.is_instance_of::<PyException>(py) {
×
NEW
1687
                        Err(create_exc_from(
×
NEW
1688
                            py,
×
NEW
1689
                            CBORDecodeError::new_err(err.to_string()),
×
NEW
1690
                            Some(err),
×
NEW
1691
                        ))
×
1692
                    } else {
NEW
1693
                        Err(err)
×
1694
                    };
1695
                }
1696
            }
1697

1698
            if frames.is_empty() {
41,544✔
1699
                // If fp was seekable and excess data has been read, empty the buffer and
1700
                // rewind the file
1701
                if self.available_bytes > 0
3,588✔
1702
                    && let Some(fp) = &self.fp
24✔
1703
                {
1704
                    let offset = -(self.available_bytes as isize);
24✔
1705
                    fp.call_method1(py, intern!(py, "seek"), (offset, SEEK_CUR))?;
24✔
1706
                    self.buffer = None;
24✔
1707
                    self.available_bytes = 0;
24✔
1708
                    self.read_position = 0;
24✔
1709
                }
3,564✔
1710
                return Ok(value.expect("stack is empty but final return value is missing"));
3,588✔
1711
            }
37,956✔
1712
        }
1713
    }
4,284✔
1714
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc