1 // @generated Code generated by gen-atomicwrapper. 2 3 // Copyright (c) 2020-2023 Uber Technologies, Inc. 4 // 5 // Permission is hereby granted, free of charge, to any person obtaining a copy 6 // of this software and associated documentation files (the "Software"), to deal 7 // in the Software without restriction, including without limitation the rights 8 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 // copies of the Software, and to permit persons to whom the Software is 10 // furnished to do so, subject to the following conditions: 11 // 12 // The above copyright notice and this permission notice shall be included in 13 // all copies or substantial portions of the Software. 14 // 15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 // THE SOFTWARE. 22 23 package atomic 24 25 import ( 26 "encoding/json" 27 ) 28 29 // Bool is an atomic type-safe wrapper for bool values. 30 type Bool struct { 31 _ nocmp // disallow non-atomic comparison 32 33 v Uint32 34 } 35 36 var _zeroBool bool 37 38 // NewBool creates a new Bool. 39 func NewBool(val bool) *Bool { 40 x := &Bool{} 41 if val != _zeroBool { 42 x.Store(val) 43 } 44 return x 45 } 46 47 // Load atomically loads the wrapped bool. 48 func (x *Bool) Load() bool { 49 return truthy(x.v.Load()) 50 } 51 52 // Store atomically stores the passed bool. 53 func (x *Bool) Store(val bool) { 54 x.v.Store(boolToInt(val)) 55 } 56 57 // CAS is an atomic compare-and-swap for bool values. 58 // 59 // Deprecated: Use CompareAndSwap. 60 func (x *Bool) CAS(old, new bool) (swapped bool) { 61 return x.CompareAndSwap(old, new) 62 } 63 64 // CompareAndSwap is an atomic compare-and-swap for bool values. 65 func (x *Bool) CompareAndSwap(old, new bool) (swapped bool) { 66 return x.v.CompareAndSwap(boolToInt(old), boolToInt(new)) 67 } 68 69 // Swap atomically stores the given bool and returns the old 70 // value. 71 func (x *Bool) Swap(val bool) (old bool) { 72 return truthy(x.v.Swap(boolToInt(val))) 73 } 74 75 // MarshalJSON encodes the wrapped bool into JSON. 76 func (x *Bool) MarshalJSON() ([]byte, error) { 77 return json.Marshal(x.Load()) 78 } 79 80 // UnmarshalJSON decodes a bool from JSON. 81 func (x *Bool) UnmarshalJSON(b []byte) error { 82 var v bool 83 if err := json.Unmarshal(b, &v); err != nil { 84 return err 85 } 86 x.Store(v) 87 return nil 88 } 89