github.com/telepresenceio/telepresence/v2@v2.20.0-pro.6.0.20240517030216-236ea954e789/pkg/vif/buffer/data_darwin.go (about)

     1  package buffer
     2  
     3  const PrefixLen = 4
     4  
     5  // Data on a macOS consists of two slices that share the same underlying byte array. The
     6  // raw data points to the beginning of the array and the buf points PrefixLen into the array.
     7  // All data manipulation is then done using the buf, except reads/writes to the tun device which
     8  // uses the raw. This setup enables the read/write to receive and write the required 4-byte
     9  // header that macOS TUN socket uses without copying data.
    10  type Data struct {
    11  	buf []byte
    12  	raw []byte
    13  }
    14  
    15  // Buf returns this Data's buffer. This is the buffer that should be used everywhere
    16  // except for the tun.Device ReadPacket and WritePacket methods.
    17  func (d *Data) Buf() []byte {
    18  	return d.buf
    19  }
    20  
    21  // Copy copies n bytes from the given Data buffer into a new Data and returns it.
    22  func (d *Data) Copy(n int) *Data {
    23  	c := NewData(n)
    24  	c.buf = c.buf[:n]
    25  	c.raw = c.raw[:n+PrefixLen]
    26  	copy(c.raw, d.raw)
    27  	return c
    28  }
    29  
    30  // Raw returns this Data's raw buffer. This is the buffer that should be used by the tun.Device
    31  // ReadPacket and WritePacket methods. It uses the same underlying byte array as Buf but might be
    32  // offset before Buf to allow for leading bytes that are provided before the IP header.
    33  func (d *Data) Raw() []byte {
    34  	return d.raw
    35  }
    36  
    37  func NewData(sz int) *Data {
    38  	raw := make([]byte, PrefixLen+sz)
    39  	return &Data{buf: raw[PrefixLen:], raw: raw}
    40  }
    41  
    42  func (d *Data) Resize(size int) {
    43  	if size <= cap(d.buf) {
    44  		d.buf = d.buf[:size]
    45  		d.raw = d.raw[:size+PrefixLen]
    46  	} else {
    47  		d.raw = make([]byte, size+PrefixLen)
    48  		d.buf = d.raw[PrefixLen:]
    49  	}
    50  }