Serializes a value of type `T` into the provided byte buffer. The serialized data is appended to the end of the buffer by default. To write from a specific position, resize the buffer before calling this method. # Type Parameters `T` - The type of the value to serialize. Must implement `Serializer`. # Arguments `buf` - A mutable reference to the byte buffer to append the serialized data to. T
(
&self,
buf: &mut Vec<u8>,
record: &T,
)
| 688 | /// assert_eq!(buf.capacity(), initial_capacity); // Still no reallocation |
| 689 | /// ``` |
| 690 | pub fn serialize_to<T: Serializer>( |
| 691 | &self, |
| 692 | buf: &mut Vec<u8>, |
| 693 | record: &T, |
| 694 | ) -> Result<usize, Error> { |
| 695 | let start = buf.len(); |
| 696 | self.with_write_context(|context| { |
| 697 | // Context from thread-local would be 'static. but context hold the buffer through `writer` field, |
| 698 | // so we should make buffer live longer. |
| 699 | // After serializing, `detach_writer` will be called, the writer in context will be set to dangling pointer. |
| 700 | // So it's safe to make buf live to the end of this method. |
| 701 | let outlive_buffer = unsafe { mem::transmute::<&mut Vec<u8>, &mut Vec<u8>>(buf) }; |
| 702 | context.attach_writer(Writer::from_buffer(outlive_buffer)); |
| 703 | let result = self.serialize_with_context(record, context); |
| 704 | let written_size = context.writer.len() - start; |
| 705 | context.detach_writer(); |
| 706 | match result { |
| 707 | Ok(_) => Ok(written_size), |
| 708 | Err(err) => Err(err), |
| 709 | } |
| 710 | }) |
| 711 | } |
| 712 | |
| 713 | /// Gets the final type resolver, building it lazily on first access. |
| 714 | #[inline(always)] |