refactor: simplify iterator.Try and remove unnecessary backtracking
Simplify Try to save/restore the index directly instead of copying and syncing the entire iterator. Remove the now-unused Copy and Sync methods. Rewrite ScanRune and ParseRawToken as peek-then-advance so they no longer need Try at all. Remove redundant Try wrappers from parse functions that are already disambiguated by their callers. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -19,18 +19,6 @@ func (i Iterator[T]) Index() int {
|
||||
return i.index
|
||||
}
|
||||
|
||||
// Copy returns a identical clone of the iterator. The underlying data structure
|
||||
// is not cloned.
|
||||
func (i Iterator[T]) Copy() *Iterator[T] {
|
||||
return &Iterator[T]{items: i.items, index: i.index}
|
||||
}
|
||||
|
||||
// Sync returns the iterator to the position of another. It is assumed that the
|
||||
// iterators both operate on the same set of data.
|
||||
func (i *Iterator[T]) Sync(o *Iterator[T]) {
|
||||
i.index = o.index
|
||||
}
|
||||
|
||||
// Get returns the datum at the current position of the iterator.
|
||||
func (i Iterator[T]) Get() (T, error) {
|
||||
var null T
|
||||
@@ -93,14 +81,14 @@ func (i *Iterator[T]) While(fn func(T) bool) {
|
||||
}
|
||||
|
||||
// Try attempts to perform an operation using the iterator. If the operation
|
||||
// succeeds, the iterator is updated. If the operation fails, the iterator is
|
||||
// rolled back, and an error is returned.
|
||||
// succeeds, the iterator keeps its new position. If the operation fails, the
|
||||
// iterator is rolled back, and an error is returned.
|
||||
func Try[T any, U any](i *Iterator[T], fn func(i *Iterator[T]) (U, error)) (U, error) {
|
||||
i2 := i.Copy()
|
||||
saved := i.index
|
||||
|
||||
out, err := fn(i2)
|
||||
if err == nil {
|
||||
i.Sync(i2)
|
||||
out, err := fn(i)
|
||||
if err != nil {
|
||||
i.index = saved
|
||||
}
|
||||
|
||||
return out, err
|
||||
|
||||
Reference in New Issue
Block a user