gitea源码

set.go 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2022 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package container
  4. import "maps"
  5. type Set[T comparable] map[T]struct{}
  6. // SetOf creates a set and adds the specified elements to it.
  7. func SetOf[T comparable](values ...T) Set[T] {
  8. s := make(Set[T], len(values))
  9. s.AddMultiple(values...)
  10. return s
  11. }
  12. // Add adds the specified element to a set.
  13. // Returns true if the element is added; false if the element is already present.
  14. func (s Set[T]) Add(value T) bool {
  15. if _, has := s[value]; !has {
  16. s[value] = struct{}{}
  17. return true
  18. }
  19. return false
  20. }
  21. // AddMultiple adds the specified elements to a set.
  22. func (s Set[T]) AddMultiple(values ...T) {
  23. for _, value := range values {
  24. s.Add(value)
  25. }
  26. }
  27. // Contains determines whether a set contains all these elements.
  28. // Returns true if the set contains all these elements; otherwise, false.
  29. func (s Set[T]) Contains(values ...T) bool {
  30. ret := true
  31. for _, value := range values {
  32. _, has := s[value]
  33. ret = ret && has
  34. }
  35. return ret
  36. }
  37. // Remove removes the specified element.
  38. // Returns true if the element is successfully found and removed; otherwise, false.
  39. func (s Set[T]) Remove(value T) bool {
  40. if _, has := s[value]; has {
  41. delete(s, value)
  42. return true
  43. }
  44. return false
  45. }
  46. // Values gets a list of all elements in the set.
  47. func (s Set[T]) Values() []T {
  48. keys := make([]T, 0, len(s))
  49. for k := range s {
  50. keys = append(keys, k)
  51. }
  52. return keys
  53. }
  54. // Union constructs a new set that is the union of the provided sets
  55. func (s Set[T]) Union(sets ...Set[T]) Set[T] {
  56. newSet := maps.Clone(s)
  57. for i := range sets {
  58. maps.Copy(newSet, sets[i])
  59. }
  60. return newSet
  61. }