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

agronholm / cbor2 / 25601657289

09 May 2026 12:55PM UTC coverage: 94.201% (-0.06%) from 94.261%
25601657289

push

github

web-flow
Fixed compatibility with 32-bit systems (#301)

20 of 22 new or added lines in 1 file covered. (90.91%)

2323 of 2466 relevant lines covered (94.2%)

1307.5 hits per line

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

92.68
/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
    CBORDecodeEOF, CBORDecodeError, CBORSimpleValue, CBORTag, DECIMAL_TYPE, FRACTION_TYPE,
10
    IPV4ADDRESS_TYPE, IPV4INTERFACE_TYPE, IPV4NETWORK_TYPE, IPV6ADDRESS_TYPE, IPV6INTERFACE_TYPE,
11
    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(u64),
67
    PythonName(Bound<'a, PyAny>),
68
}
69

70
impl<'a> Display for DisplayName<'a> {
71
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
516✔
72
        match self {
516✔
73
            DisplayName::String(s) => f.write_str(s),
492✔
74
            DisplayName::SemanticTag(tagnum) => write!(f, "semantic tag {}", tagnum),
12✔
75
            DisplayName::PythonName(obj) => write!(f, "{}", obj),
12✔
76
        }
77
    }
516✔
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✔
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>> {
800✔
132
    let array: Bound<'py, PyTuple> = value
800✔
133
        .cast_into()
800✔
134
        .map_err(|_| PyTypeError::new_err("input value must be an array"))?;
800✔
135
    if array.len() != length {
764✔
136
        return Err(PyValueError::new_err(format!(
×
137
            "expected an array with exactly {length} elements"
×
138
        )));
×
139
    }
764✔
140
    Ok(array)
764✔
141
}
800✔
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
/// :param allow_duplicate_keys:
176
///     if :data:`False`, raise a :exc:`CBORDecodeError` when a map key that has already been
177
///     decoded in the same map is encountered
178
///
179
/// .. _CBOR: https://cbor.io/
180
#[pyclass(module = "cbor2")]
181
pub struct CBORDecoder {
182
    fp: Option<Py<PyAny>>,
183
    tag_hook: Option<Py<PyAny>>,
184
    object_hook: Option<Py<PyAny>>,
185
    semantic_decoders: Option<Py<PyMapping>>,
186
    str_errors: Option<Py<PyString>>,
187
    #[pyo3(get)]
188
    read_size: usize,
189
    #[pyo3(get)]
190
    max_depth: usize,
191
    #[pyo3(get)]
192
    allow_indefinite: bool,
193
    #[pyo3(get)]
194
    allow_duplicate_keys: bool,
195

196
    read_method: Option<Py<PyAny>>,
197
    buffer: Option<Py<PyBytes>>,
198
    read_position: usize,
199
    available_bytes: usize,
200
    fp_is_seekable: bool,
201
}
202

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

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

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

305
    fn read_major_and_subtype(&mut self, py: Python<'_>) -> PyResult<(u8, u8)> {
22,344✔
306
        let initial_byte = self.read_exact::<1>(py)?[0];
22,344✔
307
        let major_type = initial_byte >> 5;
22,320✔
308
        let subtype = initial_byte & 31;
22,320✔
309
        Ok((major_type, subtype))
22,320✔
310
    }
22,344✔
311

312
    fn decode_length_finite(&mut self, py: Python<'_>, subtype: u8) -> PyResult<u64> {
7,540✔
313
        match self.decode_length(py, subtype)? {
7,540✔
314
            Some(length) => Ok(length),
7,504✔
315
            None => Err(CBORDecodeError::new_err(
24✔
316
                "indefinite length not allowed here",
24✔
317
            )),
24✔
318
        }
319
    }
7,540✔
320

321
    /// Like [`decode_length`], but converts `Some(u64)` to `Some(usize)`, returning
322
    /// a [`CBORDecodeError`] if the value exceeds the platform's address space.
323
    fn decode_length_as_usize(&mut self, py: Python<'_>, subtype: u8) -> PyResult<Option<usize>> {
12,272✔
324
        match self.decode_length(py, subtype)? {
12,272✔
325
            Some(length) => usize::try_from(length).map(Some).map_err(|_| {
11,912✔
NEW
326
                CBORDecodeError::new_err(format!(
×
327
                    "huge item length {length} exceeds the system address space"
328
                ))
NEW
329
            }),
×
330
            None => Ok(None),
348✔
331
        }
332
    }
12,272✔
333

334
    //
335
    // Decoders for major tags (0-7)
336
    //
337

338
    /// Decode the length of the next item.
339
    ///
340
    /// This is a low-level operation that may be needed by custom decoder callbacks.
341
    ///
342
    /// :param subtype:
343
    /// :return: the length of the item, or :data:`None` to indicate an indefinite-length item
344
    fn decode_length(&mut self, py: Python<'_>, subtype: u8) -> PyResult<Option<u64>> {
19,812✔
345
        let length = match subtype {
19,812✔
346
            ..24 => Some(subtype as u64),
19,812✔
347
            24 => Some(self.read_exact::<1>(py)?[0] as u64),
2,088✔
348
            25 => Some(u16::from_be_bytes(self.read_exact(py)?) as u64),
1,160✔
349
            26 => Some(u32::from_be_bytes(self.read_exact(py)?) as u64),
300✔
350
            27 => Some(u64::from_be_bytes(self.read_exact(py)?)),
284✔
351
            31 => {
352
                if !self.allow_indefinite {
384✔
353
                    return Err(CBORDecodeError::new_err(
12✔
354
                        "encountered indefinite length but it has been disabled",
12✔
355
                    ));
12✔
356
                }
372✔
357
                None
372✔
358
            }
359
            _ => {
360
                return Err(CBORDecodeError::new_err(format!(
12✔
361
                    "unknown unsigned integer subtype 0x{subtype:x}"
12✔
362
                )));
12✔
363
            }
364
        };
365
        Ok(length)
19,788✔
366
    }
19,812✔
367

368
    fn decode_uint<'py>(&mut self, py: Python<'py>, subtype: u8) -> PyResult<DecoderResult<'py>> {
3,756✔
369
        // Major tag 0
370
        let uint: u64 = self.decode_length_finite(py, subtype)?;
3,756✔
371
        Ok(Value(uint.into_bound_py_any(py)?))
3,744✔
372
    }
3,756✔
373

374
    fn decode_negint<'py>(&mut self, py: Python<'py>, subtype: u8) -> PyResult<DecoderResult<'py>> {
464✔
375
        // Major tag 1
376
        let uint: u64 = self.decode_length_finite(py, subtype)?;
464✔
377
        let signed_int = -(uint as i128) - 1;
464✔
378
        Ok(Value(signed_int.into_bound_py_any(py)?))
464✔
379
    }
464✔
380

381
    fn decode_bytestring<'py>(
1,128✔
382
        &mut self,
1,128✔
383
        py: Python<'py>,
1,128✔
384
        subtype: u8,
1,128✔
385
    ) -> PyResult<DecoderResult<'py>> {
1,128✔
386
        // Major tag 2
387
        match self.decode_length_as_usize(py, subtype)? {
1,128✔
388
            None => {
389
                // Indefinite length
390
                let mut bytes = PyBytes::new(py, b"");
72✔
391
                let sys_maxsize = *SYS_MAXSIZE.get(py).unwrap();
72✔
392
                loop {
393
                    let (major_type, subtype) = self.read_major_and_subtype(py)?;
120✔
394
                    match (major_type, subtype) {
120✔
395
                        (2, _) => {
396
                            let length = self.decode_length_finite(py, subtype)?;
84✔
397
                            if length > sys_maxsize {
72✔
398
                                return Err(CBORDecodeError::new_err(format!(
12✔
399
                                    "chunk too long in an indefinite bytestring chunk: {length}"
12✔
400
                                )));
12✔
401
                            }
60✔
402
                            let length = length as usize;
60✔
403
                            let chunk = self.read(py, length)?;
60✔
404
                            bytes = bytes.add(chunk)?.cast_into()?;
48✔
405
                        }
406
                        (7, 31) => break Ok(Value(bytes.into_any())), // break marker
12✔
407
                        _ => {
408
                            return Err(CBORDecodeError::new_err(format!(
24✔
409
                                "non-byte string (major type {major_type}) found in indefinite \
24✔
410
                                    length byte string"
24✔
411
                            )));
24✔
412
                        }
413
                    }
414
                }
415
            }
416
            Some(length) if length <= 65536 => {
1,056✔
417
                let bytes = self.read(py, length)?;
1,032✔
418
                Ok(StringValue(PyBytes::new(py, &bytes).into_any(), length))
996✔
419
            }
420
            Some(length) => {
24✔
421
                // Incrementally read the bytestring, in chunks of 65536 bytes
422
                let mut bytes = PyBytes::new(py, b"");
24✔
423
                let mut remaining_length = length;
24✔
424
                while remaining_length > 0 {
48✔
425
                    let chunk_size = remaining_length.min(65536);
36✔
426
                    let chunk = self.read(py, chunk_size)?;
36✔
427
                    remaining_length -= chunk_size;
24✔
428
                    bytes = bytes.add(chunk)?.cast_into()?;
24✔
429
                }
430
                Ok(StringValue(bytes.into_any(), length))
12✔
431
            }
432
        }
433
    }
1,128✔
434

