Skip to content

Commit

Permalink
clone proto slice util (#870)
Browse files Browse the repository at this point in the history
  • Loading branch information
paulwe authored Oct 25, 2024
1 parent caa595e commit a328ced
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 14 deletions.
23 changes: 9 additions & 14 deletions utils/guid/id.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,7 @@ import (
"github.com/livekit/protocol/utils/must"
)

const (
Size = 12
guidScratchSize = Size + 10
)
const Size = 12

const (
RoomPrefix = "RM_"
Expand All @@ -57,7 +54,7 @@ const (

var guidGeneratorPool = sync.Pool{
New: func() any {
return must.Get(newGenerator(guidScratchSize))
return must.Get(newGenerator())
},
}

Expand Down Expand Up @@ -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
}

Expand All @@ -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 {
Expand Down
8 changes: 8 additions & 0 deletions utils/proto.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

0 comments on commit a328ced

Please sign in to comment.