-
Notifications
You must be signed in to change notification settings - Fork 0
/
iterator.go
74 lines (63 loc) · 1.56 KB
/
iterator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package iterator
import (
"errors"
)
var (
ErrNoItems = errors.New("iterator: no items in iterator")
ErrMultiItems = errors.New("iterator: multiple items in iterator")
)
// Iterator defines the methods needed to conform to an iterator supported by this package
type Iterator[T any] interface {
// Next moves the iterator to the next position and reports whether
// an item exists
Next() bool
// Get returns the current item
// Multiple calls to Get without calling Next should give the same result
Get() (T, error)
// Close marks the iterator as done and frees resources
Close() error
// Err returns the first error encountered in any of the operations of the iterator
Err() error
}
// Modifier applys an operation on the iterator and returns the resultant iterator
// The given iterator should not be used for anything else after applying the modifier
// to avoid incorrect results
type Modifier[T any, S any] func(Iterator[T]) Iterator[S]
type KV[K comparable, V any] struct {
Key K
Val V
}
type ValErr[T any] struct {
Val T
Err error
}
type iterator[T any] struct {
next func() bool
get func() (T, error)
err func() error
close func() error
}
func (iter *iterator[T]) Next() bool {
if iter.next != nil {
return iter.next()
}
return false
}
func (iter *iterator[T]) Get() (T, error) {
if iter.get != nil {
return iter.get()
}
return *new(T), nil
}
func (iter *iterator[T]) Close() error {
if iter.close != nil {
return iter.close()
}
return nil
}
func (iter *iterator[T]) Err() error {
if iter.err != nil {
return iter.err()
}
return nil
}