set.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package multihash
  2. // Set is a set of Multihashes, holding one copy per Multihash.
  3. type Set struct {
  4. set map[string]struct{}
  5. }
  6. // NewSet creates a new set correctly initialized.
  7. func NewSet() *Set {
  8. return &Set{
  9. set: make(map[string]struct{}),
  10. }
  11. }
  12. // Add adds a new multihash to the set.
  13. func (s *Set) Add(m Multihash) {
  14. s.set[string(m)] = struct{}{}
  15. }
  16. // Len returns the number of elements in the set.
  17. func (s *Set) Len() int {
  18. return len(s.set)
  19. }
  20. // Has returns true if the element is in the set.
  21. func (s *Set) Has(m Multihash) bool {
  22. _, ok := s.set[string(m)]
  23. return ok
  24. }
  25. // Visit adds a multihash only if it is not in the set already. Returns true
  26. // if the multihash was added (was not in the set before).
  27. func (s *Set) Visit(m Multihash) bool {
  28. _, ok := s.set[string(m)]
  29. if !ok {
  30. s.set[string(m)] = struct{}{}
  31. return true
  32. }
  33. return false
  34. }
  35. // ForEach runs f(m) with each multihash in the set. If returns immediately if
  36. // f(m) returns an error.
  37. func (s *Set) ForEach(f func(m Multihash) error) error {
  38. for elem := range s.set {
  39. mh := Multihash(elem)
  40. if err := f(mh); err != nil {
  41. return err
  42. }
  43. }
  44. return nil
  45. }
  46. // Remove removes an element from the set.
  47. func (s *Set) Remove(m Multihash) {
  48. delete(s.set, string(m))
  49. }
  50. // All returns a slice with all the elements in the set.
  51. func (s *Set) All() []Multihash {
  52. out := make([]Multihash, 0, len(s.set))
  53. for m := range s.set {
  54. out = append(out, Multihash(m))
  55. }
  56. return out
  57. }