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
use crate::data::PINYIN_DATA;
use crate::{get_block_and_index, PinyinData};
use std::convert::TryFrom;
use std::str::Chars;
#[derive(Copy, Clone)]
pub struct Pinyin(pub(crate) &'static PinyinData);
impl Pinyin {
#[cfg(feature = "plain")]
pub fn plain(self) -> &'static str {
self.0.plain
}
#[cfg(feature = "with_tone")]
pub fn with_tone(self) -> &'static str {
self.0.with_tone
}
#[cfg(feature = "with_tone_num")]
pub fn with_tone_num(self) -> &'static str {
self.0.with_tone_num
}
#[cfg(feature = "with_tone_num_end")]
pub fn with_tone_num_end(self) -> &'static str {
self.0.with_tone_num_end
}
#[cfg(feature = "plain")]
pub fn first_letter(self) -> &'static str {
let ch = self.0.plain.chars().next().unwrap();
&self.0.plain[..ch.len_utf8()]
}
#[cfg(feature = "compat")]
pub(crate) fn initials(self) -> &'static str {
&self.0.plain[..self.0.split]
}
#[cfg(feature = "compat")]
pub(crate) fn finals_plain(self) -> &'static str {
&self.0.plain[self.0.split..]
}
#[cfg(feature = "compat")]
pub(crate) fn finals_with_tone(self) -> &'static str {
&self.0.with_tone[self.0.split..]
}
#[cfg(feature = "compat")]
pub(crate) fn finals_with_tone_num(self) -> &'static str {
&self.0.with_tone_num[self.0.split..]
}
}
pub trait ToPinyin {
type Output;
fn to_pinyin(&self) -> Self::Output;
}
impl ToPinyin for char {
type Output = Option<Pinyin>;
fn to_pinyin(&self) -> Option<Pinyin> {
get_block_and_index(*self).and_then(|(block, index)| {
match usize::try_from(block.data[index]).unwrap() {
0 => None,
idx => Some(Pinyin(&PINYIN_DATA[idx])),
}
})
}
}
impl<'a> ToPinyin for &'a str {
type Output = PinyinStrIter<'a>;
#[inline]
fn to_pinyin(&self) -> Self::Output {
PinyinStrIter(self.chars())
}
}
pub struct PinyinStrIter<'a>(Chars<'a>);
impl<'a> Iterator for PinyinStrIter<'a> {
type Item = Option<Pinyin>;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
self.0.next().map(|c| c.to_pinyin())
}
}
#[cfg(test)]
mod tests {
use crate::ToPinyin;
#[test]
fn special_code_point() {
assert!('\u{10FFFF}'.to_pinyin().is_none());
}
}