Skip to content

Commit 7ee43e1

Browse files
committed
gh-160308: Buffer punycode incremental codec input until the final call
1 parent e0d0f2e commit 7ee43e1

4 files changed

Lines changed: 166 additions & 98 deletions

File tree

‎Doc/library/codecs.rst‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1409,8 +1409,13 @@ encodings.
14091409
| palmos | | Encoding of PalmOS 3.5. |
14101410
+--------------------+---------+---------------------------+
14111411
| punycode | | Implement :rfc:`3492`. |
1412-
| | | Stateful codecs are not |
1413-
| | | supported. |
1412+
| | | The incremental encoder |
1413+
| | | and decoder buffer the |
1414+
| | | input until the final |
1415+
| | | call. Stream readers and |
1416+
| | | writers, and text files |
1417+
| | | opened for writing, are |
1418+
| | | not supported. |
14141419
| | | |
14151420
| | | .. warning:: |
14161421
| | | |

‎Lib/encodings/punycode.py‎

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -226,15 +226,22 @@ def decode(self, input, errors='strict'):
226226
res = punycode_decode(input, errors)
227227
return res, len(input)
228228

229-
class IncrementalEncoder(codecs.IncrementalEncoder):
230-
def encode(self, input, final=False):
231-
return punycode_encode(input)
229+
class IncrementalEncoder(codecs.BufferedIncrementalEncoder):
230+
def _buffer_encode(self, input, errors, final):
231+
if not final:
232+
# The encoding of each character depends on the whole string,
233+
# so keep the input until the last call
234+
return (b'', 0)
235+
return (punycode_encode(input), len(input))
232236

233-
class IncrementalDecoder(codecs.IncrementalDecoder):
234-
def decode(self, input, final=False):
235-
if self.errors not in ('strict', 'replace', 'ignore'):
236-
raise UnicodeError(f"Unsupported error handling: {self.errors}")
237-
return punycode_decode(input, self.errors)
237+
class IncrementalDecoder(codecs.BufferedIncrementalDecoder):
238+
def _buffer_decode(self, input, errors, final):
239+
if errors not in ('strict', 'replace', 'ignore'):
240+
raise UnicodeError(f"Unsupported error handling: {errors}")
241+
if not final:
242+
# Keep the input until the last call, as in IncrementalEncoder
243+
return ('', 0)
244+
return (punycode_decode(input, errors), len(input))
238245

239246
class StreamWriter(Codec,codecs.StreamWriter):
240247
pass

‎Lib/test/test_codecs.py‎

Lines changed: 138 additions & 88 deletions
Original file line numberDiff line numberDiff line change
@@ -1358,7 +1358,7 @@ def test_errors(self):
13581358
print(repr(i))
13591359

13601360

1361-
class PunycodeTest(unittest.TestCase):
1361+
class PunycodeTest(unittest.TestCase, MixInCheckStateHandling):
13621362
def test_encode(self):
13631363
for uni, puny in punycode_testcases:
13641364
# Need to convert both strings to lower case, since
@@ -1377,26 +1377,27 @@ def test_decode(self):
13771377
puny = puny.decode("ascii").encode("ascii")
13781378
self.assertEqual(uni, puny.decode("punycode"))
13791379

