Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

conn: reuse memory in Receive() #213

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 21 additions & 4 deletions conn_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package netlink
import (
"context"
"os"
"sync"
"syscall"
"time"
"unsafe"
Expand All @@ -19,7 +20,8 @@ var _ Socket = &conn{}

// A conn is the Linux implementation of a netlink sockets connection.
type conn struct {
s *socket.Conn
s *socket.Conn
bufPool sync.Pool
}

// dial is the entry point for Dial. dial opens a netlink socket using
Expand Down Expand Up @@ -70,7 +72,15 @@ func newConn(s *socket.Conn, config *Config) (*conn, uint32, error) {
return nil, 0, err
}

c := &conn{s: s}
c := &conn{
s: s,
bufPool: sync.Pool{
New: func() interface{} {
b := make([]byte, 0, os.Getpagesize())
return &b
},
},
}
if config.Strict {
// The caller has requested the strict option set. Historically we have
// recommended checking for ENOPROTOOPT if the kernel does not support
Expand Down Expand Up @@ -121,7 +131,10 @@ 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())
bufPtr := c.bufPool.Get().(*[]byte)
b := (*bufPtr)[:os.Getpagesize()]
defer c.bufPool.Put(bufPtr)

for {
// Peek at the buffer to see how many bytes are available.
//
Expand All @@ -147,7 +160,11 @@ func (c *conn) Receive() ([]Message, error) {
return nil, err
}

raw, err := syscall.ParseNetlinkMessage(b[:nlmsgAlign(n)])
// ParseNetlinkMessage references in its return the provided buffer.
// Therefore, create a new buf with the expected size.
buf := make([]byte, nlmsgAlign(n))
copy(buf, b[:nlmsgAlign(n)])
raw, err := syscall.ParseNetlinkMessage(buf)
if err != nil {
return nil, err
}
Expand Down
Loading