Skip to content

Commit

Permalink
Merge pull request luizalabs#40 from luizalabs/fix-json-serialization…
Browse files Browse the repository at this point in the history
…-readme

Update serialization docs
  • Loading branch information
cassiobotaro authored Nov 3, 2021
2 parents 274828e + b05a4d1 commit 59b04b8
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,21 @@ We use [pickle](https://docs.python.org/3/library/pickle.html) as default to rea
You can create a custom serializer by implementing the `dumps` and `loads` methods.

```python
NULL_BYTE: Final = b"\x00"


class JSONSerializer:
def dumps(self, obj: dict) -> bytes:
return json.dumps(obj).encode()
return json.dumps(obj).encode() + NULL_BYTE

def loads(self, data: bytes) -> dict:
data = data.split(NULL_BYTE, 1)[0]
return json.loads(data)

```

Note: A null byte is used to separate the dictionary contents from the bytes that are in memory.

To use the custom serializer you must set it when creating a new shared memory dict instance:

```python
Expand Down
2 changes: 1 addition & 1 deletion shared_memory_dict/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def dumps(self, obj: dict) -> bytes:
return json.dumps(obj).encode() + NULL_BYTE

def loads(self, data: bytes) -> dict:
data = bytes(data).split(NULL_BYTE, 1)[0]
data = data.split(NULL_BYTE, 1)[0]
return json.loads(data)


Expand Down

0 comments on commit 59b04b8

Please sign in to comment.