Skip to content

serde: seemingly working Path & PathBuf #899

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

Closed
wants to merge 1 commit 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
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ once_cell = { version = "1.3.1", optional = true }
pin-project-lite = { version = "0.1.4", optional = true }
pin-utils = { version = "0.1.0-alpha.4", optional = true }
slab = { version = "0.4.2", optional = true }
serde = { version = "1.0.117", optional = true, default-features = false }

# Devdepencency, but they are not allowed to be optional :/
surf = { version = "2.0.0", optional = true }
Expand Down
80 changes: 80 additions & 0 deletions src/path/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,15 @@ use crate::path::{Ancestors, Components, Display, Iter, PathBuf, StripPrefixErro
#[cfg(not(target_os = "unknown"))]
use crate::{fs, io};

#[cfg(feature = "serde")]
use {
std::fmt,
serde::{
ser::{ Serialize, Serializer },
de::{ Deserialize, Deserializer, Visitor, Unexpected, },
},
};

/// A slice of a path.
///
/// This struct is an async version of [`std::path::Path`].
Expand Down Expand Up @@ -1039,3 +1048,74 @@ impl AsRef<Path> for std::path::PathBuf {
p.into()
}
}

#[cfg(feature = "serde")]
struct PathVisitor;

#[cfg(feature = "serde")]
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: serde::de::Error,
{
Ok(v.as_ref())
}

fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
std::str::from_utf8(v)
.map(AsRef::as_ref)
.map_err(|_| serde::de::Error::invalid_value(Unexpected::Bytes(v), &self))
}
}

#[cfg(feature = "serde")]
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 = "serde")]
impl Serialize for Path {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self.inner.to_str() {
Some(s) => s.serialize(serializer),
None => Err(serde::ser::Error::custom("path contains invalid UTF-8 characters")),
}
}
}

macro_rules! forwarded_impl {
(
$(#[doc = $doc:tt])*
( $($id: ident),* ), $ty: ty, $func: expr
) => {
$(#[doc = $doc])*
impl<'de $(, $id : Deserialize<'de>,)*> Deserialize<'de> for $ty {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Deserialize::deserialize(deserializer).map($func)
}
}
}
}

#[cfg(feature = "serde")]
forwarded_impl!((), Box<Path>, PathBuf::into_boxed_path);
58 changes: 58 additions & 0 deletions src/path/pathbuf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@ use crate::path::Path;
use crate::prelude::*;
#[cfg(feature = "unstable")]
use crate::stream::{self, FromStream, IntoStream};
#[cfg(feature = "serde")]
use {
std::{ str, fmt },
serde::{
ser::{ Serialize, Serializer },
de::{ Deserialize, Deserializer, Visitor, Unexpected },
},
};

/// This struct is an async version of [`std::path::PathBuf`].
///
Expand Down Expand Up @@ -375,3 +383,53 @@ impl AsRef<std::path::Path> for PathBuf {
self.inner.as_ref()
}
}

#[cfg(feature = "serde")]
struct PathBufVisitor;

#[cfg(feature = "serde")]
impl<'de> Visitor<'de> for PathBufVisitor {
type Value = PathBuf;

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

fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(From::from(v))
}


fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
str::from_utf8(v)
.map(From::from)
.map_err(|_| serde::de::Error::invalid_value(Unexpected::Bytes(v), &self))
}

}

#[cfg(feature = "serde")]
impl Serialize for PathBuf {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.as_path().serialize(serializer)
}
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for PathBuf {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_string(PathBufVisitor)
}
}