diff --git a/Cargo.toml b/Cargo.toml index 04b086a..ac79460 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,6 +33,7 @@ documentation = "https://docs.rs/flatty" default = ["std"] std = ["alloc", "flatty-base/std", "flatty-portable/std"] alloc = ["flatty-base/alloc"] +serde = ["flatty-portable/serde"] [dependencies] flatty-macros = { workspace = true } diff --git a/portable/Cargo.toml b/portable/Cargo.toml index 2863a69..5136175 100644 --- a/portable/Cargo.toml +++ b/portable/Cargo.toml @@ -11,7 +11,9 @@ license.workspace = true [features] default = ["std"] std = ["flatty-base/std", "num-traits/std"] +serde = ["dep:serde"] [dependencies] flatty-base.workspace = true num-traits = { version = "0.2", default-features = false } +serde = { version = "1.0", optional = true } diff --git a/portable/src/float.rs b/portable/src/float.rs index 69737d6..9240996 100644 --- a/portable/src/float.rs +++ b/portable/src/float.rs @@ -1,4 +1,4 @@ -use crate::{derive_display, NativeCast, Portable}; +use crate::{impl_traits_for_native, NativeCast, Portable}; use core::{ cmp::{Ordering, PartialOrd}, ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, RemAssign, Sub, SubAssign}, @@ -189,7 +189,7 @@ macro_rules! derive_float { } } - derive_display!($self, $native); + impl_traits_for_native!($self, $native); }; } diff --git a/portable/src/int.rs b/portable/src/int.rs index 0a2999d..2f23786 100644 --- a/portable/src/int.rs +++ b/portable/src/int.rs @@ -1,4 +1,4 @@ -use crate::{derive_display, NativeCast, Portable}; +use crate::{impl_traits_for_native, NativeCast, Portable}; use core::{ cmp::{Ord, Ordering, PartialOrd}, ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, RemAssign, Sub, SubAssign}, @@ -189,7 +189,7 @@ macro_rules! derive_int { } } - derive_display!($self, $native); + impl_traits_for_native!($self, $native); }; } diff --git a/portable/src/lib.rs b/portable/src/lib.rs index 56ab696..b9c623d 100644 --- a/portable/src/lib.rs +++ b/portable/src/lib.rs @@ -45,7 +45,7 @@ pub mod traits { pub use super::{NativeCast, Portable}; } -macro_rules! derive_display { +macro_rules! impl_traits_for_native { ($self:ty, $native:ty) => { impl core::fmt::Debug for $self { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { @@ -57,7 +57,26 @@ macro_rules! derive_display { <$native as core::fmt::Display>::fmt(&self.to_native(), f) } } + + #[cfg(feature = "serde")] + impl serde::Serialize for $self { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + <$native as serde::Serialize>::serialize(&self.to_native(), serializer) + } + } + #[cfg(feature = "serde")] + impl<'de> serde::Deserialize<'de> for $self { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + <$native as serde::Deserialize<'de>>::deserialize(deserializer).map(<$self>::from_native) + } + } }; } -pub(crate) use derive_display; +pub(crate) use impl_traits_for_native;