forked from OneOfOne/genh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlvalue.go
79 lines (67 loc) · 1.5 KB
/
lvalue.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package genh
import (
"encoding/json"
"sync"
)
// LValue wraps a sync.RWMutex to allow simple and safe operation on the mutex.
type LValue[T any] struct {
mux sync.RWMutex
v T
}
// Update executes fn while the mutex is write-locked and guarantees the mutex is released even in the case of a panic.
func (m *LValue[T]) Update(fn func(old T) T) {
m.mux.Lock()
defer m.mux.Unlock()
m.v = fn(m.v)
}
// Read executes fn while the mutex is read-locked and guarantees the mutex is released even in the case of a panic.
func (m *LValue[T]) Read(fn func(v T)) {
m.mux.RLock()
defer m.mux.RUnlock()
fn(m.v)
}
func (m *LValue[T]) Get() T {
m.mux.RLock()
v := m.v
m.mux.RUnlock()
return v
}
func (m *LValue[T]) Set(v T) {
m.mux.Lock()
m.v = v
m.mux.Unlock()
}
func (m *LValue[T]) Swap(v T) (old T) {
m.mux.Lock()
old, m.v = m.v, v
m.mux.Unlock()
return
}
func (m *LValue[T]) CompareAndSwap(old, new T, eq func(a, b T) bool) (ok bool) {
m.mux.Lock()
defer m.mux.Unlock()
if ok = eq(m.v, old); ok {
m.v = new
}
return
}
func (m *LValue[T]) MarshalBinary() ([]byte, error) {
m.mux.RLock()
defer m.mux.RUnlock()
return MarshalMsgpack(m.v)
}
func (m *LValue[T]) UnmarshalBinary(b []byte) error {
m.mux.Lock()
defer m.mux.Unlock()
return UnmarshalMsgpack(b, &m.v)
}
func (m *LValue[T]) MarshalJSON() ([]byte, error) {
m.mux.RLock()
defer m.mux.RUnlock()
return json.Marshal(m.v)
}
func (m *LValue[T]) UnmarshalJSON(b []byte) error {
m.mux.Lock()
defer m.mux.Unlock()
return json.Unmarshal(b, &m.v)
}