1pub use common_strings_trait::CommonStrings;
2
3pub mod common_strings_trait;
4
5#[cfg(feature = "serde")]
6pub mod visitor;
7
8#[macro_export]
9macro_rules! common_strings {
10 (
11 $(#[$outer:meta])*
12 $vis:vis enum $EnumName:ident {
13 $(
14 $(#[$inner:ident $($args:tt)*])*
15 const $Name:ident = $value:literal;
16 )*
17 }
18 ) => {
19 $(#[$outer])*
20 $vis enum $EnumName {
21 $(
22 $(#[$inner $($args)*])*
23 $Name,
24 )*
25 Other(::std::string::String),
26 }
27
28 impl $crate::common_strings_trait::CommonStrings for $EnumName {
29 fn to_str(&self) -> &str {
30 match self {
31 $(
32 $EnumName::$Name => $value,
33 $EnumName::Other(v) => v.as_str(),
34 )*
35 }
36 }
37
38 fn into_string(self) -> ::std::string::String {
39 match self {
40 $EnumName::Other(v) => v,
41 _ => self.to_str().to_string()
42 }
43 }
44
45 fn into_cow(self) -> ::std::borrow::Cow<'static, str> {
46 match self {
47 $(
48 $EnumName::$Name => $value.into(),
49 )*
50 $EnumName::Other(v) => v.into(),
51 }
52 }
53
54 fn from_cow(v: ::std::borrow::Cow<'_, str>) -> Self {
55 match v.as_ref() {
56 $(
57 $value => $EnumName::$Name,
58 )*
59 _ => $EnumName::Other(v.into_owned().into()),
60 }
61 }
62 }
63
64 impl ::std::convert::AsRef<str> for $EnumName {
65 fn as_ref(&self) -> &str {
66 $crate::common_strings_trait::CommonStrings::to_str(self)
67 }
68 }
69
70 impl From<$EnumName> for ::std::string::String {
71 fn from(v: $EnumName) -> Self {
72 $crate::common_strings_trait::CommonStrings::into_string(v)
73 }
74 }
75
76 impl std::fmt::Display for $EnumName {
77 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78 f.write_str($crate::common_strings_trait::CommonStrings::to_str(self))
79 }
80 }
81
82 impl From<::std::string::String> for $EnumName {
83 fn from(v: ::std::string::String) -> Self {
84 $crate::common_strings_trait::CommonStrings::from_cow(v.into())
85 }
86 }
87
88 impl From<&str> for $EnumName {
89 fn from(v: &str) -> Self {
90 $crate::common_strings_trait::CommonStrings::from_cow(v.into())
91 }
92 }
93
94 impl From<$EnumName> for std::borrow::Cow<'_, str> {
95 fn from(v: $EnumName) -> Self {
96 $crate::common_strings_trait::CommonStrings::into_cow(v)
97 }
98 }
99
100 $crate::__impl_serde!($EnumName);
101 };
102}
103
104#[cfg(feature = "serde")]
105#[macro_export]
106macro_rules! __impl_serde {
107 ($EnumName:ident) => {
108 impl ::serde::Serialize for $EnumName {
109 fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
110 serializer.serialize_str(self.as_ref())
111 }
112 }
113
114 impl<'de> ::serde::Deserialize<'de> for $EnumName {
115 fn deserialize<D: ::serde::Deserializer<'de>>(
116 deserializer: D,
117 ) -> Result<Self, D::Error> {
118 deserializer.deserialize_any($crate::visitor::CommonStringsVisitor::new())
119 }
120 }
121 };
122}
123
124#[cfg(not(feature = "serde"))]
125#[macro_export(local_inner_macros)]
126macro_rules! __impl_serde {
127 ($EnumName:ident) => {};
128}