Created
July 14, 2020 23:07
-
-
Save rbranson/a76bfda7d87f63eba24ac07f1d51b5c4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package none | |
import "io" | |
func min(a int, b int) int { | |
if a < b { | |
return a | |
} | |
return b | |
} | |
func max(a int, b int) int { | |
if a > b { | |
return a | |
} | |
return b | |
} | |
type growbuf struct { | |
Min int | |
Max int | |
// keep a ref to the buffer instead of its len to support replacing the | |
// buffer with a new one in a single statement, which gives the compiler | |
// an opportunity to optimize the call if it can. | |
buf []byte | |
} | |
func boundedScale(baseline, lower, upper, coefficient int) int { | |
x := max(lower, baseline*coefficient) | |
return min(upper, x) | |
} | |
// Buffer returns a new zero-initialized buffer with a length between g.Min and | |
// g.Max. Each successive call returns a new buffer that is twice the length | |
// of the last one returned, up to g.Max. Once g.Max is reached, the next call | |
// will return an io.ErrShortBuffer error. | |
func (g *growbuf) Buffer() ([]byte, error) { | |
if len(g.buf) >= g.Max { | |
return nil, io.ErrShortBuffer | |
} | |
ln := boundedScale(len(g.buf), g.Min, g.Max, 2) | |
g.buf = make([]byte, ln) | |
return g.buf, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment