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

Borrow data in Option<Cow<str>> and Option<Cow<[u8]>> with serde(borrow) #2072

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
276 changes: 175 additions & 101 deletions serde/src/private/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,142 +55,216 @@ where
Deserialize::deserialize(deserializer)
}

#[cfg(any(feature = "std", feature = "alloc"))]
pub fn borrow_cow_str<'de: 'a, 'a, D, R>(deserializer: D) -> Result<R, D::Error>
where
D: Deserializer<'de>,
R: From<Cow<'a, str>>,
{
struct CowStrVisitor;
struct CowStrVisitor;

impl<'a> Visitor<'a> for CowStrVisitor {
type Value = Cow<'a, str>;
#[cfg(any(feature = "std", feature = "alloc"))]
impl<'a> Visitor<'a> for CowStrVisitor {
type Value = Cow<'a, str>;

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

fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Cow::Owned(v.to_owned()))
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Cow::Owned(v.to_owned()))
}

fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Cow::Borrowed(v))
}
fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Cow::Borrowed(v))
}

fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Cow::Owned(v))
}
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Cow::Owned(v))
}

fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: Error,
{
match str::from_utf8(v) {
Ok(s) => Ok(Cow::Owned(s.to_owned())),
Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)),
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: Error,
{
match str::from_utf8(v) {
Ok(s) => Ok(Cow::Owned(s.to_owned())),
Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)),
}
}

fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E>
where
E: Error,
{
match str::from_utf8(v) {
Ok(s) => Ok(Cow::Borrowed(s)),
Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)),
}
fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E>
where
E: Error,
{
match str::from_utf8(v) {
Ok(s) => Ok(Cow::Borrowed(s)),
Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)),
}
}

fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
where
E: Error,
{
match String::from_utf8(v) {
Ok(s) => Ok(Cow::Owned(s)),
Err(e) => Err(Error::invalid_value(
Unexpected::Bytes(&e.into_bytes()),
&self,
)),
}
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
where
E: Error,
{
match String::from_utf8(v) {
Ok(s) => Ok(Cow::Owned(s)),
Err(e) => Err(Error::invalid_value(
Unexpected::Bytes(&e.into_bytes()),
&self,
)),
}
}
}

#[cfg(any(feature = "std", feature = "alloc"))]
pub fn borrow_cow_str<'de: 'a, 'a, D, R>(deserializer: D) -> Result<R, D::Error>
where
D: Deserializer<'de>,
R: From<Cow<'a, str>>,
{
deserializer.deserialize_str(CowStrVisitor).map(From::from)
}

struct OptionCowStrVisitor;

#[cfg(any(feature = "std", feature = "alloc"))]
pub fn borrow_cow_bytes<'de: 'a, 'a, D, R>(deserializer: D) -> Result<R, D::Error>
impl<'a> Visitor<'a> for OptionCowStrVisitor {
type Value = Option<Cow<'a, str>>;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a string or null")
}

fn visit_none<E>(self) -> Result<Self::Value, E>
where
E: Error,
{
Ok(None)
}

fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'a>,
{
Ok(Some(deserializer.deserialize_str(CowStrVisitor)?))
}
}

#[cfg(any(feature = "std", feature = "alloc"))]
pub fn borrow_option_cow_str<'de: 'a, 'a, D, R>(deserializer: D) -> Result<R, D::Error>
where
D: Deserializer<'de>,
R: From<Cow<'a, [u8]>>,
R: From<Option<Cow<'a, str>>>,
{
struct CowBytesVisitor;
deserializer
.deserialize_option(OptionCowStrVisitor)
.map(From::from)
}

impl<'a> Visitor<'a> for CowBytesVisitor {
type Value = Cow<'a, [u8]>;
struct CowBytesVisitor;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a byte array")
}
#[cfg(any(feature = "std", feature = "alloc"))]
impl<'a> Visitor<'a> for CowBytesVisitor {
type Value = Cow<'a, [u8]>;

fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Cow::Owned(v.as_bytes().to_vec()))
}
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a byte array")
}

fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Cow::Borrowed(v.as_bytes()))
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Cow::Owned(v.as_bytes().to_vec()))
}

fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Cow::Owned(v.into_bytes()))
}
fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Cow::Borrowed(v.as_bytes()))
}

fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Cow::Owned(v.to_vec()))
}
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Cow::Owned(v.into_bytes()))
}

fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Cow::Borrowed(v))
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Cow::Owned(v.to_vec()))
}

fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Cow::Owned(v))
}
fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Cow::Borrowed(v))
}

fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Cow::Owned(v))
}
}

#[cfg(any(feature = "std", feature = "alloc"))]
pub fn borrow_cow_bytes<'de: 'a, 'a, D, R>(deserializer: D) -> Result<R, D::Error>
where
D: Deserializer<'de>,
R: From<Cow<'a, [u8]>>,
{
deserializer
.deserialize_bytes(CowBytesVisitor)
.map(From::from)
}

struct OptionCowBytesVisitor;

#[cfg(any(feature = "std", feature = "alloc"))]
impl<'a> Visitor<'a> for OptionCowBytesVisitor {
type Value = Option<Cow<'a, [u8]>>;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a byte array or null")
}

fn visit_none<E>(self) -> Result<Self::Value, E>
where
E: Error,
{
Ok(None)
}

fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'a>,
{
Ok(Some(deserializer.deserialize_str(CowBytesVisitor)?))
}
}

#[cfg(any(feature = "std", feature = "alloc"))]
pub fn borrow_option_cow_bytes<'de: 'a, 'a, D, R>(deserializer: D) -> Result<R, D::Error>
where
D: Deserializer<'de>,
R: From<Option<Cow<'a, [u8]>>>,
{
deserializer
.deserialize_option(OptionCowBytesVisitor)
.map(From::from)
}

#[cfg(any(feature = "std", feature = "alloc"))]
mod content {
// This module is private and nothing here should be used outside of
Expand Down
31 changes: 12 additions & 19 deletions serde_derive/src/internals/attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1367,24 +1367,18 @@ impl Field {
//
// impl<'de: 'a, 'a> Deserialize<'de> for Cow<'a, str>
// impl<'de: 'a, 'a> Deserialize<'de> for Cow<'a, [u8]>
if is_cow(&field.ty, is_str) {
let mut path = syn::Path {
leading_colon: None,
segments: Punctuated::new(),
};
let span = Span::call_site();
path.segments.push(Ident::new("_serde", span).into());
path.segments.push(Ident::new("__private", span).into());
path.segments.push(Ident::new("de", span).into());
path.segments
.push(Ident::new("borrow_cow_str", span).into());
let expr = syn::ExprPath {
attrs: Vec::new(),
qself: None,
path,
};
deserialize_with.set_if_none(expr);
let de_fn_name = if is_cow(&field.ty, is_str) {
Some("borrow_cow_str")
} else if is_cow(&field.ty, is_slice_u8) {
Some("borrow_cow_bytes")
} else if is_option(&field.ty, |v| is_cow(v, is_str)) {
Some("borrow_option_cow_str")
} else if is_option(&field.ty, |v| is_cow(v, is_slice_u8)) {
Some("borrow_option_cow_bytes")
} else {
None
};
if let Some(de_fn_name) = de_fn_name {
let mut path = syn::Path {
leading_colon: None,
segments: Punctuated::new(),
Expand All @@ -1393,8 +1387,7 @@ impl Field {
path.segments.push(Ident::new("_serde", span).into());
path.segments.push(Ident::new("__private", span).into());
path.segments.push(Ident::new("de", span).into());
path.segments
.push(Ident::new("borrow_cow_bytes", span).into());
path.segments.push(Ident::new(de_fn_name, span).into());
let expr = syn::ExprPath {
attrs: Vec::new(),
qself: None,
Expand Down
Loading