Skip to content

Make String#to_d accept embedded NUL bytes and reject ASCII-incompatible strings - #557

Merged
tompng merged 2 commits into
ruby:masterfrom
tompng:to_d_null_byte
Sep 12, 2026
Merged

Make String#to_d accept embedded NUL bytes and reject ASCII-incompatible strings#557
tompng merged 2 commits into
ruby:masterfrom
tompng:to_d_null_byte

Conversation

@tompng

@tompng tompng commented Sep 12, 2026

Copy link
Copy Markdown
Member

Depends on the RB_GC_GUARD PR (the first commit here is the same commit); the diff will shrink to two commits once that is merged.

String#to_d with embedded NUL

BigDecimal.interpret_loosely used StringValueCStr, so "1\0".to_d raised ArgumentError: string contains null byte even though the conversion is meant to be lenient. It now parses up to the first NUL, matching String#to_f and String#to_i:

"1\0 2".to_d  #=> 0.1e1
"\0 1".to_d   #=> 0.0

ASCII-incompatible encodings

The parser reads the string as bytes, and StringValueCStr only rejects NUL characters for wide encodings, so BigDecimal("123".encode("UTF-16LE")) was silently parsed as 1. Both BigDecimal() and String#to_d now raise Encoding::CompatibilityError via rb_must_asciicompat, the same as Float(), Integer() and String#to_f. This applies with exception: false as well, again matching Float(str, exception: false).

🤖 Generated with Claude Code

tompng and others added 2 commits September 12, 2026 22:58
BigDecimal.interpret_loosely used StringValueCStr, which raises
ArgumentError for an embedded NUL even though the conversion is meant
to be lenient. Parse up to the first NUL instead, matching String#to_f
and String#to_i. Also reject ASCII-incompatible encodings the way the
core numeric conversions do, since the parser reads the string as bytes.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
The parser reads the string as bytes, so a UTF-16 string such as
"123".encode("UTF-16LE") was silently parsed as "1". Raise
Encoding::CompatibilityError as Float() and Integer() do.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@tompng
tompng merged commit 00d26a2 into ruby:master Sep 12, 2026
83 checks passed
@tompng
tompng deleted the to_d_null_byte branch September 12, 2026 14:22
@tompng tompng added the bug label Sep 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant