forked from vectordotdev/vector
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuri.rs
More file actions
70 lines (58 loc) · 1.46 KB
/
Copy pathuri.rs
File metadata and controls
70 lines (58 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use http::Uri;
use serde::{
de::{Error, Visitor},
Deserialize, Deserializer, Serialize, Serializer,
};
use std::fmt;
/// A wrapper for `http::Uri` that implements the serde traits.
#[derive(Default, Debug, Clone)]
pub struct UriSerde(Uri);
impl Serialize for UriSerde {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let uri = format!("{}", self.0);
serializer.serialize_str(&uri)
}
}
impl<'a> Deserialize<'a> for UriSerde {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'a>,
{
deserializer.deserialize_str(UriVisitor)
}
}
impl fmt::Display for UriSerde {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
struct UriVisitor;
impl<'a> Visitor<'a> for UriVisitor {
type Value = UriSerde;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "a string containing a valid HTTP Uri")
}
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where
E: Error,
{
let uri = s.parse::<Uri>().map_err(Error::custom)?;
Ok(UriSerde(uri))
}
}
impl From<UriSerde> for Uri {
fn from(t: UriSerde) -> Self {
t.0
}
}
impl From<Uri> for UriSerde {
fn from(t: Uri) -> Self {
Self(t)
}
}
impl std::ops::Deref for UriSerde {
type Target = Uri;
fn deref(&self) -> &Self::Target {
&self.0
}
}