forked from redis/go-redis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
iterator.go
86 lines (73 loc) · 1.67 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
package redis
import "sync"
type Scanner struct {
client *cmdable
*ScanCmd
}
// Iterator creates a new ScanIterator.
func (s Scanner) Iterator() *ScanIterator {
return &ScanIterator{
Scanner: s,
}
}
// ScanIterator is used to incrementally iterate over a collection of elements.
// It's safe for concurrent use by multiple goroutines.
type ScanIterator struct {
mu sync.Mutex // protects Scanner and pos
Scanner
pos int
}
// Err returns the last iterator error, if any.
func (it *ScanIterator) Err() error {
it.mu.Lock()
err := it.ScanCmd.Err()
it.mu.Unlock()
return err
}
// Next advances the cursor and returns true if more values can be read.
func (it *ScanIterator) Next() bool {
it.mu.Lock()
defer it.mu.Unlock()
// Instantly return on errors.
if it.ScanCmd.Err() != nil {
return false
}
// Advance cursor, check if we are still within range.
if it.pos < len(it.ScanCmd.page) {
it.pos++
return true
}
for {
// Return if there is no more data to fetch.
if it.ScanCmd.cursor == 0 {
return false
}
// Fetch next page.
if it.ScanCmd._args[0] == "scan" {
it.ScanCmd._args[1] = it.ScanCmd.cursor
} else {
it.ScanCmd._args[2] = it.ScanCmd.cursor
}
it.ScanCmd.reset()
it.client.process(it.ScanCmd)
if it.ScanCmd.Err() != nil {
return false
}
it.pos = 1
// Redis can occasionally return empty page
if len(it.ScanCmd.page) > 0 {
return true
}
}
return false
}
// Val returns the key/field at the current cursor position.
func (it *ScanIterator) Val() string {
var v string
it.mu.Lock()
if it.ScanCmd.Err() == nil && it.pos > 0 && it.pos <= len(it.ScanCmd.page) {
v = it.ScanCmd.page[it.pos-1]
}
it.mu.Unlock()
return v
}