aboutsummaryrefslogtreecommitdiff
path: root/funcs.go
diff options
context:
space:
mode:
authorMatt Joiner <anacrolix@gmail.com>2021-09-04 21:09:25 +1000
committerChris Wendt <chrismwendt@gmail.com>2022-06-08 03:02:44 -0600
commit8d82a394042feb858f8b8b40f199f9ede5cc1b83 (patch)
treebfa5db946ca7ccb8d2c6cdf0f2e63c97382e90fc /funcs.go
parentBIG change: generic Var[T], txVar, etc. (diff)
downloadstm-8d82a394042feb858f8b8b40f199f9ede5cc1b83.tar.gz
stm-8d82a394042feb858f8b8b40f199f9ede5cc1b83.tar.xz
Make Operation generic
From https://github.com/anacrolix/stm/commit/80e033aa1f2218b83fb5891671ed795de72e19d5
Diffstat (limited to 'funcs.go')
-rw-r--r--funcs.go23
1 files changed, 11 insertions, 12 deletions
diff --git a/funcs.go b/funcs.go
index 3336c71..54576ea 100644
--- a/funcs.go
+++ b/funcs.go
@@ -39,7 +39,7 @@ func newTx() *Tx {
return tx
}
-func WouldBlock(fn Operation) (block bool) {
+func WouldBlock[R any](fn Operation[R]) (block bool) {
tx := newTx()
tx.reset()
_, block = catchRetry(fn, tx)
@@ -51,7 +51,7 @@ func WouldBlock(fn Operation) (block bool) {
}
// Atomically executes the atomic function fn.
-func Atomically(op Operation) interface{} {
+func Atomically[R any](op Operation[R]) R {
expvars.Add("atomically", 1)
// run the transaction
tx := newTx()
@@ -116,20 +116,19 @@ func AtomicSet[T any](v *Var[T], val interface{}) {
// Compose is a helper function that composes multiple transactions into a
// single transaction.
-func Compose(fns ...Operation) Operation {
- return func(tx *Tx) interface{} {
+func Compose[R any](fns ...Operation[R]) Operation[struct{}] {
+ return VoidOperation(func(tx *Tx) {
for _, f := range fns {
f(tx)
}
- return nil
- }
+ })
}
// Select runs the supplied functions in order. Execution stops when a
// function succeeds without calling Retry. If no functions succeed, the
// entire selection will be retried.
-func Select(fns ...Operation) Operation {
- return func(tx *Tx) interface{} {
+func Select[R any](fns ...Operation[R]) Operation[R] {
+ return func(tx *Tx) R {
switch len(fns) {
case 0:
// empty Select blocks forever
@@ -154,12 +153,12 @@ func Select(fns ...Operation) Operation {
}
}
-type Operation func(*Tx) interface{}
+type Operation[R any] func(*Tx) R
-func VoidOperation(f func(*Tx)) Operation {
- return func(tx *Tx) interface{} {
+func VoidOperation(f func(*Tx)) Operation[struct{}] {
+ return func(tx *Tx) struct{} {
f(tx)
- return nil
+ return struct{}{}
}
}