From f1a8f2714cae7d2d533ad45cfcc111a39c6705af Mon Sep 17 00:00:00 2001 From: Nicolas Lacasse Date: Thu, 6 Apr 2023 09:19:09 -0700 Subject: [PATCH] Add marshal.MarshalAll() and marshal.TotalSize(). These util methods make it easier to work with multiple marshallable structs at once. PiperOrigin-RevId: 522353552 --- pkg/marshal/util.go | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/pkg/marshal/util.go b/pkg/marshal/util.go index c1e5475bd..959d6922e 100644 --- a/pkg/marshal/util.go +++ b/pkg/marshal/util.go @@ -21,3 +21,24 @@ func Marshal(m Marshallable) []byte { m.MarshalUnsafe(buf) return buf } + +// MarshalAll returns the serialized contents of all ms in a newly allocated +// byte slice. +func MarshalAll(ms []Marshallable) []byte { + buf := make([]byte, TotalSize(ms)) + var written int + for _, m := range ms { + m.MarshalUnsafe(buf[written:]) + written += m.SizeBytes() + } + return buf +} + +// TotalSize returns the total size of all ms. +func TotalSize(ms []Marshallable) int { + var size int + for _, m := range ms { + size += m.SizeBytes() + } + return size +}