Skip to content

Commit

Permalink
Fix JSON parsing of empty arrays or objects
Browse files Browse the repository at this point in the history
  • Loading branch information
zargony committed Oct 10, 2024
1 parent aa23d6b commit 6a2aa93
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
24 changes: 16 additions & 8 deletions firmware/src/json/reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,18 +76,21 @@ impl<R: BufRead> Reader<R> {
self.expect(b'{').await?;
loop {
self.trim().await?;
let key = self.read_string().await?;
let key = match self.peek().await? {
b'}' => {
self.consume();
break Ok(obj);
}
_ => self.read_string().await?,
};
self.trim().await?;
self.expect(b':').await?;
self.trim().await?;
obj.read_next(key, self).await?;
self.trim().await?;
match self.peek().await? {
b',' => self.consume(),
b'}' => {
self.consume();
break Ok(obj);
}
b'}' => (),
ch => break Err(Error::unexpected(ch)),
}
}
Expand All @@ -101,15 +104,18 @@ impl<R: BufRead> Reader<R> {
let mut vec = T::default();
self.expect(b'[').await?;
loop {
self.trim().await?;
vec.read_next(self).await?;
self.trim().await?;
match self.peek().await? {
b',' => self.consume(),
b']' => {
self.consume();
break Ok(vec);
}
_ => vec.read_next(self).await?,
}
self.trim().await?;
match self.peek().await? {
b',' => self.consume(),
b']' => (),
ch => break Err(Error::unexpected(ch)),
}
}
Expand Down Expand Up @@ -516,6 +522,7 @@ mod tests {

#[async_std::test]
async fn read_object() {
assert_read_eq!("{}", read_object, Ok(BTreeMap::<String, String>::new()));
assert_read_eq!(
r#"{"foo": "hi", "bar": 42, "baz": true}"#,
read_object,
Expand All @@ -529,6 +536,7 @@ mod tests {

#[async_std::test]
async fn read_array() {
assert_read_eq!("[]", read_array, Ok(Vec::<u32>::new()));
assert_read_eq!("[1, 2, 3, 4]", read_array, Ok(vec![1, 2, 3, 4]));
}

Expand Down
1 change: 1 addition & 0 deletions firmware/src/json/writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -461,6 +461,7 @@ mod tests {

#[async_std::test]
async fn write_array() {
assert_write_eq!(write_array, Vec::<u32>::new(), Ok("[]"));
assert_write_eq!(write_array, [1, 2, 3, 4], Ok("[1, 2, 3, 4]"));
assert_write_eq!(write_array, &[1, 2, 3, 4], Ok("[1, 2, 3, 4]"));
assert_write_eq!(write_array, vec![1, 2, 3, 4], Ok("[1, 2, 3, 4]"));
Expand Down

0 comments on commit 6a2aa93

Please sign in to comment.