osm_tags/
key.rs

1use std::borrow::Borrow;
2use std::fmt::Display;
3use std::ops::Deref;
4
5use kstring::KString;
6
7/// A representation for the key of an OSM tag
8///
9/// ```
10/// use osm_tags::TagKey;
11/// const example_key: TagKey = TagKey::from_static("example");
12/// assert_eq!(example_key.as_str(), "example");
13/// assert_eq!((example_key + "foo").as_str(), "example:foo");
14/// ```
15#[allow(clippy::module_name_repetitions)]
16#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
17pub struct TagKey(KString);
18
19impl Display for TagKey {
20    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21        write!(f, "{}", self.0)
22    }
23}
24
25impl TagKey {
26    #[must_use]
27    pub const fn from_static(string: &'static str) -> Self {
28        Self(KString::from_static(string))
29    }
30
31    #[must_use]
32    pub fn from_ref(string: &str) -> Self {
33        Self(KString::from_ref(string))
34    }
35
36    #[must_use]
37    pub fn from_string(string: String) -> Self {
38        Self(KString::from_string(string))
39    }
40
41    #[must_use]
42    pub fn as_str(&self) -> &str {
43        self.0.as_str()
44    }
45}
46
47impl Deref for TagKey {
48    type Target = KString;
49
50    fn deref(&self) -> &Self::Target {
51        &self.0
52    }
53}
54
55impl Borrow<str> for TagKey {
56    fn borrow(&self) -> &str {
57        self.as_str()
58    }
59}
60
61impl From<String> for TagKey {
62    fn from(string: String) -> Self {
63        Self(KString::from_string(string))
64    }
65}
66
67impl From<&String> for TagKey {
68    fn from(string: &String) -> Self {
69        Self(KString::from_ref(string))
70    }
71}
72
73impl From<&'static str> for TagKey {
74    fn from(string: &'static str) -> Self {
75        Self::from_static(string)
76    }
77}
78
79impl std::str::FromStr for TagKey {
80    type Err = std::convert::Infallible;
81    #[inline]
82    fn from_str(s: &str) -> Result<Self, Self::Err> {
83        Ok(Self(KString::from_ref(s)))
84    }
85}
86
87impl AsRef<str> for TagKey {
88    fn as_ref(&self) -> &str {
89        self.as_str()
90    }
91}
92
93impl<'any> std::ops::Add<&str> for &'any TagKey {
94    type Output = TagKey;
95    fn add(self, other: &str) -> Self::Output {
96        let mut s = self.to_string();
97        s.push(':');
98        s.push_str(other);
99        Self::Output::from_string(s)
100    }
101}
102
103impl<'any> std::ops::Add for &'any TagKey {
104    type Output = TagKey;
105    fn add(self, other: Self) -> Self::Output {
106        self.add(other.as_str())
107    }
108}
109
110// To satisfy the `+` API
111
112impl std::ops::Add<&str> for TagKey {
113    type Output = Self;
114    fn add(self, other: &str) -> Self::Output {
115        (&self).add(other)
116    }
117}
118
119impl std::ops::Add for TagKey {
120    type Output = Self;
121    fn add(self, other: Self) -> Self::Output {
122        (&self).add(&other)
123    }
124}