github.com/MetalBlockchain/metalgo@v1.11.9/utils/atomic.go (about) 1 // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. 2 // See the file LICENSE for licensing terms. 3 4 package utils 5 6 import ( 7 "encoding/json" 8 "sync" 9 ) 10 11 var ( 12 _ json.Marshaler = (*Atomic[struct{}])(nil) 13 _ json.Unmarshaler = (*Atomic[struct{}])(nil) 14 ) 15 16 type Atomic[T any] struct { 17 lock sync.RWMutex 18 value T 19 } 20 21 func NewAtomic[T any](value T) *Atomic[T] { 22 return &Atomic[T]{ 23 value: value, 24 } 25 } 26 27 func (a *Atomic[T]) Get() T { 28 a.lock.RLock() 29 defer a.lock.RUnlock() 30 31 return a.value 32 } 33 34 func (a *Atomic[T]) Set(value T) { 35 a.lock.Lock() 36 defer a.lock.Unlock() 37 38 a.value = value 39 } 40 41 func (a *Atomic[T]) MarshalJSON() ([]byte, error) { 42 a.lock.RLock() 43 defer a.lock.RUnlock() 44 45 return json.Marshal(a.value) 46 } 47 48 func (a *Atomic[T]) UnmarshalJSON(b []byte) error { 49 a.lock.Lock() 50 defer a.lock.Unlock() 51 52 return json.Unmarshal(b, &a.value) 53 }