1380+
invalid_decode_testcases = [
1381+
(b"xn--w&", "strict", UnicodeDecodeError("punycode", b"", 5, 6, "")),
1382+
(b"&egbpdaj6bu4bxfgehfvwxn", "strict", UnicodeDecodeError("punycode", b"", 0, 1, "")),
1383+
(b"egbpdaj6bu&4bx&fgehfvwxn", "strict", UnicodeDecodeError("punycode", b"", 10, 11, "")),
1384+
(b"egbpdaj6bu4bxfgehfvwxn&", "strict", UnicodeDecodeError("punycode", b"", 22, 23, "")),
1385+
(b"\xFFProprostnemluvesky-uyb24dma41a", "strict", UnicodeDecodeError("ascii", b"", 0, 1, "")),
1386+
(b"Pro\xFFprostnemluvesky-uyb24dma41a", "strict", UnicodeDecodeError("ascii", b"", 3, 4, "")),
1387+
(b"Proprost&nemluvesky-uyb24&dma41a", "strict", UnicodeDecodeError("punycode", b"", 25, 26, "")),
1388+
(b"Proprostnemluvesky&-&uyb24dma41a", "strict", UnicodeDecodeError("punycode", b"", 20, 21, "")),
1389+
(b"Proprostnemluvesky-&uyb24dma41a", "strict", UnicodeDecodeError("punycode", b"", 19, 20, "")),
1390+
(b"Proprostnemluvesky-uyb24d&ma41a", "strict", UnicodeDecodeError("punycode", b"", 25, 26, "")),
1391+
(b"Proprostnemluvesky-uyb24dma41a&", "strict", UnicodeDecodeError("punycode", b"", 30, 31, "")),
1392+
# A delimiter not preceded by any basic code point (RFC 3492, 6.2)
1393+
(b"-", "strict", UnicodeDecodeError("punycode", b"", 0, 1, "")),
1394+
(b"-80a1acny", "strict", UnicodeDecodeError("punycode", b"", 0, 1, "")),
1395+
(b"xn--w&", "ignore", "xn-"),
1396+
(b"-80a1acny", "ignore", ""),
1397+
]
1398+
13801399
def test_decode_invalid(self):
1381-
testcases = [
1382-
(b"xn--w&", "strict", UnicodeDecodeError("punycode", b"", 5, 6, "")),
1383-
(b"&egbpdaj6bu4bxfgehfvwxn", "strict", UnicodeDecodeError("punycode", b"", 0, 1, "")),
1384-
(b"egbpdaj6bu&4bx&fgehfvwxn", "strict", UnicodeDecodeError("punycode", b"", 10, 11, "")),
1385-
(b"egbpdaj6bu4bxfgehfvwxn&", "strict", UnicodeDecodeError("punycode", b"", 22, 23, "")),
1386-
(b"\xFFProprostnemluvesky-uyb24dma41a", "strict", UnicodeDecodeError("ascii", b"", 0, 1, "")),
1387-
(b"Pro\xFFprostnemluvesky-uyb24dma41a", "strict", UnicodeDecodeError("ascii", b"", 3, 4, "")),
1388-
(b"Proprost&nemluvesky-uyb24&dma41a", "strict", UnicodeDecodeError("punycode", b"", 25, 26, "")),
1389-
(b"Proprostnemluvesky&-&uyb24dma41a", "strict", UnicodeDecodeError("punycode", b"", 20, 21, "")),
1390-
(b"Proprostnemluvesky-&uyb24dma41a", "strict", UnicodeDecodeError("punycode", b"", 19, 20, "")),
1391-
(b"Proprostnemluvesky-uyb24d&ma41a", "strict", UnicodeDecodeError("punycode", b"", 25, 26, "")),
1392-
(b"Proprostnemluvesky-uyb24dma41a&", "strict", UnicodeDecodeError("punycode", b"", 30, 31, "")),
1393-
# A delimiter not preceded by any basic code point (RFC 3492, 6.2)
1394-
(b"-", "strict", UnicodeDecodeError("punycode", b"", 0, 1, "")),
1395-
(b"-80a1acny", "strict", UnicodeDecodeError("punycode", b"", 0, 1, "")),
1396-
(b"xn--w&", "ignore", "xn-"),
1397-
(b"-80a1acny", "ignore", ""),
1398-
]
1399-
for puny, errors, expected in testcases:
1400+
for puny, errors, expected in self.invalid_decode_testcases:
14001401
with self.subTest(puny=puny, errors=errors):
14011402
if isinstance(expected, Exception):
14021403
with self.assertRaises(UnicodeDecodeError) as cm:
@@ -1409,6 +1410,58 @@ def test_decode_invalid(self):
14091410
else:
14101411
self.assertEqual(puny.decode("punycode", errors), expected)
14111412

