diff options
| author | Paul Chaignon <paul.chaignon@gmail.com> | 2023-11-10 15:58:33 +0100 |
|---|---|---|
| committer | Aleksandr Nogikh <nogikh@google.com> | 2023-11-13 13:40:05 +0000 |
| commit | 78b9d1a14311a5bd82c219eb4fa815a54ad832bd (patch) | |
| tree | 653928926e400e4a58f28298582e7af49a79279a /prog | |
| parent | 2c161a91dd08a981de82d650b264177c46b51e10 (diff) | |
prog: add helper function parser.HasNext
This helper function will be used in a subsequent commit to take a look
ahead at several characters.
Signed-off-by: Paul Chaignon <paul.chaignon@gmail.com>
Diffstat (limited to 'prog')
| -rw-r--r-- | prog/encoding.go | 15 | ||||
| -rw-r--r-- | prog/encoding_test.go | 23 |
2 files changed, 38 insertions, 0 deletions
diff --git a/prog/encoding.go b/prog/encoding.go index 2216955d8..be883645b 100644 --- a/prog/encoding.go +++ b/prog/encoding.go @@ -1180,6 +1180,21 @@ func (p *parser) Char() byte { return p.s[p.i] } +func (p *parser) HasNext(str string) bool { + if p.e != nil { + return false + } + if len(p.s) < p.i+len(str) { + return false + } + for i := 0; i < len(str); i++ { + if p.s[p.i+i] != str[i] { + return false + } + } + return true +} + func (p *parser) Parse(ch byte) { if p.e != nil { return diff --git a/prog/encoding_test.go b/prog/encoding_test.go index e99663aa3..daa2ac0cb 100644 --- a/prog/encoding_test.go +++ b/prog/encoding_test.go @@ -515,3 +515,26 @@ serialize0(0x0) t.Errorf("bad program comments %q\nwant: %q", p.Comments, wantComments) } } + +func TestHasNext(t *testing.T) { + testCases := []struct { + input string + expected bool + }{ + {"abcdef", true}, + {"xyz", false}, + {"ab", false}, + {"abc", true}, + } + for _, testCase := range testCases { + p := newParser(nil, []byte(testCase.input), true) + if !p.Scan() { + t.Fatalf("parser does not scan") + } + result := p.HasNext("abc") + if result != testCase.expected { + t.Errorf("expected HasNext(\"abc\") on input %q to be %v, but got %v", + testCase.input, testCase.expected, result) + } + } +} |
