Skip to content

Commit b6715cb

Browse files
committed
tryparse should still throw an exception on invalid base
1 parent 0d1cee7 commit b6715cb

File tree

2 files changed

+15
-7
lines changed

2 files changed

+15
-7
lines changed

base/parse.jl

+10-7
Original file line numberDiff line numberDiff line change
@@ -141,13 +141,16 @@ function tryparse_internal(::Type{Bool}, sbuff::Union{String,SubString},
141141
Nullable{Bool}()
142142
end
143143

144-
function tryparse{T<:Integer}(::Type{T}, s::AbstractString, base::Integer=0)
145-
return tryparse_internal(T, s, start(s), endof(s), base, false)
146-
end
147-
148-
function parse{T<:Integer}(::Type{T}, s::AbstractString, base::Integer=0)
149-
return get(tryparse_internal(T, s, start(s), endof(s), base, true))
150-
end
144+
check_valid_base(base) = 2 <= base <= 62 ? base :
145+
throw(ArgumentError("invalid base: base must be 2 ≤ base ≤ 62, got $base"))
146+
tryparse{T<:Integer}(::Type{T}, s::AbstractString, base::Integer) =
147+
tryparse_internal(T, s, start(s), endof(s), check_valid_base(base), false)
148+
tryparse{T<:Integer}(::Type{T}, s::AbstractString) =
149+
tryparse_internal(T, s, start(s), endof(s), 0, false)
150+
parse{T<:Integer}(::Type{T}, s::AbstractString, base::Integer) =
151+
get(tryparse_internal(T, s, start(s), endof(s), check_valid_base(base), true))
152+
parse{T<:Integer}(::Type{T}, s::AbstractString) =
153+
get(tryparse_internal(T, s, start(s), endof(s), 0, true))
151154

152155
## string to float functions ##
153156

test/parse.jl

+5
Original file line numberDiff line numberDiff line change
@@ -538,5 +538,10 @@ end
538538
@test_throws ArgumentError parse(Int, "2", 1)
539539
@test_throws ArgumentError parse(Int, "2", 63)
540540

541+
# issue #17333: tryparse should still throw on invalid base
542+
for T in (Int32, BigInt), base in (0,1,100)
543+
@test_throws ArgumentError tryparse(T, "0", base)
544+
end
545+
541546
# error throwing branch from #10560
542547
@test_throws ArgumentError Base.tryparse_internal(Bool, "foo", 1, 2, 10, true)

0 commit comments

Comments
 (0)