use crate::cursor::Cursor;
pub struct FieldWriter<'a> {
writer: &'a mut String,
prefix_comma: bool,
wrote_anything: bool,
}
impl<'a> FieldWriter<'a> {
pub(crate) fn new(writer: &'a mut String, prefix_comma: bool) -> Self {
Self {
writer,
prefix_comma,
wrote_anything: false,
}
}
pub(crate) fn wrote_anything(&self) -> bool {
self.wrote_anything
}
pub fn write_field(
&mut self,
key: &str,
value: impl serde::Serialize,
) -> serde_json::Result<()> {
let rollback = self.writer.len();
if self.wrote_anything || self.prefix_comma {
self.writer.push(',');
}
if let Err(error) = serde_json::to_writer(&Cursor::new(self.writer), key) {
self.writer.truncate(rollback);
return Err(error);
}
self.writer.push(':');
if let Err(error) = serde_json::to_writer(&Cursor::new(self.writer), &value) {
self.writer.truncate(rollback);
return Err(error);
}
self.wrote_anything = true;
Ok(())
}
}