1413+
def test_incremental_encode(self):
1414+
for uni, puny in punycode_testcases:
1415+
with self.subTest(uni=uni):
1416+
expected = uni.encode("punycode")
1417+
encoder = codecs.getincrementalencoder("punycode")()
1418+
result = b"".join(encoder.encode(c) for c in uni)
1419+
result += encoder.encode("", True)
1420+
self.assertEqual(encoder.getstate(), 0)
1421+
self.assertEqual(result, expected)
1422+
self.assertEqual(
1423+
b"".join(codecs.iterencode(uni, "punycode")), expected)
1424+
1425+
def test_incremental_decode(self):
1426+
for uni, puny in punycode_testcases:
1427+
with self.subTest(puny=puny):
1428+
chunks = [bytes([c]) for c in puny]
1429+
decoder = codecs.getincrementaldecoder("punycode")()
1430+
result = "".join(decoder.decode(c) for c in chunks)
1431+
result += decoder.decode(b"", True)
1432+
self.assertEqual(decoder.getstate(), (b"", 0))
1433+
self.assertEqual(result, uni)
1434+
self.assertEqual(
1435+
"".join(codecs.iterdecode(chunks, "punycode")), uni)
1436+
1437+
def test_incremental_decode_invalid(self):
1438+
for puny, errors, expected in self.invalid_decode_testcases:
1439+
with self.subTest(puny=puny, errors=errors):
1440+
chunks = (bytes([c]) for c in puny)
1441+
if isinstance(expected, Exception):
1442+
with self.assertRaises(UnicodeDecodeError) as cm:
1443+
list(codecs.iterdecode(chunks, "punycode", errors))
1444+
exc = cm.exception
1445+
self.assertEqual(exc.encoding, expected.encoding)
1446+
self.assertEqual(exc.object, puny)
1447+
self.assertEqual(exc.start, expected.start)
1448+
self.assertEqual(exc.end, expected.end)
1449+
else:
1450+
self.assertEqual(
1451+
"".join(codecs.iterdecode(chunks, "punycode", errors)),
1452+
expected)
1453+
1454+
decoder = codecs.getincrementaldecoder("punycode")("surrogateescape")
1455+
with self.assertRaises(UnicodeError):
1456+
decoder.decode(b"abc")
1457+
1458+
def test_incremental_state(self):
1459+
for uni, puny in punycode_testcases:
1460+
with self.subTest(uni=uni):
1461+
self.check_state_handling_decode("punycode", uni, puny)
1462+
self.check_state_handling_encode(
1463+
"punycode", uni, uni.encode("punycode"))
1464+
14121465

