1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
//! # aliri_macros
//!
//! Macros used by the `aliri` family of crates.

#![warn(
    missing_docs,
    unused_import_braces,
    unused_imports,
    unused_qualifications
)]
#![deny(
    missing_debug_implementations,
    missing_copy_implementations,
    trivial_casts,
    trivial_numeric_casts,
    unsafe_code,
    unused_must_use
)]

/// Constructs a strongly-typed wrapper around strings
///
/// This macro exports a line of unsafe code to manage the reinterpretation
/// of `&str` as the new reference type.
#[macro_export]
macro_rules! typed_string {
    {
        $(#[$meta:meta])*
        $v:vis struct $ty:ident (String);

        $(#[$meta_ref:meta])*
        $v_ref:vis struct $ty_ref:ident (str);
    } => {
        #[derive(Debug, Clone, Eq, PartialEq, Hash)]
        #[repr(transparent)]
        $(#[$meta])*
        $v struct $ty(String);

        impl $ty {
            /// Strongly types the given `String`.
            #[inline]
            pub fn new<T: Into<String>>(raw: T) -> Self {
                Self(raw.into())
            }

            /// Unwraps the underlying value.
            #[inline]
            pub fn into_inner(self) -> String {
                self.0
            }

            /// Provides access to the underlying value as a string slice.
            #[inline]
            pub fn as_str(&self) -> &str {
                self.0.as_str()
            }
        }

        impl From<String> for $ty {
            #[inline]
            fn from(kid: String) -> Self {
                Self::new(kid)
            }
        }

        impl From<&'_ str> for $ty {
            #[inline]
            fn from(kid: &str) -> Self {
                Self::new(String::from(kid))
            }
        }

        impl From<&'_ $ty_ref> for $ty {
            #[inline]
            fn from(kid: &$ty_ref) -> Self {
                $ty::from(kid.as_str())
            }
        }

        impl From<$ty> for String {
            #[inline]
            fn from(wrapper: $ty) -> Self {
                wrapper.0
            }
        }

        impl ::std::borrow::Borrow<$ty_ref> for $ty {
            #[inline]
            fn borrow(&self) -> &$ty_ref {
                &self
            }
        }

        impl ::std::ops::Deref for $ty {
            type Target = $ty_ref;

            #[inline]
            fn deref(&self) -> &Self::Target {
                $ty_ref::from_str(self.0.as_str())
            }
        }

        impl AsRef<$ty_ref> for $ty {
            #[inline]
            fn as_ref(&self) -> &$ty_ref {
                &self
            }
        }

        impl<'a> ::std::fmt::Display for $ty {
            #[inline]
            fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                f.write_str(self.as_str())
            }
        }

        impl ::serde::Serialize for $ty {
            fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                <String as ::serde::Serialize>::serialize(&self.0, serializer)
            }
        }

        impl<'de> ::serde::Deserialize<'de> for $ty {
            fn deserialize<D: ::serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
                let raw = <String as ::serde::Deserialize<'de>>::deserialize(deserializer)?;
                Ok(Self::new(raw))
            }
        }

        #[derive(Debug, Hash, PartialEq, Eq)]
        #[repr(transparent)]
        $(#[$meta_ref])*
        $v_ref struct $ty_ref(str);

        impl $ty_ref {
            #[allow(unsafe_code)]
            #[inline]
            /// Transparently reinterprets the string slice as a strongly-typed
            /// value.
            pub fn from_str(raw: &str) -> &Self {
                let ptr: *const str = raw;
                // `$ty_ref` is a transparent wrapper around an `str`, so this
                // transformation is safe to do.
                unsafe {
                    &*(ptr as *const Self)
                }
            }

            /// Provides access to the underlying value as a string slice.
            #[inline]
            pub const fn as_str(&self) -> &str {
                &self.0
            }
        }

        impl ToOwned for $ty_ref {
            type Owned = $ty;

            #[inline]
            fn to_owned(&self) -> Self::Owned {
                $ty(self.0.to_owned())
            }
        }

        impl AsRef<$ty_ref> for $ty_ref {
            #[inline]
            fn as_ref(&self) -> &$ty_ref {
                self
            }
        }

        impl PartialEq<$ty_ref> for $ty {
            #[inline]
            fn eq(&self, other: &$ty_ref) -> bool {
                self.0 == &other.0
            }
        }

        impl PartialEq<$ty> for $ty_ref {
            #[inline]
            fn eq(&self, other: &$ty) -> bool {
                &self.0 == other.0
            }
        }

        impl<'a> ::std::fmt::Display for &'a $ty_ref {
            #[inline]
            fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                f.write_str(&self.0)
            }
        }

        impl<'de: 'a, 'a> ::serde::Deserialize<'de> for &'a $ty_ref {
            fn deserialize<D: ::serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
                let raw = <&str as ::serde::Deserialize<'de>>::deserialize(deserializer)?;
                Ok($ty_ref::from_str(raw))
            }
        }

        impl<'a> ::serde::Serialize for &'a $ty_ref {
            fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                <&str as ::serde::Serialize>::serialize(&self.as_str(), serializer)
            }
        }
    }
}

#[cfg(doctest)]
#[doc(hidden)]
mod doctest {
    typed_string! {
        #[doc(hidden)]
        pub struct Example(String);

        #[doc(hidden)]
        pub struct ExampleRef(str);
    }

    /// Verifies that `from_str` does not extend lifetimes
    ///
    /// ```compile_fail
    /// use aliri_macros::doctest::ExampleRef;
    ///
    /// let ex_ref = {
    ///     let data = String::from("test string");
    ///     ExampleRef::from_str(data.as_str())
    /// };
    ///
    /// println!("{}", ex_ref);
    /// ```
    fn ref_from_str_does_not_extend_lifetimes() -> ! {
        loop {}
    }
}