Skip to content

Conversation

@jneen
Copy link
Contributor

@jneen jneen commented Jan 20, 2026

Depends on #16557.
Extracted from #16455.
Fixes #11259, with the exception of the methods that mutate the string.

Rationale

Ruby's comparable StringScanner library provides a number of extra convenience methods. I've gone through the list and implemented/specced the ones that make sense here.

Changes

  • #matched? : Bool to check for the presence of @last_match
  • #current_char : Char, #previous_char : Char as well as nilable variants
  • #current_byte : UInt8, #previous_byte : UInt8, as well as nilable variants
  • #beginning_of_line? I believe originally conceived because anchors like ^ were non-functional in Ruby due to a bug in their implementation - not an issue in Crystal. It is generally a useful method though, and I couldn't see an argument against including it.
  • #rewind(Int) to move the scan head backwards manually
  • #unscan for rewinding to the start of the previous scan Removed as this has some deep issues in its interactions with #check and #scan_until. Will open a separate PR for it later.

@jneen jneen changed the title Feature.string scanner convenience methods DRAFT: Feature.string scanner convenience methods Jan 20, 2026
@jneen jneen changed the title DRAFT: Feature.string scanner convenience methods DRAFT: StringScanner convenience methods Jan 20, 2026
@jneen
Copy link
Contributor Author

jneen commented Jan 21, 2026

I think the spec failure here is a flapper, it is a TCP error unrelated to the change.

@jneen jneen force-pushed the feature.string-scanner-convenience-methods branch from 81b7096 to c046758 Compare January 22, 2026 14:34
@jneen jneen changed the title DRAFT: StringScanner convenience methods StringScanner convenience methods Jan 22, 2026
@jneen jneen marked this pull request as ready for review January 22, 2026 14:37
@jneen
Copy link
Contributor Author

jneen commented Jan 26, 2026

Updated docs.

Also realized there's a subtle footgun with #unscan, which is that if the last match was from a #check(...) call, it will still rewind.

@jneen
Copy link
Contributor Author

jneen commented Jan 26, 2026

And yeah having played around with it for a bit, I think this is a tricky enough issue to warrant removing #unscan from this PR and doing a separate one. I think it may require state alongside @last_match.

@ysbaddaden ysbaddaden added this to the 1.20.0 milestone Jan 27, 2026
@straight-shoota straight-shoota changed the title StringScanner convenience methods Add convenience methods to StringScanner Jan 29, 2026
@straight-shoota straight-shoota merged commit bff5ba9 into crystal-lang:master Jan 29, 2026
41 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add missing StringScanner methods

3 participants