Skip to content

Commit

Permalink
conn.go: Create packets channel of pointers instead of slices. This b…
Browse files Browse the repository at this point in the history
…rings down memory usage.
  • Loading branch information
Sandertv committed Apr 25, 2024
1 parent 71399ab commit e66f856
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 9 deletions.
12 changes: 6 additions & 6 deletions conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ type Conn struct {
packetQueue *packetQueue
// packets is a channel containing content of packets that were fully
// processed. Calling Conn.Read() consumes a value from this channel.
packets chan []byte
packets chan *[]byte

// retransmission is a queue filled with packets that were sent with a given
// datagram sequence number.
Expand All @@ -105,7 +105,7 @@ func newConn(conn net.PacketConn, raddr net.Addr, mtu uint16, h connectionHandle
pk: new(packet),
closed: make(chan struct{}),
connected: make(chan struct{}),
packets: make(chan []byte, 512),
packets: make(chan *[]byte, 512),
splits: make(map[uint16][][]byte),
win: newDatagramWindow(),
packetQueue: newPacketQueue(),
Expand Down Expand Up @@ -284,10 +284,10 @@ func (conn *Conn) write(b []byte) (n int, err error) {
func (conn *Conn) Read(b []byte) (n int, err error) {
select {
case pk := <-conn.packets:
if len(b) < len(pk) {
if len(b) < len(*pk) {
err = conn.error(errBufferTooSmall, "read")
}
return copy(b, pk), err
return copy(b, *pk), err
case <-conn.closed:
return 0, conn.error(net.ErrClosed, "read")
case <-conn.readDeadline:
Expand All @@ -301,7 +301,7 @@ func (conn *Conn) Read(b []byte) (n int, err error) {
func (conn *Conn) ReadPacket() (b []byte, err error) {
select {
case pk := <-conn.packets:
return pk, err
return *pk, err
case <-conn.closed:
return nil, conn.error(net.ErrClosed, "read")
case <-conn.readDeadline:
Expand Down Expand Up @@ -507,7 +507,7 @@ func (conn *Conn) handlePacket(b []byte) error {
// try to escape if the connection was closed.
select {
case <-conn.closed:
case conn.packets <- b:
case conn.packets <- &b:
}
}
return nil
Expand Down
6 changes: 3 additions & 3 deletions listener.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,12 +81,12 @@ func (l ListenConfig) Listen(address string) (*Listener, error) {
conn: conn,
incoming: make(chan *Conn),
closed: make(chan struct{}),
log: slog.Default(),
log: l.ErrorLog,
id: atomic.AddInt64(&listenerID, 1),
}
listener.h = &listenerConnectionHandler{l: listener}
if l.ErrorLog != nil {
listener.log = l.ErrorLog
if l.ErrorLog == nil {
listener.log = slog.Default()
}

go listener.listen()
Expand Down

0 comments on commit e66f856

Please sign in to comment.