Debian Codegraph @

awscrt/cbor.py

raw symbols SCIP
1 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 # SPDX-License-Identifier: Apache-2.0.
3
4 import _awscrt
5
6 from awscrt import NativeResource
7 from enum import IntEnum
8 from typing import Callable, Any, Union
9
10
11 class AwsCborType(IntEnum):
12 """CBOR data type enumeration.
13
14 Corresponds to `enum aws_cbor_type` in aws/common/cbor.h from AWS C Common Runtime.
15 These values represent the different types of data items that can be encoded/decoded in CBOR format
16 according to RFC 8949.
17
18 Attributes:
19 Unknown: Unknown/uninitialized type
20 UnsignedInt: Unsigned integer (major type 0)
21 NegativeInt: Negative integer (major type 1)
22 Float: Floating-point number (major type 7, simple value 25/26/27)
23 Bytes: Byte string (major type 2)
24 Text: Text string (major type 3)
25 ArrayStart: Start of definite-length array (major type 4)
26 MapStart: Start of definite-length map (major type 5)
27 Tag: Semantic tag (major type 6)
28 Bool: Boolean value (major type 7, simple value 20/21)
29 Null: Null value (major type 7, simple value 22)
30 Undefined: Undefined value (major type 7, simple value 23)
31 Break: Break stop code for indefinite-length items (major type 7, simple value 31)
32 IndefBytes: Start of indefinite-length byte string (major type 2)
33 IndefStr: Start of indefinite-length text string (major type 3)
34 IndefArray: Start of indefinite-length array (major type 4)
35 IndefMap: Start of indefinite-length map (major type 5)
36 """
37 Unknown = 0
38 UnsignedInt = 1
39 NegativeInt = 2
40 Float = 3
41 Bytes = 4
42 Text = 5
43 ArrayStart = 6
44 MapStart = 7
45 Tag = 8
46 Bool = 9
47 Null = 10
48 Undefined = 11
49 Break = 12
50 IndefBytes = 13
51 IndefStr = 14
52 IndefArray = 15
53 IndefMap = 16
54
55
56 class AwsCborEncoder(NativeResource):
57 """CBOR encoder for converting Python objects to CBOR binary format.
58
59 This class provides methods to encode various Python data types into CBOR (Concise Binary Object
60 Representation) format as defined in RFC 8949. The encoder builds CBOR data incrementally by
61 calling write_* methods in sequence.
62
63 Thread Safety:
64 This class is NOT thread-safe. Each encoder instance should only be used from a single thread.
65 Create separate encoder instances for concurrent encoding operations.
66
67 Memory Management:
68 The encoder automatically manages internal memory and integrates with AWS CRT memory management.
69 Call reset() to clear internal buffers for reuse, or let the encoder be garbage collected.
70
71 Typical Usage:
72 ```python
73 encoder = AwsCborEncoder()
74 encoder.write_int(42)
75 encoder.write_text("hello")
76 encoder.write_array_start(2)
77 encoder.write_bool(True)
78 encoder.write_null()
79 cbor_data = encoder.get_encoded_data()
80 ```
81
82 For complex data structures, use write_data_item() which automatically handles nested objects:
83 ```python
84 encoder = AwsCborEncoder()
85 data = {"numbers": [1, 2, 3], "text": "example", "flag": True}
86 encoder.write_data_item(data)
87 cbor_data = encoder.get_encoded_data()
88 ```
89 """
90
91 def __init__(self):
92 super().__init__()
93 self._binding = _awscrt.cbor_encoder_new()
94
95 def get_encoded_data(self) -> bytes:
96 """Return the current encoded data as bytes
97
98 Returns:
99 bytes: The encoded data currently
100 """
101 return _awscrt.cbor_encoder_get_encoded_data(self._binding)
102
103 def reset(self):
104 """Clear the encoder's internal buffer and reset to initial state.
105
106 After calling this method, the encoder is ready to encode new data from scratch.
107 Any previously encoded data is discarded and cannot be recovered.
108
109 This is useful for reusing the same encoder instance to encode multiple
110 independent CBOR documents without creating new encoder objects.
111
112 Note:
113 This operation does not raise exceptions and always succeeds.
114 """
115 return _awscrt.cbor_encoder_reset(self._binding)
116
117 def write_int(self, val: int):
118 """Write an int as cbor formatted,
119 val less than -2^64 will be encoded as Negative bignum for CBOR
120 val between -2^64 to -1, inclusive, will be encode as negative integer for CBOR
121 val between 0 to 2^64 - 1, inclusive, will be encoded as unsigned integer for CBOR
122 val greater than 2^64 - 1 will be encoded as Unsigned bignum for CBOR (Not implemented yet)
123
124 Args:
125 val (int): value to be encoded and written to the encoded data.
126 """
127 if val >= 0:
128 return _awscrt.cbor_encoder_write_uint(self._binding, val)
129 else:
130 # For negative value, the value to encode is -1 - val.
131 val_to_encode = -1 - val
132 return _awscrt.cbor_encoder_write_negint(self._binding, val_to_encode)
133
134 def write_float(self, val: float):
135 """Write a double as cbor formatted
136 Encodes as the most compact CBOR representation without loss of precision.
137
138 Args:
139 val (float): value to be encoded and written to the encoded data.
140 """
141 # Floating point numbers are usually implemented using double in C
142 return _awscrt.cbor_encoder_write_float(self._binding, val)
143
144 def write_bytes(self, val: bytes):
145 """Write bytes as cbor formatted
146
147 Args:
148 val (bytes): value to be encoded and written to the encoded data.
149 """
150 return _awscrt.cbor_encoder_write_bytes(self._binding, val)
151
152 def write_text(self, val: str):
153 """Write text as cbor formatted
154
155 Args:
156 val (str): value to be encoded and written to the encoded data.
157 """
158 return _awscrt.cbor_encoder_write_text(self._binding, val)
159
160 def write_array_start(self, number_entries: int):
161 """Add a start of array element.
162 for a number of the cbor data items to be included in the array.
163 `number_entries` should 0 to 2^64 inclusive.
164 Otherwise, ValueError will be raised.
165
166 Args:
167 number_entries (int): number of entries in the array to be written
168 """
169 if number_entries < 0 or number_entries > 2**64:
170 raise ValueError(f"{number_entries} must be between 0 and 2^64")
171
172 return _awscrt.cbor_encoder_write_array_start(self._binding, number_entries)
173
174 def write_map_start(self, number_entries: int):
175 """Add a start of map element, with the `number_entries`
176 for the number of pair of cbor data items to be included in the map.
177 `number_entries` should 0 to 2^64 inclusive.
178 Otherwise, ValueError will be raised.
179
180 Args:
181 number_entries (int): number of entries in the map to be written
182 """
183 if number_entries < 0 or number_entries > 2**64:
184 raise ValueError(f"{number_entries} must be between 0 and 2^64")
185
186 return _awscrt.cbor_encoder_write_map_start(self._binding, number_entries)
187
188 def write_tag(self, tag_number: int):
189 """Add a tag number.
190 Notes: it's user's responsibility to keep the integrity of the tagged value to follow the RFC8949 section 3.4
191
192 Args:
193 tag_number (int): the tag number, refer to RFC8949 section 3.4 for the valid tag number.
194 """
195 if tag_number < 0 or tag_number > 2**64:
196 raise ValueError(f"{tag_number} must be between 0 and 2^64")
197
198 return _awscrt.cbor_encoder_write_tag(self._binding, tag_number)
199
200 def write_null(self):
201 """Add a simple value 22 as null. Refer to RFC8949 section 3.3
202 """
203 return _awscrt.cbor_encoder_write_simple_types(self._binding, AwsCborType.Null)
204
205 def write_undefined(self):
206 """Add a simple value 23 as undefined. Refer to RFC8949 section 3.3
207 """
208 return _awscrt.cbor_encoder_write_simple_types(self._binding, AwsCborType.Undefined)
209
210 def write_indef_array_start(self):
211 """Begin an indefinite-length array. Must be closed with write_break().
212 Refer to RFC8949 section 3.2.2
213 """
214 return _awscrt.cbor_encoder_write_simple_types(self._binding, AwsCborType.IndefArray)
215
216 def write_indef_map_start(self):
217 """Begin an indefinite-length map. Must be closed with write_break().
218 Refer to RFC8949 section 3.2.2
219 """
220 return _awscrt.cbor_encoder_write_simple_types(self._binding, AwsCborType.IndefMap)
221
222 def write_indef_bytes_start(self):
223 """Begin an indefinite-length byte string. Must be followed by definite-length
224 byte strings and closed with write_break().
225 Refer to RFC8949 section 3.2.2
226 """
227 return _awscrt.cbor_encoder_write_simple_types(self._binding, AwsCborType.IndefBytes)
228
229 def write_indef_text_start(self):
230 """Begin an indefinite-length text string. Must be followed by definite-length
231 text strings and closed with write_break().
232 Refer to RFC8949 section 3.2.2
233 """
234 return _awscrt.cbor_encoder_write_simple_types(self._binding, AwsCborType.IndefStr)
235
236 def write_break(self):
237 """Write a break code (0xFF) to close an indefinite-length item.
238 Refer to RFC8949 section 3.2.2
239 """
240 return _awscrt.cbor_encoder_write_simple_types(self._binding, AwsCborType.Break)
241
242 def write_bool(self, val: bool):
243 """Add a simple value 20/21 as false/true. Refer to RFC8949 section 3.3
244 """
245 return _awscrt.cbor_encoder_write_bool(self._binding, val)
246
247 def write_epoch_time(self, val: float):
248 """Helper to write second-based epoch time as cbor formatted
249 Args:
250 val (float): second-based epoch time, float value to represent the precision less than 1 second.
251 """
252 # The epoch time is a tag 1, which is defined in RFC8949 section 3.4
253 _awscrt.cbor_encoder_write_tag(self._binding, 1)
254 # write the epoch time as float, which will be encoded as small as possible without loss of precision.
255 return _awscrt.cbor_encoder_write_float(self._binding, val)
256
257 def write_list(self, val: list):
258 """Generic helper API to write the whole list as cbor formatted.
259 The content of the list will be encoded as data_item.
260 """
261 return _awscrt.cbor_encoder_write_py_list(self._binding, val)
262
263 def write_dict(self, val: dict):
264 """Generic helper API to write the whole dict as cbor formatted.
265 The content of the dict will be encoded as data_item.
266 """
267 return _awscrt.cbor_encoder_write_py_dict(self._binding, val)
268
269 def write_data_item(self, data_item: Any):
270 """Generic API to write any type of an data_item as cbor formatted.
271 Specifically, it will be based on the type of data_item to decide how to encode it.
272 The supported type of data_item are:
273 - int
274 - float
275 - bool
276 - bytes
277 - str
278 - list
279 - dict
280
281 Args:
282 data_item (Any): any type of data_item. If the type is not supported to be converted to cbor format, ValueError will be raised.
283 """
284 return _awscrt.cbor_encoder_write_data_item(self._binding, data_item)
285
286
287 class AwsCborDecoder(NativeResource):
288 """CBOR decoder for converting CBOR binary format to Python objects.
289
290 This class provides methods to decode CBOR (Concise Binary Object Representation) binary data
291 into Python data types as defined in RFC 8949. The decoder processes CBOR data sequentially
292 using a peek-and-pop approach, allowing fine-grained control over the decoding process.
293
294 Thread Safety:
295 This class is NOT thread-safe. Each decoder instance should only be used from a single thread.
296 Create separate decoder instances for concurrent decoding operations.
297
298 Memory Management:
299 The decoder holds a reference to the source data and automatically manages internal state.
300 Use reset_src() to decode new data with the same decoder instance, or let the decoder
301 be garbage collected when no longer needed.
302
303 Decoding Workflow:
304 The decoder uses a sequential peek-and-pop pattern:
305 1. Use peek_next_type() to inspect the next data item type without consuming it
306 2. Use appropriate pop_next_*() method to decode and consume the data item
307 3. Repeat until all expected data is decoded
308 4. Check get_remaining_bytes_len() to get the remaining unprocessed data.
309
310 Basic Usage:
311 ```python
312 # Decode simple values
313 decoder = AwsCborDecoder(cbor_data)
314 if decoder.peek_next_type() == AwsCborType.UnsignedInt:
315 value = decoder.pop_next_unsigned_int()
316 ```
317
318 Generic Decoding:
319 For automatic type detection and conversion, use pop_next_data_item():
320 ```python
321 decoder = AwsCborDecoder(cbor_data)
322 python_object = decoder.pop_next_data_item() # Automatically handles any CBOR type
323 ```
324
325 Complex Structures:
326 ```python
327 decoder = AwsCborDecoder(cbor_data)
328
329 # Manually decode an array
330 if decoder.peek_next_type() == AwsCborType.ArrayStart:
331 array_length = decoder.pop_next_array_start()
332 items = []
333 for _ in range(array_length):
334 items.append(decoder.pop_next_data_item())
335
336 # Or use the convenience method
337 array = decoder.pop_next_list() # Handles both definite and indefinite arrays
338 ```
339
340 Tagged Values and Callbacks:
341 Handle semantic tags (like timestamps) with custom processing:
342 ```python
343 def handle_timestamp(epoch_secs):
344 return datetime.fromtimestamp(epoch_secs, tz=timezone.utc)
345
346 decoder = AwsCborDecoder(cbor_data, on_epoch_time=handle_timestamp)
347 timestamp = decoder.pop_next_data_item() # Returns datetime object for tag 1
348 ```
349
350 Error Handling:
351 The decoder raises exceptions for malformed data, type mismatches, and unexpected end-of-data.
352 Always handle these exceptions in production code:
353 ```python
354 try:
355 decoder = AwsCborDecoder(cbor_data)
356 result = decoder.pop_next_data_item()
357 except ValueError as e:
358 print(f"CBOR decoding error: {e}")
359 ```
360 """
361
362 def __init__(self, src: bytes, on_epoch_time: Callable[[Union[int, float]], Any] = None, **kwargs):
363 """Create an instance of AwsCborDecoder with the src data to be decoded.
364 The src data should be a bytes of cbor formatted data.
365
366 Args:
367 src (bytes): the bytes of cbor formatted data to be decoded.
368 on_epoch_time (Callable[[int, Any], Any], optional): Optional callback invoked once tags
369 with id: 1, which is the epoch time, are encountered during decoding a data_item.
370
371 The function should take the following arguments:
372 * `epoch_secs` (int | float): the seconds since epoch.
373
374 The function should return
375 * `result` (Any): The PyObject the epoch time converted to.
376 """
377 super().__init__()
378 self._src = src
379 self._binding = _awscrt.cbor_decoder_new(self, src)
380 self._on_epoch_time = on_epoch_time
381
382 def _on_epoch_time_callback(self, epoch_secs: Union[int, float]) -> Any:
383 if self._on_epoch_time is not None:
384 return self._on_epoch_time(epoch_secs)
385 else:
386 # just default to the numeric type.
387 return epoch_secs
388
389 def peek_next_type(self) -> AwsCborType:
390 """Return the AwsCborType of the next data item in the cbor formatted data
391 """
392 return AwsCborType(_awscrt.cbor_decoder_peek_type(self._binding))
393
394 def get_remaining_bytes_len(self) -> int:
395 """Return the number of bytes not consumed yet of the src data.
396 """
397 return _awscrt.cbor_decoder_get_remaining_bytes_len(self._binding)
398
399 def get_remaining_bytes(self) -> bytes:
400 """Return the remaining unprocessed CBOR data as bytes.
401
402 This method returns a slice of the original source data that has not yet been
403 consumed by the decoder. Useful for debugging, validation, or passing remaining
404 data to another decoder instance.
405
406 Returns:
407 bytes: The remaining unprocessed CBOR data. Returns empty bytes (b'') if
408 all data has been consumed.
409
410 Warning:
411 The returned bytes share memory with the original source data. Modifications
412 to the source data after decoder creation may affect the returned bytes.
413 """
414 remaining_length = _awscrt.cbor_decoder_get_remaining_bytes_len(self._binding)
415 if remaining_length <= 0:
416 return b''
417 start_idx = len(self._src) - remaining_length
418 return self._src[start_idx:]
419
420 def reset_src(self, src: bytes):
421 """Reset the src data to be decoded.
422 Note: the previous src data will be discarded.
423 Use `get_remaining_bytes` to fetch the remaining bytes if needed before invoking this function.
424 """
425 self._src = src
426 _awscrt.cbor_decoder_reset_src(self._binding, src)
427
428 def consume_next_single_element(self):
429 """
430 Consume the next single element, without the content followed by the element.
431
432 As an example for the following cbor, this function will only consume the
433 0xBF, "Start indefinite-length map", not any content of the map represented.
434 The next element to decode will start from 0x63:
435
436 0xbf6346756ef563416d7421ff
437 BF -- Start indefinite-length map
438 63 -- First key, UTF-8 string length 3
439 46756e -- "Fun"
440 F5 -- First value, true
441 63 -- Second key, UTF-8 string length 3
442 416d74 -- "Amt"
443 21 -- Second value, -2
444 FF -- "break"
445 """
446 return _awscrt.cbor_decoder_consume_next_element(self._binding)
447
448 def consume_next_whole_data_item(self):
449 """
450 Consume the next data item, includes all the content within the data item.
451 Specifically, it read extra for the types listed below:
452 1. `AwsCborType.IndefArray`, `AwsCborType.IndefMap`, `AwsCborType.IndefBytes` and `AwsCborType.IndefStr`. It read until
453 the `AwsCborType.Break` is read.
454 2. `AwsCborType.ArrayStart` and `AwsCborType.MapStart`. It read the number of data items in the array/map.
455 3. `AwsCborType.Tag`. It read the one extra data item as the value of the tag.
456
457 As an example for the following cbor, this function will consume all the data
458 as it's only one cbor data item, an indefinite map with 2 <key, value> pair:
459
460 0xbf6346756ef563416d7421ff
461 BF -- Start indefinite-length map
462 63 -- First key, UTF-8 string length 3
463 46756e -- "Fun"
464 F5 -- First value, true
465 63 -- Second key, UTF-8 string length 3
466 416d74 -- "Amt"
467 21 -- Second value, -2
468 FF -- "break"
469 """
470 return _awscrt.cbor_decoder_consume_next_data_item(self._binding)
471
472 def pop_next_unsigned_int(self) -> int:
473 """Return and consume the next data item as unsigned int if it's a `AwsCborType.UnsignedInt`
474 Otherwise, it will raise ValueError.
475 """
476 return _awscrt.cbor_decoder_pop_next_unsigned_int(self._binding)
477
478 def pop_next_negative_int(self) -> int:
479 """Return and consume the next data item as negative int if it's a `AwsCborType.NegativeInt`
480 Otherwise, it will raise ValueError.
481
482 Note: CBOR stores negative integers as -(val + 1), so we convert back
483 to the actual negative value by computing -(val + 1) = -1 - val.
484 """
485 encoded_val = _awscrt.cbor_decoder_pop_next_negative_int(self._binding)
486 return -1 - encoded_val
487
488 def pop_next_double(self) -> float:
489 """Return and consume the next data item as float if it's a `AwsCborType.Float`
490 Otherwise, it will raise ValueError.
491 """
492 return _awscrt.cbor_decoder_pop_next_float(self._binding)
493
494 def pop_next_bool(self) -> bool:
495 """Return and consume the next data item as bool if it's a `AwsCborType.Bool`
496 Otherwise, it will raise ValueError.
497 """
498 return _awscrt.cbor_decoder_pop_next_boolean(self._binding)
499
500 def pop_next_bytes(self) -> bytes:
501 """Return and consume the next data item as bytes if it's a `AwsCborType.Bytes`
502 Otherwise, it will raise ValueError.
503 """
504 return _awscrt.cbor_decoder_pop_next_bytes(self._binding)
505
506 def pop_next_text(self) -> str:
507 """Return and consume the next data item as text if it's a `AwsCborType.Text`
508 Otherwise, it will raise ValueError.
509 """
510 return _awscrt.cbor_decoder_pop_next_text(self._binding)
511
512 def pop_next_array_start(self) -> int:
513 """Return and consume the next data item as int if it's a `AwsCborType.ArrayStart`
514 Otherwise, it will raise ValueError.
515 The return value is the number of date items followed as the content of the array.
516
517 Notes: For indefinite-length, this function will fail with unexpected type. The designed way to
518 handle indefinite-length array is:
519 - Get `AwsCborType.IndefArray` from `peek_next_type`
520 - call `consume_next_single_element` to pop the indefinite-length start.
521 - Decode the next data item until `AwsCborType.Break` read.
522 """
523 return _awscrt.cbor_decoder_pop_next_array_start(self._binding)
524
525 def pop_next_map_start(self) -> int:
526 """Return and consume the next data item as int if it's a `AwsCborType.MapStart`
527 Otherwise, it will raise ValueError.
528 The return value is the number of paired date items followed as the content of the map.
529
530 Notes: For indefinite-length, this function will fail with unexpected type.
531 """
532 return _awscrt.cbor_decoder_pop_next_map_start(self._binding)
533
534 def pop_next_tag_val(self) -> int:
535 """Return and consume the next data item as int if it's a `AwsCborType.Tag`
536 Otherwise, it will raise ValueError.
537
538 The return value is the tag ID. Refer the RFC8949 section 3.4 for
539 corresponding expected data item to follow by the tag id as value.
540 """
541 return _awscrt.cbor_decoder_pop_next_tag(self._binding)
542
543 def pop_next_list(self) -> list:
544 """Return and consume the next data item as list if it's a `AwsCborType.ArrayStart` or `AwsCborType.IndefArray`
545 Otherwise, it will raise ValueError.
546 It consumes the all the content of the array as `pop_next_data_item`.
547 """
548 return _awscrt.cbor_decoder_pop_next_py_list(self._binding)
549
550 def pop_next_map(self) -> dict:
551 """Return and consume the next data item as list if it's a `AwsCborType.MapStart` or `AwsCborType.IndefMap`
552 Otherwise, it will raise ValueError.
553 It consumes the all the content of the map as `pop_next_data_item`.
554 """
555 return _awscrt.cbor_decoder_pop_next_py_dict(self._binding)
556
557 def pop_next_data_item(self) -> Any:
558 """Generic API to decode cbor formatted data to a python object.
559 This consumes the next data item and return the decoded object.
560 The type of the python object will be based on the cbor data item type.
561 a full map from the cbor data item type to the python object type is:
562 - `AwsCborType.UnsignedInt` or `AwsCborType.NegativeInt` -> int
563 - `AwsCborType.Float` -> float
564 - `AwsCborType.Bytes` or `AwsCborType.IndefBytes` -> bytes
565 - `AwsCborType.Text` or `AwsCborType.IndefStr` -> str
566 - `AwsCborType.Null` or `AwsCborType.Undefined` -> none
567 - `AwsCborType.Bool` -> bool
568 - `AwsCborType.ArrayStart` or `AwsCborType.IndefArray` and all the followed data items in the array -> list
569 - `AwsCborType.MapStart` or `AwsCborType.IndefMap` and all the followed data items in the map -> dict
570 - `AwsCborType.Tag`: For tag with id 1, as the epoch time, it invokes the _on_epoch_time for python to convert to expected type.
571 For the reset tag, exception will be raised.
572 """
573 return _awscrt.cbor_decoder_pop_next_data_item(self._binding)