435
    fn decode_string<'py>(&mut self, py: Python<'py>, subtype: u8) -> PyResult<DecoderResult<'py>> {
2,280✔
436
        // Major tag 3
437
        match self.decode_length_as_usize(py, subtype)? {
2,280✔
438
            None => {
439
                // Indefinite length
440
                let mut string = PyString::new(py, "");
96✔
441
                loop {
442
                    let (major_type, subtype) = self.read_major_and_subtype(py)?;
168✔
443
                    let sys_maxsize = *SYS_MAXSIZE.get(py).unwrap();
168✔
444
                    match (major_type, subtype) {
168✔
445
                        (3, _) => {
446
                            let length = self.decode_length_finite(py, subtype)?;
120✔
447
                            if length > sys_maxsize {
108✔
448
                                return Err(CBORDecodeError::new_err(format!(
12✔
449
                                    "chunk too long in an indefinite text string chunk: {length}"
12✔
450
                                )));
12✔
451
                            }
96✔
452
                            let length = length as usize;
96✔
453
                            let bytes = self.read(py, length)?;
96✔
454
                            let decoded = match self.str_errors.as_ref() {
84✔
455
                                None => PyString::from_bytes(py, bytes.as_slice()),
84✔
456
                                Some(str_errors) => bytes
×
457
                                    .into_bound_py_any(py)?
×
458
                                    .call_method1(
×
459
                                        intern!(py, "decode"),
×
460
                                        (intern!(py, "utf-8"), str_errors),
×
461
                                    )
462
                                    .and_then(|string| string.cast_into().map_err(PyErr::from)),
×
463
                            }?;
12✔
464
                            string = string.add(decoded)?.cast_into()?;
72✔
465
                        }
466
                        (7, 31) => break Ok(Value(string.into_any())), // break marker
24✔
467
                        _ => {
468
                            return Err(CBORDecodeError::new_err(format!(
24✔
469
                                "non-text string (major type {major_type}) found in indefinite \
24✔
470
                                    length text string"
24✔
471
                            )));
24✔
472
                        }
473
                    }
474
                }
475
            }
476
            Some(length) if length <= 65536 => {
2,172✔
477
                let bytes = self.read(py, length)?;
2,124✔
478
                let decoded_string: Bound<'_, PyAny> = match self.str_errors.as_ref() {
2,076✔
479
                    None => PyString::from_bytes(py, bytes.as_slice())?.into_any(),
2,052✔
480
                    Some(str_errors) => bytes.into_bound_py_any(py)?.call_method1(
24✔
481
                        intern!(py, "decode"),
24✔
482
                        (intern!(py, "utf-8"), str_errors.bind(py)),
24✔
483
                    )?,
×
484
                };
485
                Ok(StringValue(decoded_string, length))
2,040✔
486
            }
487
            Some(mut length) => {
48✔
488
                // Incrementally decode the string, in chunks of 65536 bytes
489
                let decoder_class = INCREMENTAL_UTF8_DECODER
48✔
490
                    .get_or_try_init(py, || -> PyResult<Py<PyAny>> {
48✔
491
                        let decoder = py
12✔
492
                            .import("codecs")?
12✔
493
                            .getattr("lookup")?
12✔
494
                            .call1(("utf-8",))?
12✔
495
                            .getattr("incrementaldecoder")?;
12✔
496
                        Ok(decoder.unbind())
12✔
497
                    })?
12✔
498
                    .bind(py);
48✔
499
                let decoder = match self.str_errors.as_ref() {
48✔
500
                    None => decoder_class.call0()?,
24✔
501
                    Some(str_errors) => decoder_class.call1((str_errors,))?,
24✔
502
                };
503
                let mut string = PyString::new(py, "").into_any();
48✔
504
                while length > 0 {
168✔
505
                    let chunk_size = length.min(65536);
120✔
506
                    let chunk = self.read(py, chunk_size)?;
120✔
507
                    length -= chunk_size;
120✔
508
                    let is_final_chunk = length == 0;
120✔
509
                    let decoded_chunk =
120✔
510
                        decoder.call_method1(intern!(py, "decode"), (chunk, is_final_chunk))?;
120✔
511
                    string = string.add(decoded_chunk)?;
120✔
512
                }
513
                Ok(StringValue(string.into_any(), length))
48✔
514
            }
515
        }
516
    }
2,280✔
517

518
    fn decode_array<'py>(
7,072✔
519
        &mut self,
7,072✔
520
        py: Python<'py>,
7,072✔
521
        subtype: u8,
7,072✔
522
        immutable: bool,
7,072✔
523
    ) -> PyResult<DecoderResult<'py>> {
7,072✔
524
        // Major tag 4
525
        let optional_length = self.decode_length_as_usize(py, subtype)?;
7,072✔
526
        if immutable {
7,072✔
527
            let mut items: Vec<Bound<'py, PyAny>> = Vec::new();
1,192✔
528
            let callback: Box<DecoderCallback<'py>> = if let Some(length) = optional_length {
1,192✔
529
                if length == 0 {
1,168✔
530
                    return Ok(Value(PyTuple::empty(py).into_any()));
24✔
531
                }
1,144✔
532

533
                Box::new(move |item: Bound<'py, PyAny>, _immutable: bool| {
2,440✔
534
                    items.push(item);
2,440✔
535
                    if items.len() == length {
2,440✔
536
                        Ok(CompleteFrame(
537
                            PyTuple::new(py, take(&mut items))?.into_any(),
1,096✔
538
                        ))
539
                    } else {
540
                        Ok(ContinueFrame(false))
1,344✔
541
                    }
542
                })
2,440✔
543
            } else {
544
                let break_marker = BREAK_MARKER.get(py).unwrap().bind(py);
24✔
545
                Box::new(move |item: Bound<'py, PyAny>, _immutable: bool| {
72✔
546
                    if item.is(break_marker) {
72✔
547
                        Ok(CompleteFrame(
548
                            PyTuple::new(py, take(&mut items))?.into_any(),
12✔
549
                        ))
550
                    } else {
551
                        items.push(item);
60✔
552
                        Ok(ContinueFrame(false))
60✔
553
                    }
554
                })
72✔
555
            };
556
            Ok(BeginFrame(
1,168✔
557
                callback,
1,168✔
558
                false,
1,168✔
559
                None,
1,168✔
560
                DisplayName::String("array"),
1,168✔
561
            ))
1,168✔
562
        } else {
563
            let mut list = PyList::empty(py);
5,880✔
564
            let container = list.clone().into_any();
5,880✔
565
            let callback: Box<DecoderCallback<'py>> = if let Some(length) = optional_length {
5,880✔
566
                if length == 0 {
5,784✔
567
                    return Ok(Value(PyList::empty(py).into_any()));
104✔
568
                }
5,680✔
569

570
                Box::new(move |item, _immutable: bool| {
5,680✔
571
                    list.append(item)?;
2,128✔
572
                    if list.len() == length {
2,128✔
573
                        Ok(CompleteFrame(
712✔
574
                            replace(&mut list, PyList::empty(py)).into_any(),
712✔
575
                        ))
712✔
576
                    } else {
577
                        Ok(ContinueFrame(false))
1,416✔
578
                    }
579
                })
2,128✔
580
            } else {
581
                let break_marker = BREAK_MARKER.get(py).unwrap().bind(py);
96✔
582
                Box::new(move |item: Bound<'py, PyAny>, _immutable: bool| {
564✔
583
                    if item.is(break_marker) {
564✔
584
                        Ok(CompleteFrame(
96✔
585
                            replace(&mut list, PyList::empty(py)).into_any(),
96✔
586
                        ))
96✔
587
                    } else {
588
                        list.append(item)?;
468✔
589
                        Ok(ContinueFrame(false))
468✔
590
                    }
591
                })
564✔
592
            };
593
            Ok(BeginFrame(
5,776✔
594
                callback,
5,776✔
595
                false,
5,776✔
596
                Some(container),
5,776✔
597
                DisplayName::String("array"),
5,776✔
598
            ))
5,776✔
599
        }
600
    }
7,072✔
601

602
    fn decode_map<'py>(
1,792✔
603
        &mut self,
1,792✔
604
        py: Python<'py>,
1,792✔
605
        subtype: u8,
1,792✔
606
        immutable: bool,
1,792✔
607
    ) -> PyResult<DecoderResult<'py>> {
1,792✔
608
        // Major tag 5
609

610
        #[cfg(Py_3_15)]
611
        fn create_frozen_dict<'py>(
12✔
612
            py: Python<'py>,
12✔
613
            items: Vec<(Bound<'py, PyAny>, Bound<'py, PyAny>)>,
12✔
614
        ) -> PyResult<Bound<'py, PyAny>> {
12✔
615
            FROZEN_DICT
12✔
616
                .get(py)?
12✔
617
                .call1((items,))?
12✔
618
                .cast_into()
12✔
619
                .map_err(|e| PyErr::from(e))
12✔
620
        }
12✔
621
        #[cfg(not(Py_3_15))]
622
        fn create_frozen_dict<'py>(
132✔
623
            py: Python<'py>,
132✔
624
            items: Vec<(Bound<'py, PyAny>, Bound<'py, PyAny>)>,
132✔
625
        ) -> PyResult<Bound<'py, PyAny>> {
132✔
626
            FrozenDict::from_items(py, items).map(|dict| dict.into_any())
132✔
627
        }
132✔
628

629
        #[inline]
630
        fn maybe_call_object_hook<'py>(
