]> git.proxmox.com Git - rustc.git/blob - vendor/camino/src/serde_impls.rs
New upstream version 1.58.1+dfsg1
[rustc.git] / vendor / camino / src / serde_impls.rs
1 // Copyright (c) The camino Contributors
2 // SPDX-License-Identifier: MIT OR Apache-2.0
3
4 //! Serde implementations for `Utf8Path`.
5 //!
6 //! The Serde implementations for `Utf8PathBuf` are derived, but `Utf8Path` is an unsized type which
7 //! the derive impls can't handle. Implement these by hand.
8
9 use crate::Utf8Path;
10 use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
11 use std::fmt;
12
13 struct Utf8PathVisitor;
14
15 impl<'a> de::Visitor<'a> for Utf8PathVisitor {
16 type Value = &'a Utf8Path;
17
18 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
19 formatter.write_str("a borrowed path")
20 }
21
22 fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E>
23 where
24 E: de::Error,
25 {
26 Ok(v.as_ref())
27 }
28
29 fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E>
30 where
31 E: de::Error,
32 {
33 std::str::from_utf8(v)
34 .map(AsRef::as_ref)
35 .map_err(|_| de::Error::invalid_value(de::Unexpected::Bytes(v), &self))
36 }
37 }
38
39 impl<'de: 'a, 'a> Deserialize<'de> for &'a Utf8Path {
40 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
41 where
42 D: Deserializer<'de>,
43 {
44 deserializer.deserialize_str(Utf8PathVisitor)
45 }
46 }
47
48 impl Serialize for Utf8Path {
49 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
50 where
51 S: Serializer,
52 {
53 self.as_str().serialize(serializer)
54 }
55 }