From 41e7f91c4c58226b5899b0a489eb220dd0146a5f Mon Sep 17 00:00:00 2001 From: acul71 Date: Mon, 7 Sep 2026 21:18:22 +0200 Subject: [PATCH] Cache CIDv1.buffer after first access. Avoid recomputing the byte representation on every encode/to_bytes/key_string call. Co-authored-by: Cursor --- cid/cid.py | 7 ++++++- newsfragments/70.performance.rst | 1 + tests/test_cid.py | 4 ++++ 3 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 newsfragments/70.performance.rst diff --git a/cid/cid.py b/cid/cid.py index 49b3f15..71cec8c 100644 --- a/cid/cid.py +++ b/cid/cid.py @@ -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: @@ -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: """ diff --git a/newsfragments/70.performance.rst b/newsfragments/70.performance.rst new file mode 100644 index 0000000..0d9d0b3 --- /dev/null +++ b/newsfragments/70.performance.rst @@ -0,0 +1 @@ +Cache ``CIDv1.buffer`` after the first access so repeated serialization does not recompute the byte representation. diff --git a/tests/test_cid.py b/tests/test_cid.py index da7b6f3..518b9cd 100644 --- a/tests/test_cid.py +++ b/tests/test_cid.py @@ -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"