1,588✔
631
            py: Python<'py>,
1,588✔
632
            dict: Bound<'py, PyAny>,
1,588✔
633
            object_hook: Option<&Py<PyAny>>,
1,588✔
634
            immutable: bool,
1,588✔
635
        ) -> PyResult<Bound<'py, PyAny>> {
1,588✔
636
            if let Some(object_hook) = object_hook {
1,588✔
637
                object_hook.bind(py).call1((dict, immutable))
24✔
638
            } else {
639
                Ok(dict)
1,564✔
640
            }
641
        }
1,588✔
642

643
        let object_hook = self.object_hook.as_ref().map(|hook| hook.clone_ref(py));
1,792✔
644
        let allow_duplicate_keys = self.allow_duplicate_keys;
1,792✔
645
        let length_or_none = self.decode_length_as_usize(py, subtype)?;
1,792✔
646

647
        // Return immediately if this is an empty dict
648
        if let Some(length) = length_or_none
1,792✔
649
            && length == 0
1,732✔
650
        {
651
            let container: Bound<'py, PyAny> = if immutable {
256✔
652
                create_frozen_dict(py, Vec::new())?
×
653
            } else {
654
                PyDict::new(py).into_any()
256✔
655
            };
656
            let transformed =
256✔
657
                maybe_call_object_hook(py, container, object_hook.as_ref(), immutable)?;
256✔
658
            return Ok(Value(transformed));
256✔
659
        };
1,536✔
660

661
        let mut key: Option<Bound<'py, PyAny>> = None;
1,536✔
662
        if immutable {
1,536✔
663
            let seen_keys: Option<Bound<'py, PySet>> = if allow_duplicate_keys {
300✔
664
                None
276✔
665
            } else {
666
                Some(PySet::empty(py)?)
24✔
667
            };
668
            let check_duplicate = move |key: &Bound<'py, PyAny>| -> PyResult<()> {
300✔
669
                let seen = seen_keys.as_ref().unwrap();
48✔
670
                if seen.contains(key)? {
48✔
671
                    let repr = key.repr()?;
24✔
672
                    return Err(CBORDecodeError::new_err(format!(
24✔
673
                        "Duplicate map key: {}",
674
                        repr.to_str()?
24✔
675
                    )));
676
                }
24✔
677
                seen.add(key.clone())
24✔
678
            };
48✔
679

680
            let mut items: Vec<(Bound<'py, PyAny>, Bound<'py, PyAny>)> = Vec::new();
300✔
681
            let callback: Box<DecoderCallback<'py>> = if let Some(length) = length_or_none {
300✔
682
                Box::new(move |item: Bound<'py, PyAny>, _immutable: bool| {
396✔
683
                    if let Some(key) = key.take() {
396✔
684
                        if !allow_duplicate_keys {
192✔
685
                            check_duplicate(&key)?;
24✔
686
                        }
168✔
687
                        items.push((key, item));
180✔
688
                        if items.len() == length {
180✔
689
                            let transformed = maybe_call_object_hook(
144✔
690
                                py,
144✔
691
                                create_frozen_dict(py, take(&mut items))?,
144✔
692
                                object_hook.as_ref(),
144✔
693
                                immutable,
144✔
694
                            )?;
×
695
                            return Ok(CompleteFrame(transformed));
144✔
696
                        }
36✔
697
                        Ok(ContinueFrame(true))
36✔
698
                    } else {
699
                        key = Some(item);
204✔
700
                        Ok(ContinueFrame(false))
204✔
701
                    }
702
                })
396✔
703
            } else {
704
                let break_marker = BREAK_MARKER.get(py).unwrap().bind(py);
12✔
705
                Box::new(move |item: Bound<'py, PyAny>, _immutable: bool| {
48✔
706
                    if item.is(break_marker) {
48✔
707
                        let container = create_frozen_dict(py, take(&mut items))?;
×
708
                        let transformed = maybe_call_object_hook(
×
709
                            py,
×
710
                            container.into_any(),
×
711
                            object_hook.as_ref(),
×
712
                            immutable,
×
713
                        )?;
×
714
                        Ok(CompleteFrame(transformed))
×
715
                    } else if let Some(key) = key.take() {
48✔
716
                        if !allow_duplicate_keys {
24✔
717
                            check_duplicate(&key)?;
24✔
718
                        }
×
719
                        items.push((key, item));
12✔
720
                        Ok(ContinueFrame(true))
12✔
721
                    } else {
722
                        key = Some(item);
24✔
723
                        Ok(ContinueFrame(false))
24✔
724
                    }
725
                })
48✔
726
            };
727
            Ok(BeginFrame(callback, true, None, DisplayName::String("map")))
300✔
728
        } else {
729
            fn check_duplicate(key: &Bound<PyAny>, dict: &Bound<PyDict>) -> PyResult<()> {
48✔
730
                if dict.contains(key)? {
48✔
731
                    let repr = key.repr()?;
24✔
732
                    return Err(CBORDecodeError::new_err(format!(
24✔
733
                        "Duplicate map key: {}",
734
                        repr.to_str()?
24✔
735
                    )));
736
                }
24✔
737
                Ok(())
24✔
738
            }
48✔
739

740
            let mut dict = PyDict::new(py);
1,236✔
741
            let container = dict.clone().into_any();
1,236✔
742
            let callback: Box<DecoderCallback<'py>> = if let Some(length) = length_or_none {
1,236✔
743
                let mut count = 0usize;
1,188✔
744
                Box::new(move |item: Bound<'py, PyAny>, _immutable: bool| {
3,536✔
745
                    if let Some(key) = key.take() {
3,536✔
746
                        if !allow_duplicate_keys {
1,768✔
747
                            check_duplicate(&key, &dict)?;
24✔
748
                        }
1,744✔
749
                        dict.set_item(&key, item)?;
1,756✔
750
                        count += 1;
1,756✔
751
                        if count == length {
1,756✔
752
                            let dict = replace(&mut dict, PyDict::new(py));
1,152✔
753
                            let transformed = maybe_call_object_hook(
1,152✔
754
                                py,
1,152✔
755
                                dict.into_any(),
1,152✔
756
                                object_hook.as_ref(),
1,152✔
757
                                immutable,
1,152✔
758
                            )?;
12✔
759
                            return Ok(CompleteFrame(transformed));
1,140✔
760
                        }
604✔
761
                        Ok(ContinueFrame(true))
604✔
762
                    } else {
763
                        key = Some(item);
1,768✔
764
                        Ok(ContinueFrame(false))
1,768✔
765
                    }
766
                })
3,536✔
767
            } else {
768
                let break_marker = BREAK_MARKER.get(py).unwrap().bind(py);
48✔
769
                Box::new(move |item: Bound<'py, PyAny>, _immutable: bool| {
204✔
770
                    if item.is(break_marker) {
204✔
771
                        let dict = replace(&mut dict, PyDict::new(py));
36✔
772
                        let transformed = maybe_call_object_hook(
36✔
773
                            py,
36✔
774
                            dict.into_any(),
36✔
775
                            object_hook.as_ref(),
36✔
776
                            immutable,
36✔
777
                        )?;
×
778
                        Ok(CompleteFrame(transformed))
36✔
779
                    } else if let Some(key) = key.take() {
168✔
780
                        if !allow_duplicate_keys {
84✔
781
                            check_duplicate(&key, &dict)?;
24✔
782
                        }
60✔
783
                        dict.set_item(&key, item)?;
72✔
784
                        Ok(ContinueFrame(true))
72✔
785
                    } else {
786
                        key = Some(item);
84✔
787
                        Ok(ContinueFrame(false))
84✔
788
                    }
789
                })
204✔
790
            };
791
            Ok(BeginFrame(
1,236✔
792
                callback,
1,236✔
793
                true,
1,236✔
794
                Some(container),
1,236✔
795
                DisplayName::String("map"),
1,236✔
796
            ))
1,236✔
797
        }
798
    }
1,792✔
799

800
    fn decode_semantic<'py>(
3,116✔
801
        &mut self,
3,116✔
802
        py: Python<'py>,
3,116✔
803
        subtype: u8,
3,116✔
804
        immutable: bool,
3,116✔
805
    ) -> PyResult<DecoderResult<'py>> {
3,116✔
806
        let tagnum = self.decode_length_finite(py, subtype)?;
