reduce copying

This commit is contained in:
Jay Wren
2025-11-11 14:51:53 -05:00
parent ef0a022375
commit 0f9b33aa36
2 changed files with 48 additions and 8 deletions

View File

@@ -92,9 +92,24 @@ func (w *wgDeviceWrapper) Read(b []byte) (int, error) {
}
func (w *wgDeviceWrapper) Write(b []byte) (int, error) {
// Allocate buffer with space for virtio header
buf := make([]byte, virtioNetHdrLen+len(b))
copy(buf[virtioNetHdrLen:], b)
// Check if buffer has the expected headroom pattern to avoid copy
var buf []byte
if cap(b) >= len(b)+virtioNetHdrLen {
buf = b[:cap(b)]
if len(buf) == len(b)+virtioNetHdrLen {
// Perfect! Buffer has headroom, no copy needed
buf = buf[:len(b)+virtioNetHdrLen]
} else {
// Unexpected capacity, safer to copy
buf = make([]byte, virtioNetHdrLen+len(b))
copy(buf[virtioNetHdrLen:], b)
}
} else {
// No headroom, need to allocate and copy
buf = make([]byte, virtioNetHdrLen+len(b))
copy(buf[virtioNetHdrLen:], b)
}
bufs := [][]byte{buf}
n, err := w.dev.Write(bufs, virtioNetHdrLen)
@@ -404,9 +419,28 @@ func (t *tun) BatchSize() int {
func (t *tun) Write(b []byte) (int, error) {
if t.wgDevice != nil {
// Use wireguard device which handles virtio headers internally
// Allocate buffer with space for virtio header
buf := make([]byte, virtioNetHdrLen+len(b))
copy(buf[virtioNetHdrLen:], b)
// Check if buffer has the expected headroom pattern:
// cap(b) should be len(b) + virtioNetHdrLen, indicating pre-allocated headroom
var buf []byte
if cap(b) >= len(b)+virtioNetHdrLen {
// Buffer likely has headroom - use unsafe to access it
// Create a slice that includes the headroom by re-slicing from capacity
buf = b[:cap(b)]
// Check if we have exactly the right amount of extra capacity
if len(buf) == len(b)+virtioNetHdrLen {
// Perfect! This buffer was allocated with headroom, no copy needed
buf = buf[:len(b)+virtioNetHdrLen]
} else {
// Unexpected capacity, safer to copy
buf = make([]byte, virtioNetHdrLen+len(b))
copy(buf[virtioNetHdrLen:], b)
}
} else {
// No headroom, need to allocate and copy
buf = make([]byte, virtioNetHdrLen+len(b))
copy(buf[virtioNetHdrLen:], b)
}
bufs := [][]byte{buf}
n, err := t.wgDevice.Write(bufs, virtioNetHdrLen)