Skip to content

Commit 2e64ffd

Browse files
committed
Make CStruct/MemCStruct Pickle Friendly
1 parent 400c88e commit 2e64ffd

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

cstruct/abstract.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,3 +229,23 @@ def __str__(self) -> str:
229229

230230
def __repr__(self) -> str: # pragma: no cover
231231
return self.__str__()
232+
233+
def __getstate__(self) -> bytes:
234+
"""
235+
This method is called and the returned object is pickled
236+
as the contents for the instance, instead of the contents of
237+
the instance’s dictionary
238+
239+
Returns:
240+
bytes: The packed structure
241+
"""
242+
return self.pack()
243+
244+
def __setstate__(self, state: bytes) -> bool:
245+
"""
246+
This method it is called with the unpickled state
247+
248+
Args:
249+
state: bytes to be unpacked
250+
"""
251+
return self.unpack(state)

tests/test_pickle.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#!/usr/bin/env python
2+
3+
import pickle
4+
import cstruct
5+
6+
7+
class Position(cstruct.CStruct):
8+
__byte_order__ = cstruct.LITTLE_ENDIAN
9+
__def__ = """
10+
struct {
11+
unsigned char head;
12+
unsigned char sector;
13+
unsigned char cyl;
14+
}
15+
"""
16+
17+
18+
class MemPosition(cstruct.MemCStruct):
19+
__byte_order__ = cstruct.LITTLE_ENDIAN
20+
__def__ = """
21+
struct {
22+
unsigned char head;
23+
unsigned char sector;
24+
unsigned char cyl;
25+
}
26+
"""
27+
28+
29+
def test_pickle():
30+
# pickle an object
31+
original_pos = Position(head=254, sector=63, cyl=134)
32+
pickled_bytes = pickle.dumps(original_pos)
33+
34+
# reconstitute a pickled object
35+
reconstituted_pos = pickle.loads(pickled_bytes)
36+
37+
assert reconstituted_pos.head == original_pos.head
38+
assert reconstituted_pos.sector == original_pos.sector
39+
assert reconstituted_pos.cyl == original_pos.cyl
40+
41+
42+
def test_mem_pickle():
43+
# pickle an object
44+
original_pos = MemPosition(head=254, sector=63, cyl=134)
45+
pickled_bytes = pickle.dumps(original_pos)
46+
47+
# reconstitute a pickled object
48+
reconstituted_pos = pickle.loads(pickled_bytes)
49+
50+
assert reconstituted_pos.head == original_pos.head
51+
assert reconstituted_pos.sector == original_pos.sector
52+
assert reconstituted_pos.cyl == original_pos.cyl

0 commit comments

Comments
 (0)