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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
macro_rules! implement_utf16_macro {
    ($(#[$m:meta])* $name:ident $extra_len:literal $str:ident $fn:ident) => {
        $(#[$m])*
        #[macro_export]
        macro_rules! $name {
            ($text:expr) => {{
                const _WIDESTRING_U16_MACRO_UTF8: &$crate::internals::core::primitive::str = $text;
                const _WIDESTRING_U16_MACRO_LEN: $crate::internals::core::primitive::usize =
                    $crate::internals::length_as_utf16(_WIDESTRING_U16_MACRO_UTF8) + $extra_len;
                const _WIDESTRING_U16_MACRO_UTF16: [$crate::internals::core::primitive::u16;
                        _WIDESTRING_U16_MACRO_LEN] = {
                    let mut buffer = [0u16; _WIDESTRING_U16_MACRO_LEN];
                    let mut bytes = _WIDESTRING_U16_MACRO_UTF8.as_bytes();
                    let mut i = 0;
                    while let Some((ch, rest)) = $crate::internals::next_code_point(bytes) {
                        bytes = rest;
                        // https://doc.rust-lang.org/std/primitive.char.html#method.encode_utf16
                        if ch & 0xFFFF == ch {
                            buffer[i] = ch as $crate::internals::core::primitive::u16;
                            i += 1;
                        } else {
                            let code = ch - 0x1_0000;
                            buffer[i] = 0xD800 | ((code >> 10) as $crate::internals::core::primitive::u16);
                            buffer[i + 1] = 0xDC00 | ((code as $crate::internals::core::primitive::u16) & 0x3FF);
                            i += 2;
                        }
                    }
                    buffer
                };
                #[allow(unused_unsafe)]
                unsafe { $crate::$str::$fn(&_WIDESTRING_U16_MACRO_UTF16) }
            }};
        }
    }
}

implement_utf16_macro! {
    /// Converts a string literal into a `const` UTF-16 string slice of type
    /// [`Utf16Str`][crate::Utf16Str].
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "alloc")] {
    /// use widestring::{utf16str, Utf16Str, Utf16String};
    ///
    /// const STRING: &Utf16Str = utf16str!("My string");
    /// assert_eq!(Utf16String::from_str("My string"), STRING);
    /// # }
    /// ```
    utf16str 0 Utf16Str from_slice_unchecked
}

implement_utf16_macro! {
    /// Converts a string literal into a `const` UTF-16 string slice of type
    /// [`U16Str`][crate::U16Str].
    ///
    /// The resulting `const` string slice will always be valid UTF-16.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "alloc")] {
    /// use widestring::{u16str, U16Str, U16String};
    ///
    /// const STRING: &U16Str = u16str!("My string");
    /// assert_eq!(U16String::from_str("My string"), STRING);
    /// # }
    /// ```
    u16str 0 U16Str from_slice
}

implement_utf16_macro! {
    /// Converts a string literal into a `const` UTF-16 string slice of type
    /// [`U16CStr`][crate::U16CStr].
    ///
    /// The resulting `const` string slice will always be valid UTF-16 and include a nul terminator.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "alloc")] {
    /// use widestring::{u16cstr, U16CStr, U16CString};
    ///
    /// const STRING: &U16CStr = u16cstr!("My string");
    /// assert_eq!(U16CString::from_str("My string").unwrap(), STRING);
    /// # }
    /// ```
    u16cstr 1 U16CStr from_slice_unchecked
}

macro_rules! implement_utf32_macro {
    ($(#[$m:meta])* $name:ident $extra_len:literal $str:ident $fn:ident) => {
        $(#[$m])*
        #[macro_export]
        macro_rules! $name {
            ($text:expr) => {{
                const _WIDESTRING_U32_MACRO_UTF8: &$crate::internals::core::primitive::str = $text;
                const _WIDESTRING_U32_MACRO_LEN: $crate::internals::core::primitive::usize =
                    $crate::internals::length_as_utf32(_WIDESTRING_U32_MACRO_UTF8) + $extra_len;
                const _WIDESTRING_U32_MACRO_UTF32: [$crate::internals::core::primitive::u32;
                        _WIDESTRING_U32_MACRO_LEN] = {
                    let mut buffer = [0u32; _WIDESTRING_U32_MACRO_LEN];
                    let mut bytes = _WIDESTRING_U32_MACRO_UTF8.as_bytes();
                    let mut i = 0;
                    while let Some((ch, rest)) = $crate::internals::next_code_point(bytes) {
                        bytes = rest;
                        buffer[i] = ch;
                        i += 1;
                    }
                    buffer
                };
                #[allow(unused_unsafe)]
                unsafe { $crate::$str::$fn(&_WIDESTRING_U32_MACRO_UTF32) }
            }};
        }
    }
}

implement_utf32_macro! {
    /// Converts a string literal into a `const` UTF-32 string slice of type
    /// [`Utf32Str`][crate::Utf32Str].
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "alloc")] {
    /// use widestring::{utf32str, Utf32Str, Utf32String};
    ///
    /// const STRING: &Utf32Str = utf32str!("My string");
    /// assert_eq!(Utf32String::from_str("My string"), STRING);
    /// # }
    /// ```
    utf32str 0 Utf32Str from_slice_unchecked
}

implement_utf32_macro! {
    /// Converts a string literal into a `const` UTF-32 string slice of type
    /// [`U32Str`][crate::U32Str].
    ///
    /// The resulting `const` string slice will always be valid UTF-32.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "alloc")] {
    /// use widestring::{u32str, U32Str, U32String};
    ///
    /// const STRING: &U32Str = u32str!("My string");
    /// assert_eq!(U32String::from_str("My string"), STRING);
    /// # }
    /// ```
    u32str 0 U32Str from_slice
}

implement_utf32_macro! {
    /// Converts a string literal into a `const` UTF-32 string slice of type
    /// [`U32CStr`][crate::U32CStr].
    ///
    /// The resulting `const` string slice will always be valid UTF-32 and include a nul terminator.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "alloc")] {
    /// use widestring::{u32cstr, U32CStr, U32CString};
    ///
    /// const STRING: &U32CStr = u32cstr!("My string");
    /// assert_eq!(U32CString::from_str("My string").unwrap(), STRING);
    /// # }
    /// ```
    u32cstr 1 U32CStr from_slice_unchecked
}

/// Alias for [`u16str`] or [`u32str`] macros depending on platform. Intended to be used when using
/// [`WideStr`][crate::WideStr] type alias.
#[cfg(not(windows))]
#[macro_export]
macro_rules! widestr {
    ($text:expr) => {{
        use $crate::*;
        u32str!($text)
    }};
}

/// Alias for [`utf16str`] or [`utf32str`] macros depending on platform. Intended to be used when
/// using [`WideUtfStr`][crate::WideUtfStr] type alias.
#[cfg(not(windows))]
#[macro_export]
macro_rules! wideutfstr {
    ($text:expr) => {{
        use $crate::*;
        utf32str!($text)
    }};
}

/// Alias for [`u16cstr`] or [`u32cstr`] macros depending on platform. Intended to be used when
/// using [`WideCStr`][crate::WideCStr] type alias.
#[cfg(not(windows))]
#[macro_export]
macro_rules! widecstr {
    ($text:expr) => {{
        use $crate::*;
        u32cstr!($text)
    }};
}

/// Alias for [`u16str`] or [`u32str`] macros depending on platform. Intended to be used when using
/// [`WideStr`][crate::WideStr] type alias.
#[cfg(windows)]
#[macro_export]
macro_rules! widestr {
    ($text:expr) => {{
        use $crate::*;
        u16str!($text)
    }};
}

/// Alias for [`utf16str`] or [`utf32str`] macros depending on platform. Intended to be used when
/// using [`WideUtfStr`][crate::WideUtfStr] type alias.
#[cfg(windows)]
#[macro_export]
macro_rules! wideutfstr {
    ($text:expr) => {{
        use $crate::*;
        utf16str!($text)
    }};
}

/// Alias for [`u16cstr`] or [`u32cstr`] macros depending on platform. Intended to be used when
/// using [`WideCStr`][crate::WideCStr] type alias.
#[cfg(windows)]
#[macro_export]
macro_rules! widecstr {
    ($text:expr) => {{
        use $crate::*;
        u16cstr!($text)
    }};
}

#[doc(hidden)]
pub mod internals {
    pub use core;

    // A const implementation of https://github.com/rust-lang/rust/blob/d902752866cbbdb331e3cf28ff6bba86ab0f6c62/library/core/src/str/mod.rs#L509-L537
    // Assumes `utf8` is a valid &str
    pub const fn next_code_point(utf8: &[u8]) -> Option<(u32, &[u8])> {
        const CONT_MASK: u8 = 0b0011_1111;
        match utf8 {
            [one @ 0..=0b0111_1111, rest @ ..] => Some((*one as u32, rest)),
            [one @ 0b1100_0000..=0b1101_1111, two, rest @ ..] => Some((
                (((*one & 0b0001_1111) as u32) << 6) | ((*two & CONT_MASK) as u32),
                rest,
            )),
            [one @ 0b1110_0000..=0b1110_1111, two, three, rest @ ..] => Some((
                (((*one & 0b0000_1111) as u32) << 12)
                    | (((*two & CONT_MASK) as u32) << 6)
                    | ((*three & CONT_MASK) as u32),
                rest,
            )),
            [one, two, three, four, rest @ ..] => Some((
                (((*one & 0b0000_0111) as u32) << 18)
                    | (((*two & CONT_MASK) as u32) << 12)
                    | (((*three & CONT_MASK) as u32) << 6)
                    | ((*four & CONT_MASK) as u32),
                rest,
            )),
            [..] => None,
        }
    }

    // A const implementation of `s.chars().map(|ch| ch.len_utf16()).sum()`
    pub const fn length_as_utf16(s: &str) -> usize {
        let mut bytes = s.as_bytes();
        let mut len = 0;
        while let Some((ch, rest)) = next_code_point(bytes) {
            bytes = rest;
            len += if (ch & 0xFFFF) == ch { 1 } else { 2 };
        }
        len
    }

    // A const implementation of `s.chars().len()`
    pub const fn length_as_utf32(s: &str) -> usize {
        let mut bytes = s.as_bytes();
        let mut len = 0;
        while let Some((_, rest)) = next_code_point(bytes) {
            bytes = rest;
            len += 1;
        }
        len
    }
}

#[cfg(all(test, feature = "alloc"))]
mod test {
    use crate::{
        U16CStr, U16Str, U32CStr, U32Str, Utf16Str, Utf16String, Utf32Str, Utf32String, WideCStr,
        WideStr, WideString,
    };

    const UTF16STR_TEST: &Utf16Str = utf16str!("⚧️🏳️‍⚧️➡️s");
    const U16STR_TEST: &U16Str = u16str!("⚧️🏳️‍⚧️➡️s");
    const U16CSTR_TEST: &U16CStr = u16cstr!("⚧️🏳️‍⚧️➡️s");
    const UTF32STR_TEST: &Utf32Str = utf32str!("⚧️🏳️‍⚧️➡️s");
    const U32STR_TEST: &U32Str = u32str!("⚧️🏳️‍⚧️➡️s");
    const U32CSTR_TEST: &U32CStr = u32cstr!("⚧️🏳️‍⚧️➡️s");
    const WIDESTR_TEST: &WideStr = widestr!("⚧️🏳️‍⚧️➡️s");
    const WIDECSTR_TEST: &WideCStr = widecstr!("⚧️🏳️‍⚧️➡️s");

    #[test]
    fn str_macros() {
        let str = Utf16String::from_str("⚧️🏳️‍⚧️➡️s");
        assert_eq!(&str, UTF16STR_TEST);
        assert_eq!(&str, U16STR_TEST);
        assert_eq!(&str, U16CSTR_TEST);
        assert!(matches!(U16CSTR_TEST.as_slice_with_nul().last(), Some(&0)));

        let str = Utf32String::from_str("⚧️🏳️‍⚧️➡️s");
        assert_eq!(&str, UTF32STR_TEST);
        assert_eq!(&str, U32STR_TEST);
        assert_eq!(&str, U32CSTR_TEST);
        assert!(matches!(U32CSTR_TEST.as_slice_with_nul().last(), Some(&0)));

        let str = WideString::from_str("⚧️🏳️‍⚧️➡️s");
        assert_eq!(&str, WIDESTR_TEST);
        assert_eq!(&str, WIDECSTR_TEST);
        assert!(matches!(WIDECSTR_TEST.as_slice_with_nul().last(), Some(&0)));
    }
}