Skip to content

Commit a47cf00

Browse files
authored
add better implementations for generic findprev findnext for AbstractString (#35742)
* add better implementations for generic findprev findnext for AbstractString
1 parent d4d9303 commit a47cf00

File tree

1 file changed

+15
-16
lines changed

1 file changed

+15
-16
lines changed

base/strings/search.jl

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -127,16 +127,17 @@ findfirst(ch::AbstractChar, string::AbstractString) = findfirst(==(ch), string)
127127
function findnext(testf::Function, s::AbstractString, i::Integer)
128128
i = Int(i)
129129
z = ncodeunits(s) + 1
130-
1 i  z || throw(BoundsError(s, i))
130+
1 i z || throw(BoundsError(s, i))
131131
@inbounds i == z || isvalid(s, i) || string_index_err(s, i)
132-
for (j, d) in pairs(SubString(s, i))
133-
if testf(d)
134-
return i + j - 1
135-
end
132+
e = lastindex(s)
133+
while i <= e
134+
testf(@inbounds s[i]) && return i
135+
i = @inbounds nextind(s, i)
136136
end
137137
return nothing
138138
end
139139

140+
140141
in(c::AbstractChar, s::AbstractString) = (findfirst(isequal(c),s)!==nothing)
141142

142143
function _searchindex(s::Union{AbstractString,ByteArray},
@@ -334,18 +335,16 @@ findlast(ch::AbstractChar, string::AbstractString) = findlast(==(ch), string)
334335

335336
# AbstractString implementation of the generic findprev interface
336337
function findprev(testf::Function, s::AbstractString, i::Integer)
337-
if i < 1
338-
return i == 0 ? nothing : throw(BoundsError(s, i))
339-
end
340-
n = ncodeunits(s)
341-
if i > n
342-
return i == n+1 ? nothing : throw(BoundsError(s, i))
338+
i = Int(i)
339+
z = ncodeunits(s) + 1
340+
0 i z || throw(BoundsError(s, i))
341+
i == z && return nothing
342+
@inbounds i == 0 || isvalid(s, i) || string_index_err(s, i)
343+
while i >= 1
344+
testf(@inbounds s[i]) && return i
345+
i = @inbounds prevind(s, i)
343346
end
344-
# r[reverseind(r,i)] == reverse(r)[i] == s[i]
345-
# s[reverseind(s,j)] == reverse(s)[j] == r[j]
346-
r = reverse(s)
347-
j = findnext(testf, r, reverseind(r, i))
348-
j === nothing ? nothing : reverseind(s, j)
347+
return nothing
349348
end
350349

351350
function _rsearchindex(s::AbstractString,

0 commit comments

Comments
 (0)