2019-04-08 03:05:15 -06:00
|
|
|
package redis
|
|
|
|
|
2020-09-27 15:09:46 -06:00
|
|
|
import (
|
2021-02-10 14:28:32 -07:00
|
|
|
"context"
|
2020-09-27 15:09:46 -06:00
|
|
|
"sync"
|
|
|
|
)
|
2019-04-08 03:05:15 -06:00
|
|
|
|
|
|
|
// 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
|
|
|
|
cmd *ScanCmd
|
|
|
|
pos int
|
|
|
|
}
|
|
|
|
|
|
|
|
// Err returns the last iterator error, if any.
|
|
|
|
func (it *ScanIterator) Err() error {
|
|
|
|
it.mu.Lock()
|
|
|
|
err := it.cmd.Err()
|
|
|
|
it.mu.Unlock()
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Next advances the cursor and returns true if more values can be read.
|
2021-02-10 14:28:32 -07:00
|
|
|
func (it *ScanIterator) Next(ctx context.Context) bool {
|
2019-04-08 03:05:15 -06:00
|
|
|
it.mu.Lock()
|
|
|
|
defer it.mu.Unlock()
|
|
|
|
|
|
|
|
// Instantly return on errors.
|
|
|
|
if it.cmd.Err() != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// Advance cursor, check if we are still within range.
|
|
|
|
if it.pos < len(it.cmd.page) {
|
|
|
|
it.pos++
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
for {
|
|
|
|
// Return if there is no more data to fetch.
|
|
|
|
if it.cmd.cursor == 0 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// Fetch next page.
|
2021-02-10 14:28:32 -07:00
|
|
|
switch it.cmd.args[0] {
|
|
|
|
case "scan", "qscan":
|
2020-09-27 15:09:46 -06:00
|
|
|
it.cmd.args[1] = it.cmd.cursor
|
2021-02-10 14:28:32 -07:00
|
|
|
default:
|
2020-09-27 15:09:46 -06:00
|
|
|
it.cmd.args[2] = it.cmd.cursor
|
2019-04-08 03:05:15 -06:00
|
|
|
}
|
|
|
|
|
2021-02-10 14:28:32 -07:00
|
|
|
err := it.cmd.process(ctx, it.cmd)
|
2019-04-08 03:05:15 -06:00
|
|
|
if err != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
it.pos = 1
|
|
|
|
|
|
|
|
// Redis can occasionally return empty page.
|
|
|
|
if len(it.cmd.page) > 0 {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Val returns the key/field at the current cursor position.
|
|
|
|
func (it *ScanIterator) Val() string {
|
|
|
|
var v string
|
|
|
|
it.mu.Lock()
|
|
|
|
if it.cmd.Err() == nil && it.pos > 0 && it.pos <= len(it.cmd.page) {
|
|
|
|
v = it.cmd.page[it.pos-1]
|
|
|
|
}
|
|
|
|
it.mu.Unlock()
|
|
|
|
return v
|
|
|
|
}
|