3,116✔
807
        if let Some(semantic_decoders) = &self.semantic_decoders {
3,116✔
808
            match semantic_decoders.bind(py).get_item(tagnum) {
120✔
809
                Ok(decoder) => {
96✔
810
                    let name = decoder.getattr_opt(intern!(py, NAME_ATTR))?;
96✔
811

812
                    // If these attributes are present, this callable was decorated with
813
                    // @shareable_decoder
814
                    return if let Some(name) = name {
96✔
815
                        let require_immutable: bool = decoder
60✔
816
                            .getattr_opt(intern!(py, IMMUTABLE_ATTR))?
60✔
817
                            .map(|x| x.is_truthy())
60✔
818
                            .transpose()?
60✔
819
                            .unwrap_or(false);
60✔
820
                        let retval = decoder.call1((immutable,))?;
60✔
821
                        let tuple: Bound<'_, PyTuple> = retval.cast_into()?;
60✔
822
                        if tuple.len() != 2 {
60✔
823
                            return Err(CBORDecodeError::new_err(format!(
×
824
                                "{decoder} returned a tuple of {} items, expected 2",
×
825
                                tuple.len()
×
826
                            )));
×
827
                        }
60✔
828
                        let container: Bound<'_, PyAny> = tuple.get_item(0)?.cast_into()?;
60✔
829
                        let callback: Bound<'_, PyAny> = tuple.get_item(1)?.cast_into()?;
60✔
830
                        Ok(BeginFrame(
831
                            Box::new(
60✔
832
                                move |item, _immutable: bool| -> PyResult<DecoderResult<'py>> {
60✔
833
                                    callback.call1((item,)).map(CompleteFrame)
60✔
834
                                },
60✔
835
                            ),
836
                            require_immutable,
60✔
837
                            if container.is_none() {
60✔
838
                                None
48✔
839
                            } else {
840
                                Some(container)
12✔
841
                            },
842
                            if name.is_none() {
60✔
843
                                DisplayName::SemanticTag(tagnum)
12✔
844
                            } else {
845
                                DisplayName::PythonName(name.clone())
48✔
846
                            },
847
                        ))
848
                    } else {
849
                        let callback =
36✔
850
                            move |item, new_immutable: bool| -> PyResult<DecoderResult<'py>> {
36✔
851
                                decoder.call1((item, new_immutable)).map(CompleteFrame)
36✔
852
                            };
36✔
853
                        Ok(BeginFrame(
36✔
854
                            Box::new(callback),
36✔
855
                            immutable,
36✔
856
                            None,
36✔
857
                            DisplayName::SemanticTag(tagnum),
36✔
858
                        ))
36✔
859
                    };
860
                }
861
                Err(e) if e.is_instance_of::<PyLookupError>(py) => {}
24✔
862
                Err(e) => return Err(e),
×
863
            }
864
        };
2,996✔
865

866
        // No semantic decoder lookup map – fall back to the hard coded switchboard
867
        let (callback, typename): (Box<DecoderCallback<'py>>, &str) = match tagnum {
3,020✔
868
            0 => (
488✔
869
                Box::new(Self::decode_datetime_string),
488✔
870
                "string-form datetime",
488✔
871
            ),
488✔
872
            1 => (Box::new(Self::decode_epoch_datetime), "epoch-form datetime"),
60✔
873
            2 => (Box::new(Self::decode_positive_bignum), "positive bignum"),
168✔
874
            3 => (Box::new(Self::decode_negative_bignum), "negative bignum"),
40✔
875
            4 => (Box::new(Self::decode_fraction), "decimal fraction"),
280✔
876
            5 => (Box::new(Self::decode_bigfloat), "bigfloat"),
24✔
877
            25 => (Box::new(Self::decode_stringref), "string reference"),
96✔
878
            28 => return Ok(Shareable),
240✔
879
            29 => (Box::new(Self::decode_sharedref), "shared reference"),
180✔
880
            30 => (Box::new(Self::decode_rational), "rational"),
244✔
881
            35 => (Box::new(Self::decode_regexp), "regular expression"),
36✔
882
            36 => (Box::new(Self::decode_mime), "MIME message"),
36✔
883
            37 => (Box::new(Self::decode_uuid), "UUID"),
208✔
884
            52 => (Box::new(Self::decode_ipv4), "IPv4 address"),
60✔
885
            54 => (Box::new(Self::decode_ipv6), "IPv6 address"),
60✔
886
            100 => (Box::new(Self::decode_epoch_date), "epoch-form date"),
12✔
887
            256 => return Ok(StringNamespace),
36✔
888
            258 => return self.decode_set(py, immutable),
200✔
889
            260 => (Box::new(Self::decode_ipaddress), "IP address"),
84✔
890
            261 => (Box::new(Self::decode_ipnetwork), "IP network"),
84✔
891
            1004 => (Box::new(Self::decode_date_string), "string-form date"),
12✔
892
            43000 => (Box::new(Self::decode_complex), "complex number"),
252✔
893
            55799 => (
24✔
894
                Box::new(Self::decode_self_describe_cbor),
24✔
895
                "self-described CBOR value",
24✔
896
            ),
24✔
897
            _ => {
898
                // For a tag with no designated decoder, check if we have a tag hook, and call
899
                // that with the tag object, using its return value as the decoded value.
900
                let tag = CBORTag::new(tagnum.into_bound_py_any(py)?, py.None().into_bound(py))?;
96✔
901
                let bound_tag = Bound::new(py, tag)?.into_any();
96✔
902
                let container = bound_tag.clone();
96✔
903
                let mut tag_hook = self
96✔
904
                    .tag_hook
96✔
905
                    .as_ref()
96✔
906
                    .map(|hook| hook.clone_ref(py).into_bound(py));
96✔
907
                let callback = Box::new(move |item: Bound<'py, PyAny>, _immutable: bool| {
96✔
908
                    let tag: &Bound<'py, CBORTag> = bound_tag.cast()?;
84✔
909
                    tag.borrow_mut().value = item.unbind();
84✔
910
                    if let Some(tag_hook) = tag_hook.take() {
84✔
911
                        tag_hook.call1((&bound_tag, immutable)).map(CompleteFrame)
60✔
912
                    } else {
913
                        Ok(CompleteFrame(bound_tag.clone()))
24✔
914
                    }
915
                });
84✔
916
                return Ok(BeginFrame(
96✔
917
                    callback,
96✔
918
                    true,
96✔
919
                    Some(container),
96✔
920
                    DisplayName::SemanticTag(tagnum),
96✔
921
                ));
96✔
922
            }
923
        };
924
        Ok(BeginFrame(
2,448✔
925
            callback,
2,448✔
926
            true,
2,448✔
927
            None,
2,448✔
928
            DisplayName::String(typename),
2,448✔
929
        ))
2,448✔
930
    }
3,116✔
931

932
    fn decode_special<'py>(
2,424✔
933
        &mut self,
2,424✔
934
        py: Python<'py>,
2,424✔
935
        subtype: u8,
2,424✔
936
    ) -> PyResult<DecoderResult<'py>> {
2,424✔
937
        // Major tag 7
938
        match subtype {
2,424✔
939
            0..20 => {
2,424✔
940
                let value = subtype.into_pyobject(py)?;
72✔
941
                CBORSimpleValue::new(value)?.into_bound_py_any(py)
72✔
942
            }
943
            20 => Ok(false.into_bound_py_any(py)?),
120✔
944
            21 => Ok(true.into_bound_py_any(py)?),
120✔
945
            22 => Ok(py.None().into_bound_py_any(py)?),
600✔
946
            23 => Ok(UNDEFINED.get(py).unwrap().into_bound_py_any(py)?),
24✔
947
            24 => {
948
                let value = self.read_exact::<1>(py)?[0];
84✔
949
                if value < 0x20 {
84✔
950
                    return Err(CBORDecodeError::new_err(
36✔
951
                        "invalid two-byte sequence for simple value",
36✔
952
                    ));
36✔
953
                }
48✔
954
                CBORSimpleValue::new(value.into_pyobject(py)?)?.into_bound_py_any(py)
48✔
955
            }
956
            25 => {
957
                let bytes = self.read_exact::<2>(py)?;
648✔
958
                f16::from_be_bytes(bytes).to_f32().into_bound_py_any(py)
648✔
959
            }
960
            26 => {
961
                let bytes = self.read_exact::<4>(py)?;
108✔
962
                f32::from_be_bytes(bytes).into_bound_py_any(py)
108✔
963
            }
964
            27 => {
965
                let bytes = self.read_exact::<8>(py)?;
456✔
966
                f64::from_be_bytes(bytes).into_bound_py_any(py)
456✔
967
            }
968
            31 => Ok(BREAK_MARKER.get(py).unwrap().into_bound_py_any(py)?),
156✔
969
            _ => Err(CBORDecodeError::new_err(format!(
36✔
970
                "undefined reserved major type 7 subtype 0x{subtype:x}"
36✔
971
            ))),
36✔
972
        }
973
        .map(Value)
2,388✔
974
    }
2,424✔
975

976
    //
977
    // Decoders for semantic tags (major tag 6)
978
    //
979

980
    fn decode_datetime_string<'py>(
488✔
981
        value: Bound<'py, PyAny>,
488✔
982
        _immutable: bool,
488✔
983
    ) -> PyResult<DecoderResult<'py>> {
488✔
984
        // Semantic tag 0
985
        let py = value.py();
488✔
986
        let value_type = value.get_type();
488✔
987
        let mut datetime_str: Bound<'py, PyString> = value.cast_into().map_err(|e| {
488✔
988
            create_exc_from(
×
989
                py,
×
990
                CBORDecodeError::new_err(format!(
×
991
                    "expected string for tag, got {} instead",
992
                    value_type
993
                )),
994
                Some(PyErr::from(e)),
×
995
            )
996
        })?;
×
997

998
        // Python 3.10 has impaired parsing of the ISO format:
999
        // * It doesn't handle the standard "Z" suffix
1000
        // * It doesn't handle the fractional seconds part having fewer than 6 digits
