set.go 827 Bytes
Newer Older
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
package cid

type Set struct {
	set map[string]struct{}
}

func NewSet() *Set {
	return &Set{set: make(map[string]struct{})}
}

func (s *Set) Add(c *Cid) {
	s.set[string(c.Bytes())] = struct{}{}
}

func (s *Set) Has(c *Cid) bool {
	_, ok := s.set[string(c.Bytes())]
	return ok
}

func (s *Set) Remove(c *Cid) {
	delete(s.set, string(c.Bytes()))
}

func (s *Set) Len() int {
	return len(s.set)
}

func (s *Set) Keys() []*Cid {
29
	out := make([]*Cid, 0, len(s.set))
30 31 32 33 34 35
	for k, _ := range s.set {
		c, _ := Cast([]byte(k))
		out = append(out, c)
	}
	return out
}
36 37 38 39 40 41 42 43 44

func (s *Set) Visit(c *Cid) bool {
	if !s.Has(c) {
		s.Add(c)
		return true
	}

	return false
}
45 46 47 48 49 50 51 52 53 54 55

func (s *Set) ForEach(f func(c *Cid) error) error {
	for cs, _ := range s.set {
		c, _ := Cast([]byte(cs))
		err := f(c)
		if err != nil {
			return err
		}
	}
	return nil
}