-
-
Notifications
You must be signed in to change notification settings - Fork 5.7k
Description
The string index arithmetic API has grown organically over time and while it works, it feels a bit less minimal than it could be – three functions to navigate between the characters in a function is more than one might hope for. By comparison, relative array index navigation can be done entirely with a single operation: +. I'd like to propose a single charseek function to replace thisind, nextind and prevind:
charseek(s::AbstractString, i::Integer, n::Integer)Advance to the index of a character in
srelative to the character insthat indexipoints into. The indexidoes not need to be the lead index of a character but the returned index is guaranteed to be the index of a character (or out of bounds).
This allows us to replace the current functions like so:
thisind(s, i)=>charseek(s, i, 0)nextind(s, i, n)=>charseek(s, i, n)prevind(s, i, n)=>charseek(s, i, -n)if you know thatiis validcharseek(s, i, 1-n)if you know thatiis invalidcharseek(s, charseek(s, i, 1), -n)ifimight be valid or invalid
This function obeys nice identities, such as:
charseek(s, charseek(s, i, m), n) == charseek(s, i, m + n)charseek(s, i, -n) < i < charseek(s, i, n)forn > 0
On top of #24999 this is a simulation of charseek if someone wants to try it out:
charseek(s::AbstractString, i::Integer, n::Integer) =
n < 0 ? prevind(s, i, (checkbounds(Bool,s,i) && !isvalid(s,i))-n) :
n > 0 ? nextind(s, i, n) : thisind(s, i)