Skip to content

gh-155016: Fix encoding to Windows code pages which require dwFlags=0 - #155018

Open
serhiy-storchaka wants to merge 1 commit into
python:mainfrom
serhiy-storchaka:gh-155016-win-codepage-flags
Open

gh-155016: Fix encoding to Windows code pages which require dwFlags=0#155018
serhiy-storchaka wants to merge 1 commit into
python:mainfrom
serhiy-storchaka:gh-155016-win-codepage-flags

Conversation

@serhiy-storchaka

@serhiy-storchaka serhiy-storchaka commented Aug 1, 2026

Copy link
Copy Markdown
Member

Encode with dwFlags = 0 and lpUsedDefaultChar = NULL to the code pages which only support this: 42 (Symbol), 50220, 50221, 50222, 50225, 50227, 50229 (ISO-2022), 52936 (HZ-GB2312), 54936 (GB18030) and 57002-57011 (ISCII). UTF-7 was already special cased, now it shares the same code.

Since lpUsedDefaultChar is no longer available for these code pages, replaced characters are detected by decoding the encoded string back and comparing it with the original string. This also detects best fit characters, which dwFlags = 0 re-enables.

The per-character buffer in encode_code_page_errors() is enlarged from 4 to 16 bytes, because a single character encoded together with escape sequences is longer than that (up to 9 bytes in cp50220). Only code pages encoded with dwFlags = 0 use more than 4 bytes per character.

>>> codecs.code_page_encode(50220, '')
(b'\x1b$B$"\x1b(B', 1)
>>> '[€]'.encode('cp50220', 'backslashreplace')
b'[\\u20ac]'

…lags=0

WideCharToMultiByte() only converts to some code pages (ISO-2022, HZ-GB2312,
GB18030, ISCII and UTF-7) with dwFlags set to 0 and lpUsedDefaultChar set to
NULL, and rejects any other call with ERROR_INVALID_PARAMETER. Encode to them
with these arguments, and detect replaced characters by decoding the result
back, since lpUsedDefaultChar is no longer available for this.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant