Skip to content

Commit

Permalink
add better implementations for generic findprev findnext for Abstract…
Browse files Browse the repository at this point in the history
…String
  • Loading branch information
KristofferC committed May 5, 2020
1 parent d07fadf commit cbff131
Showing 1 changed file with 15 additions and 16 deletions.
31 changes: 15 additions & 16 deletions base/strings/search.jl
Original file line number Diff line number Diff line change
Expand Up @@ -127,16 +127,17 @@ findfirst(ch::AbstractChar, string::AbstractString) = findfirst(==(ch), string)
function findnext(testf::Function, s::AbstractString, i::Integer)
i = Int(i)
z = ncodeunits(s) + 1
1 i  z || throw(BoundsError(s, i))
1 i z || throw(BoundsError(s, i))
@inbounds i == z || isvalid(s, i) || string_index_err(s, i)
for (j, d) in pairs(SubString(s, i))
if testf(d)
return i + j - 1
end
e = lastindex(s)
@inbounds while i <= e
testf(s[i]) && return i
i = nextind(s, i)
end
return nothing
end


in(c::AbstractChar, s::AbstractString) = (findfirst(isequal(c),s)!==nothing)

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

# AbstractString implementation of the generic findprev interface
function findprev(testf::Function, s::AbstractString, i::Integer)
if i < 1
return i == 0 ? nothing : throw(BoundsError(s, i))
end
n = ncodeunits(s)
if i > n
return i == n+1 ? nothing : throw(BoundsError(s, i))
i = Int(i)
z = ncodeunits(s) + 1
0 i z || throw(BoundsError(s, i))
i == z && return nothing
@inbounds i == 0 || isvalid(s, i) || string_index_err(s, i)
@inbounds while i >= 1
testf(s[i]) && return i
i = prevind(s, i)
end
# r[reverseind(r,i)] == reverse(r)[i] == s[i]
# s[reverseind(s,j)] == reverse(s)[j] == r[j]
r = reverse(s)
j = findnext(testf, r, reverseind(r, i))
j === nothing ? nothing : reverseind(s, j)
return nothing
end

function _rsearchindex(s::AbstractString,
Expand Down

0 comments on commit cbff131

Please sign in to comment.