Skip to content

Commit

Permalink
conn: reduce initial memory in Receive()
Browse files Browse the repository at this point in the history
Reduce memory footprint by starting with a smaller buffer and adjust the
buffer size accordingly after peeking at the upcoming netlink message.

Signed-off-by: Florian Lehner <dev@der-flo.net>
  • Loading branch information
florianl committed Jun 25, 2024
1 parent 13a521f commit 9b038ba
Showing 1 changed file with 11 additions and 19 deletions.
30 changes: 11 additions & 19 deletions conn_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,28 +121,20 @@ func (c *conn) Send(m Message) error {

// Receive receives one or more Messages from netlink.
func (c *conn) Receive() ([]Message, error) {
b := make([]byte, os.Getpagesize())
for {
// Peek at the buffer to see how many bytes are available.
//
// TODO(mdlayher): deal with OOB message data if available, such as
// when PacketInfo ConnOption is true.
n, _, _, _, err := c.s.Recvmsg(context.Background(), b, nil, unix.MSG_PEEK)
if err != nil {
return nil, err
}

// Break when we can read all messages
if n < len(b) {
break
}

// Double in size if not enough bytes
b = make([]byte, len(b)*2)
b := make([]byte, unix.SizeofNlMsghdr)
// Peek at the buffer to see how many bytes are available.
//
// TODO(mdlayher): deal with OOB message data if available, such as
// when PacketInfo ConnOption is true.
n, _, _, _, err := c.s.Recvmsg(context.Background(), b, nil, unix.MSG_PEEK|unix.MSG_TRUNC)
if err != nil {
return nil, err
}
// Resize buffer to the expected size.
b = make([]byte, nlmsgAlign(n))

// Read out all available messages
n, _, _, _, err := c.s.Recvmsg(context.Background(), b, nil, 0)
n, _, _, _, err = c.s.Recvmsg(context.Background(), b, nil, 0)
if err != nil {
return nil, err
}
Expand Down

0 comments on commit 9b038ba

Please sign in to comment.