stringset.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package types
  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. func (mss MapStringSet) Add(n string, v string) {
  13. _, ok := mss[n]
  14. if !ok {
  15. mss[n] = make(StringSet)
  16. }
  17. mss[n].Set(v)
  18. }
  19. // Set sets key in StringSet.
  20. func (set StringSet) Set(v string) {
  21. set[v] = struct{}{}
  22. }
  23. // Get returns true if the key exists in the set.
  24. func (set StringSet) Get(v string) bool {
  25. _, exists := set[v]
  26. return exists
  27. }
  28. // Remove deletes a key from the set.
  29. func (set StringSet) Remove(v string) {
  30. delete(set, v)
  31. }
  32. // ToSlice turns all keys into a string slice.
  33. func (set StringSet) ToSlice() []string {
  34. slice := make([]string, 0, len(set))
  35. for v := range set {
  36. slice = append(slice, v)
  37. }
  38. return slice
  39. }
  40. // Copy copies a StringSet into a new structure of the same type.
  41. func (set StringSet) Copy() StringSet {
  42. newSet := make(StringSet)
  43. for str := range set {
  44. newSet.Set(str)
  45. }
  46. return newSet
  47. }
  48. // SliceToStringSet creates a new StringSet from an input slice
  49. func SliceToStringSet(in []string) StringSet {
  50. set := make(StringSet)
  51. for _, v := range in {
  52. set.Set(v)
  53. }
  54. return set
  55. }
  56. // MakeStringSet creates a new StringSet from a set of arguments
  57. func MakeStringSet(in ...string) StringSet {
  58. return SliceToStringSet(in)
  59. }
  60. // StringSetEqual compares if two StringSets have the same values
  61. func StringSetEqual(a, b StringSet) bool {
  62. if a == nil && b == nil {
  63. return true
  64. }
  65. if a == nil || b == nil {
  66. return false
  67. }
  68. if len(a) != len(b) {
  69. return false
  70. }
  71. for n := range a {
  72. if !b.Get(n) {
  73. return false
  74. }
  75. }
  76. return true
  77. }