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