1001
        if py.version_info() <= (3, 10) {
488✔
1002
            // Convert Z to +00:00
1003
            let mut temp_str = datetime_str.to_string().replacen("Z", "+00:00", 1);
136✔
1004

1005
            // Pad any microseconds part with zeros
1006
            if let Some((first, second)) = temp_str.split_once('.')
136✔
1007
                && let Some(index) = second.find(|c: char| !c.is_numeric())
688✔
1008
            {
1009
                let (mut micros, tz_part) = second.split_at(index);
94✔
1010
                // Cut off excess zeroes from the start of the microseconds part
1011
                if micros.len() >= 6 {
94✔
1012
                    micros = &micros[..6];
79✔
1013
                }
79✔
1014

1015
                // Reconstitute the datetime string, right-padding the microseconds part
1016
                // with zeroes
1017
                temp_str = format!("{first}.{micros:0<6}{tz_part}");
94✔
1018
            }
42✔
1019

1020
            datetime_str = temp_str.into_pyobject(py)?;
136✔
1021
        }
352✔
1022

1023
        DATETIME_FROMISOFORMAT
488✔
1024
            .get(py)?
488✔
1025
            .call1((&datetime_str,))
488✔
1026
            .map(CompleteFrame)
488✔
1027
    }
488✔
1028

1029
    fn decode_epoch_datetime(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
60✔
1030
        // Semantic tag 1
1031
        let py = value.py();
60✔
1032
        let utc = UTC.get(py)?;
60✔
1033
        DATETIME_FROMTIMESTAMP
60✔
1034
            .get(py)?
60✔
1035
            .call1((value, utc))
60✔
1036
            .map(CompleteFrame)
60✔
1037
    }
60✔
1038

1039
    fn decode_positive_bignum(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
144✔
1040
        // Semantic tag 2
1041
        let py = value.py();
144✔
1042
        INT_FROMBYTES
144✔
1043
            .get(py)?
144✔
1044
            .call1((value, intern!(py, "big")))
144✔
1045
            .map(CompleteFrame)
144✔
1046
    }
144✔
1047

1048
    fn decode_negative_bignum(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
40✔
1049
        // Semantic tag 3
1050
        let py = value.py();
40✔
1051
        let int = INT_FROMBYTES.get(py)?.call1((value, intern!(py, "big")))?;
40✔
1052
        int.neg()?.add(-1).map(CompleteFrame)
40✔
1053
    }
40✔
1054

1055
    fn decode_fraction(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
280✔
1056
        // Semantic tag 4
1057
        let py = value.py();
280✔
1058
        let tuple = require_tuple(value, 2)?;
280✔
1059
        let decimal_class = DECIMAL_TYPE.get(py)?;
268✔
1060
        {
1061
            let exp = tuple.get_item(0)?;
268✔
1062
            let sig_tuple = decimal_class
268✔
1063
                .call1((tuple.get_item(1)?,))?
268✔
1064
                .call_method0(intern!(py, "as_tuple"))?
268✔
1065
                .cast_into::<PyTuple>()?;
268✔
1066
            let sign = sig_tuple.get_item(0)?;
268✔
1067
            let digits = sig_tuple.get_item(1)?;
268✔
1068
            let args_tuple = PyTuple::new(py, [sign, digits, exp])?;
268✔
1069
            decimal_class.call1((args_tuple,)).map(CompleteFrame)
268✔
1070
        }
1071
    }
280✔
1072

1073
    fn decode_bigfloat(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
24✔
1074
        // Semantic tag 5
1075
        let py = value.py();
24✔
1076
        let tuple = require_tuple(value, 2)?;
24✔
1077
        let decimal_class = DECIMAL_TYPE.get(py)?;
12✔
1078
        {
1079
            let exp = decimal_class.call1((tuple.get_item(0)?,))?;
12✔
1080
            let sig = decimal_class.call1((tuple.get_item(1)?,))?;
12✔
1081
            let exp = PyInt::new(py, 2).pow(exp, py.None())?;
12✔
1082
            sig.mul(exp).map(CompleteFrame)
12✔
1083
        }
1084
    }
24✔
1085

1086
    fn decode_stringref(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
96✔
1087
        // Semantic tag 25
1088
        let index: usize = value.extract()?;
96✔
1089
        Ok(StringReference(index))
96✔
1090
    }
96✔
1091

1092
    fn decode_sharedref(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
180✔
1093
        // Semantic tag 29
1094
        let index: usize = value.extract()?;
180✔
1095
        Ok(SharedReference(index))
180✔
1096
    }
180✔
1097

1098
    fn decode_rational(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
244✔
1099
        // Semantic tag 30
1100
        let py = value.py();
244✔
1101
        let tuple = require_tuple(value, 2)?;
244✔
1102
        FRACTION_TYPE.get(py)?.call1(tuple).map(CompleteFrame)
232✔
1103
    }
244✔
1104

1105
    fn decode_regexp(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
36✔
1106
        // Semantic tag 35
1107
        RE_COMPILE
36✔
1108
            .get(value.py())?
36✔
1109
            .call1((value,))
36✔
1110
            .map(CompleteFrame)
36✔
1111
    }
36✔
1112

1113
    fn decode_mime(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
24✔
1114
        // Semantic tag 36
1115
        let py = value.py();
24✔
1116
        let parser = EMAIL_PARSER.get(py)?.call0()?;
24✔
1117
        parser
24✔
1118
            .call_method1(intern!(py, "parsestr"), (value,))
24✔
1119
            .map(CompleteFrame)
24✔
1120
    }
24✔
1121

1122
    fn decode_uuid(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
208✔
1123
        // Semantic tag 37
1124
        let py = value.py();
208✔
1125
        let kwargs = PyDict::new(py);
208✔
1126
        kwargs.set_item(intern!(py, "bytes"), value)?;
208✔
1127
        UUID_TYPE
208✔
1128
            .get(py)?
208✔
1129
            .call((), Some(&kwargs))
208✔
1130
            .map(CompleteFrame)
208✔
1131
    }
208✔
1132

1133
    fn decode_ipv4(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
60✔
1134
        // Semantic tag 52
1135
        let py = value.py();
60✔
1136
        let addr = if let Ok(bytes) = value.cast::<PyBytes>() {
60✔
1137
            // The decoded value was a bytestring, so this is an IPv4 address
1138
            IPV4ADDRESS_TYPE.get(py)?.call1((bytes,))?
36✔
1139
        } else if let Ok(tuple) = value.cast_into::<PyTuple>()
24✔
1140
            && tuple.len() == 2
24✔
1141
        {
1142
            // The decoded value was a 2-item array. Check the types of the elements:
1143
            // (int, bytes) -> network
1144
            // (bytes, int) -> interface
1145
            let first_item = tuple.get_item(0)?;
24✔
1146
            let second_item = tuple.get_item(1)?;
24✔
1147
            if let Ok(prefix) = first_item.cast::<PyInt>()
24✔
1148
                && let Ok(address) = second_item.cast::<PyBytes>()
12✔
1149
            {
1150
                let mut address_vec: Vec<u8> = address.extract()?;
12✔
1151
                address_vec.resize(4, 0);
12✔
1152
                IPV4NETWORK_TYPE.get(py)?.call1(((address_vec, prefix),))?
12✔
1153
            } else if let Ok(address) = first_item.cast::<PyBytes>()
12✔
1154
                && let Ok(prefix) = second_item.cast::<PyInt>()
12✔
1155
            {
1156
                IPV4INTERFACE_TYPE.get(py)?.call1(((address, prefix),))?
12✔
1157
            } else {
1158
                return Err(CBORDecodeError::new_err("invalid types in input array"));
×
1159
            }
1160
        } else {
1161
            return Err(CBORDecodeError::new_err(
×
1162
                "input value must be a bytestring or an array of 2 elements",
×
1163
            ));
×
1164
        };
1165
        Ok(CompleteFrame(addr))
60✔
1166
    }
60✔
1167

1168
    fn decode_ipv6(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
60✔
1169
        // Semantic tag 54
1170
        let py = value.py();
60✔
1171
        let ipv6addr_class = IPV6ADDRESS_TYPE.get(py)?;
60✔
1172
        let addr = if let Ok(bytes) = value.cast::<PyBytes>() {
60✔
1173
            // The decoded value was a bytestring, so this is an IPv6 address
1174
            ipv6addr_class.call1((bytes,))?
24✔
1175
        } else if let Ok(tuple) = value.cast_into::<PyTuple>()
36✔
1176
            && (2..=3).contains(&tuple.len())
36✔
1177
        {
1178
            // The decoded value was a 2-item (or 3 with zone ID) array.
1179
            // Check the types of the elements:
1180
            // (int, bytes) -> network
1181
            // (bytes, int) -> interface
1182
            let first_item = tuple.get_item(0)?;
36✔
1183
            let second_item = tuple.get_item(1)?;
36✔
1184
            let zone_id = tuple.get_item(2).ok();
36✔
1185
            let (class, addr_bytes, prefix) = if let Ok(prefix) = first_item.cast::<PyInt>()
36✔
1186
                && let Ok(address) = second_item.cast::<PyBytes>()
12✔
1187
            {
1188
                let mut address_vec: Vec<u8> = address.extract()?;
12✔
1189
                address_vec.resize(16, 0);
12✔
1190
                Ok((
1191
                    IPV6NETWORK_TYPE.get(py)?,
12✔
1192
                    PyBytes::new(py, address_vec.as_slice()),
12✔
1193
                    prefix,
12✔
1194
                ))
1195
            } else if let Ok(address) = first_item.cast_into::<PyBytes>()
24✔
1196
                && let Ok(prefix) = second_item.cast::<PyInt>()
24✔
1197
            {
1198
                Ok((IPV6INTERFACE_TYPE.get(py)?, address, prefix))
24✔
1199
            } else {
1200
                Err(CBORDecodeError::new_err("invalid types in input array"))
×
1201
            }?;
×
1202
            let addr_obj = ipv6addr_class.call1((addr_bytes,))?;
36✔
1203

1204
            // Format the zone ID suffix if a zone ID was included
1205
            // (bytes or integer as the last item of a 3-tuple)
1206
            let zone_id_suffix = if let Some(zone_id) = zone_id {
36✔
1207
                if let Ok(zone_id_bytes) = zone_id.cast::<PyBytes>() {
24✔
1208
                    let zone_id_str = String::from_utf8(zone_id_bytes.as_bytes().to_vec())?;
12✔
1209
                    format!("%{zone_id_str}")
12✔
1210
                } else if let Ok(zone_id_int) = zone_id.cast::<PyInt>() {
12✔
1211
                    format!("%{zone_id_int}")
12✔
1212
                } else {
1213
                    return Err(CBORDecodeError::new_err(
×
1214
                        "zone ID must be an integer or a bytestring",
×
1215
                    ));
×
1216
                }
1217
            } else {
1218
                String::default()
12✔
1219
            };
1220

1221
            let formatted_addr = format!("{addr_obj}{zone_id_suffix}/{prefix}");
36✔
1222
            class.call1((formatted_addr,))?
36✔
1223
        } else {
1224
            return Err(CBORDecodeError::new_err(
×
1225
                "input value must be a bytestring or an array of 2 elements",
×
1226
            ));
×
1227
        };
1228
        Ok(CompleteFrame(addr))
60✔
1229
    }
