Skip to content

Commit

Permalink
add support for pickle (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
guillp authored Aug 5, 2023
1 parent 6983e38 commit 213b58b
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ isinstance(bp, bytes)
## Features

- Fluent interface, based on a `bytes` subclass
- Provides a convenient interface over `hashlib`, `base64`, `zlib`, `urllib.parse`, `json` and more
- Provides a convenient interface over `hashlib`, `base64`, `zlib`, `urllib.parse`, `json`, `pickle` and more
- Easy to extend with new formats

## TODO
Expand Down
1 change: 1 addition & 0 deletions binapy/parsing/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
"""This module contains helpers for parsing or serializing data in various formats."""
from .json import *
from .pickle import *
33 changes: 33 additions & 0 deletions binapy/parsing/pickle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"""This module implements helpers for (de)serializing to/from Python `pickle` objects."""

import pickle
from typing import Any, Optional

from binapy import binapy_parser, binapy_serializer


@binapy_serializer("pickle")
def to_pickle(
o: object,
protocol: Optional[int] = None,
fix_imports: bool = True,
buffer_callback: Any = None,
) -> bytes:
"""Serialize an object using `pickle.dumps()`."""
return pickle.dumps(
o, protocol=protocol, fix_imports=fix_imports, buffer_callback=buffer_callback
)


@binapy_parser("pickle")
def from_pickle(
bp: bytes,
fix_imports: bool = True,
encoding: str = "ASCII",
errors: str = "strict",
buffers: Any = None,
) -> object:
"""Deserialize an object using `pickle.loads()`."""
return pickle.loads(
bp, fix_imports=fix_imports, encoding=encoding, errors=errors, buffers=buffers
)
20 changes: 20 additions & 0 deletions tests/test_pickle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from __future__ import annotations

import secrets

from binapy import BinaPy


class PickleTester:
def __init__(self) -> None:
self.random = secrets.token_hex()

def __eq__(self, other: object) -> bool:
return isinstance(other, PickleTester) and other.random == self.random


o = PickleTester()


def test_pickle() -> None:
assert BinaPy.serialize_to("pickle", o).parse_from("pickle") == o

0 comments on commit 213b58b

Please sign in to comment.