Skip to content

Commit f102123

Browse files
committed
libserialize: Do not coerce to integer when decoding a float value
When an integral value is expected by the user but a fractional value is found, the current implementation uses std::num::cast() to coerce to an integer type, losing the fractional part. This behavior is not desirable because the number loses precision without notice. This commit makes it raise ExpectedError when such a situation arises. [breaking-change]
1 parent ca4f536 commit f102123

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed

src/libserialize/json.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1974,10 +1974,7 @@ macro_rules! read_primitive {
19741974
}
19751975
}
19761976
Json::F64(f) => {
1977-
match num::cast(f) {
1978-
Some(f) => Ok(f),
1979-
None => Err(ExpectedError("Number".to_string(), format!("{}", f))),
1980-
}
1977+
Err(ExpectedError("Integer".to_string(), format!("{}", f)))
19811978
}
19821979
Json::String(s) => {
19831980
// re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
@@ -2830,6 +2827,9 @@ mod tests {
28302827

28312828
let v: i64 = super::decode("9223372036854775807").unwrap();
28322829
assert_eq!(v, i64::MAX);
2830+
2831+
let res: DecodeResult<i64> = super::decode("765.25252");
2832+
assert_eq!(res, Err(ExpectedError("Integer".into_string(), "765.25252".into_string())));
28332833
}
28342834

28352835
#[test]

0 commit comments

Comments
 (0)