60✔
1230

1231
    fn decode_epoch_date(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
12✔
1232
        // Semantic tag 100
1233
        let py = value.py();
12✔
1234
        let value = value.extract::<i32>()? + 719163;
12✔
1235
        DATE_FROMORDINAL.get(py)?.call1((value,)).map(CompleteFrame)
12✔
1236
    }
12✔
1237

1238
    fn decode_ipaddress(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
84✔
1239
        // Semantic tag 260 (deprecated)
1240
        let py = value.py();
84✔
1241
        let value = value.cast_into::<PyBytes>()?;
84✔
1242
        let addr_obj = match value.len()? {
72✔
1243
            4 | 16 => IPADDRESS_FUNC.get(py)?.call1((value,)),
48✔
1244
            6 => Ok(Bound::new(py, CBORTag::new_internal(260, value.into_any()))?.into_any()), // MAC address
12✔
1245
            length => Err(CBORDecodeError::new_err(format!(
12✔
1246
                "invalid IP address length ({length})"
12✔
1247
            ))),
12✔
1248
        }?;
12✔
1249
        Ok(CompleteFrame(addr_obj))
60✔
1250
    }
84✔
1251

1252
    fn decode_ipnetwork<'py>(
84✔
1253
        value: Bound<'py, PyAny>,
84✔
1254
        _immutable: bool,
84✔
1255
    ) -> PyResult<DecoderResult<'py>> {
84✔
1256
        // Semantic tag 261 (deprecated)
1257
        let py = value.py();
84✔
1258
        let value: Bound<'py, PyMapping> = value.cast_into()?;
84✔
1259
        let length = value.len()?;
84✔
1260
        if length != 1 {
84✔
1261
            return Err(CBORDecodeError::new_err(format!(
12✔
1262
                "invalid input map length for IP network: {}",
12✔
1263
                length
12✔
1264
            )));
12✔
1265
        }
72✔
1266
        let first_item = value.items()?.get_item(0)?;
72✔
1267
        let mask_length = first_item.get_item(1)?;
72✔
1268
        if !mask_length.is_exact_instance_of::<PyInt>() {
72✔
1269
            return Err(CBORDecodeError::new_err(format!(
12✔
1270
                "invalid mask length for IP network: {mask_length}"
12✔
1271
            )));
12✔
1272
        }
60✔
1273

1274
        let addr_obj = match IPNETWORK_FUNC.get(py)?.call1((&first_item,)) {
60✔
1275
            Ok(ip_network) => Ok(ip_network),
48✔
1276
            Err(e) => {
12✔
1277
                // A CompleteFrameError may indicate that the bytestring has host bits set, so try parsing
1278
                // it as an IP interface instead
1279
                if e.is_instance_of::<PyValueError>(py) {
12✔
1280
                    IPINTERFACE_FUNC.get(py)?.call1((first_item,))
12✔
1281
                } else {
1282
                    Err(e)
×
1283
                }
1284
            }
1285
        }?;
×
1286
        Ok(CompleteFrame(addr_obj))
60✔
1287
    }
84✔
1288

1289
    fn decode_date_string(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
12✔
1290
        // Semantic tag 1004
1291
        let py = value.py();
12✔
1292
        let date = DATE_FROMISOFORMAT.get(py)?.call1((value,))?;
12✔
1293
        Ok(CompleteFrame(date))
12✔
1294
    }
12✔
1295

1296
    fn decode_complex(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
252✔
1297
        // Semantic tag 43000
1298
        let py = value.py();
252✔
1299
        let tuple = require_tuple(value, 2)?;
252✔
1300
        let real: f64 = tuple.get_item(0)?.extract()?;
252✔
1301
        let imag: f64 = tuple.get_item(1)?.extract()?;
252✔
1302
        Ok(CompleteFrame(
252✔
1303
            PyComplex::from_doubles(py, real, imag).into_any(),
252✔
1304
        ))
252✔
1305
    }
252✔
1306

1307
    fn decode_self_describe_cbor(value: Bound<PyAny>, _immutable: bool) -> PyResult<DecoderResult> {
24✔
1308
        // Semantic tag 55799
1309
        Ok(CompleteFrame(value))
24✔
1310
    }
24✔
1311

1312
    fn decode_set<'py>(
200✔
1313
        &mut self,
200✔
1314
        py: Python<'py>,
200✔
1315
        immutable: bool,
200✔
1316
    ) -> PyResult<DecoderResult<'py>> {
200✔
1317
        // Semantic tag 258
1318
        let mut set_or_none = if immutable {
200✔
1319
            None
36✔
1320
        } else {
1321
            Some(PySet::empty(py)?.into_any())
164✔
1322
        };
1323
        let container = set_or_none.clone();
200✔
1324
        let callback = move |item: Bound<'py, PyAny>, _immutable: bool| {
200✔
1325
            let container: Bound<'py, PyAny> = if let Some(set) = set_or_none.take() {
188✔
1326
                set.call_method1(intern!(py, "update"), (item,))?;
152✔
1327
                set.into_any()
152✔
1328
            } else {
1329
                let tuple = item.cast_into::<PyTuple>()?;
36✔
1330
                PyFrozenSet::new(py, tuple)?.into_any()
36✔
1331
            };
1332
            Ok(CompleteFrame(container))
188✔
1333
        };
188✔
1334
        Ok(BeginFrame(
200✔
1335
            Box::new(callback),
200✔
1336
            true,
200✔
1337
            container,
200✔
1338
            DisplayName::String("set"),
200✔
1339
        ))
200✔
1340
    }
200✔
1341
}
1342

1343
#[pymethods]
×
1344
impl CBORDecoder {
1345
    #[new]
1346
    #[pyo3(signature = (
1347
        fp,
1348
        *,
1349
        tag_hook = None,
1350
        object_hook = None,
1351
        semantic_decoders = None,
1352
        str_errors = "strict",
1353
        read_size = 4096,
1354
        max_depth = 400,
1355
        allow_indefinite = true,
1356
        allow_duplicate_keys = true,
1357
    ))]
1358
    pub fn new(
408✔
1359
        py: Python<'_>,
408✔
1360
        fp: &Bound<'_, PyAny>,
408✔
1361
        tag_hook: Option<&Bound<'_, PyAny>>,
408✔
1362
        object_hook: Option<&Bound<'_, PyAny>>,
408✔
1363
        semantic_decoders: Option<&Bound<'_, PyMapping>>,
408✔
1364
        str_errors: &str,
408✔
1365
        read_size: usize,
408✔
1366
        max_depth: usize,
408✔
1367
        allow_indefinite: bool,
408✔
1368
        allow_duplicate_keys: bool,
408✔
1369
    ) -> PyResult<Self> {
408✔
1370
        Self::new_internal(
408✔
1371
            py,
408✔
1372
            Some(fp),
408✔
1373
            None,
408✔
1374
            tag_hook,
408✔
1375
            object_hook,
408✔
1376
            semantic_decoders,
408✔
1377
            str_errors,
408✔
1378
            read_size,
408✔
1379
            max_depth,
408✔
1380
            allow_indefinite,
408✔
1381
            allow_duplicate_keys,
408✔
1382
        )
1383
    }
408✔
1384

1385
    #[getter]
1386
    fn fp(&self, py: Python<'_>) -> Option<Py<PyAny>> {
×
1387
        self.fp.as_ref().map(|fp| fp.clone_ref(py))
×
1388
    }
×
1389

1390
    #[setter]
1391
    fn set_fp(&mut self, fp: &Bound<'_, PyAny>) -> PyResult<()> {
420✔
1392
        let result = fp.call_method0("readable");
420✔
1393
        if let Ok(readable) = &result
420✔
1394
            && readable.is_truthy()?
408✔
1395
        {
1396
            self.fp_is_seekable = fp.call_method0("seekable")?.is_truthy()?;
396✔
1397
            let fp = fp.clone();
396✔
1398
            self.read_method = Some(fp.getattr("read")?.unbind());
396✔
1399
            self.fp = Some(fp.unbind());
396✔
1400
            self.available_bytes = 0;
396✔
1401
            self.read_position = 0;
396✔
1402
            self.buffer = None;
396✔
1403
            Ok(())
396✔
1404
        } else {
1405
            raise_exc_from(
24✔
1406
                fp.py(),
24✔
1407
                PyValueError::new_err("fp must be a readable file-like object"),
24✔
1408
                result.err(),
24✔
1409
            )
1410
        }
1411
    }
