handle.go 835 B

123456789101112131415161718192021222324252627282930313233343536
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package set
  4. // HandleSet is a set of T.
  5. //
  6. // It is not safe for concurrent use.
  7. type HandleSet[T any] map[Handle]T
  8. // Handle is an opaque comparable value that's used as the map key in a
  9. // HandleSet.
  10. type Handle struct {
  11. v *byte
  12. }
  13. // NewHandle returns a new handle value.
  14. func NewHandle() Handle {
  15. return Handle{new(byte)}
  16. }
  17. // Add adds the element (map value) e to the set.
  18. //
  19. // It returns a new handle (map key) with which e can be removed, using a map
  20. // delete or the [HandleSet.Delete] method.
  21. func (s *HandleSet[T]) Add(e T) Handle {
  22. h := NewHandle()
  23. if *s == nil {
  24. *s = make(HandleSet[T])
  25. }
  26. (*s)[h] = e
  27. return h
  28. }
  29. // Delete removes the element with handle h from the set.
  30. func (s HandleSet[T]) Delete(h Handle) { delete(s, h) }