rust_i18n_support/
cow_str.rs

1use std::borrow::Cow;
2use std::sync::Arc;
3
4/// A wrapper for `Cow<'a, str>` that is specifically designed for use with the `t!` macro.
5///
6/// This wrapper provides additional functionality or optimizations when handling strings in the `t!` macro.
7pub struct CowStr<'a>(Cow<'a, str>);
8
9impl<'a> CowStr<'a> {
10    pub fn as_str(&self) -> &str {
11        self.0.as_ref()
12    }
13
14    pub fn into_inner(self) -> Cow<'a, str> {
15        self.0
16    }
17}
18
19macro_rules! impl_convert_from_numeric {
20    ($typ:ty) => {
21        impl<'a> From<$typ> for CowStr<'a> {
22            fn from(val: $typ) -> Self {
23                Self(Cow::from(format!("{}", val)))
24            }
25        }
26    };
27}
28
29impl_convert_from_numeric!(i8);
30impl_convert_from_numeric!(i16);
31impl_convert_from_numeric!(i32);
32impl_convert_from_numeric!(i64);
33impl_convert_from_numeric!(i128);
34impl_convert_from_numeric!(isize);
35
36impl_convert_from_numeric!(u8);
37impl_convert_from_numeric!(u16);
38impl_convert_from_numeric!(u32);
39impl_convert_from_numeric!(u64);
40impl_convert_from_numeric!(u128);
41impl_convert_from_numeric!(usize);
42
43impl<'a> From<Arc<str>> for CowStr<'a> {
44    #[inline]
45    fn from(s: Arc<str>) -> Self {
46        Self(Cow::Owned(s.to_string()))
47    }
48}
49
50impl<'a> From<Box<str>> for CowStr<'a> {
51    #[inline]
52    fn from(s: Box<str>) -> Self {
53        Self(Cow::Owned(s.to_string()))
54    }
55}
56
57impl<'a> From<&'a str> for CowStr<'a> {
58    #[inline]
59    fn from(s: &'a str) -> Self {
60        Self(Cow::Borrowed(s))
61    }
62}
63
64impl<'a> From<&&'a str> for CowStr<'a> {
65    #[inline]
66    fn from(s: &&'a str) -> Self {
67        Self(Cow::Borrowed(s))
68    }
69}
70
71impl<'a> From<Arc<&'a str>> for CowStr<'a> {
72    #[inline]
73    fn from(s: Arc<&'a str>) -> Self {
74        Self(Cow::Borrowed(*s))
75    }
76}
77
78impl<'a> From<Box<&'a str>> for CowStr<'a> {
79    #[inline]
80    fn from(s: Box<&'a str>) -> Self {
81        Self(Cow::Borrowed(*s))
82    }
83}
84
85impl<'a> From<String> for CowStr<'a> {
86    #[inline]
87    fn from(s: String) -> Self {
88        Self(Cow::from(s))
89    }
90}
91
92impl<'a> From<&'a String> for CowStr<'a> {
93    #[inline]
94    fn from(s: &'a String) -> Self {
95        Self(Cow::Borrowed(s))
96    }
97}
98
99impl<'a> From<Arc<String>> for CowStr<'a> {
100    #[inline]
101    fn from(s: Arc<String>) -> Self {
102        Self(Cow::Owned(s.to_string()))
103    }
104}
105
106impl<'a> From<Box<String>> for CowStr<'a> {
107    #[inline]
108    fn from(s: Box<String>) -> Self {
109        Self(Cow::from(*s))
110    }
111}