Debian Codegraph @

iterator.go

raw
1 package redis
2
3 import "sync"
4
5 // ScanIterator is used to incrementally iterate over a collection of elements.
6 // It's safe for concurrent use by multiple goroutines.
7 type ScanIterator struct {
8 mu sync.Mutex // protects Scanner and pos
9 cmd *ScanCmd
10 pos int
11 }
12
13 // Err returns the last iterator error, if any.
14 func (it *ScanIterator) Err() error {
15 it.mu.Lock()
16 err := it.cmd.Err()
17 it.mu.Unlock()
18 return err
19 }
20
21 // Next advances the cursor and returns true if more values can be read.
22 func (it *ScanIterator) Next() bool {
23 it.mu.Lock()
24 defer it.mu.Unlock()
25
26 // Instantly return on errors.
27 if it.cmd.Err() != nil {
28 return false
29 }
30
31 // Advance cursor, check if we are still within range.
32 if it.pos < len(it.cmd.page) {
33 it.pos++
34 return true
35 }
36
37 for {
38 // Return if there is no more data to fetch.
39 if it.cmd.cursor == 0 {
40 return false
41 }
42
43 // Fetch next page.
44 if it.cmd._args[0] == "scan" {
45 it.cmd._args[1] = it.cmd.cursor
46 } else {
47 it.cmd._args[2] = it.cmd.cursor
48 }
49
50 err := it.cmd.process(it.cmd)
51 if err != nil {
52 return false
53 }
54
55 it.pos = 1
56
57 // Redis can occasionally return empty page.
58 if len(it.cmd.page) > 0 {
59 return true
60 }
61 }
62 }
63
64 // Val returns the key/field at the current cursor position.
65 func (it *ScanIterator) Val() string {
66 var v string
67 it.mu.Lock()
68 if it.cmd.Err() == nil && it.pos > 0 && it.pos <= len(it.cmd.page) {
69 v = it.cmd.page[it.pos-1]
70 }
71 it.mu.Unlock()
72 return v
73 }