go-ceph/internal/retry/example_sizer_test.go
Sven Anderson e01eb03284 retry: add a helper lib for retrying common operations
Our first operation is generating sizes for various caller-allocated
buffers.  The WithSizes function "suggests" sizes to an anonymous
function that takes a size as an argument and returns a hint how
sucessful the attempt was.  If required the same function is called
again with a larger size.  Errors and other results of that anonymous
function are "communicated" with variables of the surrounding scope
in wich the function is defined.

Signed-off-by: John Mulligan <jmulligan@redhat.com>
Signed-off-by: Sven Anderson <sven@redhat.com>
2020-04-20 15:08:36 -04:00

57 lines
1.0 KiB
Go

package retry
import (
"fmt"
)
var errTooSmall = fmt.Errorf("too small")
func fakeComplexOp(v []string) error {
if len(v) < 30 {
fmt.Println("too small:", len(v))
return errTooSmall
}
fmt.Println("good size:", len(v))
return nil
}
func ExampleWithSizes() {
var err error
WithSizes(1, 128, func(size int) Hint {
buf := make([]string, size)
// do something complex with buf
err = fakeComplexOp(buf)
return DoubleSize.If(err == errTooSmall)
})
// Output:
// too small: 1
// too small: 2
// too small: 4
// too small: 8
// too small: 16
// good size: 32
}
func fakeComplexOp2(v []string, s *int) error {
if len(v) < 30 {
fmt.Println("too small:", len(v))
*s = 30
return errTooSmall
}
fmt.Println("good size:", len(v))
return nil
}
func ExampleWithSizes_hint() {
var err error
WithSizes(1, 128, func(size int) Hint {
buf := make([]string, size)
// do something complex with buf
err = fakeComplexOp2(buf, &size)
return Size(size).If(err == errTooSmall)
})
// Output:
// too small: 1
// good size: 30
}