1use crate::Result;
2use dsq_formats::{format::DataFormat, serialize, FormatWriteOptions, WriteOptions};
3use dsq_shared::value::Value;
4use std::io::Cursor;
5
6use super::traits::DataWriter;
7
8pub struct MemoryWriter {
10 buffer: Vec<u8>,
11 format: DataFormat,
12 format_options: FormatWriteOptions,
13}
14
15impl MemoryWriter {
16 pub fn new(format: DataFormat) -> Self {
18 Self {
19 buffer: Vec::new(),
20 format,
21 format_options: FormatWriteOptions::default(),
22 }
23 }
24
25 pub fn with_format_options(mut self, options: FormatWriteOptions) -> Self {
27 self.format_options = options;
28 self
29 }
30
31 pub fn into_inner(self) -> Vec<u8> {
33 self.buffer
34 }
35
36 pub fn as_slice(&self) -> &[u8] {
38 &self.buffer
39 }
40}
41
42impl DataWriter for MemoryWriter {
43 fn write(&mut self, value: &Value, options: &WriteOptions) -> Result<()> {
44 let cursor = Cursor::new(&mut self.buffer);
45 serialize(cursor, value, self.format, options, &self.format_options)?;
46 Ok(())
47 }
48
49 fn format(&self) -> DataFormat {
50 self.format
51 }
52}
53
54pub fn to_memory(format: DataFormat) -> MemoryWriter {
56 MemoryWriter::new(format)
57}