windy 0.3.1

A Windows strings library that supports AString (ANSI string) and WString (Unicode string)
Documentation
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
// Copyright takubokudori.
// This source code is licensed under the MIT or Apache-2.0 license.
use crate::{
    __lib::{
        convert::{TryFrom, TryInto},
        fmt::Write,
        ops, slice,
    },
    convert::*,
    *,
};

macro_rules! str_impl_debug {
    ($x:ident) => {
        impl fmt::Debug for $x {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_char('"')?;
                #[cfg(not(feature = "std"))]
                {
                    fmt::Debug::fmt(&self.to_bytes_with_nul(), f)?;
                }
                #[cfg(feature = "std")]
                {
                    fmt::Display::fmt(&self.to_string_lossy(), f)?;
                }
                f.write_char('"')
            }
        }
        impl fmt::Display for $x {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                #[cfg(not(feature = "std"))]
                {
                    fmt::Debug::fmt(&self.to_bytes_with_nul(), f)
                }
                #[cfg(feature = "std")]
                {
                    fmt::Display::fmt(&self.to_string_lossy(), f)
                }
            }
        }
    };
}

fn concat_slice<T: Clone>(x: &[T], y: &[T]) -> Vec<T> {
    let mut inner = Vec::with_capacity(x.len() + y.len());
    inner.extend_from_slice(x);
    inner.extend_from_slice(y);
    inner
}

/// Represents a wide string (Unicode string).
#[repr(C)]
#[derive(Clone, PartialOrd, PartialEq, Eq, Ord, Hash)]
pub struct WString {
    inner: Box<[wchar_t]>,
}

impl WString {
    #[inline]
    pub fn as_bytes_with_nul(&self) -> &[u16] { &self.inner }

    #[inline]
    pub fn as_bytes_with_nul_mut(&mut self) -> &mut [u16] { &mut self.inner }

    #[inline]
    pub fn as_bytes(&self) -> &[u16] {
        &self.as_bytes_with_nul()[..self.inner.len() - 1]
    }

    #[inline]
    pub fn as_u8_bytes_with_nul(&self) -> &[u8] {
        unsafe {
            slice::from_raw_parts(
                self.inner.as_ptr() as *const u8,
                self.inner.len() * 2,
            )
        }
    }

    #[inline]
    pub fn as_u8_bytes(&self) -> &[u8] {
        &self.as_u8_bytes_with_nul()[..self.inner.len() - 2]
    }

    /// Returns &[`WStr`].
    #[inline]
    pub fn as_c_str(&self) -> &WStr { self }

    /// Returns &mut [`WStr`].
    #[inline]
    pub fn as_mut_c_str(&mut self) -> &mut WStr {
        unsafe {
            WStr::from_bytes_with_nul_unchecked_mut(
                self.as_bytes_with_nul_mut(),
            )
        }
    }

    /// Returns the length of bytes.
    #[inline]
    pub fn len(&self) -> usize { self.to_u8_bytes_with_nul().len() }

    /// Returns `true` if the length of bytes is 0.
    #[inline]
    pub fn is_empty(&self) -> bool { self.len() == 0 }

    /// Creates [`WString`] from [`Vec`]<u16> without any encoding checks.
    ///
    /// # Safety
    ///
    /// `v` must be a correct Unicode string.
    pub unsafe fn new_unchecked<T: Into<Vec<u16>>>(v: T) -> Self {
        unsafe { Self::_new(v.into()) }
    }

    /// Creates [`WString`] from [`Vec`]<u8> without any encoding checks.
    ///
    /// # Safety
    ///
    /// `v` must be a correct Unicode string.
    pub unsafe fn new_c_unchecked<T: Into<Vec<u8>>>(v: T) -> Self {
        unsafe { Self::_new2(v.into()) }
    }

    #[inline]
    pub(crate) unsafe fn _new(mut v: Vec<u16>) -> Self {
        unsafe {
            let len = wcsnlen(v.as_ptr(), v.len());
            if len == v.len() {
                // append NULL.
                v.reserve_exact(1);
                v.push(0);
            }
            v.set_len(len + 1);
            Self::_new_nul_unchecked(v)
        }
    }

