Skip to content

Commit

Permalink
Implement Ser+De for Saturating<T>
Browse files Browse the repository at this point in the history
This implementation is heavily inspired by the existing trait
implentation for `std::num::Wrapping<T>`.

fix serde-rs#2708
  • Loading branch information
Jörn Bethune committed Mar 27, 2024
1 parent 74d0670 commit 0f1d753
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 0 deletions.
6 changes: 6 additions & 0 deletions serde/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,12 @@ fn main() {
if minor < 64 {
println!("cargo:rustc-cfg=no_core_cstr");
}

// Support for core::num::Saturating and std::num::Saturating stabilized in Rust 1.74
// https://blog.rust-lang.org/2023/11/16/Rust-1.74.0.html#stabilized-apis
if minor < 74 {
println!("cargo:rustc-cfg=no_core_num_saturating");
}
}

fn rustc_minor_version() -> Option<u32> {
Expand Down
13 changes: 13 additions & 0 deletions serde/src/de/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3004,6 +3004,19 @@ where
}
}

#[cfg(not(no_core_num_saturating))]
impl<'de, T> Deserialize<'de> for Saturating<T>
where
T: Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Deserialize::deserialize(deserializer).map(Saturating)
}
}

#[cfg(all(feature = "std", not(no_std_atomic)))]
macro_rules! atomic_impl {
($($ty:ident $size:expr)*) => {
Expand Down
3 changes: 3 additions & 0 deletions serde/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,9 @@ mod lib {
pub use std::sync::atomic::{AtomicI64, AtomicU64};
#[cfg(all(feature = "std", not(no_target_has_atomic), target_has_atomic = "ptr"))]
pub use std::sync::atomic::{AtomicIsize, AtomicUsize};

#[cfg(not(no_core_num_saturating))]
pub use self::core::num::Saturating;
}

// None of this crate's error handling needs the `From::from` error conversion
Expand Down
14 changes: 14 additions & 0 deletions serde/src/ser/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1026,6 +1026,20 @@ where
}
}

#[cfg(not(no_core_num_saturating))]
impl<T> Serialize for Saturating<T>
where
T: Serialize,
{
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.0.serialize(serializer)
}
}

impl<T> Serialize for Reverse<T>
where
T: Serialize,
Expand Down

0 comments on commit 0f1d753

Please sign in to comment.