Merge pull request #924 from pshc/deserialize-borrowed-path

impl Deserialize for &'a Path
This commit is contained in:
David Tolnay 2017-05-10 10:14:25 -07:00 committed by GitHub
commit bafa941004
2 changed files with 44 additions and 1 deletions

View File

@ -897,6 +897,44 @@ parse_impl!(net::SocketAddrV6);
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
#[cfg(feature = "std")]
struct PathVisitor;
#[cfg(feature = "std")]
impl<'a> Visitor<'a> for PathVisitor {
type Value = &'a Path;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a borrowed path")
}
fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E>
where
E: Error,
{
Ok(v.as_ref())
}
fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E>
where
E: Error,
{
str::from_utf8(v)
.map(AsRef::as_ref)
.map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self))
}
}
#[cfg(feature = "std")]
impl<'de: 'a, 'a> Deserialize<'de> for &'a Path {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_str(PathVisitor)
}
}
#[cfg(feature = "std")] #[cfg(feature = "std")]
struct PathBufVisitor; struct PathBufVisitor;

View File

@ -13,7 +13,7 @@ extern crate serde_derive;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::net; use std::net;
use std::path::PathBuf; use std::path::{Path, PathBuf};
use std::time::Duration; use std::time::Duration;
use std::default::Default; use std::default::Default;
use std::ffi::{CString, OsString}; use std::ffi::{CString, OsString};
@ -710,6 +710,11 @@ declare_tests! {
"1.2.3.4:1234".parse::<net::SocketAddrV4>().unwrap() => &[Token::Str("1.2.3.4:1234")], "1.2.3.4:1234".parse::<net::SocketAddrV4>().unwrap() => &[Token::Str("1.2.3.4:1234")],
"[::1]:1234".parse::<net::SocketAddrV6>().unwrap() => &[Token::Str("[::1]:1234")], "[::1]:1234".parse::<net::SocketAddrV6>().unwrap() => &[Token::Str("[::1]:1234")],
} }
test_path {
Path::new("/usr/local/lib") => &[
Token::BorrowedStr("/usr/local/lib"),
],
}
test_path_buf { test_path_buf {
PathBuf::from("/usr/local/lib") => &[ PathBuf::from("/usr/local/lib") => &[
Token::String("/usr/local/lib"), Token::String("/usr/local/lib"),