420✔
1412

1413
    #[getter]
1414
    fn tag_hook(&self, py: Python<'_>) -> Option<Py<PyAny>> {
12✔
1415
        self.tag_hook
12✔
1416
            .as_ref()
12✔
1417
            .map(|tag_hook| tag_hook.clone_ref(py))
12✔
1418
    }
12✔
1419

1420
    #[setter]
1421
    fn set_tag_hook(&mut self, tag_hook: Option<&Bound<'_, PyAny>>) -> PyResult<()> {
4,548✔
1422
        if let Some(tag_hook) = tag_hook {
4,548✔
1423
            if !tag_hook.is_callable() {
132✔
1424
                return Err(PyErr::new::<PyTypeError, _>(
12✔
1425
                    "tag_hook must be callable or None",
12✔
1426
                ));
12✔
1427
            }
120✔
1428

1429
            self.tag_hook = Some(tag_hook.clone().unbind());
120✔
1430
        } else {
4,416✔
1431
            self.tag_hook = None;
4,416✔
1432
        }
4,416✔
1433
        Ok(())
4,536✔
1434
    }
4,548✔
1435

1436
    #[getter]
1437
    fn object_hook(&self, py: Python<'_>) -> Option<Py<PyAny>> {
12✔
1438
        self.object_hook
12✔
1439
            .as_ref()
12✔
1440
            .map(|object_hook| object_hook.clone_ref(py))
12✔
1441
    }
12✔
1442

1443
    #[setter]
1444
    fn set_object_hook(&mut self, object_hook: Option<&Bound<'_, PyAny>>) -> PyResult<()> {
4,536✔
1445
        if let Some(object_hook) = object_hook {
4,536✔
1446
            if !object_hook.is_callable() {
48✔
1447
                return Err(PyErr::new::<PyTypeError, _>(
12✔
1448
                    "object_hook must be callable or None",
12✔
1449
                ));
12✔
1450
            }
36✔
1451

1452
            self.object_hook = Some(object_hook.clone().unbind());
36✔
1453
        } else {
4,488✔
1454
            self.object_hook = None;
4,488✔
1455
        }
4,488✔
1456
        Ok(())
4,524✔
1457
    }
4,536✔
1458

1459
    #[getter]
1460
    fn str_errors(&self, py: Python<'_>) -> Py<PyString> {
60✔
1461
        if let Some(str_errors) = self.str_errors.as_ref() {
60✔
1462
            str_errors.clone_ref(py)
48✔
1463
        } else {
1464
            intern!(py, "strict").clone().unbind()
12✔
1465
        }
1466
    }
60✔
1467

1468
    #[setter]
1469
    fn set_str_errors(&mut self, str_errors: &Bound<'_, PyString>) -> PyResult<()> {
4,524✔
1470
        let as_string: &str = str_errors.extract()?;
4,524✔
1471
        self.str_errors = match as_string {
4,524✔
1472
            "strict" => None,
4,524✔
1473
            "ignore" | "replace" | "backslashreplace" | "surrogateescape" => {
108✔
1474
                Some(str_errors.clone().unbind())
96✔
1475
            }
1476
            _ => {
1477
                return Err(PyValueError::new_err(format!(
12✔
1478
                    "invalid str_errors value: '{str_errors}'"
12✔
1479
                )));
12✔
1480
            }
1481
        };
1482
        Ok(())
4,512✔
1483
    }
4,524✔
1484

1485
    /// Read bytes from the data stream.
1486
    ///
1487
    /// :param amount: the number of bytes to read
1488
    #[pyo3(signature = (amount, /))]
1489
    fn read(&mut self, py: Python<'_>, amount: usize) -> PyResult<Vec<u8>> {
3,504✔
1490
        if amount == 0 {
3,504✔
1491
            return Ok(Vec::default());
160✔
1492
        }
3,344✔
1493

1494
        if self.available_bytes == 0 {
3,344✔
1495
            // No buffer
1496
            let (new_bytes, amount_read) = self.read_from_fp(py, amount)?;
72✔
1497
            self.read_position = amount;
12✔
1498
            self.available_bytes = amount_read - amount;
12✔
1499
            let new_buffer = new_bytes.as_bytes()[..amount].to_vec();
12✔
1500
            self.buffer = Some(new_bytes.unbind());
12✔
1501
            Ok(new_buffer)
12✔
1502
        } else if self.available_bytes < amount {
3,272✔
1503
            // Combine the remnants of the partial buffer with new data read from the file
1504
            let needed_bytes = amount - self.available_bytes;
72✔
1505
            let mut concatenated_buffer: Vec<u8> =
72✔
1506
                self.buffer.take().unwrap().as_bytes(py).to_vec();
72✔
1507
            let (new_bytes, amount_read) = self.read_from_fp(py, needed_bytes)?;
72✔
1508
            concatenated_buffer.extend_from_slice(&new_bytes[..needed_bytes]);
×
1509
            self.buffer = Some(new_bytes.unbind());
×
1510
            self.available_bytes = amount_read - needed_bytes;
×
1511
            self.read_position = needed_bytes;
×
1512
            Ok(concatenated_buffer)
×
1513
        } else {
1514
            // Return a slice from the existing bytes object
1515
            let vec = self.buffer.as_ref().unwrap().as_bytes(py)
3,200✔
1516
                [self.read_position..self.read_position + amount]
3,200✔
1517
                .to_vec();
3,200✔
1518
            self.available_bytes -= amount;
3,200✔
1519
            self.read_position += amount;
3,200✔
1520
            Ok(vec)
3,200✔
1521
        }
1522
    }
3,504✔
1523

1524
    /// Decode the next value from the stream.
1525
    ///
1526
    /// :param immutable: if :data:`True`, decode the next item as an immutable type
1527
    ///     (e.g. :class:`tuple` instead of a :class:`list`), if possible
1528
    /// :return: the decoded object
1529
    /// :raises CBORDecodeError: if there is any problem decoding the stream
1530
    #[pyo3(signature = (*, immutable = false))]
1531
    pub fn decode<'py>(&mut self, py: Python<'py>, immutable: bool) -> PyResult<Bound<'py, PyAny>> {
4,392✔
1532
        let mut frames: Vec<StackFrame> = Vec::new();
4,392✔
1533

1534
        fn add_frame<'a>(
11,596✔
1535
            frames: &mut Vec<StackFrame<'a>>,
11,596✔
1536
            max_depth: usize,
11,596✔
1537
            frame: StackFrame<'a>,
11,596✔
1538
        ) -> PyResult<()> {
11,596✔
1539
            if frames.len() == max_depth {
11,596✔
1540
                return Err(CBORDecodeError::new_err(format!(
24✔
1541
                    "maximum container nesting depth ({max_depth}) exceeded",
24✔
1542
                )));
24✔
1543
            }
11,572✔
1544

1545
            frames.push(frame);
11,572✔
1546
            Ok(())
11,572✔
1547
        }
11,596✔
1548

1549
        fn wrap_exception(py: Python<'_>, err: PyErr, typename: &DisplayName) -> PyErr {
636✔
1550
            if err.is_instance_of::<CBORDecodeEOF>(py) {
636✔
1551
                err
120✔
1552
            } else if err.is_instance_of::<CBORDecodeError>(py) {
516✔
1553
                CBORDecodeError::new_err(format!(
276✔
1554
                    "error decoding {}: {}",
1555
                    typename,
1556
                    err.arguments(py)
276✔
1557
                ))
1558
            } else {
1559
                create_exc_from(
240✔
1560
                    py,
240✔
1561
                    CBORDecodeError::new_err(format!("error decoding {}", typename)),
240✔
1562
                    Some(err),
240✔
1563
                )
1564
            }
1565
        }
636✔
1566

1567
        let mut shareables: Vec<Option<Bound<'py, PyAny>>> = Vec::new();
4,392✔
1568
        let mut string_namespaces: Vec<Vec<Bound<'py, PyAny>>> = Vec::new();
4,392✔
1569
        let mut value: Option<Bound<'py, PyAny>> = None;
4,392✔
1570
        let mut current_immutable: bool = immutable;
