Skip to content

Commit

Permalink
Writing operator switches to object mode. Trim spaces around equal op
Browse files Browse the repository at this point in the history
If someone is using the writer but doesn't know what the upcoming
container type is (array, object, mixed). There is no way to switch
without peeking. This allows the writer to always start with an array
and then if an operator is encountered (like an equals operator), the
container will be switched to object mode

And if equals is being written, there shouldn't be any spaces around it.
  • Loading branch information
nickbabcock committed Nov 20, 2023
1 parent db9ef14 commit 5b4cca2
Showing 1 changed file with 35 additions and 2 deletions.
37 changes: 35 additions & 2 deletions src/text/writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,11 @@ where
}
}

/// Write an non-equal operator
/// Write an operator. Writing an equal operator is optional whenever
/// an object is being written.
///
/// If an array was being written, the operator will switch to writing
/// an object
///
/// ```
/// use jomini::{text::Operator, TextWriterBuilder};
Expand All @@ -186,7 +190,13 @@ where
/// ```
pub fn write_operator(&mut self, data: Operator) -> Result<(), Error> {
if self.mixed_mode == MixedMode::Disabled {
write!(self.writer, " {} ", data)?;
if data == Operator::Equal {
write!(self.writer, "{}", data)?;
} else {
write!(self.writer, " {} ", data)?;
}

self.mode = DepthMode::Object;
self.state = WriteState::ObjectValue;
} else {
write!(self.writer, "{}", data)?;
Expand Down Expand Up @@ -1084,6 +1094,29 @@ mod tests {
Ok(())
}

#[test]
fn write_operator_equal() -> Result<(), Box<dyn Error>> {
let mut out: Vec<u8> = Vec::new();
let mut writer = TextWriterBuilder::new().from_writer(&mut out);
writer.write_unquoted(b"data")?;
writer.write_array_start()?;
writer.write_unquoted(b"a")?;
writer.write_operator(Operator::Equal)?;
writer.write_unquoted(b"b")?;
writer.write_end()?;
writer.write_unquoted(b"data")?;
writer.write_object_start()?;
writer.write_unquoted(b"a")?;
writer.write_operator(Operator::Equal)?;
writer.write_unquoted(b"b")?;
writer.write_end()?;
assert_eq!(
std::str::from_utf8(&out).unwrap(),
"data={\n a=b\n}\ndata={\n a=b\n}"
);
Ok(())
}

#[test]
fn write_mixed_container_1() -> Result<(), Box<dyn Error>> {
let mut out: Vec<u8> = Vec::new();
Expand Down

0 comments on commit 5b4cca2

Please sign in to comment.