intset.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. Copyright 2018 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package node
  14. // intSet maintains a set of ints, and supports promoting and culling the previous generation.
  15. // this allows tracking a large, mostly-stable set without constantly reallocating the entire set.
  16. type intSet struct {
  17. currentGeneration byte
  18. members map[int]byte
  19. }
  20. func newIntSet() *intSet {
  21. return &intSet{members: map[int]byte{}}
  22. }
  23. // has returns true if the specified int is in the set.
  24. // it is safe to call concurrently, but must not be called concurrently with any of the other methods.
  25. func (s *intSet) has(i int) bool {
  26. if s == nil {
  27. return false
  28. }
  29. _, present := s.members[i]
  30. return present
  31. }
  32. // startNewGeneration begins a new generation.
  33. // it must be followed by a call to mark() for every member of the generation,
  34. // then a call to sweep() to remove members not present in the generation.
  35. // it is not thread-safe.
  36. func (s *intSet) startNewGeneration() {
  37. s.currentGeneration++
  38. }
  39. // mark indicates the specified int belongs to the current generation.
  40. // it is not thread-safe.
  41. func (s *intSet) mark(i int) {
  42. s.members[i] = s.currentGeneration
  43. }
  44. // sweep removes items not in the current generation.
  45. // it is not thread-safe.
  46. func (s *intSet) sweep() {
  47. for k, v := range s.members {
  48. if v != s.currentGeneration {
  49. delete(s.members, k)
  50. }
  51. }
  52. }