Skip to content
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

Support 128-bit integers in to_value #982

Merged
merged 2 commits into from Feb 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
34 changes: 30 additions & 4 deletions src/value/ser.rs
Expand Up @@ -5,6 +5,8 @@ use crate::value::{to_value, Value};
use alloc::borrow::ToOwned;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
#[cfg(not(feature = "arbitrary_precision"))]
use core::convert::TryFrom;
use core::fmt::Display;
use core::result;
use serde::ser::{Impossible, Serialize};
Expand Down Expand Up @@ -92,9 +94,22 @@ impl serde::Serializer for Serializer {
Ok(Value::Number(value.into()))
}

#[cfg(feature = "arbitrary_precision")]
fn serialize_i128(self, value: i128) -> Result<Value> {
Ok(Value::Number(value.into()))
#[cfg(feature = "arbitrary_precision")]
{
Ok(Value::Number(value.into()))
}

#[cfg(not(feature = "arbitrary_precision"))]
{
if let Ok(value) = u64::try_from(value) {
Ok(Value::Number(value.into()))
} else if let Ok(value) = i64::try_from(value) {
Ok(Value::Number(value.into()))
} else {
Err(Error::syntax(ErrorCode::NumberOutOfRange, 0, 0))
}
}
}

#[inline]
Expand All @@ -117,9 +132,20 @@ impl serde::Serializer for Serializer {
Ok(Value::Number(value.into()))
}

#[cfg(feature = "arbitrary_precision")]
fn serialize_u128(self, value: u128) -> Result<Value> {
Ok(Value::Number(value.into()))
#[cfg(feature = "arbitrary_precision")]
{
Ok(Value::Number(value.into()))
}

#[cfg(not(feature = "arbitrary_precision"))]
{
if let Ok(value) = u64::try_from(value) {
Ok(Value::Number(value.into()))
} else {
Err(Error::syntax(ErrorCode::NumberOutOfRange, 0, 0))
}
}
}

#[inline]
Expand Down
21 changes: 21 additions & 0 deletions tests/test.rs
Expand Up @@ -2180,6 +2180,27 @@ fn test_integer128() {
]);
}

#[test]
fn test_integer128_to_value() {
let signed = &[i128::from(i64::min_value()), i128::from(u64::max_value())];
let unsigned = &[0, u128::from(u64::max_value())];

for integer128 in signed {
let expected = integer128.to_string();
assert_eq!(to_value(integer128).unwrap().to_string(), expected);
}

for integer128 in unsigned {
let expected = integer128.to_string();
assert_eq!(to_value(integer128).unwrap().to_string(), expected);
}

if !cfg!(feature = "arbitrary_precision") {
let err = to_value(u128::from(u64::max_value()) + 1).unwrap_err();
assert_eq!(err.to_string(), "number out of range");
}
}

#[cfg(feature = "raw_value")]
#[test]
fn test_borrowed_raw_value() {
Expand Down