Skip to content

Commit

Permalink
Add SerializeAs support for Pin<&'a T> and Pin<&'a mut T>
Browse files Browse the repository at this point in the history
  • Loading branch information
jonasbb committed Apr 22, 2024
1 parent 9c2dac7 commit 04de4ce
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
11 changes: 8 additions & 3 deletions serde_with/src/ser/impls.rs
Expand Up @@ -13,6 +13,8 @@ use indexmap_2::{IndexMap as IndexMap2, IndexSet as IndexSet2};
#[cfg(feature = "alloc")]
type BoxedSlice<T> = Box<[T]>;
type Slice<T> = [T];
type Ref<'a, T> = &'a T;
type RefMut<'a, T> = &'a mut T;

pub(crate) mod macros {
// The unused_imports lint has false-positives around macros
Expand Down Expand Up @@ -86,12 +88,12 @@ pub(crate) mod macros {

#[allow(unused_macros)]
macro_rules! pinned_wrapper {
($wrapper:ident) => {
impl<T, U> SerializeAs<Pin<$wrapper<T>>> for Pin<$wrapper<U>>
($wrapper:ident $($lifetime:lifetime)?) => {
impl<$($lifetime,)? T, U> SerializeAs<Pin<$wrapper<$($lifetime,)? T>>> for Pin<$wrapper<$($lifetime,)? U>>
where
U: SerializeAs<T>,
{
fn serialize_as<S>(source: &Pin<$wrapper<T>>, serializer: S) -> Result<S::Ok, S::Error>
fn serialize_as<S>(source: &Pin<$wrapper<$($lifetime,)? T>>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
Expand Down Expand Up @@ -129,6 +131,9 @@ where
}
}

pinned_wrapper!(Ref 'a);
pinned_wrapper!(RefMut 'a);

#[cfg(feature = "alloc")]
impl<T, U> SerializeAs<Box<T>> for Box<U>
where
Expand Down
7 changes: 7 additions & 0 deletions serde_with/tests/serde_as/lib.rs
Expand Up @@ -45,6 +45,13 @@ fn test_basic_wrappers() {

is_equal(SBox(Box::new(123)), expect![[r#""123""#]]);

// Deserialization in generally is not possible, only for unpin types
#[serde_as]
#[derive(Debug, Serialize, PartialEq)]
struct SPin<'a>(#[serde_as(as = "Pin<&DisplayFromStr>")] Pin<&'a u32>);
let tmp = 123;
check_serialization(SPin(Pin::new(&tmp)), expect![[r#""123""#]]);

#[serde_as]
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct SPinBox(#[serde_as(as = "Pin<Box<DisplayFromStr>>")] Pin<Box<u32>>);
Expand Down

0 comments on commit 04de4ce

Please sign in to comment.