Skip to content

Conversation

AliudRish
Copy link

@AliudRish AliudRish commented Sep 1, 2025

Current behavior

Both Seal and Open can allocate twice if the destination buffer is not nil, but it's capacity is insufficient:

if cap(dst)-len(dst) >= outLen {
	inplace = true
	buf = dst[len(dst) : len(dst)+outLen]
} else {
	buf = make([]byte, outLen) <-- first allocation, we confirm cap(dst)-len(dst) < outLen
}

...

if inplace {
	return dst[:len(dst)+outLen]
}
return append(dst, buf...) <-- second allocation, since cap(dst) is insufficient

Proposed change

Introduce a small helper function that either grows into destination buffer in place, or allocates the final return slice once and provides a “tail” view to work on:

func sliceGrowOrNew(s []byte, l int) (full, tail []byte) {
	if cap(s)-len(s) >= l {
		return s[:len(s)+l], s[len(s) : len(s)+l]
	} else {
		n := make([]byte, len(s)+l)
		copy(n, s)
		return n, n[len(s):]
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant