Skip to content

Commit

Permalink
fix(ser): Error on too-large u64
Browse files Browse the repository at this point in the history
This is better than going negative

Fixes #511
  • Loading branch information
epage committed Feb 7, 2023
1 parent cd4139f commit d6964ab
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 3 deletions.
4 changes: 2 additions & 2 deletions crates/toml/tests/testsuite/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -955,8 +955,8 @@ fn integer_too_big() {
let native = Foo { a_b: u64::MAX };
let err = Table::try_from(native.clone()).unwrap_err();
snapbox::assert_eq("u64 value was too large", err.to_string());
let err = toml::to_string(&native).unwrap();
snapbox::assert_eq("a_b = -1\n", err.to_string());
let err = toml::to_string(&native).unwrap_err();
snapbox::assert_eq("out-of-range value for u64 type", err.to_string());
}

#[test]
Expand Down
4 changes: 4 additions & 0 deletions crates/toml_edit/src/ser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ use crate::visit_mut::VisitMut;
pub enum Error {
/// Type could not be serialized to TOML
UnsupportedType(Option<&'static str>),
/// Value was out of range for the given type
OutOfRange(Option<&'static str>),
/// `None` could not be serialized to TOML
UnsupportedNone,
/// Key was not convertable to `String` for serializing to TOML
Expand Down Expand Up @@ -53,6 +55,8 @@ impl std::fmt::Display for Error {
match self {
Self::UnsupportedType(Some(t)) => write!(formatter, "unsupported {t} type"),
Self::UnsupportedType(None) => write!(formatter, "unsupported rust type"),
Self::OutOfRange(Some(t)) => write!(formatter, "out-of-range value for {t} type"),
Self::OutOfRange(None) => write!(formatter, "out-of-range value"),
Self::UnsupportedNone => "unsupported None value".fmt(formatter),
Self::KeyNotString => "map key was not a string".fmt(formatter),
Self::DateInvalid => "a serialized date was invalid".fmt(formatter),
Expand Down
5 changes: 4 additions & 1 deletion crates/toml_edit/src/ser/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,10 @@ impl serde::ser::Serializer for ValueSerializer {
}

fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
self.serialize_i64(v as i64)
let v: i64 = v
.try_into()
.map_err(|_err| Error::OutOfRange(Some("u64")))?;
self.serialize_i64(v)
}

fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
Expand Down

0 comments on commit d6964ab

Please sign in to comment.