Skip to content

Fix lossy str->bytes conversion that corrupts non-ASCII input - #78

Merged
kurok merged 1 commit into
masterfrom
fix-issue-19-lossless-str-bytes
Jun 12, 2026
Merged

kurok merged 1 commit into
masterfrom
fix-issue-19-lossless-str-bytes

Conversation

@kurok

@kurok kurok commented Jun 12, 2026

Copy link
Copy Markdown
Contributor

Summary

parse_email accepts str or bytes. For str input, to_bytes() in src/fast_mail_parser.rs mapped each code point to its low byte (chars().map(|c| c as u8), with an is_ascii() fast path). For non-ASCII input this truncated code points (e.g. 'é' U+00E9 -> 0xE9, '日' U+65E5 -> 0xE5), silently corrupting the bytes handed to the parser.

This fix decodes str losslessly as its UTF-8 bytes via text.as_bytes().to_vec() for all strings, dropping both the is_ascii() branch and the lossy per-char cast. The bytes path and the TypeError fallback are unchanged.

Behavior change

This changes output for non-ASCII str input (now lossless UTF-8 instead of truncated). It is a correctness fix for a corruption bug; ASCII input and bytes input are unchanged. Consumers should be unaffected unless they relied on the (buggy) truncation.

Tests

Reworked tests/test_contract.py::test__non_ascii_str_decodes_as_truncated_code_points -> test__non_ascii_str_decodes_as_utf8 to assert the new correct behavior: a non-ASCII str parses identically to its explicit UTF-8 encoding. test__accepts_str_and_bytes_equivalently still passes. Full suite: 70 passed.

Closes #19

parse_email's str path mapped each code point to its low byte
(chars().map(|c| c as u8)), truncating non-ASCII code points and
silently corrupting the bytes handed to the parser (e.g. 'é' U+00E9
-> 0xE9, '日' U+65E5 -> 0xE5).

Decode str losslessly as its UTF-8 bytes via text.as_bytes().to_vec()
for all strings. ASCII is unaffected (ASCII == its own UTF-8); the
bytes path and TypeError fallback are unchanged.

Closes #19

Signed-off-by: yuriyryabikov <22548029+kurok@users.noreply.github.com>
@kurok
kurok merged commit c05a4b5 into master Jun 12, 2026
7 checks passed
@kurok
kurok deleted the fix-issue-19-lossless-str-bytes branch June 12, 2026 20:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Fix lossy str→bytes conversion that corrupts non-ASCII input

1 participant