Skip to content

Commit

Permalink
fix: support smallest possible CBOR integer (#19)
Browse files Browse the repository at this point in the history
The smallest possible CBOR integer value is -2^64. `u64::MAX` is (2^64) - 1.
This means that we need to test for `-(u64::MAX + 1)`.

Related to #14 and #15.
  • Loading branch information
vmx committed Sep 12, 2023
1 parent f73c450 commit 46e87e1
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 3 deletions.
4 changes: 2 additions & 2 deletions src/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -302,9 +302,9 @@ impl<'a, W: enc::Write> serde::Serializer for &'a mut Serializer<W> {

#[inline]
fn serialize_i128(self, v: i128) -> Result<Self::Ok, Self::Error> {
if !(u64::MAX as i128 >= v && -(u64::MAX as i128) <= v) {
if !(u64::MAX as i128 >= v && -(u64::MAX as i128 + 1) <= v) {
return Err(EncodeError::Msg(
"Integer must be within [-u64::MAX, u64::MAX] range".into(),
"Integer must be within [-u64::MAX-1, u64::MAX] range".into(),
));
}

Expand Down
5 changes: 4 additions & 1 deletion tests/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,11 @@ fn test_integer() {
// i128 within -u64 range
let vec = to_vec(&(-(u64::MAX as i128))).unwrap();
assert_eq!(vec, b"\x3B\xff\xff\xff\xff\xff\xff\xff\xfe");
// minimum CBOR integer value
let vec = to_vec(&(-(u64::MAX as i128 + 1))).unwrap();
assert_eq!(vec, b"\x3B\xff\xff\xff\xff\xff\xff\xff\xff");
// i128 out of -u64 range
assert!(to_vec(&(-(u64::MAX as i128) - 1)).is_err());
assert!(to_vec(&i128::MIN).is_err());
}

#[test]
Expand Down

0 comments on commit 46e87e1

Please sign in to comment.