Skip to content

Commit 1bfe930

Browse files
committed
Issue #25384: Fix binascii.rledecode_hqx()
Fix usage of _PyBytesWriter API. Use the new _PyBytesWriter_Resize() function instead of _PyBytesWriter_Prepare().
1 parent c3d2bc1 commit 1bfe930

2 files changed

Lines changed: 22 additions & 5 deletions

File tree

Lib/test/test_binascii.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -159,11 +159,25 @@ def test_hqx(self):
159159
# Then calculate the hexbin4 binary-to-ASCII translation
160160
rle = binascii.rlecode_hqx(self.data)
161161
a = binascii.b2a_hqx(self.type2test(rle))
162+
162163
b, _ = binascii.a2b_hqx(self.type2test(a))
163164
res = binascii.rledecode_hqx(b)
164-
165165
self.assertEqual(res, self.rawdata)
166166

167+
def test_rle(self):
168+
# test repetition with a repetition longer than the limit of 255
169+
data = (b'a' * 100 + b'b' + b'c' * 300)
170+
171+
encoded = binascii.rlecode_hqx(data)
172+
self.assertEqual(encoded,
173+
(b'a\x90d' # 'a' * 100
174+
b'b' # 'b'
175+
b'c\x90\xff' # 'c' * 255
176+
b'c\x90-')) # 'c' * 45
177+
178+
decoded = binascii.rledecode_hqx(encoded)
179+
self.assertEqual(decoded, data)
180+
167181
def test_hex(self):
168182
# test hexlification
169183
s = b'{s\005\000\000\000worldi\002\000\000\000s\005\000\000\000helloi\001\000\000\0000'

Modules/binascii.c

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -800,14 +800,15 @@ binascii_rledecode_hqx_impl(PyModuleDef *module, Py_buffer *data)
800800
return PyErr_NoMemory();
801801

802802
/* Allocate a buffer of reasonable size. Resized when needed */
803-
out_len = in_len * 2;
803+
out_len = in_len;
804804
out_data = _PyBytesWriter_Alloc(&writer, out_len);
805805
if (out_data == NULL)
806806
return NULL;
807807

808808
/* Use overallocation */
809809
writer.overallocate = 1;
810-
out_len_left = writer.allocated;
810+
out_len = writer.allocated;
811+
out_len_left = out_len;
811812

812813
/*
813814
** We need two macros here to get/put bytes and handle
@@ -830,10 +831,12 @@ binascii_rledecode_hqx_impl(PyModuleDef *module, Py_buffer *data)
830831
overallocate the buffer anymore */ \
831832
writer.overallocate = 0; \
832833
} \
833-
out_data = _PyBytesWriter_Prepare(&writer, out_data, 1); \
834+
out_data = _PyBytesWriter_Resize(&writer, out_data, \
835+
writer.allocated + 1); \
834836
if (out_data == NULL) \
835837
goto error; \
836-
out_len_left = writer.allocated; \
838+
out_len_left = writer.allocated - out_len - 1; \
839+
out_len = writer.allocated; \
837840
} \
838841
*out_data++ = b; \
839842
} while(0)

0 commit comments

Comments
 (0)