From 2745fd42e3384b629975c5a1a76d87d2caf5bfc0 Mon Sep 17 00:00:00 2001 From: liam Date: Sat, 4 Jan 2025 04:21:11 -0800 Subject: [PATCH] Don't use checkpoint type alias It gets very verbose when you need to do more skipping around --- core/input.go | 21 ++++++++++++--------- core/input_test.go | 11 +++++++++++ 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/core/input.go b/core/input.go index 5eef279..96000ba 100644 --- a/core/input.go +++ b/core/input.go @@ -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 } @@ -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 diff --git a/core/input_test.go b/core/input_test.go index 7c82240..3374570 100644 --- a/core/input_test.go +++ b/core/input_test.go @@ -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) + }) }