Add marshal.MarshalAll() and marshal.TotalSize().

These util methods make it easier to work with multiple marshallable structs at
once.

PiperOrigin-RevId: 522353552
This commit is contained in:
Nicolas Lacasse
2023-04-06 09:21:56 -07:00
committed by gVisor bot
parent 59329f20b5
commit f1a8f2714c
+21
View File
@@ -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
}