Skip to content

Commit 8003187

Browse files
authored
Merge pull request #513 from epage/u64
fix(ser): Error on too-large u64
2 parents c8e6d3d + d6964ab commit 8003187

File tree

3 files changed

+22
-1
lines changed

3 files changed

+22
-1
lines changed

crates/toml/tests/testsuite/serde.rs

+14
Original file line numberDiff line numberDiff line change
@@ -945,6 +945,20 @@ fn integer_min() {
945945
}
946946
}
947947

948+
#[test]
949+
fn integer_too_big() {
950+
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
951+
struct Foo {
952+
a_b: u64,
953+
}
954+
955+
let native = Foo { a_b: u64::MAX };
956+
let err = Table::try_from(native.clone()).unwrap_err();
957+
snapbox::assert_eq("u64 value was too large", err.to_string());
958+
let err = toml::to_string(&native).unwrap_err();
959+
snapbox::assert_eq("out-of-range value for u64 type", err.to_string());
960+
}
961+
948962
#[test]
949963
fn integer_max() {
950964
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]

crates/toml_edit/src/ser/mod.rs

+4
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ use crate::visit_mut::VisitMut;
2020
pub enum Error {
2121
/// Type could not be serialized to TOML
2222
UnsupportedType(Option<&'static str>),
23+
/// Value was out of range for the given type
24+
OutOfRange(Option<&'static str>),
2325
/// `None` could not be serialized to TOML
2426
UnsupportedNone,
2527
/// Key was not convertable to `String` for serializing to TOML
@@ -53,6 +55,8 @@ impl std::fmt::Display for Error {
5355
match self {
5456
Self::UnsupportedType(Some(t)) => write!(formatter, "unsupported {t} type"),
5557
Self::UnsupportedType(None) => write!(formatter, "unsupported rust type"),
58+
Self::OutOfRange(Some(t)) => write!(formatter, "out-of-range value for {t} type"),
59+
Self::OutOfRange(None) => write!(formatter, "out-of-range value"),
5660
Self::UnsupportedNone => "unsupported None value".fmt(formatter),
5761
Self::KeyNotString => "map key was not a string".fmt(formatter),
5862
Self::DateInvalid => "a serialized date was invalid".fmt(formatter),

crates/toml_edit/src/ser/value.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,10 @@ impl serde::ser::Serializer for ValueSerializer {
9898
}
9999

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

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

0 commit comments

Comments
 (0)