From 115fc28bbe3667b30b3919ec03e4869a33fcc1db Mon Sep 17 00:00:00 2001 From: Marten Seemann Date: Wed, 17 Feb 2021 11:39:49 +0800 Subject: [PATCH] avoid initializing a math/rand.Rand in the connIDManager math/rand.Source uses a lot of memory, as it keeps an array of 607 int64s as internal state. --- conn_id_manager.go | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/conn_id_manager.go b/conn_id_manager.go index 75a34486..35b04d33 100644 --- a/conn_id_manager.go +++ b/conn_id_manager.go @@ -1,10 +1,7 @@ package quic import ( - "crypto/rand" - "encoding/binary" "fmt" - mrand "math/rand" "github.com/lucas-clemente/quic-go/internal/protocol" "github.com/lucas-clemente/quic-go/internal/qerr" @@ -25,7 +22,7 @@ type connIDManager struct { // protocol.PacketsPerConnectionID packets. The actual value is randomized // hide the packet loss rate from on-path observers. packetsSinceLastChange uint64 - rand *mrand.Rand + rand utils.Rand packetsPerConnectionID uint64 addStatelessResetToken func(protocol.StatelessResetToken) @@ -39,15 +36,11 @@ func newConnIDManager( removeStatelessResetToken func(protocol.StatelessResetToken), queueControlFrame func(wire.Frame), ) *connIDManager { - b := make([]byte, 8) - _, _ = rand.Read(b) // ignore the error here. Nothing bad will happen if the seed is not perfectly random. - seed := int64(binary.BigEndian.Uint64(b)) return &connIDManager{ activeConnectionID: initialDestConnID, addStatelessResetToken: addStatelessResetToken, removeStatelessResetToken: removeStatelessResetToken, queueControlFrame: queueControlFrame, - rand: mrand.New(mrand.NewSource(seed)), } } @@ -155,7 +148,7 @@ func (h *connIDManager) updateConnectionID() { h.activeConnectionID = front.ConnectionID h.activeStatelessResetToken = &front.StatelessResetToken h.packetsSinceLastChange = 0 - h.packetsPerConnectionID = protocol.PacketsPerConnectionID/2 + uint64(h.rand.Int63n(protocol.PacketsPerConnectionID)) + h.packetsPerConnectionID = protocol.PacketsPerConnectionID/2 + uint64(h.rand.Int31n(protocol.PacketsPerConnectionID)) h.addStatelessResetToken(*h.activeStatelessResetToken) }