Skip to content

Commit

Permalink
Support deserializing bool in map keys
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed Aug 15, 2023
1 parent 283a68b commit 68a5582
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 3 deletions.
37 changes: 36 additions & 1 deletion src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2203,6 +2203,41 @@ where
deserialize_numeric_key!(deserialize_f32, deserialize_f32);
deserialize_numeric_key!(deserialize_f64);

fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
self.de.eat_char();

let peek = match tri!(self.de.next_char()) {
Some(b) => b,
None => {
return Err(self.de.peek_error(ErrorCode::EofWhileParsingValue));
}
};

let value = match peek {
b't' => {
tri!(self.de.parse_ident(b"rue\""));
visitor.visit_bool(true)
}
b'f' => {
tri!(self.de.parse_ident(b"alse\""));
visitor.visit_bool(false)
}
_ => {
self.de.scratch.clear();
let s = tri!(self.de.read.parse_str(&mut self.de.scratch));
Err(de::Error::invalid_type(Unexpected::Str(&s), &visitor))
}
};

match value {
Ok(value) => Ok(value),
Err(err) => Err(self.de.fix_position(err)),
}
}

#[inline]
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
where
Expand Down Expand Up @@ -2258,7 +2293,7 @@ where
}

forward_to_deserialize_any! {
bool char str string unit unit_struct seq tuple tuple_struct map struct
char str string unit unit_struct seq tuple tuple_struct map struct
identifier ignored_any
}
}
Expand Down
20 changes: 18 additions & 2 deletions src/value/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1183,6 +1183,22 @@ impl<'de> serde::Deserializer<'de> for MapKeyDeserializer<'de> {
deserialize_numeric_key!(deserialize_i128, do_deserialize_i128);
deserialize_numeric_key!(deserialize_u128, do_deserialize_u128);

fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Error>
where
V: Visitor<'de>,
{
if self.key == "true" {
visitor.visit_bool(true)
} else if self.key == "false" {
visitor.visit_bool(false)
} else {
Err(serde::de::Error::invalid_type(
Unexpected::Str(&self.key),
&visitor,
))
}
}

#[inline]
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error>
where
Expand Down Expand Up @@ -1219,8 +1235,8 @@ impl<'de> serde::Deserializer<'de> for MapKeyDeserializer<'de> {
}

forward_to_deserialize_any! {
bool char str string bytes byte_buf unit unit_struct seq tuple
tuple_struct map struct identifier ignored_any
char str string bytes byte_buf unit unit_struct seq tuple tuple_struct
map struct identifier ignored_any
}
}

Expand Down

0 comments on commit 68a5582

Please sign in to comment.