Skip to content

Commit

Permalink
feat[serializers]: specify default JSON encoders to make subclassing …
Browse files Browse the repository at this point in the history
…more easily
  • Loading branch information
spaceone committed Nov 6, 2021
1 parent bf22c57 commit cb07dbf
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,19 +62,22 @@ NULL_BYTE: Final = b"\x00"


class JSONSerializer:

encoder = json.JSONEncoder
decoder = json.JSONDecoder

def dumps(self, obj: dict) -> bytes:
try:
return json.dumps(obj).encode() + NULL_BYTE
return json.dumps(obj, cls=self.encoder).encode() + NULL_BYTE
except (ValueError, TypeError):
raise SerializationError(obj)

def loads(self, data: bytes) -> dict:
data = data.split(NULL_BYTE, 1)[0]
try:
return json.loads(data)
return json.loads(data, cls=self.decoder)
except json.JSONDecodeError:
raise DeserializationError(data)

```

Note: A null byte is used to separate the dictionary contents from the bytes that are in memory.
Expand Down
8 changes: 6 additions & 2 deletions shared_memory_dict/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,20 @@ def loads(self, data: bytes) -> dict:


class JSONSerializer:

encoder = json.JSONEncoder
decoder = json.JSONDecoder

def dumps(self, obj: dict) -> bytes:
try:
return json.dumps(obj).encode() + NULL_BYTE
return json.dumps(obj, cls=self.encoder).encode() + NULL_BYTE
except (ValueError, TypeError):
raise SerializationError(obj)

def loads(self, data: bytes) -> dict:
data = data.split(NULL_BYTE, 1)[0]
try:
return json.loads(data)
return json.loads(data, cls=self.decoder)
except json.JSONDecodeError:
raise DeserializationError(data)

Expand Down

0 comments on commit cb07dbf

Please sign in to comment.