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
// Copyright takubokudori.
// This source code is licensed under the MIT or Apache-2.0 license.
use crate::{
    __lib::{cmp::Ordering, fmt::Write, slice},
    *,
};

#[cfg(feature = "std")]
use crate::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('"')
            }
        }
    };
}

/// Represents a borrowed Unicode string.
#[repr(C)]
pub struct WStr {
    inner: [wchar_t],
}

impl WStr {
    #[inline]
    pub fn as_ptr(&self) -> *const wchar_t { self.inner.as_ptr() }

    #[inline]
    pub fn as_mut_ptr(&mut self) -> *mut wchar_t { self.inner.as_mut_ptr() }

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

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

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

    pub fn to_bytes(&self) -> &[u16] {
        let bytes = self.to_bytes_with_nul();
        &bytes[..bytes.len() - 1]
    }

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

    pub fn to_u8_bytes(&self) -> &[u8] {
        let bytes = self.to_u8_bytes_with_nul();
        &bytes[..bytes.len() - 2]
    }

    #[cfg(feature = "std")]
    /// Converts [`WString`] to UTF-8 string.
    ///
    /// If an input has an invalid character, this function returns [`ConvertError::ConvertToUtf8Error`].
    pub fn try_to_string(&self) -> ConvertResult<String> {
        unsafe {
            let mut mb = wide_to_utf8(self.to_bytes_with_nul())
                .map_err(conv_err!(@utf8))?;
            mb.set_len(mb.len() - 1); // remove NULL
            // valid UTF-8 string
            Ok(String::from_utf8_unchecked(mb))
        }
    }

    #[cfg(feature = "std")]
    /// Converts [`WStr`] to UTF-8 string.
    ///
    /// The function replaces Illegal sequences with with `\u{FFFD}`.
    pub fn to_string_lossy(&self) -> String {
        unsafe {
            let mut mb = wide_to_utf8_lossy(self.to_bytes_with_nul())
                .map_err(conv_err!(@utf8))
                .unwrap();
            mb.set_len(mb.len() - 1); // remove NULL
            // valid UTF-8 string
            String::from_utf8_unchecked(mb)
        }
    }

    /// Creates [`WString`] from [`WStr`].
    #[cfg(feature = "std")]
    pub fn to_wstring(&self) -> WString {
        unsafe { WString::new_nul_unchecked(&self.inner) }
    }

    #[cfg(feature = "std")]
    /// Converts [`WStr`] to [`AString`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// use windy::{AString, WString};
    /// let s = AString::from_str("test").unwrap();
    /// let s2 = WString::from_str("test").unwrap().to_astring().unwrap();
    /// assert_eq!(s, s2);
    /// ```
    pub fn to_astring(&self) -> ConvertResult<AString> {
        let mb =
            wide_to_mb(self.to_bytes_with_nul()).map_err(conv_err!(@ansi))?;
        // valid ANSI string
        unsafe { Ok(AString::new_unchecked(mb)) }
    }

    #[cfg(feature = "std")]
    /// Converts [`WStr`] to [`AString`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// use windy::{AString, WString};
    /// let s = AString::from_str("test").unwrap();
    /// let s2 = WString::from_str("test").unwrap().to_astring_lossy();
    /// assert_eq!(s, s2);
    /// ```
    pub fn to_astring_lossy(&self) -> AString {
        let mb = wide_to_mb_lossy(self.to_bytes_with_nul()).unwrap();
        // valid ANSI string
        unsafe { AString::new_unchecked(mb) }
    }

    /// Creates a new `&WStr` from `bytes`.
    ///
    /// # Safety
    ///
    /// `bytes` must be a correct Unicode string.
    #[inline]
    pub unsafe fn from_bytes_with_nul_unchecked(bytes: &[u16]) -> &Self {
        unsafe { &*(bytes as *const [u16] as *const Self) }
    }

    /// Creates a new `&WStr` from `bytes`.
    ///
    /// # Safety
    ///
    /// `bytes` must be a correct Unicode string.
    #[inline]
    pub unsafe fn from_bytes_with_nul_unchecked_mut(
        bytes: &mut [u16],
    ) -> &mut Self {
        unsafe { &mut *(bytes as *mut [u16] as *mut Self) }
    }

    /// Creates &[`WStr`] from `ptr`.
    ///
    /// # Safety
    ///
    /// `ptr` must be a null-terminated Unicode string.
    pub unsafe fn from_raw<'a>(ptr: *const wchar_t) -> &'a Self {
        unsafe { Self::from_raw_s_unchecked(ptr, wcslen(ptr)) }
    }

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

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

impl PartialEq for WStr {
    fn eq(&self, other: &Self) -> bool { self.to_bytes().eq(other.to_bytes()) }
}

impl Eq for WStr {}

impl PartialOrd for WStr {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for WStr {
    fn cmp(&self, other: &Self) -> Ordering {
        self.to_bytes().cmp(other.to_bytes())
    }
}

/// Represents a borrowed ANSI string.
#[repr(C)]
pub struct AStr {
    inner: [u8],
}

impl AStr {
    #[inline]
    pub fn as_ptr(&self) -> *const i8 { self.inner.as_ptr() as *const i8 }

    #[inline]
    pub fn as_mut_ptr(&mut self) -> *mut i8 {
        self.inner.as_mut_ptr() as *mut i8
    }

    #[inline]
    pub fn as_u8_ptr(&self) -> *const u8 { self.inner.as_ptr() }

    #[inline]
    pub fn as_mut_u8_ptr(&mut self) -> *mut u8 { self.inner.as_mut_ptr() }

    /// 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 }

    #[inline]
    pub fn to_bytes_with_nul(&self) -> &[u8] { &self.inner }

    #[inline]
    pub fn to_bytes(&self) -> &[u8] {
        let bytes = self.to_bytes_with_nul();
        &bytes[..bytes.len() - 1]
    }

    /// Creates [`String`] from [`AStr`].
    #[cfg(feature = "std")]
    pub fn try_to_string(&self) -> ConvertResult<String> {
        // ANSI -> Unicode -> UTF-8
        self.to_wstring()?.try_to_string()
    }

    /// Creates [`String`] from [`AStr`].
    #[cfg(feature = "std")]
    pub fn to_string_lossy(&self) -> String {
        // ANSI -> Unicode -> UTF-8
        self.to_wstring_lossy().to_string_lossy()
    }

    /// Creates [`AString`] from [`AStr`].
    #[cfg(feature = "std")]
    pub fn to_astring(&self) -> AString {
        unsafe { AString::new_nul_unchecked(&self.inner) }
    }

    /// Converts [`AStr`] to [`WString`].
    ///
    /// Returns [`ConvertError::ConvertToUnicodeError`] if an input cannot be converted to a wide char.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use windy::{AString, WString};
    /// let s = WString::from_str("test").unwrap();
    /// let s2 = AString::from_str("test").unwrap().to_wstring().unwrap();
    /// assert_eq!(s, s2);
    /// ```
    #[cfg(feature = "std")]
    pub fn to_wstring(&self) -> ConvertResult<WString> {
        let wc = mb_to_wide(self.to_bytes()).map_err(conv_err!(@unicode))?;
        // valid Unicode string
        unsafe { Ok(WString::_new(wc)) }
    }

    /// Converts [`AStr`] to [`WString`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// use windy::{AString, WString};
    /// let s = WString::from_str("test").unwrap();
    /// let s2 = AString::from_str("test").unwrap().to_wstring_lossy();
    /// assert_eq!(s, s2);
    /// ```
    #[cfg(feature = "std")]
    pub fn to_wstring_lossy(&self) -> WString {
        let wc = mb_to_wide_lossy(self.to_bytes())
            .map_err(conv_err!(@unicode))
            .unwrap();
        // valid Unicode string
        unsafe { WString::_new(wc) }
    }

    /// Creates a new `&AStr` from `bytes`.
    ///
    /// # Safety
    ///
    /// `bytes` must be a correct ANSI string.
    #[inline]
    pub unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &Self {
        unsafe { &*(bytes as *const [u8] as *const Self) }
    }

    /// Creates a new `mut &AStr` from `bytes`.
    ///
    /// # Safety
    ///
    /// `bytes` must be a correct ANSI string.
    #[inline]
    pub unsafe fn from_bytes_with_nul_unchecked_mut(
        bytes: &mut [u8],
    ) -> &mut Self {
        unsafe { &mut *(bytes as *mut [u8] as *mut Self) }
    }

    /// Creates &[`AStr`] from `ptr`.
    ///
    /// # Safety
    ///
    /// `ptr` must be a null-terminated ANSI string.
    pub unsafe fn from_raw<'a>(ptr: *const u8) -> &'a Self {
        unsafe { Self::from_raw_s_unchecked(ptr, strlen(ptr)) }
    }

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

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

impl PartialEq for AStr {
    fn eq(&self, other: &Self) -> bool { self.to_bytes().eq(other.to_bytes()) }
}

impl Eq for AStr {}

impl PartialOrd for AStr {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for AStr {
    fn cmp(&self, other: &Self) -> Ordering {
        self.to_bytes().cmp(other.to_bytes())
    }
}

str_impl_debug!(WStr);
str_impl_debug!(AStr);