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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
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 _widestring_buffer: [$crate::internals::core::primitive::u16; _WIDESTRING_U16_MACRO_LEN] = [0; _WIDESTRING_U16_MACRO_LEN];
                    let mut _widestring_bytes = _WIDESTRING_U16_MACRO_UTF8.as_bytes();
                    let mut _widestring_i = 0;
                    while let $crate::internals::core::option::Option::Some((_widestring_ch, _widestring_rest)) = $crate::internals::next_code_point(_widestring_bytes) {
                        _widestring_bytes = _widestring_rest;
                        if $extra_len > 0 && _widestring_ch == 0 {
                            panic!("invalid NUL value found in string literal");
                        }
                        // https://doc.rust-lang.org/std/primitive.char.html#method.encode_utf16
                        if _widestring_ch & 0xFFFF == _widestring_ch {
                            _widestring_buffer[_widestring_i] = _widestring_ch as $crate::internals::core::primitive::u16;
                            _widestring_i += 1;
                        } else {
                            let _widestring_code = _widestring_ch - 0x1_0000;
                            _widestring_buffer[_widestring_i] = 0xD800 | ((_widestring_code >> 10) as $crate::internals::core::primitive::u16);
                            _widestring_buffer[_widestring_i + 1] = 0xDC00 | ((_widestring_code as $crate::internals::core::primitive::u16) & 0x3FF);
                            _widestring_i += 2;
                        }
                    }
                    _widestring_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 _widestring_buffer: [$crate::internals::core::primitive::u32; _WIDESTRING_U32_MACRO_LEN] = [0; _WIDESTRING_U32_MACRO_LEN];
                    let mut _widestring_bytes = _WIDESTRING_U32_MACRO_UTF8.as_bytes();
                    let mut _widestring_i = 0;
                    while let $crate::internals::core::option::Option::Some((_widestring_ch, _widestring_rest)) = $crate::internals::next_code_point(_widestring_bytes) {
                        if $extra_len > 0 && _widestring_ch == 0 {
                            panic!("invalid NUL value found in string literal");
                        }
                        _widestring_bytes = _widestring_rest;
                        _widestring_buffer[_widestring_i] = _widestring_ch;
                        _widestring_i += 1;
                    }
                    _widestring_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)
    }};
}

/// Includes a UTF-16 encoded file as a [`Utf16Str`][crate::Utf16Str].
///
/// This uses [`include_bytes`](core::include_bytes) to accomplish this.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "alloc")] {
/// use widestring::{include_utf16str, Utf16Str, Utf16String};
///
/// const STRING: &Utf16Str = include_utf16str!("example.txt");
/// assert_eq!(Utf16String::from_str("My string"), STRING);
/// # }
/// ```
#[macro_export]
macro_rules! include_utf16str {
    ($text:expr) => {{
        const _WIDESTRING_U16_INCLUDE_MACRO_U8: &[$crate::internals::core::primitive::u8] =
            $crate::internals::core::include_bytes!($text);
        const _WIDESTRING_U16_INCLUDE_MACRO_LEN: $crate::internals::core::primitive::usize = {
            let _widestring_len =
                <[$crate::internals::core::primitive::u8]>::len(_WIDESTRING_U16_INCLUDE_MACRO_U8);
            if _widestring_len % $crate::internals::core::mem::size_of::<u16>() != 0 {
                panic!("file not encoded as UTF-16")
            }
            _widestring_len / 2
        };
        const _WIDESTRING_U16_INCLUDE_MACRO_UTF16: (
            [$crate::internals::core::primitive::u16; _WIDESTRING_U16_INCLUDE_MACRO_LEN],
            bool,
            bool,
        ) = {
            let mut _widestring_buffer: [$crate::internals::core::primitive::u16;
                _WIDESTRING_U16_INCLUDE_MACRO_LEN] = [0; _WIDESTRING_U16_INCLUDE_MACRO_LEN];
            let mut _widestring_bytes = _WIDESTRING_U16_INCLUDE_MACRO_U8;
            let mut _widestring_i = 0;
            let mut _widestring_decode = $crate::internals::DecodeUtf16 {
                bom: $crate::internals::core::option::Option::None,
                eof: false,
                next: $crate::internals::core::option::Option::None,
                forward_buf: $crate::internals::core::option::Option::None,
                back_buf: $crate::internals::core::option::Option::None,
            };

            loop {
                match $crate::internals::DecodeUtf16::next_code_point(
                    _widestring_decode,
                    _widestring_bytes,
                ) {
                    Ok((_widestring_new_decode, _widestring_ch, _widestring_rest)) => {
                        _widestring_decode = _widestring_new_decode;

                        _widestring_bytes = _widestring_rest;
                        _widestring_buffer[_widestring_i] = _widestring_ch;
                        _widestring_i += 1;
                    }
                    Err(_widestring_new_decode) => {
                        _widestring_decode = _widestring_new_decode;
                        break;
                    }
                }
            }

            (
                _widestring_buffer,
                if let Some(Some(_)) = _widestring_decode.bom {
                    true
                } else {
                    false
                },
                _widestring_decode.eof,
            )
        };
        const _WIDESTRING_U16_INCLUDE_MACRO_UTF16_TRIMMED:
            &[$crate::internals::core::primitive::u16] = {
            match &_WIDESTRING_U16_INCLUDE_MACRO_UTF16 {
                (buffer, false, false) => buffer,
                ([_bom, rest @ ..], true, false) => rest,
                ([rest @ .., _eof], false, true) => rest,
                ([_bom, rest @ .., _eof], true, true) => rest,
            }
        };

        #[allow(unused_unsafe)]
        unsafe {
            $crate::Utf16Str::from_slice_unchecked(_WIDESTRING_U16_INCLUDE_MACRO_UTF16_TRIMMED)
        }
    }};
}

