Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion cid/cid.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,7 @@ class CIDv1(BaseCID):

def __init__(self, codec: str, multihash: str | bytes) -> None:
super().__init__(1, codec, multihash)
self._buffer: bytes | None = None

@property
def buffer(self) -> bytes:
Expand All @@ -286,7 +287,11 @@ def buffer(self) -> bytes:
:return: raw representation of the CID
:rtype: bytes
"""
return b"".join([bytes([self.version]), multicodec.add_prefix(self.codec, self.multihash)])
if self._buffer is None:
self._buffer = b"".join(
[bytes([self.version]), multicodec.add_prefix(self.codec, self.multihash)]
)
return self._buffer

def encode(self, encoding: str | None = "base32") -> bytes:
"""
Expand Down
1 change: 1 addition & 0 deletions newsfragments/70.performance.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Cache ``CIDv1.buffer`` after the first access so repeated serialization does not recompute the byte representation.
4 changes: 4 additions & 0 deletions tests/test_cid.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,10 @@ def test_buffer(self, cid):
assert buffer[0] == 1
assert buffer[1:] == multicodec.add_prefix(self.TEST_CODEC, cid.multihash)

def test_buffer_cached(self, cid):
""".buffer: same bytes object is returned on repeated access"""
assert cid.buffer is cid.buffer

def test_encode_default(self, cid):
"""#encode defaults to base32 encoding"""
assert cid.encode() == b"bafybeifzjut3te2nhyekklss27nh3k72ysco7y32koao5eei66wof36n5e"
Expand Down
Loading