You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

set.go 1.3KB

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