Skip to content

Commit 8377220

Browse files
stevengjtkelman
authored andcommitted
tryparse should still throw an exception on invalid base (#17333)
1 parent dad6836 commit 8377220

File tree

2 files changed

+15
-7
lines changed

2 files changed

+15
-7
lines changed

base/parse.jl

Lines changed: 10 additions & 7 deletions
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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -546,5 +546,10 @@ end
546546
@test_throws ArgumentError parse(Int, "2", 1)
547547
@test_throws ArgumentError parse(Int, "2", 63)
548548

549+
# issue #17333: tryparse should still throw on invalid base
550+
for T in (Int32, BigInt), base in (0,1,100)
551+
@test_throws ArgumentError tryparse(T, "0", base)
552+
end
553+
549554
# error throwing branch from #10560
550555
@test_throws ArgumentError Base.tryparse_internal(Bool, "foo", 1, 2, 10, true)

0 commit comments

Comments
 (0)