From 8d82a394042feb858f8b8b40f199f9ede5cc1b83 Mon Sep 17 00:00:00 2001 From: Matt Joiner Date: Sat, 4 Sep 2021 21:09:25 +1000 Subject: Make Operation generic From https://github.com/anacrolix/stm/commit/80e033aa1f2218b83fb5891671ed795de72e19d5 --- funcs.go | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) (limited to 'funcs.go') 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{}{} } } -- cgit v1.2.3