Browse Source

lexer: introduce Reader.Accept()/AcceptAll()

Signed-off-by: Alejandro Mery <amery@jpi.io>
pull/5/head
Alejandro Mery 1 year ago
parent
commit
d83b128c30
  1. 35
      lexer/reader.go

35
lexer/reader.go

@ -198,6 +198,41 @@ func (b *Reader) PeekRune() (rune, int, error) {
return r, l, err
}
// Accept consumes a rune from the source if it meets the condition.
// it returns true if the condition was met and false if it wasn't.
func (b *Reader) Accept(cond func(r rune) bool) bool {
r, _, err := b.ReadRune()
switch {
case err != nil:
return false
case cond(r):
return true
default:
_ = b.UnreadRune()
return false
}
}
// AcceptAll consumes runes from the source as long as they meet the
// condition. it returns true if the condition was met for at least one rune,
// and false if it wasn't.
func (b *Reader) AcceptAll(cond func(r rune) bool) bool {
var accepted bool
for {
r, _, err := b.ReadRune()
switch {
case err != nil:
return accepted
case cond(r):
accepted = true
default:
_ = b.UnreadRune()
return accepted
}
}
}
// NewReader creates a new runes [Reader] using the given [io.Reader]
func NewReader(r io.Reader) *Reader {
if r == nil {

Loading…
Cancel
Save