Skip to content

Conversation

Mingun
Copy link
Contributor

@Mingun Mingun commented May 8, 2025

As all known, when you deserialize Cow, it will always be deserialized as Owned, which makes it difficult to implement effective deserialization when you manually want to deserialize Cow<str> or Cow<[u8]>. This PR adds two helper types, CowStrVisitor and CowBytesVisitor, which both serves as a Visitor and a DeserializeSeed and allows you to read borrowed data from, for example, MapAccess:

use serde::de::{DeserializeSeed, Deserializer, MapAccess, Visitor};
use serde::de::value::CowStrVisitor;
use std::borrow::Cow;

/// A simple XML DOM node.
struct Element<'a> {
    name: Cow<'a, str>,
    children: Vec<Node<'a>>,
}
enum Node<'a> {
    Text(Cow<'a, str>),
    Element(Element<'a>),
}

impl<'de> Visitor<'de> for Element<'de> {
    type Value = Self;

    fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.write_str("a map")
    }

    fn visit_map<A>(mut self, mut map: A) -> Result<Self::Value, A::Error>
    where
        A: MapAccess<'de>,
    {
        while let Some(key) = map.next_key_seed(CowStrVisitor)? {
            if "$text" == key {
                let text = map.next_value_seed(CowStrVisitor)?;
                self.children.push(Node::Text(text));
            } else {
                let elem = Element { name: key, children: Vec::new() };
                let elem = map.next_value_seed(elem)?;
                self.children.push(Node::Element(elem));
            }
        }
        Ok(self)
    }
}

impl<'de> DeserializeSeed<'de> for Element<'de> {
    type Value = Self;

    fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_map(self)
    }
}

Copy link
Member

@oli-obk oli-obk left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

makes sense. Please add a test for it

@Mingun
Copy link
Contributor Author

Mingun commented May 8, 2025

Doctests is not enough?

@oli-obk
Copy link
Member

oli-obk commented May 8, 2025

They just test compilation, not execution actually producing Cow::Borrowed

@Mingun
Copy link
Contributor Author

Mingun commented May 8, 2025

Ah, yes. Will be soon

BorrowedBytesDeserializer, BorrowedStrDeserializer, CowBytesVisitor, CowStrVisitor, Error,
MapDeserializer,
};
use serde::de::{Deserialize, DeserializeSeed, Deserializer, IntoDeserializer};
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DeserializeSeed is required to be in scope to be able to call it methods on Cow...Visitors

let de_bytes = BorrowedBytesDeserializer::<Error>::new(b"borrowed");

// This example shows, that without CowStrVisitor the result is different
match Cow::<str>::deserialize(de_str) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm guessing we can't use the new visitor in the Cow impl because that's generic?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, because of that.

@oli-obk
Copy link
Member

oli-obk commented May 8, 2025

@dtolnay this seems like a good addition to serde. even if it could live out of tree, it's for basic libstd types

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

Successfully merging this pull request may close these issues.

3 participants