Skip to content

Commit 1a1dd13

Browse files
nsajkoKristofferC
authored andcommitted
strings: type assert in the generic nextind, prevind methods (#57608)
The type assertions are valid according to the doc strings of these functions in the case of `AbstractString`. Should prevent some invalidation on loading user code. Fixes #57605 (cherry picked from commit 6c9c336)
1 parent 5ab4295 commit 1a1dd13

File tree

2 files changed

+11
-6
lines changed

2 files changed

+11
-6
lines changed

base/strings/basic.jl

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -498,11 +498,11 @@ prevind(s::AbstractString, i::Int) = prevind(s, i, 1)
498498

499499
function prevind(s::AbstractString, i::Int, n::Int)
500500
n < 0 && throw(ArgumentError("n cannot be negative: $n"))
501-
z = ncodeunits(s) + 1
501+
z = ncodeunits(s)::Int + 1
502502
@boundscheck 0 < i z || throw(BoundsError(s, i))
503-
n == 0 && return thisind(s, i) == i ? i : string_index_err(s, i)
503+
n == 0 && return thisind(s, i)::Int == i ? i : string_index_err(s, i)
504504
while n > 0 && 1 < i
505-
@inbounds n -= isvalid(s, i -= 1)
505+
@inbounds n -= isvalid(s, i -= 1)::Bool
506506
end
507507
return i - n
508508
end
@@ -557,11 +557,11 @@ nextind(s::AbstractString, i::Int) = nextind(s, i, 1)
557557

558558
function nextind(s::AbstractString, i::Int, n::Int)
559559
n < 0 && throw(ArgumentError("n cannot be negative: $n"))
560-
z = ncodeunits(s)
560+
z = ncodeunits(s)::Int
561561
@boundscheck 0 i z || throw(BoundsError(s, i))
562-
n == 0 && return thisind(s, i) == i ? i : string_index_err(s, i)
562+
n == 0 && return thisind(s, i)::Int == i ? i : string_index_err(s, i)
563563
while n > 0 && i < z
564-
@inbounds n -= isvalid(s, i += 1)
564+
@inbounds n -= isvalid(s, i += 1)::Bool
565565
end
566566
return i + n
567567
end

test/strings/basic.jl

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -872,6 +872,11 @@ end
872872
end
873873
end
874874
end
875+
876+
@testset "return type infers to `Int`" begin
877+
@test Int === Base.infer_return_type(prevind, Tuple{AbstractString, Vararg})
878+
@test Int === Base.infer_return_type(nextind, Tuple{AbstractString, Vararg})
879+
end
875880
end
876881

877882
@testset "first and last" begin

0 commit comments

Comments
 (0)