Skip to content

Commit 510db13

Browse files
authored
Fix tryparse for invalid Chars (#32351)
This fix adapts the fast path from UInt32(::Char) to the case of digit parsing.
1 parent 9bd5c18 commit 510db13

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

base/parse.jl

+4-2
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,8 @@ function tryparse_internal(::Type{T}, s::AbstractString, startpos::Int, endpos::
123123
_Z = UInt32('Z')
124124
_z = UInt32('z')
125125
while n <= m
126-
_c = UInt32(c)
126+
# Fast path from `UInt32(::Char)`; non-ascii will be >= 0x80
127+
_c = reinterpret(UInt32, c) >> 24
127128
d::T = _0 <= _c <= _9 ? _c-_0 :
128129
_A <= _c <= _Z ? _c-_A+ UInt32(10) :
129130
_a <= _c <= _z ? _c-_a+a : base
@@ -142,7 +143,8 @@ function tryparse_internal(::Type{T}, s::AbstractString, startpos::Int, endpos::
142143
end
143144
(T <: Signed) && (n *= sgn)
144145
while !isspace(c)
145-
_c = UInt32(c)
146+
# Fast path from `UInt32(::Char)`; non-ascii will be >= 0x80
147+
_c = reinterpret(UInt32, c) >> 24
146148
d::T = _0 <= _c <= _9 ? _c-_0 :
147149
_A <= _c <= _Z ? _c-_A+ UInt32(10) :
148150
_a <= _c <= _z ? _c-_a+a : base

test/strings/basic.jl

+6
Original file line numberDiff line numberDiff line change
@@ -377,6 +377,12 @@ end
377377
@test tryparse(Float32, "32o") === nothing
378378
end
379379

380+
@testset "tryparse invalid chars" begin
381+
# #32314: tryparse shouldn't throw, even given strings with invalid Chars
382+
@test tryparse(UInt8, "\xb5") === nothing
383+
@test tryparse(UInt8, "100\xb5") === nothing # Code path for numeric overflow
384+
end
385+
380386
import Unicode
381387

382388
@testset "issue #10994: handle embedded NUL chars for string parsing" begin

0 commit comments

Comments
 (0)