[#58] object: Allow to set marshal data

Now it is possible set marshaled data to reduce memory
allocations.

Signed-off-by: Dmitrii Stepanov <d.stepanov@yadro.com>
This commit is contained in:
Dmitrii Stepanov 2023-10-06 15:05:30 +03:00
parent 309aa4ac78
commit f50872f1bc
5 changed files with 94 additions and 4 deletions

View file

@ -19,6 +19,11 @@ type (
StableMarshal([]byte) []byte
StableSize() int
}
setMarshalData interface {
SetMarshalData([]byte)
StableSize() int
}
)
func BytesMarshal(field int, buf, v []byte) int {
@ -263,6 +268,26 @@ func NestedStructureMarshal[T stableMarshaller](field int64, buf []byte, v T) in
return offset + n
}
// NestedStructureSetMarshalData calculates offset for field in parentData
// and calls SetMarshalData for nested structure.
//
// Returns marshalled data length of nested structure.
func NestedStructureSetMarshalData(field int64, parentData []byte, v setMarshalData) int {
n := v.StableSize()
if n == 0 {
return 0
}
buf := make([]byte, binary.MaxVarintLen64)
prefix := protowire.EncodeTag(protowire.Number(field), protowire.BytesType)
offset := binary.PutUvarint(buf, prefix)
offset += binary.PutUvarint(buf, uint64(n))
v.SetMarshalData(parentData[offset : offset+n])
return offset + n
}
func NestedStructureSize[T stableMarshaller](field int64, v T) (size int) {
n := v.StableSize()
if n == 0 {