go.mway.dev/x@v0.0.0-20240520034138-950aede9a3fb/sync/atomic/value.go (about) 1 // Copyright (c) 2023 Matt Way 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 5 // deal in the Software without restriction, including without limitation the 6 // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 7 // sell 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 18 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 19 // IN THE THE SOFTWARE. 20 21 // Package atomic provides atomicity-related types and helpers. 22 package atomic 23 24 import ( 25 "sync/atomic" 26 ) 27 28 // Value is a strongly-typed atomic value. It is otherwise identical to the 29 // standard library's atomic.Value. 30 type Value[T any] struct { 31 value atomic.Value 32 } 33 34 // NewValue creates a new Value that can store values of type T, initializing 35 // the Value with the given initial value. 36 func NewValue[T any](initial T) *Value[T] { 37 v := &Value[T]{} 38 v.value.Store(initial) 39 return v 40 } 41 42 // CompareAndSwap performs an atomic compare and swap using oldval and newval. 43 // The return value indicates whether a swap took place. 44 func (v *Value[T]) CompareAndSwap(oldval T, newval T) bool { 45 return v.value.CompareAndSwap(oldval, newval) 46 } 47 48 // Load loads the currently held T value. 49 func (v *Value[T]) Load() T { 50 return v.value.Load().(T) 51 } 52 53 // Store stores the given T value. 54 func (v *Value[T]) Store(val T) { 55 v.value.Store(val) 56 } 57 58 // Swap swaps the currently held T value with the given value, returning the 59 // previous T. 60 func (v *Value[T]) Swap(val T) T { 61 return v.value.Swap(val).(T) 62 }