-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathcursor.go
125 lines (98 loc) · 2.2 KB
/
cursor.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
package lungo
import (
"context"
"fmt"
"io"
"sync"
"time"
"github.com/256dpi/lungo/bsonkit"
)
var _ ICursor = &Cursor{}
// Cursor wraps a list to be mongo compatible.
type Cursor struct {
list bsonkit.List
pos int
closed bool
mutex sync.Mutex
}
// All implements the ICursor.All method.
func (c *Cursor) All(_ context.Context, out interface{}) error {
// acquire mutex
c.mutex.Lock()
defer c.mutex.Unlock()
// check if closed
if c.closed {
return fmt.Errorf("cursor closed")
}
// decode items
err := bsonkit.DecodeList(c.list, out)
if err != nil {
return err
}
// close cursor
c.closed = true
return nil
}
// Close implements the ICursor.Close method.
func (c *Cursor) Close(context.Context) error {
// acquire mutex
c.mutex.Lock()
defer c.mutex.Unlock()
// close cursor
c.closed = true
return nil
}
// Decode implements the ICursor.Decode method.
func (c *Cursor) Decode(out interface{}) error {
// acquire mutex
c.mutex.Lock()
defer c.mutex.Unlock()
// check if exhausted
if c.pos == 0 || c.pos > len(c.list) {
return io.EOF
}
// decode item
err := bsonkit.Decode(c.list[c.pos-1], out)
if err != nil {
return err
}
return nil
}
// Err implements the ICursor.Err method.
func (c *Cursor) Err() error {
return nil
}
// ID implements the ICursor.ID method.
func (c *Cursor) ID() int64 {
return 0
}
// Next implements the ICursor.Next method.
func (c *Cursor) Next(context.Context) bool {
// acquire mutex
c.mutex.Lock()
defer c.mutex.Unlock()
// check if closed
if c.closed {
return false
}
// increment position
if c.pos < len(c.list) {
c.pos++
return true
}
return false
}
// RemainingBatchLength implements the ICursor.RemainingBatchLength method.
func (c *Cursor) RemainingBatchLength() int {
return len(c.list) - c.pos
}
// SetBatchSize implements the ICursor.SetBatchSize method.
func (c *Cursor) SetBatchSize(int32) {}
// SetComment implements the ICursor.SetComment method.
func (c *Cursor) SetComment(interface{}) {}
// SetMaxTime implements the ICursor.SetMaxTime method.
func (c *Cursor) SetMaxTime(time.Duration) {}
// TryNext implements the ICursor.TryNext method.
func (c *Cursor) TryNext(ctx context.Context) bool {
return c.Next(ctx)
}