-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcommon.py
More file actions
45 lines (32 loc) · 1.09 KB
/
common.py
File metadata and controls
45 lines (32 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from __future__ import annotations
from collections.abc import Sequence
from typing import Any, Protocol
import json
import cbor2
class SerializationFormat(Protocol):
def dumps(self, obj: Any) -> bytes: ...
def loads(self, data: bytes) -> Any: ...
class json_as_bytes:
"""
JSON encoding as per the `json` module,
but making sure that the output type is `bytes` rather than `str`.
"""
@classmethod
def dumps(cls, obj: Any) -> bytes:
return json.dumps(obj).encode()
@classmethod
def loads(cls, data: bytes) -> Any:
return json.loads(data.decode())
DEFAULT_SERIALIZATION_FORMAT: SerializationFormat = cbor2
def encode_chunk(
chunk: Sequence[Any], serialization_format: SerializationFormat
) -> bytes:
return serialization_format.dumps(chunk)
def decode_chunk(
chunk: bytes, serialization_format: SerializationFormat
) -> Sequence[Any]:
res = serialization_format.loads(chunk)
assert isinstance(res, Sequence), (
f"Decoding a chunk should always return a sequence, got unexpected type {type(res)}"
)
return res