From 1c9a3962eca146a67d3dd9d4fafc923bc2828de0 Mon Sep 17 00:00:00 2001 From: milarin Date: Sat, 21 Jan 2023 00:18:38 +0100 Subject: [PATCH] new constructors --- reader.go | 31 ++++++++++++++++++++++--------- reader_test.go | 4 ++-- 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/reader.go b/reader.go index f584b20..7329593 100644 --- a/reader.go +++ b/reader.go @@ -14,7 +14,7 @@ type Reader struct { pos *Position } -func NewReader(r io.Reader) *Reader { +func New(r io.Reader) *Reader { return &Reader{ buf: ds.NewArrayStack[posRune](), src: bufio.NewReader(r), @@ -22,6 +22,10 @@ func NewReader(r io.Reader) *Reader { } } +func NewFromString(str string) *Reader { + return New(strings.NewReader(str)) +} + func (r *Reader) psrn(rn rune) posRune { return posRune{ Rune: rn, @@ -149,12 +153,6 @@ func (r *Reader) PeekStringWhile(f ...RuneFunc) (string, error) { return str, nil } -// SkipStringWhile acts as StringWhile but discards the string -func (r *Reader) SkipStringWhile(f ...RuneFunc) error { - _, err := r.StringWhile(f...) - return err -} - // StringUntil reads runes and calls all functions for each one. // It returns all runes as a string for which all functions returned true. // It stops when any function returns false or an error occured. @@ -177,12 +175,27 @@ func (r *Reader) PeekStringUntil(f ...RuneFunc) (string, error) { return str, nil } -// SkipStringUntil acts as StringUntil but discards the string -func (r *Reader) SkipStringUntil(f ...RuneFunc) error { +// SkipUntil acts as StringUntil but discards the string +func (r *Reader) SkipUntil(f ...RuneFunc) error { _, err := r.StringUntil(f...) return err } +// SkipWhile acts as StringWhile but discards the string +func (r *Reader) SkipWhile(f ...RuneFunc) error { + _, err := r.StringWhile(f...) + return err +} + +// ExpectRune returns true if any function returns true for the next rune read from r +func (r *Reader) ExpectRune(f ...RuneFunc) (bool, error) { + rn, err := r.Rune() + if err != nil { + return false, err + } + return findFirstTrue(rn, f), nil +} + // Commit clears the internal buffer and therefore removes all data which were already read. // After calling Commit any unreads will return ErrNothingToUnread until another read occured. func (r *Reader) Commit() { diff --git a/reader_test.go b/reader_test.go index 35f39d8..09401de 100644 --- a/reader_test.go +++ b/reader_test.go @@ -7,7 +7,7 @@ import ( ) func TestPos(t *testing.T) { - r := NewReader(strings.NewReader("hello world\nsecond line")) + r := New(strings.NewReader("hello world\nsecond line")) unread := false for rn, err := r.Rune(); err == nil; rn, err = r.Rune() { @@ -24,7 +24,7 @@ func TestPos(t *testing.T) { } func TestEOF(t *testing.T) { - r := NewReader(strings.NewReader("hello world\nasddsa")) + r := New(strings.NewReader("hello world\nasddsa")) var line string var err error