lindera_dependency/schema/
normalization.rs1use std::borrow::Cow;
4
5use crate::bytes::{Reader, push_string, push_u32};
6use crate::error::{Error, Result};
7
8const MAX_RULES: u32 = 1 << 20;
10
11#[derive(Debug, Clone, PartialEq, Eq, Default)]
39pub struct Normalization {
40 rules: Vec<(String, String)>,
42 longest: usize,
44}
45
46impl Normalization {
47 pub fn new(rules: &[(&str, &str)]) -> Result<Self> {
61 let mut sorted: Vec<(String, String)> = rules
62 .iter()
63 .map(|(from, to)| (from.to_string(), to.to_string()))
64 .collect();
65 sorted.sort();
66 sorted.dedup();
67 Self::from_sorted(sorted)
68 }
69
70 fn from_sorted(rules: Vec<(String, String)>) -> Result<Self> {
81 if let Some((_, to)) = rules.iter().find(|(from, _)| from.is_empty()) {
82 return Err(Error::Schema(format!(
83 "a rule of the normalization replaces an empty string by {to:?}"
84 )));
85 }
86 if let Some(pair) = rules.windows(2).find(|pair| pair[0].0 >= pair[1].0) {
87 return Err(Error::Schema(format!(
88 "the rules of the normalization replace {:?} twice, or are not sorted",
89 pair[1].0
90 )));
91 }
92 let longest = rules.iter().map(|(from, _)| from.len()).max().unwrap_or(0);
93 Ok(Self { rules, longest })
94 }
95
96 pub fn is_empty(&self) -> bool {
102 self.rules.is_empty()
103 }
104
105 pub fn rules(&self) -> impl Iterator<Item = (&str, &str)> {
112 self.rules
113 .iter()
114 .map(|(from, to)| (from.as_str(), to.as_str()))
115 }
116
117 pub fn apply<'a>(&self, surface: &'a str) -> Cow<'a, str> {
128 if self.rules.is_empty() {
129 return Cow::Borrowed(surface);
130 }
131 let mut output: Option<String> = None;
132 let mut position = 0;
133 while position < surface.len() {
134 let rest = &surface[position..];
135 let step = match self.longest_rule(rest) {
136 Some((from, to)) => {
137 output
138 .get_or_insert_with(|| surface[..position].to_string())
139 .push_str(to);
140 from.len()
141 }
142 None => {
143 let step = rest.chars().next().map_or(1, char::len_utf8);
144 if let Some(output) = output.as_mut() {
145 output.push_str(&rest[..step]);
146 }
147 step
148 }
149 };
150 position += step;
151 }
152 output.map_or(Cow::Borrowed(surface), Cow::Owned)
153 }
154
155 fn longest_rule(&self, rest: &str) -> Option<(&str, &str)> {
165 let mut end = self.longest.min(rest.len());
166 while end > 0 {
167 if rest.is_char_boundary(end) {
168 let prefix = &rest[..end];
169 if let Ok(index) = self
170 .rules
171 .binary_search_by(|(from, _)| from.as_str().cmp(prefix))
172 {
173 let (from, to) = &self.rules[index];
174 return Some((from.as_str(), to.as_str()));
175 }
176 }
177 end -= 1;
178 }
179 None
180 }
181
182 pub(super) fn write(&self, bytes: &mut Vec<u8>) {
189 push_u32(bytes, self.rules.len() as u32);
190 for (from, to) in &self.rules {
191 push_string(bytes, from);
192 push_string(bytes, to);
193 }
194 }
195
196 pub(super) fn read(reader: &mut Reader) -> Result<Self> {
206 let count = reader.u32()?;
207 if count > MAX_RULES {
208 return Err(reader.error(format_args!(
209 "has {count} rules of normalization, more than {MAX_RULES}"
210 )));
211 }
212 let mut rules = Vec::new();
213 for _ in 0..count {
214 let from = reader.string()?;
215 let to = reader.string()?;
216 rules.push((from, to));
217 }
218 Self::from_sorted(rules).map_err(|error| {
219 reader.error(format_args!("has a normalization that is not one: {error}"))
220 })
221 }
222}
223
224#[cfg(test)]
225mod tests {
226 use super::*;
227
228 #[test]
229 fn the_longest_rule_at_a_position_is_applied() {
230 let table = Normalization::new(&[("カ", "カ"), ("ガ", "ガ"), ("゙", "゛")]).unwrap();
231 assert_eq!(table.apply("ガ"), "ガ");
232 assert_eq!(table.apply("カ"), "カ");
233 assert_eq!(table.apply("カガ゙"), "カガ゛");
234 }
235
236 #[test]
237 fn what_no_rule_matches_is_kept() {
238 let table = Normalization::new(&[("1", "1"), (" ", "___")]).unwrap();
239 assert_eq!(table.apply("第10回 大会"), "第10回___大会");
240 assert_eq!(table.apply(""), "");
241 }
242
243 #[test]
244 fn the_result_of_a_rule_is_not_normalized_again() {
245 let table = Normalization::new(&[("a", "b"), ("b", "c")]).unwrap();
246 assert_eq!(table.apply("ab"), "bc");
247 }
248
249 #[test]
250 fn a_surface_without_a_match_is_borrowed() {
251 let table = Normalization::new(&[("1", "1")]).unwrap();
252 assert!(matches!(table.apply("読ん"), Cow::Borrowed("読ん")));
253 assert!(matches!(table.apply("1"), Cow::Owned(_)));
254 assert!(matches!(
255 Normalization::default().apply("1"),
256 Cow::Borrowed("1")
257 ));
258 }
259
260 #[test]
261 fn an_empty_table_changes_nothing() {
262 let table = Normalization::default();
263 assert!(table.is_empty());
264 assert_eq!(table.apply("ガ1 "), "ガ1 ");
265 assert_eq!(table, Normalization::new(&[]).unwrap());
266 }
267
268 #[test]
269 fn the_rules_are_sorted_and_each_is_there_once() {
270 let table = Normalization::new(&[("イ", "イ"), ("ア", "ア"), ("イ", "イ")]).unwrap();
271 let rules: Vec<(&str, &str)> = table.rules().collect();
272 assert_eq!(rules, [("ア", "ア"), ("イ", "イ")]);
273 assert!(!table.is_empty());
274 }
275
276 #[test]
277 fn refuses_rules_that_are_not_a_table() {
278 let error = Normalization::new(&[("", "x")]).unwrap_err();
279 assert!(error.to_string().contains("empty string"), "{error}");
280 let error = Normalization::new(&[("a", "x"), ("a", "y")]).unwrap_err();
281 assert!(error.to_string().contains("\"a\" twice"), "{error}");
282 }
283
284 #[test]
285 fn a_table_is_read_as_it_was_written() {
286 let table = Normalization::new(&[("ガ", "ガ"), ("1", "1"), (" ", "___")]).unwrap();
287 let mut bytes = Vec::new();
288 table.write(&mut bytes);
289 let mut reader = Reader::new(&bytes, "model", Error::Model);
290 assert_eq!(Normalization::read(&mut reader).unwrap(), table);
291
292 let mut bytes = Vec::new();
293 Normalization::default().write(&mut bytes);
294 assert_eq!(bytes, [0, 0, 0, 0]);
295 }
296
297 #[test]
298 fn refuses_bytes_that_are_not_a_table() {
299 let mut bytes = Vec::new();
301 push_u32(&mut bytes, 2);
302 for text in ["b", "x", "a", "y"] {
303 push_string(&mut bytes, text);
304 }
305 let error =
306 Normalization::read(&mut Reader::new(&bytes, "model", Error::Model)).unwrap_err();
307 assert!(error.to_string().contains("normalization"), "{error}");
308
309 let mut bytes = Vec::new();
311 push_u32(&mut bytes, MAX_RULES + 1);
312 let error =
313 Normalization::read(&mut Reader::new(&bytes, "model", Error::Model)).unwrap_err();
314 assert!(
315 error.to_string().contains("rules of normalization"),
316 "{error}"
317 );
318
319 let mut bytes = Vec::new();
321 push_u32(&mut bytes, 1);
322 assert!(Normalization::read(&mut Reader::new(&bytes, "model", Error::Model)).is_err());
323 }
324}