    #[inline]
    pub(crate) unsafe fn _new2(mut v: Vec<u8>) -> Self {
        if v.len() & 1 == 1 {
            v.push(0);
        } // Make the length even.
        let v = v.leak();
        unsafe {
            let x = Vec::from_raw_parts(
                v.as_ptr() as *mut u16,
                v.len() / 2,
                v.len() / 2,
            );
            Self::_new(x)
        }
    }

    /// Creates [`WString`] from `v` without a null-terminated check and any encoding checks.
    ///
    /// # Safety
    ///
    /// `v` must be a null-terminated Unicode string.
    pub unsafe fn new_nul_unchecked<T: Into<Vec<u16>>>(v: T) -> Self {
        unsafe {
            let v = v.into();
            Self::_new_nul_unchecked(v)
        }
    }

    #[inline]
    unsafe fn _new_nul_unchecked(v: Vec<u16>) -> Self {
        Self {
            inner: v.into_boxed_slice(),
        }
    }

    /// Converts `&str` to [`WString`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// use windy::WString;
    /// let s = WString::from_str("test🍣").unwrap();
    /// println!("{:?}", s);
    /// ```
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> ConvertResult<Self> {
        let wb = utf8_to_wide(s).map_err(conv_err!(@unicode))?;
        // valid UTF-8 string
        unsafe { Ok(Self::_new(wb)) }
    }

    /// Converts `&str` to [`WString`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// use windy::WString;
    /// let s = WString::from_str_lossy("test🍣");
    /// println!("{:?}", s);
    /// ```
    pub fn from_str_lossy(s: &str) -> Self {
        let wb = utf8_to_wide_lossy(s).unwrap();
        // valid UTF-8 string
        unsafe { Self::_new(wb) }
    }

    /// Creates [`WString`] from `ptr`.
    ///
    /// # Safety
    ///
    /// `ptr` must be a null-terminated Unicode string.
    pub unsafe fn clone_from_raw(ptr: *const wchar_t) -> Self {
        unsafe { Self::clone_from_raw_s_unchecked(ptr, wcslen(ptr)) }
    }

    /// Creates [`WString`] from `ptr` and `len`.
    ///
    /// # Safety
    /// `ptr` must be a null-terminated Unicode string.
    pub unsafe fn clone_from_raw_s(
        ptr: *const wchar_t,
        mut len: usize,
    ) -> Self {
        unsafe {
            let len2 = wcsnlen(ptr, len);
            if len2 < len {
                len = len2;
            }
            Self::clone_from_raw_s_unchecked(ptr, len)
        }
    }

    /// Creates [`WString`] from `ptr` and `len` without length check.
    ///
    /// # Safety
    ///
    /// `ptr` must be a null-terminated Unicode string.
    #[inline]
    pub unsafe fn clone_from_raw_s_unchecked(
        ptr: *const wchar_t,
        len: usize,
    ) -> Self {
        unsafe {
            let slice = slice::from_raw_parts(ptr, len + 1);
            Self {
                inner: slice.to_vec().into_boxed_slice(),
            }
        }
    }
}

impl ops::Deref for WString {
    type Target = WStr;

    fn deref(&self) -> &Self::Target {
        unsafe { WStr::from_bytes_with_nul_unchecked(self.as_bytes_with_nul()) }
    }
}

impl ops::Index<ops::RangeFull> for WString {
    type Output = WStr;

    #[inline]
    fn index(&self, _: ops::RangeFull) -> &Self::Output { self }
}

impl Drop for WString {
    fn drop(&mut self) {
        unsafe {
            *self.inner.as_mut_ptr() = 0;
        }
    }
}

impl TryInto<String> for WString {
    type Error = ConvertError;

    #[inline]
    fn try_into(self) -> Result<String, Self::Error> { self.try_to_string() }
}

impl TryFrom<&str> for WString {
    type Error = ConvertError;

    #[inline]
    fn try_from(x: &str) -> Result<Self, Self::Error> { Self::from_str(x) }
}

impl TryFrom<String> for WString {
    type Error = ConvertError;

    #[inline]
    fn try_from(x: String) -> Result<Self, Self::Error> {
        Self::try_from(x.as_str())
    }
}

