Skip to content

charseek: replace thisind, nextind and prevind? #25019

@StefanKarpinski

Description

@StefanKarpinski

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 s relative to the character in s that index i points into. The index i does 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 that i is valid
    • charseek(s, i, 1-n) if you know that i is invalid
    • charseek(s, charseek(s, i, 1), -n) if i might 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) for n > 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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions