stringset.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package stringset
  2. // StringSet is a basic set implementation for strings.
  3. // This is used a lot so it deserves its own type.
  4. // Other types of sets are used throughout the code but do not have
  5. // their own typedef.
  6. // String sets and <type>sets should be used throughout the code when applicable,
  7. // they are a lot more flexible than slices and provide easy lookup.
  8. type StringSet map[string]struct{}
  9. // MapStringSet is a Map of StringSets.
  10. type MapStringSet map[string]StringSet
  11. // Add adds a new value to the Map.
  12. // If n is already in the map, then v is appended to the StringSet under that key.
  13. // Otherwise a new StringSet is creayed containing v.
  14. func (mss MapStringSet) Add(n, v string) {
  15. if _, ok := mss[n]; !ok {
  16. mss[n] = make(StringSet)
  17. }
  18. mss[n].Set(v)
  19. }
  20. // Set sets key in StringSet.
  21. func (set StringSet) Set(v string) {
  22. set[v] = struct{}{}
  23. }
  24. // Extend sets multiple keys in StringSet.
  25. func (set StringSet) Extend(s ...string) {
  26. for _, v := range s {
  27. set[v] = struct{}{}
  28. }
  29. }
  30. // Get returns true if the key exists in the set.
  31. func (set StringSet) Get(v string) bool {
  32. _, exists := set[v]
  33. return exists
  34. }
  35. // Remove deletes a key from the set.
  36. func (set StringSet) Remove(v string) {
  37. delete(set, v)
  38. }
  39. // ToSlice turns all keys into a string slice.
  40. func (set StringSet) ToSlice() []string {
  41. slice := make([]string, 0, len(set))
  42. for v := range set {
  43. slice = append(slice, v)
  44. }
  45. return slice
  46. }
  47. // Copy copies a StringSet into a new structure of the same type.
  48. func (set StringSet) Copy() StringSet {
  49. newSet := make(StringSet)
  50. for str := range set {
  51. newSet.Set(str)
  52. }
  53. return newSet
  54. }
  55. // FromSlice creates a new StringSet from an input slice.
  56. func FromSlice(in []string) StringSet {
  57. set := make(StringSet)
  58. for _, v := range in {
  59. set.Set(v)
  60. }
  61. return set
  62. }
  63. // Make creates a new StringSet from a set of arguments.
  64. func Make(in ...string) StringSet {
  65. return FromSlice(in)
  66. }
  67. // Equal compares if two StringSets have the same values.
  68. func Equal(a, b StringSet) bool {
  69. if a == nil && b == nil {
  70. return true
  71. }
  72. if a == nil || b == nil {
  73. return false
  74. }
  75. if len(a) != len(b) {
  76. return false
  77. }
  78. for n := range a {
  79. if !b.Get(n) {
  80. return false
  81. }
  82. }
  83. return true
  84. }