1use serde::{Deserialize, Serialize};
2use std::convert::Infallible;
3use std::fmt;
4use std::str::FromStr;
5
6#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
7pub struct StringId(String);
8
9impl StringId {
10 pub fn new(id: String) -> Self {
11 Self(id)
12 }
13 pub fn as_str(&self) -> &str {
14 &self.0
15 }
16 pub fn into_string(self) -> String {
17 self.0
18 }
19}
20
21impl From<StringId> for String {
22 fn from(id: StringId) -> Self {
23 id.0
24 }
25}
26
27impl From<String> for StringId {
28 fn from(id: String) -> Self {
29 StringId(id)
30 }
31}
32
33impl<'a> From<&'a String> for StringId {
34 fn from(id: &'a String) -> Self {
35 StringId(id.to_string())
36 }
37}
38
39impl<'a> From<&'a str> for StringId {
40 fn from(id: &'a str) -> Self {
41 StringId(id.to_string())
42 }
43}
44
45impl FromStr for StringId {
46 type Err = Infallible;
47 fn from_str(s: &str) -> Result<Self, Self::Err> {
48 Ok(Self(s.to_string()))
49 }
50}
51
52impl fmt::Display for StringId {
53 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54 f.write_str(&self.0)
55 }
56}
57
58impl PartialEq<String> for StringId {
59 fn eq(&self, other: &String) -> bool {
60 &self.0 == other
61 }
62}
63impl PartialEq<str> for StringId {
64 fn eq(&self, other: &str) -> bool {
65 self.0 == other
66 }
67}
68impl PartialEq<&str> for StringId {
69 fn eq(&self, other: &&str) -> bool {
70 self.0 == *other
71 }
72}
73
74impl Serialize for StringId {
75 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
76 where
77 S: serde::Serializer,
78 {
79 serializer.serialize_str(&self.to_string())
80 }
81}
82
83impl<'de> Deserialize<'de> for StringId {
84 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
85 where
86 D: serde::Deserializer<'de>,
87 {
88 Ok(StringId(String::deserialize(deserializer)?))
89 }
90}
91
92pub trait IntoStringId: fmt::Display {
93 fn into_id(self) -> StringId;
94}
95
96impl IntoStringId for StringId {
97 fn into_id(self) -> StringId {
98 self
99 }
100}
101
102impl IntoStringId for String {
103 fn into_id(self) -> StringId {
104 StringId(self)
105 }
106}
107
108impl<'a> IntoStringId for &'a String {
109 fn into_id(self) -> StringId {
110 StringId(self.to_string())
111 }
112}
113
114impl<'a> IntoStringId for &'a str {
115 fn into_id(self) -> StringId {
116 StringId(self.to_string())
117 }
118}