#[doc(hidden)]
#[allow(missing_debug_implementations)]
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,
        }
    }

    pub enum BoM {
        Little,
        Big,
    }

    pub struct DecodeUtf16 {
        pub bom: Option<Option<BoM>>,
        pub eof: bool,
        pub next: Option<u16>,
        pub forward_buf: Option<u16>,
        pub back_buf: Option<u16>,
    }

    impl DecodeUtf16 {
        pub const fn next_code_point(
            mut self,
            mut utf16: &[u8],
        ) -> Result<(Self, u16, &[u8]), Self> {
            if let [one, two] = utf16 {
                if u16::from_le_bytes([*one, *two]) == 0x0000 {
                    self.eof = true;
                }
            }

            if self.bom.is_none() {
                if let [one, two, ..] = utf16 {
                    let ch = u16::from_le_bytes([*one, *two]);
                    if ch == 0xfeff {
                        self.bom = Some(Some(BoM::Little));
                    } else if ch == 0xfffe {
                        self.bom = Some(Some(BoM::Big));
                    } else {
                        self.bom = Some(None);
                    }
                }
            }

            // Copied from `DecodeUtf16`
            if let Some(u) = self.next {
                self.next = None;
                return Ok((self, u, utf16));
            }

            let u = if let Some(u) = self.forward_buf {
                self.forward_buf = None;
                u
            } else if let [one, two, rest @ ..] = utf16 {
                utf16 = rest;
                match self.bom {
                    Some(Some(BoM::Big)) => u16::from_be_bytes([*one, *two]),
                    _ => u16::from_le_bytes([*one, *two]),
                }
            } else if let Some(u) = self.back_buf {
                self.back_buf = None;
                u
            } else {
                return Err(self);
            };

            if !crate::is_utf16_surrogate(u) {
                Ok((self, u, utf16))
            } else if crate::is_utf16_low_surrogate(u) {
                panic!("unpaired surrogate found")
            } else {
                let u2 = if let [one, two, rest @ ..] = utf16 {
                    utf16 = rest;
                    match self.bom {
                        Some(Some(BoM::Big)) => u16::from_be_bytes([*one, *two]),
                        _ => u16::from_le_bytes([*one, *two]),
                    }
                } else if let Some(u) = self.back_buf {
                    self.back_buf = None;
                    u
                } else {
                    panic!("unpaired surrogate found")
                };

                if !crate::is_utf16_low_surrogate(u2) {
                    panic!("unpaired surrogate found")
                }

                self.next = Some(u2);

                Ok((self, u, utf16))
            }
        }
    }

    // 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 UTF16STR_INCLUDE_LE_TEST: &Utf16Str = include_utf16str!("test_le.txt");
    const UTF16STR_INCLUDE_BE_TEST: &Utf16Str = include_utf16str!("test_be.txt");
    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, UTF16STR_INCLUDE_LE_TEST);
        assert_eq!(&str, UTF16STR_INCLUDE_BE_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)));
    }
}