impl TryFrom<&String> for WString {
    type Error = ConvertError;

    #[inline]
    fn try_from(x: &String) -> Result<Self, Self::Error> {
        Self::try_from(x.as_str())
    }
}

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

impl AsRef<[u16]> for WString {
    #[inline]
    fn as_ref(&self) -> &[u16] { self.as_bytes() }
}

impl From<&WStr> for WString {
    fn from(x: &WStr) -> Self {
        unsafe { Self::new_nul_unchecked(x.to_bytes_with_nul().to_vec()) }
    }
}

impl TryFrom<&AStr> for WString {
    type Error = ConvertError;

    #[inline]
    fn try_from(x: &AStr) -> Result<Self, Self::Error> { x.to_wstring() }
}

impl TryFrom<AString> for WString {
    type Error = ConvertError;

    #[inline]
    fn try_from(x: AString) -> Result<Self, Self::Error> {
        Self::try_from(x.as_c_str())
    }
}

impl TryFrom<&AString> for WString {
    type Error = ConvertError;

    #[inline]
    fn try_from(x: &AString) -> Result<Self, Self::Error> {
        Self::try_from(x.as_c_str())
    }
}

impl ops::Add<&WStr> for WString {
    type Output = Self;

    fn add(self, rhs: &WStr) -> Self::Output {
        let inner = concat_slice(self.as_bytes(), rhs.to_bytes_with_nul());
        unsafe { Self::new_nul_unchecked(inner) }
    }
}

/// Represents ANSI string.
#[repr(C)]
#[derive(Clone, PartialOrd, PartialEq, Eq, Ord, Hash)]
pub struct AString {
    inner: Box<[u8]>,
}

impl AString {
    /// Returns `&[u8]`.
    #[inline]
    pub fn as_bytes_with_nul(&self) -> &[u8] { &self.inner }

    /// Returns `&mut [u8]`.
    #[inline]
    unsafe fn as_bytes_with_nul_mut(&mut self) -> &mut [u8] { &mut self.inner }

    /// Returns `&[u8]`.
    #[inline]
    pub fn as_bytes(&self) -> &[u8] {
        &self.as_bytes_with_nul()[..self.inner.len() - 1]
    }

    #[inline]
    pub fn as_c_str(&self) -> &AStr { self }

    /// Returns &mut [`AStr`].
    #[inline]
    pub fn as_mut_c_str(&mut self) -> &mut AStr {
        unsafe {
            AStr::from_bytes_with_nul_unchecked_mut(
                self.as_bytes_with_nul_mut(),
            )
        }
    }

    /// Returns the length of bytes.
    #[inline]
    pub fn len(&self) -> usize { self.inner.len() }

    /// Returns `true` if the length of bytes is 0.
    #[inline]
    pub fn is_empty(&self) -> bool { self.len() == 0 }

    /// Creates [`AString`] from `v` without any encoding checks.
    ///
    /// # Safety
    ///
    /// `v` must be a correct ANSI string.
    pub unsafe fn new_unchecked<T: Into<Vec<u8>>>(v: T) -> Self {
        unsafe {
            let mut v = v.into();
            let len = strnlen(v.as_ptr(), v.len());
            if len == v.len() {
                v.reserve_exact(1);
                v.push(0);
            }
            v.set_len(len + 1);
            Self::new_nul_unchecked(v)
        }
    }

    /// Creates [`AString`] from `v` without a null-terminated check and any encoding checks.
    ///
    /// # Safety
    ///
    /// `v` must be a null-terminated ANSI string.
    #[inline]
    pub unsafe fn new_nul_unchecked<T: Into<Vec<u8>>>(v: T) -> Self {
        let v = v.into();
        Self {
            inner: v.into_boxed_slice(),
        }
    }

    /// Converts `&str` to [`AString`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// use windy::AString;
    /// let s = AString::from_str("test").unwrap();
    /// println!("{:?}", s);
    /// ```
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(x: &str) -> ConvertResult<Self> {
        // UTF-8 -> Unicode -> ANSI
        WString::try_from(x)?.to_astring()
    }

    /// Converts `&str` to [`AString`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// use windy::AString;
    /// let s = AString::from_str_lossy("test🍣");
    /// println!("{:?}", s);
    /// ```
    pub fn from_str_lossy(x: &str) -> Self {
        // UTF-8 -> Unicode -> ANSI
        WString::from_str_lossy(x).to_astring_lossy()
    }

    /// Creates [`AString`] from `ptr`.
    ///
    /// # Safety
    /// `ptr` must be a null-terminated ANSI string.
    pub unsafe fn clone_from_raw(ptr: *const u8) -> Self {
        unsafe { Self::clone_from_raw_s_unchecked(ptr, strlen(ptr)) }
    }

    /// Creates [`AString`] from `ptr` and `len`.
    ///
    /// # Safety
    ///
    /// `ptr` must be a null-terminated ANSI string.
    pub unsafe fn clone_from_raw_s(ptr: *const u8, mut len: usize) -> Self {
        unsafe {
            let len2 = strnlen(ptr, len);
            if len2 < len {
                len = len2;
            }
            Self::clone_from_raw_s_unchecked(ptr, len)
        }
    }

    /// Creates [`AString`] from `ptr` and `len` without length check.
    ///
    /// # Safety
    ///
    /// `ptr` must be a null-terminated ANSI string.
    #[inline]
    pub unsafe fn clone_from_raw_s_unchecked(
        ptr: *const u8,
        len: usize,
    ) -> Self {
        unsafe {
            let slice = slice::from_raw_parts(ptr, len + 1);
            Self {
                inner: slice.to_vec().into_boxed_slice(),
            }
        }
    }
}

impl ops::Deref for AString {
    type Target = AStr;

    fn deref(&self) -> &Self::Target {
        unsafe { AStr::from_bytes_with_nul_unchecked(self.as_bytes_with_nul()) }
    }
}

impl ops::Index<ops::RangeFull> for AString {
    type Output = AStr;

    #[inline]
    fn index(&self, _: ops::RangeFull) -> &Self::Output { self }
}

impl Drop for AString {
    fn drop(&mut self) {
        unsafe {
            *self.inner.as_mut_ptr() = 0;
        }
    }
}

impl From<&AStr> for AString {
    fn from(x: &AStr) -> Self {
        unsafe { Self::new_nul_unchecked(x.to_bytes_with_nul().to_vec()) }
    }
}

impl TryInto<String> for AString {
    type Error = ConvertError;

    #[inline]
    fn try_into(self) -> Result<String, Self::Error> { self.try_to_string() }
}

impl TryFrom<&str> for AString {
    type Error = ConvertError;

    #[inline]
    fn try_from(x: &str) -> Result<Self, Self::Error> { Self::from_str(x) }
}

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

impl AsRef<[u8]> for AString {
    #[inline]
    fn as_ref(&self) -> &[u8] { self.as_bytes() }
}

impl TryFrom<String> for AString {
    type Error = ConvertError;

    #[inline]
    fn try_from(x: String) -> Result<Self, Self::Error> {
        Self::try_from(x.as_str())
    }
}

impl TryFrom<&String> for AString {
    type Error = ConvertError;

    #[inline]
    fn try_from(x: &String) -> Result<Self, Self::Error> {
        Self::try_from(x.as_str())
    }
}

impl TryFrom<&WStr> for AString {
    type Error = ConvertError;

    #[inline]
    fn try_from(x: &WStr) -> Result<Self, Self::Error> { x.to_astring() }
}

impl TryFrom<WString> for AString {
    type Error = ConvertError;

    #[inline]
    fn try_from(x: WString) -> Result<Self, Self::Error> {
        Self::try_from(x.as_c_str())
    }
}

impl TryFrom<&WString> for AString {
    type Error = ConvertError;

    #[inline]
    fn try_from(x: &WString) -> Result<Self, Self::Error> {
        Self::try_from(x.as_c_str())
    }
}

impl ops::Add<&AStr> for AString {
    type Output = Self;

    fn add(self, rhs: &AStr) -> Self::Output {
        let inner = concat_slice(self.as_bytes(), rhs.to_bytes_with_nul());
        unsafe { Self::new_nul_unchecked(inner) }
    }
}

str_impl_debug!(WString);
str_impl_debug!(AString);