From ff5a3d1335cc5e7e5587f0702d82f16a43d8f2bf Mon Sep 17 00:00:00 2001 From: AMIRUL IAN Date: Sat, 28 Nov 2026 09:40:51 +0800 Subject: [PATCH] Avoid copying remaining buffer in Decoder._decode_literal --- src/hpack/hpack.py | 17 ++++++----------- tests/test_hpack.py | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/src/hpack/hpack.py b/src/hpack/hpack.py index 1aff8ab..7a1c68f 100644 --- a/src/hpack/hpack.py +++ b/src/hpack/hpack.py @@ -599,9 +599,6 @@ def _decode_literal(self, data: bytes | memoryview, should_index: bool) -> tuple """ Decodes a header represented with a literal. """ - if isinstance(data, memoryview): - data = data.tobytes() # pragma: no cover - total_consumed = 0 # When should_index is true, if the low six bits of the first byte are @@ -631,26 +628,24 @@ def _decode_literal(self, data: bytes | memoryview, should_index: bool) -> tuple data = data[1:] length, consumed = decode_integer(data, 7) - name = data[consumed:consumed + length] - if len(name) != length: + raw_name = data[consumed:consumed + length] + if len(raw_name) != length: msg = "Truncated header block" raise HPACKDecodingError(msg) - if data[0] & 0x80: - name = decode_huffman(name) + name = decode_huffman(raw_name) if data[0] & 0x80 else bytes(raw_name) total_consumed = consumed + length + 1 # Since we moved forward 1. data = data[consumed + length:] # The header value is definitely length-based. length, consumed = decode_integer(data, 7) - value = data[consumed:consumed + length] - if len(value) != length: + raw_value = data[consumed:consumed + length] + if len(raw_value) != length: msg = "Truncated header block" raise HPACKDecodingError(msg) - if data[0] & 0x80: - value = decode_huffman(value) + value = decode_huffman(raw_value) if data[0] & 0x80 else bytes(raw_value) # Updated the total consumed length. total_consumed += length + consumed diff --git a/tests/test_hpack.py b/tests/test_hpack.py index e9c170c..d8e25b8 100644 --- a/tests/test_hpack.py +++ b/tests/test_hpack.py @@ -766,6 +766,22 @@ def test_truncated_header_value(self): with pytest.raises(HPACKDecodingError): d.decode(data) + def test_decode_many_literal_headers_memoryview(self): + """ + Decoding a block of many literal headers avoids copying the remaining + buffer on each field and returns bytes for both raw and decoded output. + """ + d = Decoder(max_header_list_size=1024 * 1024) + entry = b'\x00\x01k\x01v' + count = 2000 + data = entry * count + + raw_headers = d.decode(data, raw=True) + assert len(raw_headers) == count + assert raw_headers[0] == (b'k', b'v') + assert isinstance(raw_headers[0][0], bytes) + assert isinstance(raw_headers[0][1], bytes) + class TestDictToIterable: """