Skip to content

Write i128 and u128 as smallest types they can fit into #352

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions rmp-serde/src/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -604,7 +604,12 @@ where
}

fn serialize_i128(self, v: i128) -> Result<Self::Ok, Self::Error> {
self.serialize_bytes(&v.to_be_bytes())
if let Ok(v_i64) = i64::try_from(v) {
encode::write_sint(&mut self.wr, v_i64)?;
} else {
self.serialize_bytes(&v.to_be_bytes())?;
}
Ok(())
}

fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
Expand All @@ -625,7 +630,12 @@ where
}

fn serialize_u128(self, v: u128) -> Result<Self::Ok, Self::Error> {
self.serialize_bytes(&v.to_be_bytes())
if let Ok(v_u64) = u64::try_from(v) {
encode::write_uint(&mut self.wr, v_u64)?;
} else {
self.serialize_bytes(&v.to_be_bytes())?;
}
Ok(())
}

fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
Expand Down
21 changes: 21 additions & 0 deletions rmp-serde/tests/round.rs
Original file line number Diff line number Diff line change
Expand Up @@ -666,6 +666,27 @@ fn roundtrip_some_failures() {
assert_roundtrips(Some(None::<()>));
}

#[test]
fn roundtrip_i128_and_u128() {
assert_roundtrips(i8::MIN as i128);
assert_roundtrips(i16::MIN as i128);
assert_roundtrips(i32::MIN as i128);
assert_roundtrips(i64::MIN as i128);
assert_roundtrips(i128::MIN);

assert_roundtrips(i8::MAX as i128);
assert_roundtrips(i16::MAX as i128);
assert_roundtrips(i32::MAX as i128);
assert_roundtrips(i64::MAX as i128);
assert_roundtrips(i128::MAX);

assert_roundtrips(u8::MAX as u128);
assert_roundtrips(u16::MAX as u128);
assert_roundtrips(u32::MAX as u128);
assert_roundtrips(u64::MAX as u128);
assert_roundtrips(u128::MAX);
}

#[cfg(test)]
#[track_caller]
fn assert_roundtrips<T: PartialEq + std::fmt::Debug + Serialize + for<'a> Deserialize<'a>>(val: T) {
Expand Down