lsp_types/
uri.rs

1use std::{hash::Hash, ops::Deref, str::FromStr};
2
3use serde::{de::Error, Deserialize, Serialize};
4
5/// Newtype struct around `fluent_uri::Uri<String>` with serialization implementations that use `as_str()` and 'from_str()' respectively.
6#[derive(Debug, Clone)]
7pub struct Uri(fluent_uri::Uri<String>);
8
9impl Serialize for Uri {
10    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
11    where
12        S: serde::Serializer,
13    {
14        self.as_str().serialize(serializer)
15    }
16}
17
18impl<'de> Deserialize<'de> for Uri {
19    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
20    where
21        D: serde::Deserializer<'de>,
22    {
23        let string = String::deserialize(deserializer)?;
24        fluent_uri::Uri::<String>::parse_from(string)
25            .map(Uri)
26            .map_err(|(_, error)| Error::custom(error.to_string()))
27    }
28}
29
30impl Ord for Uri {
31    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
32        self.as_str().cmp(other.as_str())
33    }
34}
35
36impl PartialOrd for Uri {
37    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
38        Some(self.cmp(other))
39    }
40}
41
42impl FromStr for Uri {
43    type Err = fluent_uri::ParseError;
44
45    fn from_str(s: &str) -> Result<Self, Self::Err> {
46        // TOUCH-UP:
47        // Use upstream `FromStr` implementation if and when
48        // https://github.com/yescallop/fluent-uri-rs/pull/10
49        // gets merged.
50        // fluent_uri::Uri::from_str(s).map(Self)
51        fluent_uri::Uri::parse(s).map(|uri| Self(uri.to_owned()))
52    }
53}
54
55impl Deref for Uri {
56    type Target = fluent_uri::Uri<String>;
57
58    fn deref(&self) -> &Self::Target {
59        &self.0
60    }
61}
62
63/*
64    TOUCH-UP: `PartialEq`, `Eq` and `Hash` could all be derived
65    if and when the respective implementations get merged upstream:
66    https://github.com/yescallop/fluent-uri-rs/pull/9
67*/
68impl PartialEq for Uri {
69    fn eq(&self, other: &Self) -> bool {
70        self.as_str() == other.as_str()
71    }
72}
73
74impl Eq for Uri {}
75
76impl Hash for Uri {
77    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
78        self.as_str().hash(state)
79    }
80}