Skip to content

Commit

Permalink
Fix tryparse for invalid Chars (#32351)
Browse files Browse the repository at this point in the history
This fix adapts the fast path from UInt32(::Char) to the case of digit
parsing.

(cherry picked from commit 510db13)
  • Loading branch information
c42f authored and KristofferC committed Feb 20, 2020
1 parent 90caa80 commit 195b23e
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
6 changes: 4 additions & 2 deletions base/parse.jl
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,8 @@ function tryparse_internal(::Type{T}, s::AbstractString, startpos::Int, endpos::
_Z = UInt32('Z')
_z = UInt32('z')
while n <= m
_c = UInt32(c)
# Fast path from `UInt32(::Char)`; non-ascii will be >= 0x80
_c = reinterpret(UInt32, c) >> 24
d::T = _0 <= _c <= _9 ? _c-_0 :
_A <= _c <= _Z ? _c-_A+ UInt32(10) :
_a <= _c <= _z ? _c-_a+a : base
Expand All @@ -139,7 +140,8 @@ function tryparse_internal(::Type{T}, s::AbstractString, startpos::Int, endpos::
end
(T <: Signed) && (n *= sgn)
while !isspace(c)
_c = UInt32(c)
# Fast path from `UInt32(::Char)`; non-ascii will be >= 0x80
_c = reinterpret(UInt32, c) >> 24
d::T = _0 <= _c <= _9 ? _c-_0 :
_A <= _c <= _Z ? _c-_A+ UInt32(10) :
_a <= _c <= _z ? _c-_a+a : base
Expand Down
6 changes: 6 additions & 0 deletions test/strings/basic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,12 @@ end
@test tryparse(Float32, "32o") === nothing
end

@testset "tryparse invalid chars" begin
# #32314: tryparse shouldn't throw, even given strings with invalid Chars
@test tryparse(UInt8, "\xb5") === nothing
@test tryparse(UInt8, "100\xb5") === nothing # Code path for numeric overflow
end

import Unicode

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

0 comments on commit 195b23e

Please sign in to comment.