pointer_go119.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright (c) 2022 Uber Technologies, Inc.
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. //
  10. // The above copyright notice and this permission notice shall be included in
  11. // all copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. // THE SOFTWARE.
  20. //go:build go1.19
  21. // +build go1.19
  22. package atomic
  23. import "sync/atomic"
  24. // Pointer is an atomic pointer of type *T.
  25. type Pointer[T any] struct {
  26. _ nocmp // disallow non-atomic comparison
  27. p atomic.Pointer[T]
  28. }
  29. // NewPointer creates a new Pointer.
  30. func NewPointer[T any](v *T) *Pointer[T] {
  31. var p Pointer[T]
  32. if v != nil {
  33. p.p.Store(v)
  34. }
  35. return &p
  36. }
  37. // Load atomically loads the wrapped value.
  38. func (p *Pointer[T]) Load() *T {
  39. return p.p.Load()
  40. }
  41. // Store atomically stores the passed value.
  42. func (p *Pointer[T]) Store(val *T) {
  43. p.p.Store(val)
  44. }
  45. // Swap atomically swaps the wrapped pointer and returns the old value.
  46. func (p *Pointer[T]) Swap(val *T) (old *T) {
  47. return p.p.Swap(val)
  48. }
  49. // CompareAndSwap is an atomic compare-and-swap.
  50. func (p *Pointer[T]) CompareAndSwap(old, new *T) (swapped bool) {
  51. return p.p.CompareAndSwap(old, new)
  52. }