1use crate::slice::advance;
2
3pub struct CharEncodeUtf16 {
4 buf: [u16; 2],
5}
6
7impl CharEncodeUtf16 {
8 pub const fn new(ch: char) -> Self {
10 let mut code = ch as u32;
11 let mut buf = [0; 2];
12 if (code & 0xFFFF) == code {
13 buf[0] = code as u16;
14 } else {
15 code -= 0x1_0000;
16 buf[0] = 0xD800 | ((code >> 10) as u16);
17 buf[1] = 0xDC00 | ((code as u16) & 0x3FF);
18 }
19 Self { buf }
20 }
21
22 pub const fn has_second(&self) -> bool {
23 self.buf[1] != 0
24 }
25
26 pub const fn first(&self) -> u16 {
27 self.buf[0]
28 }
29 pub const fn second(&self) -> u16 {
30 self.buf[1]
31 }
32}
33
34pub const fn str_len_utf16(s: &str) -> usize {
35 let mut s = s.as_bytes();
36 let mut ans = 0;
37 while let Some((ch, count)) = crate::utf8::next_char(s) {
38 s = advance(s, count);
39 ans += ch.len_utf16(); }
41 ans
42}