aboutsummaryrefslogtreecommitdiff
path: root/var.go
diff options
context:
space:
mode:
authorChris Wendt <chrismwendt@gmail.com>2022-06-08 02:28:37 -0600
committerChris Wendt <chrismwendt@gmail.com>2022-06-08 03:02:44 -0600
commit30943ded71e123886291ad393e55bfb6aa837df3 (patch)
treeca7cc2520959386d6c57d9204f284be217bb0b72 /var.go
parentuse generic atomic (diff)
downloadstm-30943ded71e123886291ad393e55bfb6aa837df3.tar.gz
stm-30943ded71e123886291ad393e55bfb6aa837df3.tar.xz
BIG change: generic Var[T], txVar, etc.
Diffstat (limited to 'var.go')
-rw-r--r--var.go32
1 files changed, 22 insertions, 10 deletions
diff --git a/var.go b/var.go
index ec85996..40c3c74 100644
--- a/var.go
+++ b/var.go
@@ -7,13 +7,25 @@ import (
)
// Holds an STM variable.
-type Var struct {
+type Var[T any] struct {
value atomic.Value[VarValue]
watchers sync.Map
mu sync.Mutex
}
-func (v *Var) changeValue(new interface{}) {
+func (v *Var[T]) getValue() *atomic.Value[VarValue] {
+ return &v.value
+}
+
+func (v *Var[T]) getWatchers() *sync.Map {
+ return &v.watchers
+}
+
+func (v *Var[T]) getLock() *sync.Mutex {
+ return &v.mu
+}
+
+func (v *Var[T]) changeValue(new interface{}) {
old := v.value.Load()
newVarValue := old.Set(new)
v.value.Store(newVarValue)
@@ -22,7 +34,7 @@ func (v *Var) changeValue(new interface{}) {
}
}
-func (v *Var) wakeWatchers(new VarValue) {
+func (v *Var[T]) wakeWatchers(new VarValue) {
v.watchers.Range(func(k, _ interface{}) bool {
tx := k.(*Tx)
// We have to lock here to ensure that the Tx is waiting before we signal it. Otherwise we
@@ -45,25 +57,25 @@ type varSnapshot struct {
}
// Returns a new STM variable.
-func NewVar(val interface{}) *Var {
- v := &Var{}
+func NewVar[T any](val interface{}) *Var[T] {
+ v := &Var[T]{}
v.value.Store(versionedValue{
value: val,
})
return v
}
-func NewCustomVar(val interface{}, changed func(interface{}, interface{}) bool) *Var {
- v := &Var{}
- v.value.Store(customVarValue{
+func NewCustomVar[T any](val T, changed func(T, T) bool) *Var[T] {
+ v := &Var[T]{}
+ v.value.Store(customVarValue[T]{
value: val,
changed: changed,
})
return v
}
-func NewBuiltinEqVar(val interface{}) *Var {
- return NewCustomVar(val, func(a, b interface{}) bool {
+func NewBuiltinEqVar[T comparable](val T) *Var[T] {
+ return NewCustomVar(val, func(a, b T) bool {
return a != b
})
}