4,392✔
1571
        loop {
1572
            let result: PyResult<DecoderResult<'py>> = if let Some(previous_value) = value.take() {
34,308✔
1573
                // Call the decoder callback of the last frame
1574
                let frame = frames.last_mut().unwrap();
12,252✔
1575
                if let Some(decoder_callback) = frame.decoder_callback.as_mut() {
12,252✔
1576
                    decoder_callback(previous_value, frame.immutable)
12,168✔
1577
                        .map_err(|e| wrap_exception(py, e, &frame.typename))
12,168✔
1578
                } else if frame.contains_string_namespace {
84✔
1579
                    string_namespaces
12✔
1580
                        .pop()
12✔
1581
                        .expect("no string namespaces to pop from");
12✔
1582
                    Ok(CompleteFrame(previous_value))
12✔
1583
                } else if let Some(shareable_index) = frame.shareable_index {
72✔
1584
                    shareables[shareable_index].get_or_insert_with(|| previous_value.clone());
72✔
1585
                    Ok(CompleteFrame(previous_value))
72✔
1586
                } else {
1587
                    panic!("no decoder callback, shareable index or string namespace");
×
1588
                }
1589
            } else {
1590
                let (major_type, subtype) = self.read_major_and_subtype(py)?;
22,056✔
1591
                match major_type {
22,032✔
1592
                    0 => self.decode_uint(py, subtype),
3,756✔
1593
                    1 => self.decode_negint(py, subtype),
464✔
1594
                    2 => self.decode_bytestring(py, subtype),
1,128✔
1595
                    3 => self.decode_string(py, subtype),
2,280✔
1596
                    4 => self.decode_array(py, subtype, current_immutable),
7,072✔
1597
                    5 => self.decode_map(py, subtype, current_immutable),
1,792✔
1598
                    6 => self.decode_semantic(py, subtype, current_immutable),
3,116✔
1599
                    7 => self.decode_special(py, subtype),
2,424✔
1600
                    _ => Err(CBORDecodeError::new_err(format!(
×
1601
                        "invalid major type: {major_type}"
×
1602
                    ))),
×
1603
                }
1604
                .map_err(|e| {
22,032✔
1605
                    let typename = match major_type {
360✔
1606
                        0 => "unsigned integer",
12✔
1607
                        1 => "negative integer",
×
1608
                        2 => "byte string",
108✔
1609
                        3 => "text string",
168✔
1610
                        4 => "array",
×
1611
                        5 => "map",
×
1612
                        6 => "semantic tag",
×
1613
                        7 => "special value",
72✔
1614
                        _ => unreachable!("invalid major types should have been handled earlier"),
×
1615
                    };
1616
                    wrap_exception(py, e, &DisplayName::String(typename))
360✔
1617
                })
360✔
1618
            };
1619

1620
            match result {
33,648✔
1621
                Ok(BeginFrame(callback, requested_immutable, container, typename)) => {
11,320✔
1622
                    if let Some(frame) = frames.last_mut()
11,320✔
1623
                        && let Some(container) = container
8,784✔
1624
                        && let Some(shareable_index) = frame.shareable_index
5,896✔
1625
                    {
156✔
1626
                        frames.pop();
156✔
1627
                        shareables[shareable_index] = Some(container.clone());
156✔
1628
                    }
11,164✔
1629
                    current_immutable = current_immutable || requested_immutable;
11,320✔
1630
                    add_frame(
11,320✔
1631
                        &mut frames,
11,320✔
1632
                        self.max_depth,
11,320✔
1633
                        StackFrame {
11,320✔
1634
                            immutable: current_immutable,
11,320✔
1635
                            decoder_callback: Some(callback),
11,320✔
1636
                            shareable_index: None,
11,320✔
1637
                            typename,
11,320✔
1638
                            contains_string_namespace: false,
11,320✔
1639
                        },
11,320✔
1640
                    )?;
24✔
1641
                }
1642
                Ok(ContinueFrame(require_immutable)) => {
6,092✔
1643
                    // If require_immutable is true, the next value must be immutable
1644
                    // Otherwise, restore the immutable flag to the previous value
1645
                    current_immutable = if frames.len() >= 2 {
6,092✔
1646
                        frames.get(frames.len() - 2).unwrap().immutable
3,036✔
1647
                    } else {
1648
                        immutable
3,056✔
1649
                    } || require_immutable;
4,412✔
1650
                    frames.last_mut().unwrap().immutable = current_immutable;
6,092✔
1651
                }
1652
                Ok(CompleteFrame(new_value)) => {
5,608✔
1653
                    frames
5,608✔
1654
                        .pop()
5,608✔
1655
                        .expect("received frame completion but there are no frames on the stack");
5,608✔
1656
                    current_immutable = frames.last().map_or(immutable, |frame| frame.immutable);
5,608✔
1657
                    value = Some(new_value);
5,608✔
1658
                }
1659
                Ok(Value(new_value)) => {
6,980✔
1660
                    value = Some(new_value);
6,980✔
1661
                }
6,980✔
1662
                Ok(StringNamespace) => {
1663
                    add_frame(
36✔
1664
                        &mut frames,
36✔
1665
                        self.max_depth,
36✔
1666
                        StackFrame {
36✔
1667
                            immutable: current_immutable,
36✔
1668
                            decoder_callback: None,
36✔
1669
                            shareable_index: None,
36✔
1670
                            typename: DisplayName::String("string namespace"),
36✔
1671
                            contains_string_namespace: true,
36✔
1672
                        },
36✔
1673
                    )?;
×
1674
                    string_namespaces.push(Vec::new());
36✔
1675
                }
1676
                Ok(StringValue(string, length)) => {
3,096✔
1677
                    // Conditionally add the string to the innermost string namespace
1678
                    if let Some(namespace) = string_namespaces.last_mut()
3,096✔
1679
                        && match namespace.len() {
48✔
1680
                            0..24 => length >= 3,
48✔
1681
                            24..256 => length >= 4,
×
1682
                            256..65536 => length >= 5,
×
1683
                            65536..=4294967295 => length >= 6,
×
1684
                            _ => length >= 11,
×
1685
                        }
1686
                    {
48✔
1687
                        namespace.push(string.clone());
48✔
1688
                    }
3,048✔
1689
                    value = Some(string);
3,096✔
1690
                }
1691
                Ok(StringReference(index)) => {
96✔
1692
                    frames
96✔
1693
                        .pop()
96✔
1694
                        .expect("  received string reference but there are no frames on the stack");
96✔
1695
                    if let Some(namespace) = string_namespaces.last() {
96✔
1696
                        if let Some(string) = namespace.get(index) {
84✔
1697
                            value = Some(string.clone());
72✔
1698
                        } else {
72✔
1699
                            return Err(CBORDecodeError::new_err(format!(
12✔
1700
                                "string reference {index} not found"
12✔
1701
                            )));
12✔
1702
                        }
1703
                    } else {
1704
                        return Err(CBORDecodeError::new_err(
12✔
1705
                            "string reference outside of namespace",
12✔
1706
                        ));
12✔
1707
                    }
1708
                    current_immutable = frames
72✔
1709
                        .last()
72✔
1710
                        .map_or(current_immutable, |frame| frame.immutable);
72✔
1711
                }
1712
                Ok(Shareable) => {
1713
                    add_frame(
240✔
1714
                        &mut frames,
240✔
1715
                        self.max_depth,
240✔
1716
                        StackFrame {
240✔
1717
                            immutable: current_immutable,
240✔
1718
                            decoder_callback: None,
240✔
1719
                            shareable_index: Some(shareables.len()),
240✔
1720
                            typename: DisplayName::String("shareable value"),
240✔
1721
                            contains_string_namespace: false,
240✔
1722
                        },
240✔
1723
                    )?;
×
1724
                    shareables.push(None);
240✔
1725
                }
1726
                Ok(SharedReference(index)) => {
180✔
1727
                    frames
180✔
1728
                        .pop()
180✔
1729
                        .expect("received shared reference but there are no frames on the stack");
180✔
1730
                    value = match shareables.get(index) {
180✔
1731
                        Some(Some(value)) => Some(value.clone()),
144✔
1732
                        Some(None) => {
1733
                            return Err(CBORDecodeError::new_err(format!(
12✔
1734
                                "shared value {index} has not been initialized"
12✔
1735
                            )));
12✔
1736
                        }
1737
                        None => {
1738
                            return Err(CBORDecodeError::new_err(format!(
24✔
1739
                                "shared reference {index} not found"
24✔
1740
                            )));
24✔
1741
                        }
1742
                    };
1743
                    current_immutable = frames
144✔
1744
                        .last()
144✔
1745
                        .map_or(current_immutable, |frame| frame.immutable);
144✔
1746
                }
1747
                Err(err) => {
636✔
1748
                    // If an Exception was raised, wrap it in a CBORDecodeError
1749
                    // If a ValueError was raised, wrap it in a CBORDecodeError
1750
                    return if err.is_instance_of::<CBORDecodeError>(py) {
636✔
1751
                        Err(err)
636✔
1752
                    } else if err.is_instance_of::<PyValueError>(py)
×
1753
                        || err.is_instance_of::<PyException>(py)
×
1754
                    {
1755
                        Err(create_exc_from(
×
1756
                            py,
×
1757
                            CBORDecodeError::new_err(err.to_string()),
×
1758
                            Some(err),
×
1759
                        ))
×
1760
                    } else {
1761
                        Err(err)
×
1762
                    };
1763
                }
1764
            }
1765

1766
            if frames.is_empty() {
33,564✔
1767
                // If fp was seekable and excess data has been read, empty the buffer and
1768
                // rewind the file
1769
                if self.available_bytes > 0
3,648✔
1770
                    && let Some(fp) = &self.fp
24✔
1771
                {
1772
                    let offset = -(self.available_bytes as isize);
24✔
1773
                    fp.call_method1(py, intern!(py, "seek"), (offset, SEEK_CUR))?;
24✔
1774
                    self.buffer = None;
24✔
1775
                    self.available_bytes = 0;
24✔
1776
                    self.read_position = 0;
24✔
1777
                }
3,624✔
1778
                return Ok(value.expect("stack is empty but final return value is missing"));
3,648✔
1779
            }
29,916✔
1780
        }
1781
    }
4,392✔
1782
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc