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 for Arc #43

Open
yossyX opened this issue Nov 4, 2023 · 2 comments
Open

Support for Arc #43

yossyX opened this issue Nov 4, 2023 · 2 comments

Comments

@yossyX
Copy link

yossyX commented Nov 4, 2023

serde supports Arc with the 'rc' feature. Is it possible to have support for Arc<Vec< u8>>?

@yossyX
Copy link
Author

yossyX commented Nov 5, 2023

In the meantime, the following code can be used to address this issue.

struct Data {
    #[serde(with = "arc_bytes")]
    pub val: std::sync::Arc<Vec<u8>>,
    #[serde(with = "option_arc_bytes")]
    pub val2: Option<std::sync::Arc<Vec<u8>>>,
}
mod arc_bytes {
    use serde::{Deserialize, Deserializer, Serializer};
    use serde_bytes::ByteBuf;
    use std::sync::Arc;

    pub fn serialize<S>(data: &Arc<Vec<u8>>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_bytes(data.as_slice())
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Arc<Vec<u8>>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let buf = ByteBuf::deserialize(deserializer)?;
        Ok(Arc::new(buf.into_vec()))
    }
}
mod option_arc_bytes {
    use serde::{Deserialize, Deserializer, Serializer};
    use serde_bytes::ByteBuf;
    use std::sync::Arc;

    pub fn serialize<S>(data: &Option<Arc<Vec<u8>>>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match data {
            Some(value) => serializer.serialize_bytes(value.as_slice()),
            None => serializer.serialize_none(),
        }
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Arc<Vec<u8>>>, D::Error>
    where
        D: Deserializer<'de>,
    {
        match Option::<ByteBuf>::deserialize(deserializer)? {
            Some(buf) => Ok(Some(Arc::new(buf.into_vec()))),
            None => Ok(None),
        }
    }
}

@tekacs
Copy link

tekacs commented Mar 6, 2024

Just putting in another request here for this -- have also worked around it myself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants