From a328ced3d5ec946e88b52201e154c50655f05bc5 Mon Sep 17 00:00:00 2001 From: Paul Wells Date: Fri, 25 Oct 2024 05:26:48 -0700 Subject: [PATCH] clone proto slice util (#870) --- utils/guid/id.go | 23 +++++++++-------------- utils/proto.go | 8 ++++++++ 2 files changed, 17 insertions(+), 14 deletions(-) diff --git a/utils/guid/id.go b/utils/guid/id.go index 89da4e41..00dda832 100644 --- a/utils/guid/id.go +++ b/utils/guid/id.go @@ -30,10 +30,7 @@ import ( "github.com/livekit/protocol/utils/must" ) -const ( - Size = 12 - guidScratchSize = Size + 10 -) +const Size = 12 const ( RoomPrefix = "RM_" @@ -57,7 +54,7 @@ const ( var guidGeneratorPool = sync.Pool{ New: func() any { - return must.Get(newGenerator(guidScratchSize)) + return must.Get(newGenerator()) }, } @@ -96,19 +93,17 @@ func newB57Index() [256]byte { } type guidGenerator struct { - scratch []byte - rng *mrand.ChaCha8 + rng *mrand.ChaCha8 } -func newGenerator(scratchSize int) (*guidGenerator, error) { +func newGenerator() (*guidGenerator, error) { var seed [32]byte if _, err := rand.Read(seed[:]); err != nil { return nil, err } return &guidGenerator{ - scratch: make([]byte, scratchSize), - rng: mrand.NewChaCha8(seed), + rng: mrand.NewChaCha8(seed), }, nil } @@ -130,10 +125,10 @@ func (g *guidGenerator) readIDChars(b []byte) { } func (g *guidGenerator) New(prefix string) string { - s := append(g.scratch[:0], make([]byte, len(prefix)+Size)...) - copy(s, prefix) - g.readIDChars(s[len(prefix):]) - return string(s) + b := make([]byte, len(prefix)+Size) + copy(b, prefix) + g.readIDChars(b[len(prefix):]) + return unsafe.String(unsafe.SliceData(b), len(b)) } func guidPrefix[T livekit.Guid]() string { diff --git a/utils/proto.go b/utils/proto.go index 61389d00..53fb80e6 100644 --- a/utils/proto.go +++ b/utils/proto.go @@ -19,3 +19,11 @@ import "google.golang.org/protobuf/proto" func CloneProto[T proto.Message](m T) T { return proto.Clone(m).(T) } + +func CloneProtoSlice[T proto.Message](ms []T) []T { + cs := make([]T, len(ms)) + for i := range ms { + cs[i] = CloneProto(ms[i]) + } + return cs +}