Documentation
¶
Index ¶
Examples ¶
Constants ¶
const DoubleSize = hintInt(0)
DoubleSize is a hint to retry with double the size
Variables ¶
This section is empty.
Functions ¶
func WithSizes ¶
WithSizes repeatingly calls a SizeFunc with increasing sizes until either it returns nil, or the max size has been reached. If the returned hint is DoubleSize or indicating a size not greater than the current size, the size is doubled. If the hint or next size is greater than the max size, the max size is used for a last retry.
Example ¶
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
Example (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
func WithTries ¶ added in v0.42.0
WithTries repeatedly calls a SizeFunc with increasing sizes until either it returns nil, or a maximum number of tries has been reached. If the returned hint is DoubleSize or indicating a size not greater than the current size, the size is doubled. WithTries should be used in conjunction with functions that provide a size hint other than DoubleSize. If the underlying function provides a size hint then the number of iterations can be kept low (ideally 2) and the system will make fewer memory allocations.
Types ¶
type SizeFunc ¶
SizeFunc is used to implement 'resize loops' that hides the complexity of the sizing away from most of the application. It's a function that takes a size argument and returns nil, if no retry is necessary, or a hint indicating the size for the next retry. If errors or other results are required from the function, the function can write them to function closures of the surrounding scope. See tests for examples.