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
use crate::shared::{IResult, NomErr, NomErrorReason};
use nom::{
bytes::complete::is_not,
character::complete::char,
combinator::{map, opt},
multi::separated_list1,
sequence::tuple,
};
use serde::{Deserialize, Serialize};
use std::convert::TryFrom;
use thiserror::Error;
#[derive(Debug, PartialEq, Eq, Clone, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Kunyomi {
pub reading: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub okurigana: Option<String>,
pub kind: KunyomiKind,
}
#[derive(Debug, PartialEq, Eq, Clone, Copy, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum KunyomiKind {
Normal,
Prefix,
Suffix,
}
#[derive(Debug, Error, PartialEq, Eq, Clone)]
pub enum KunyomiParseError {
#[error("(Kunyomi) Format: {0}")]
Format(NomErrorReason),
#[error("(Kunyomi) Expected one or two kunyomi reading pieces")]
IncorrectPieces,
}
impl<'a> From<NomErr<'a>> for KunyomiParseError {
fn from(err: NomErr<'a>) -> Self {
Self::Format(err.into())
}
}
impl TryFrom<&str> for Kunyomi {
type Error = KunyomiParseError;
fn try_from(text: &str) -> Result<Self, Self::Error> {
let (_i, (pre, pieces, post)) = parts(text)?;
let kind = if pre {
KunyomiKind::Prefix
} else if post {
KunyomiKind::Suffix
} else {
KunyomiKind::Normal
};
let mut iter = pieces.into_iter();
let reading = iter.next().ok_or(KunyomiParseError::IncorrectPieces)?;
let okurigana = iter.next();
if iter.next().is_some() {
return Err(KunyomiParseError::IncorrectPieces);
}
Ok(Kunyomi {
reading,
okurigana,
kind,
})
}
}
fn parts(s: &str) -> IResult<(bool, Vec<String>, bool)> {
tuple((fix, okurigana, fix))(s)
}
fn okurigana(s: &str) -> IResult<Vec<String>> {
separated_list1(char('.'), map(is_not("-."), |s: &str| s.into()))(s)
}
fn fix(s: &str) -> IResult<bool> {
map(opt(char('-')), |c| c.is_some())(s)
}