-
Notifications
You must be signed in to change notification settings - Fork 0
/
traverse.go
68 lines (62 loc) · 1.62 KB
/
traverse.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
package rangeset
// traverse.go has methods to process the elements of a set
import "context"
// Iterate calls f on every element in the set.
func (s Set[T]) Iterate(f func(T)) {
for _, v := range s {
for e := v.b; e < v.t; e++ {
f(e)
}
}
}
// Filter deletes elements from s for which f returns false.
// Time complexity is O(n)
// TODO look at optimising (eg by bunching into whole ranges before adding to toDelete)
func (s *Set[T]) Filter(f func(T) bool) {
toDelete := Make[T]()
for _, v := range *s {
for e := v.b; e < v.t; e++ {
if !f(e) {
toDelete.Add(e) // keep track of elts to delete
}
}
}
s.SubSet(toDelete) // delete the elts
}
// Iterator returns a channel that receives the elements of the set in order.
// To terminate the go-routine before all elements have been seen, cancel the
// context (first parameter to the method). Note that after the context is
// canceled another element *may* be seen on the chan before it is closed.
// To avoid a goroutine leak you need to read from the channel until it is
// closed or cancel the context.
func (s Set[T]) Iterator(ctx context.Context) <-chan T {
r := make(chan T)
go func(ch chan<- T) {
defer close(ch)
for _, v := range s {
for e := v.b; e < v.t; e++ {
select {
case <-ctx.Done():
return
case ch <- e:
}
}
}
}(r)
return r
}
// ReadAll adds elements to the set by reading them from the channel until it
// is closed or the context is canceled.
func (s *Set[T]) ReadAll(ctx context.Context, c <-chan T) {
for {
select {
case <-ctx.Done():
return
case v, ok := <-c:
if !ok {
return
}
_ = s.Add(v)
}
}
}