blob: edcbb1bc6da005ddf567443ba1404e1fecd26b0c [file] [log] [blame]
Marcel van Lohuizen00c373d2019-06-07 01:08:23 +02001// Copyright 2019 CUE Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package cuetest
16
17import (
18 "bytes"
19 "testing"
20)
21
22// A Chunker is used to find segments in text.
23type Chunker struct {
24 t *testing.T
25 b []byte
26 s []byte
27 p int
28}
29
30// NewChunker returns a new chunker.
31func NewChunker(t *testing.T, b []byte) *Chunker {
32 return &Chunker{t: t, b: b}
33}
34
35// Next finds the first occurrence from the current scan position of beg,
36// records the segment from that position until the first occurrence of end
37// and then updates the current position. It reports whether a segment enclosed
38// by beg and end can be found.
39func (c *Chunker) Next(beg, end string) bool {
40 if !c.Find(beg) {
41 return false
42 }
43 if !c.Find(end) {
44 c.t.Fatalf("quotes at position %d not terminated", c.p)
45 }
46 return true
47}
48
49// Text returns the text segment captured by the last call to Next or Find.
50func (c *Chunker) Text() string {
51 return string(c.s)
52}
53
54// Bytes returns the segment captured by the last call to Next or Find.
55func (c *Chunker) Bytes() []byte {
56 return c.s
57}
58
59// Find searches for key from the current position and sets the current segment
60// to the text from current position up till the key's position. If successful,
61// the position is updated to point directly after the occurrence of key.
62func (c *Chunker) Find(key string) bool {
63 p := bytes.Index(c.b, []byte(key))
64 if p == -1 {
65 c.s = c.b
66 return false
67 }
68 c.p += p + len(key)
69 b := c.b
70 c.s = b[:p]
71 c.b = b[p+len(key):]
72 return true
73}