Skip to main content

realhydroper_utf16/
utf16str.rs

1use crate::{slice::SliceIndex, Utf16CharIndices, Utf16Chars, Utf16Str, Utf16String};
2
3impl Utf16Str {
4    /// Returns the number of UTF-16 code units representing the string.
5    #[inline]
6    pub fn len(&self) -> usize {
7        self.raw.len()
8    }
9
10    #[inline]
11    pub fn as_ptr(&self) -> *const u16 {
12        self.raw.as_ptr()
13    }
14
15    #[inline]
16    pub fn as_mut_ptr(&mut self) -> *mut u16 {
17        self.raw.as_mut_ptr()
18    }
19
20    pub unsafe fn from_utf16_unchecked(raw: &[u16]) -> &Self {
21        unsafe { &*(raw as *const [u16] as *const Self) }
22    }
23
24    pub unsafe fn from_utf16_unchecked_mut(raw: &mut [u16]) -> &mut Self {
25        unsafe { &mut *(raw as *mut [u16] as *mut Self) }
26    }
27
28    /// Iterates the UTF-16 code units.
29    pub fn code_units(&self) -> std::slice::Iter<u16> {
30        self.raw.iter()
31    }
32
33    /// Iterates the code points in the string.
34    pub fn chars(&self) -> Utf16Chars {
35        Utf16Chars {
36            slice: self,
37            index: 0,
38        }
39    }
40
41    /// Iterates the indices and their code pointss in the string.
42    pub fn char_indices(&self) -> Utf16CharIndices {
43        Utf16CharIndices {
44            slice: self,
45            index: 0,
46        }
47    }
48
49    #[inline]
50    pub fn get<I: SliceIndex<Utf16Str>>(&self, index: I) -> Option<&<I as SliceIndex<Utf16Str>>::Output> {
51        index.get(self)
52    }
53
54    #[inline]
55    pub fn get_mut<I: SliceIndex<Utf16Str>>(&mut self, index: I) -> Option<&mut <I as SliceIndex<Utf16Str>>::Output> {
56        index.get_mut(self)
57    }
58
59    #[inline]
60    pub unsafe fn get_unchecked<I: SliceIndex<Utf16Str>>(&self, index: I) -> &<I as SliceIndex<Utf16Str>>::Output {
61        unsafe { index.get_unchecked(self) }
62    }
63
64    #[inline]
65    pub unsafe fn get_unchecked_mut<I: SliceIndex<Utf16Str>>(&mut self, index: I) -> &mut <I as SliceIndex<Utf16Str>>::Output {
66        unsafe { index.get_unchecked_mut(self) }
67    }
68
69    #[inline]
70    pub fn is_empty(&self) -> bool {
71        self.raw.len() == 0
72    }
73
74    pub fn to_owned(&self) -> Utf16String {
75        Utf16String {
76            buf: self.raw.to_owned(),
77        }
78    }
79
80    pub fn to_utf8(&self) -> String {
81        let mut r = String::new();
82        for ch in self.chars() {
83            r.push(ch);
84        }
85        r
86    }
87
88    pub fn to_lowercase(&self) -> Utf16String {
89        self.to_utf8().to_lowercase().into()
90    }
91
92    pub fn to_uppercase(&self) -> Utf16String {
93        self.to_utf8().to_uppercase().into()
94    }
95}
96
97impl std::ops::Index<usize> for Utf16Str {
98    type Output = u16;
99
100    fn index(&self, index: usize) -> &Self::Output {
101        self.raw.get(index).expect("Reading position out of bounds of Utf16Str.")
102    }
103}