unsafe_pointer.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright (c) 2021 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. package atomic
  21. import (
  22. "sync/atomic"
  23. "unsafe"
  24. )
  25. // UnsafePointer is an atomic wrapper around unsafe.Pointer.
  26. type UnsafePointer struct {
  27. _ nocmp // disallow non-atomic comparison
  28. v unsafe.Pointer
  29. }
  30. // NewUnsafePointer creates a new UnsafePointer.
  31. func NewUnsafePointer(val unsafe.Pointer) *UnsafePointer {
  32. return &UnsafePointer{v: val}
  33. }
  34. // Load atomically loads the wrapped value.
  35. func (p *UnsafePointer) Load() unsafe.Pointer {
  36. return atomic.LoadPointer(&p.v)
  37. }
  38. // Store atomically stores the passed value.
  39. func (p *UnsafePointer) Store(val unsafe.Pointer) {
  40. atomic.StorePointer(&p.v, val)
  41. }
  42. // Swap atomically swaps the wrapped unsafe.Pointer and returns the old value.
  43. func (p *UnsafePointer) Swap(val unsafe.Pointer) (old unsafe.Pointer) {
  44. return atomic.SwapPointer(&p.v, val)
  45. }
  46. // CAS is an atomic compare-and-swap.
  47. func (p *UnsafePointer) CAS(old, new unsafe.Pointer) (swapped bool) {
  48. return atomic.CompareAndSwapPointer(&p.v, old, new)
  49. }