14131466
utf_7_imap_testcases = [
14141467
# (unicode, modified UTF-7)
@@ -2292,7 +2345,7 @@ def test_basic(self):
22922345
# to work:
22932346
# "undefined"
22942347

2295-
# The following encodings don't work in stateful mode
2348+
# The following encodings don't work with stream readers and writers
22962349
broken_unicode_with_stateful = [
22972350
"punycode",
22982351
]
@@ -2335,89 +2388,87 @@ def test_basics(self):
23352388
decodedresult += reader.read()
23362389
self.assertEqual(decodedresult, s, "encoding=%r" % encoding)
23372390

2338-
if encoding not in broken_unicode_with_stateful:
2339-
# check incremental decoder/encoder and iterencode()/iterdecode()
2391+
# check incremental decoder/encoder and iterencode()/iterdecode()
2392+
try:
2393+
encoder = codecs.getincrementalencoder(encoding)()
2394+
except LookupError: # no IncrementalEncoder
2395+
pass
2396+
else:
2397+
# check incremental decoder/encoder
2398+
encodedresult = b""
2399+
for c in s:
2400+
encodedresult += encoder.encode(c)
2401+
encodedresult += encoder.encode("", True)
2402+
decoder = codecs.getincrementaldecoder(encoding)()
2403+
decodedresult = ""
2404+
for c in encodedresult:
2405+
decodedresult += decoder.decode(bytes([c]))
2406+
decodedresult += decoder.decode(b"", True)
2407+
self.assertEqual(decodedresult, s,
2408+
"encoding=%r" % encoding)
2409+
2410+
# check iterencode()/iterdecode()
2411+
result = "".join(codecs.iterdecode(
2412+
codecs.iterencode(s, encoding), encoding))
2413+
self.assertEqual(result, s, "encoding=%r" % encoding)
2414+
2415+
# check iterencode()/iterdecode() with empty string
2416+
result = "".join(codecs.iterdecode(
2417+
codecs.iterencode("", encoding), encoding))
2418+
self.assertEqual(result, "")
2419+
2420+
if encoding not in ("idna", "mbcs", "punycode"):
2421+
# check incremental decoder/encoder with errors argument
23402422
try:
2341-
encoder = codecs.getincrementalencoder(encoding)()
2423+
encoder = codecs.getincrementalencoder(encoding)("ignore")
23422424
except LookupError: # no IncrementalEncoder
23432425
pass
23442426
else:
2345-
# check incremental decoder/encoder
2346-
encodedresult = b""
2347-
for c in s:
2348-
encodedresult += encoder.encode(c)
2349-
encodedresult += encoder.encode("", True)
2350-
decoder = codecs.getincrementaldecoder(encoding)()
2351-
decodedresult = ""
2352-
for c in encodedresult:
2353-
decodedresult += decoder.decode(bytes([c]))
2354-
decodedresult += decoder.decode(b"", True)
2427+
encodedresult = b"".join(encoder.encode(c) for c in s)
2428+
decoder = codecs.getincrementaldecoder(encoding)("ignore")
2429+
decodedresult = "".join(decoder.decode(bytes([c]))
2430+
for c in encodedresult)
23552431
self.assertEqual(decodedresult, s,
23562432
"encoding=%r" % encoding)
23572433

2358-
# check iterencode()/iterdecode()
2359-
result = "".join(codecs.iterdecode(
2360-
codecs.iterencode(s, encoding), encoding))
2361-
self.assertEqual(result, s, "encoding=%r" % encoding)
2362-
2363-
# check iterencode()/iterdecode() with empty string
2364-
result = "".join(codecs.iterdecode(
2365-
codecs.iterencode("", encoding), encoding))
2366-
self.assertEqual(result, "")
2367-
2368-
if encoding not in ("idna", "mbcs"):
2369-
# check incremental decoder/encoder with errors argument
2370-
try:
2371-
encoder = codecs.getincrementalencoder(encoding)("ignore")
2372-
except LookupError: # no IncrementalEncoder
2373-
pass
2374-
else:
2375-
encodedresult = b"".join(encoder.encode(c) for c in s)
2376-
decoder = codecs.getincrementaldecoder(encoding)("ignore")
2377-
decodedresult = "".join(decoder.decode(bytes([c]))
2378-
for c in encodedresult)
2379-
self.assertEqual(decodedresult, s,
2380-
"encoding=%r" % encoding)
2381-
23822434
@support.cpython_only
23832435
@unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
23842436
def test_basics_capi(self):
23852437
s = "abc123" # all codecs should be able to encode these
23862438
for encoding in all_unicode_encodings:
2387-
if encoding not in broken_unicode_with_stateful:
2388-
# check incremental decoder/encoder (fetched via the C API)
2439+
# check incremental decoder/encoder (fetched via the C API)
2440+
try:
2441+
cencoder = _testlimitedcapi.codec_incrementalencoder(encoding)
2442+
except LookupError: # no IncrementalEncoder
2443+
pass
2444+
else:
2445+
# check C API
2446+
encodedresult = b""
2447+
for c in s:
2448+
encodedresult += cencoder.encode(c)
2449+
encodedresult += cencoder.encode("", True)
2450+
cdecoder = _testlimitedcapi.codec_incrementaldecoder(encoding)
2451+
decodedresult = ""
2452+
for c in encodedresult:
2453+
decodedresult += cdecoder.decode(bytes([c]))
2454+
decodedresult += cdecoder.decode(b"", True)
2455+
self.assertEqual(decodedresult, s,
2456+
"encoding=%r" % encoding)
2457+
2458+
if encoding not in ("idna", "mbcs", "punycode"):
2459+
# check incremental decoder/encoder with errors argument
23892460
try:
2390-
cencoder = _testlimitedcapi.codec_incrementalencoder(encoding)
2461+
cencoder = _testlimitedcapi.codec_incrementalencoder(encoding, "ignore")
23912462
except LookupError: # no IncrementalEncoder
23922463
pass
23932464
else:
2394-
# check C API
2395-
encodedresult = b""
2396-
for c in s:
2397-
encodedresult += cencoder.encode(c)
2398-
encodedresult += cencoder.encode("", True)
2399-
cdecoder = _testlimitedcapi.codec_incrementaldecoder(encoding)
2400-
decodedresult = ""
2401-
for c in encodedresult:
2402-
decodedresult += cdecoder.decode(bytes([c]))
2403-
decodedresult += cdecoder.decode(b"", True)
2465+
encodedresult = b"".join(cencoder.encode(c) for c in s)
2466+
cdecoder = _testlimitedcapi.codec_incrementaldecoder(encoding, "ignore")
2467+
decodedresult = "".join(cdecoder.decode(bytes([c]))
2468+
for c in encodedresult)
24042469
self.assertEqual(decodedresult, s,
24052470
"encoding=%r" % encoding)
24062471

2407-
if encoding not in ("idna", "mbcs"):
2408-
# check incremental decoder/encoder with errors argument
2409-
try:
2410-
cencoder = _testlimitedcapi.codec_incrementalencoder(encoding, "ignore")
2411-
except LookupError: # no IncrementalEncoder
2412-
pass
2413-
else:
2414-
encodedresult = b"".join(cencoder.encode(c) for c in s)
2415-
cdecoder = _testlimitedcapi.codec_incrementaldecoder(encoding, "ignore")
2416-
decodedresult = "".join(cdecoder.decode(bytes([c]))
2417-
for c in encodedresult)
2418-
self.assertEqual(decodedresult, s,
2419-
"encoding=%r" % encoding)
2420-
24212472
def test_seek(self):
24222473
# all codecs should be able to encode these
24232474
s = "%s\n%s\n" % (100*"abc123", 100*"def456")
@@ -2455,9 +2506,8 @@ def test_decoder_state(self):
24552506
# Check that getstate() and setstate() handle the state properly
24562507
u = "abc123"
24572508
for encoding in all_unicode_encodings:
2458-
if encoding not in broken_unicode_with_stateful:
2459-
self.check_state_handling_decode(encoding, u, u.encode(encoding))
2460-
self.check_state_handling_encode(encoding, u, u.encode(encoding))
2509+
self.check_state_handling_decode(encoding, u, u.encode(encoding))
2510+
self.check_state_handling_encode(encoding, u, u.encode(encoding))
24612511

24622512

24632513
class CharmapTest(unittest.TestCase):
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
Fix the ``punycode`` incremental encoder and decoder, which gave wrong
2+
results when the input was passed in more than one chunk, for example
3+
through :func:`codecs.iterencode` or :func:`codecs.iterdecode`. They now
4+
buffer the input until the final call, so text files opened for writing
5+
with this encoding no longer write any output. The incremental decoder no
6+
longer accepts :class:`str`.

0 commit comments

Comments
 (0)