Avoid allocations during serialization

- count number of bytes before writing nested structs