Skip to content

Instantly share code, notes, and snippets.

@karrick
Last active August 8, 2018 20:59
Show Gist options
  • Save karrick/8fa3654ac478997fa47d0c6a2443322d to your computer and use it in GitHub Desktop.
Save karrick/8fa3654ac478997fa47d0c6a2443322d to your computer and use it in GitHub Desktop.
growByteSlice will return a byte slice with a capacity at least equal to the specified size.
// growByteSlice will return a byte slice with a capacity at least equal to the
// specified size.
func growByteSlice(buf []byte, need int) []byte {
// Optimization for when buffer might be required to grow by more than
// double its size.
if need > cap(buf)<<1 {
t := make([]byte, need)
copy(t, buf)
return t
}
for cap(buf) < need {
buf = append(buf[:cap(buf)], 0)
}
return buf[:cap(buf)]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment