···
1
+
from datetime import tzinfo
6
+
from .data import dataHook, Data
9
+
def tagHook(decoder: cbor2.CBORDecoder, tag: cbor2.CBORTag, shareable_index=None):
11
+
A simple tag hook for CID support.
13
+
return cid.from_bytes(tag.value) if tag.tag == 42 else tag
16
+
class CBOREncoder(cbor2.CBOREncoder):
18
+
Wrapper of cbor2.CBOREncoder.
23
+
fp: typing.IO[bytes],
24
+
datetime_as_timestamp: bool = False,
25
+
timezone: tzinfo | None = None,
26
+
value_sharing: bool = False,
28
+
typing.Callable[[cbor2.CBOREncoder, typing.Any], typing.Any] | None
30
+
canonical: bool = False,
31
+
date_as_datetime: bool = False,
32
+
string_referencing: bool = False,
33
+
indefinite_containers: bool = False,
37
+
datetime_as_timestamp,
44
+
indefinite_containers,
47
+
@cbor2.shareable_encoder
48
+
def cidOrDataEncoder(self: cbor2.CBOREncoder, value: cid.CIDv0 | cid.CIDv1 | Data):
50
+
Encode CID or Data to CBOR Tag.
52
+
if isinstance(value, (cid.CIDv0, cid.CIDv1)):
53
+
self.encode(cbor2.CBORTag(42, value.encode()))
54
+
elif isinstance(value, Data):
55
+
self.encode(value.data())
58
+
def _cborObjectHook(decoder: cbor2.CBORDecoder, value):
59
+
return dataHook(value)
62
+
class CBORDecoder(cbor2.CBORDecoder):
64
+
Wrapper of cbor2.CBORDecoder.
69
+
fp: typing.IO[bytes],
71
+
typing.Callable[[cbor2.CBORDecoder, cbor2.CBORTag], typing.Any] | None
75
+
[cbor2.CBORDecoder, dict[typing.Any, typing.Any]], typing.Any
78
+
) = _cborObjectHook,
79
+
str_errors: typing.Literal["strict", "error", "replace"] = "strict",
81
+
super().__init__(fp, tag_hook, object_hook, str_errors)
84
+
# Make things for CBOR again.
86
+
from io import BytesIO
91
+
datetime_as_timestamp: bool = False,
92
+
timezone: tzinfo | None = None,
93
+
value_sharing: bool = False,
94
+
default: typing.Callable[[cbor2.CBOREncoder, typing.Any], typing.Any] | None = None,
95
+
canonical: bool = False,
96
+
date_as_datetime: bool = False,
97
+
string_referencing: bool = False,
98
+
indefinite_containers: bool = False,
100
+
with BytesIO() as fp:
103
+
datetime_as_timestamp=datetime_as_timestamp,
105
+
value_sharing=value_sharing,
107
+
canonical=canonical,
108
+
date_as_datetime=date_as_datetime,
109
+
string_referencing=string_referencing,
110
+
indefinite_containers=indefinite_containers,
112
+
return fp.getvalue()
117
+
fp: typing.IO[bytes],
118
+
datetime_as_timestamp: bool = False,
119
+
timezone: tzinfo | None = None,
120
+
value_sharing: bool = False,
121
+
default: typing.Callable[[cbor2.CBOREncoder, typing.Any], typing.Any] | None = None,
122
+
canonical: bool = False,
123
+
date_as_datetime: bool = False,
124
+
string_referencing: bool = False,
125
+
indefinite_containers: bool = False,
129
+
datetime_as_timestamp=datetime_as_timestamp,
131
+
value_sharing=value_sharing,
133
+
canonical=canonical,
134
+
date_as_datetime=date_as_datetime,
135
+
string_referencing=string_referencing,
136
+
indefinite_containers=indefinite_containers,