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