Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 12 additions & 9 deletions core/input.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,11 @@ import (
"strings"
)

// Use unexported type alias so we control the interface and prevent people doing arbirary things e.g. use negative ints.
type checkpoint int

type Input interface {
Peek(n int) (string, bool)
Take(n int) (string, bool)
Checkpoint() checkpoint
Restore(cp checkpoint)
Checkpoint() int
Restore(checkpoint int)
Debug() string
}

Expand Down Expand Up @@ -63,13 +60,19 @@ func (i *input) Take(n int) (s string, ok bool) {
}

// Take a snapshot of the current parsing position
func (i *input) Checkpoint() checkpoint {
return checkpoint(i.index)
func (i *input) Checkpoint() int {
return i.index
}

// Restore the parsing position to a previous snapshot
func (i *input) Restore(cp checkpoint) {
i.index = int(cp)
func (i *input) Restore(checkpoint int) {
if checkpoint < 0 {
checkpoint = 0
}
if checkpoint > len(i.s) {
checkpoint = len(i.s)
}
i.index = checkpoint
}

// Outputs the full input string with a marker at the current parsing position
Expand Down
11 changes: 11 additions & 0 deletions core/input_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,5 +95,16 @@ func TestInput(t *testing.T) {
assert.False(t, ok)
assert.Equal(t, "", s)
})
t.Run("Restore negative int", func(t *testing.T) {
i.Take(10)
i.Restore(-1)
assert.Equal(t, 0, i.Checkpoint())
})
t.Run("Restore beyond end", func(t *testing.T) {
i.Restore(len(input))
assert.Equal(t, len(input), i.Checkpoint())
_, ok := i.Peek(1)
assert.False(t, ok)
})

}
Loading