set.go 782 Bytes
Newer Older
1
package cidutil
2

Łukasz Magiera's avatar
Łukasz Magiera committed
3 4
import (
	"context"
5

6
	c "gitlab.dms3.io/dms3/go-cid"
7
)
8

9
type Set = c.Set
10

11
func NewSet() *Set { return c.NewSet() }
Łukasz Magiera's avatar
Łukasz Magiera committed
12 13 14 15 16

// StreamingSet is an extension of Set which allows to implement back-pressure
// for the Visit function
type StreamingSet struct {
	Set *Set
17
	New chan c.Cid
Łukasz Magiera's avatar
Łukasz Magiera committed
18 19 20 21 22
}

// NewStreamingSet initializes and returns new Set.
func NewStreamingSet() *StreamingSet {
	return &StreamingSet{
23
		Set: c.NewSet(),
24
		New: make(chan c.Cid),
Łukasz Magiera's avatar
Łukasz Magiera committed
25 26 27 28 29
	}
}

// Visitor creates new visitor which adds a Cids to the set and emits them to
// the set.New channel
30 31
func (s *StreamingSet) Visitor(ctx context.Context) func(c c.Cid) bool {
	return func(c c.Cid) bool {
Łukasz Magiera's avatar
Łukasz Magiera committed
32 33 34 35 36 37 38 39 40 41 42
		if s.Set.Visit(c) {
			select {
			case s.New <- c:
			case <-ctx.Done():
			}
			return true
		}

		return false
	}
}