-
Notifications
You must be signed in to change notification settings - Fork 741
/
Copy pathiterator.go
132 lines (104 loc) · 2.3 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package pebble
import (
"errors"
"fmt"
"slices"
"sync"
"github.com/cockroachdb/pebble"
"github.com/ava-labs/avalanchego/database"
)
var (
_ database.Iterator = (*iter)(nil)
errCouldntGetValue = errors.New("couldnt get iterator value")
)
type iter struct {
// [lock] ensures that only one goroutine can access [iter] at a time.
// Note that [Database.Close] calls [iter.Release] so we need [lock] to ensure
// that the user and [Database.Close] don't execute [iter.Release] concurrently.
// Invariant: [Database.lock] is never grabbed while holding [lock].
lock sync.Mutex
db *Database
iter *pebble.Iterator
initialized bool
closed bool
err error
hasNext bool
nextKey []byte
nextVal []byte
}
// Must not be called with [db.lock] held.
func (it *iter) Next() bool {
it.lock.Lock()
defer it.lock.Unlock()
switch {
case it.err != nil:
it.hasNext = false
return false
case it.closed:
it.hasNext = false
it.err = database.ErrClosed
return false
case !it.initialized:
it.hasNext = it.iter.First()
it.initialized = true
default:
it.hasNext = it.iter.Next()
}
if !it.hasNext {
return false
}
it.nextKey = it.iter.Key()
var err error
it.nextVal, err = it.iter.ValueAndErr()
if err != nil {
it.hasNext = false
it.err = fmt.Errorf("%w: %w", errCouldntGetValue, err)
return false
}
return true
}
func (it *iter) Error() error {
it.lock.Lock()
defer it.lock.Unlock()
if it.err != nil || it.closed {
return it.err
}
return updateError(it.iter.Error())
}
func (it *iter) Key() []byte {
it.lock.Lock()
defer it.lock.Unlock()
if !it.hasNext {
return nil
}
return slices.Clone(it.nextKey)
}
func (it *iter) Value() []byte {
it.lock.Lock()
defer it.lock.Unlock()
if !it.hasNext {
return nil
}
return slices.Clone(it.nextVal)
}
func (it *iter) Release() {
it.db.lock.Lock()
defer it.db.lock.Unlock()
it.lock.Lock()
defer it.lock.Unlock()
it.release()
}
// Assumes [it.lock] and [it.db.lock] are held.
func (it *iter) release() {
if it.closed {
return
}
// Remove the iterator from the list of open iterators.
it.db.openIterators.Remove(it)
it.closed = true
if err := it.iter.Close(); err != nil {
it.err = updateError(err)
}
}