use crate::params::{
ARABIC_LETTERS, COUNTING_LIMIT, DECIMAL_PLACES, DIGIT_SIGN_WRAP, HEBREW_NINE_AND,
RIGHT_TO_LEFT_CYCLE, SHORT_COUNTING_LIMIT, TEN_THOUSAND_DIGITS_LIMIT,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Form {
Digits(&'static [char; 10]),
DigitsBelowTenThousand(&'static [char; 10]),
WrappedDigits(&'static [char; 10]),
Counting(&'static Counting),
ShortCounting(&'static Counting, &'static [char; 10]),
KoreanWords,
Listed(&'static [&'static str]),
Cycled(&'static [&'static str]),
Repeated(&'static [&'static str], i64),
StemsAndBranches,
Hebrew,
Ordinal,
InDashes,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PlainUnit {
Never,
First,
Always,
}
#[derive(Debug, PartialEq, Eq)]
pub struct Counting {
digits: [char; 9],
units: [char; 4],
zero: Option<char>,
plain: [PlainUnit; 4],
}
pub const IDEOGRAPH_DIGITS: [char; 10] =
['〇', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
pub const CIRCLE_ZERO_DIGITS: [char; 10] =
['○', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
pub const KOREAN_DIGITS: [char; 10] = ['영', '일', '이', '삼', '사', '오', '육', '칠', '팔', '구'];
pub const HANJA_DIGITS: [char; 10] = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
pub const FULL_WIDTH_DIGITS: [char; 10] =
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
pub const DEVANAGARI_DIGITS: [char; 10] = ['०', '१', '२', '३', '४', '५', '६', '७', '८', '९'];
pub const THAI_DIGITS: [char; 10] = ['๐', '๑', '๒', '๓', '๔', '๕', '๖', '๗', '๘', '๙'];
const CJK_ONES: [char; 9] = ['一', '二', '三', '四', '五', '六', '七', '八', '九'];
pub const CHINESE_COUNTING: Counting = Counting {
digits: CJK_ONES,
units: ['十', '百', '千', '万'],
zero: Some('〇'),
plain: [
PlainUnit::First,
PlainUnit::Never,
PlainUnit::Never,
PlainUnit::Never,
],
};
pub const TAIWANESE_COUNTING: Counting = Counting {
digits: CJK_ONES,
units: ['十', '百', '千', '萬'],
zero: Some('零'),
plain: CHINESE_COUNTING.plain,
};
pub const JAPANESE_COUNTING: Counting = Counting {
digits: CJK_ONES,
units: ['十', '百', '千', '万'],
zero: None,
plain: [
PlainUnit::Always,
PlainUnit::Always,
PlainUnit::First,
PlainUnit::Never,
],
};
pub const KOREAN_COUNTING: Counting = Counting {
digits: ['일', '이', '삼', '사', '오', '육', '칠', '팔', '구'],
units: ['십', '백', '천', '만'],
zero: None,
plain: [
PlainUnit::Always,
PlainUnit::Always,
PlainUnit::First,
PlainUnit::Always,
],
};
const LEGAL: [PlainUnit; 4] = [PlainUnit::Never; 4];
pub const JAPANESE_LEGAL: Counting = Counting {
digits: ['壱', '弐', '参', '四', '伍', '六', '七', '八', '九'],
units: ['拾', '百', '阡', '萬'],
zero: None,
plain: LEGAL,
};
pub const TRADITIONAL_LEGAL: Counting = Counting {
digits: ['壹', '貳', '參', '肆', '伍', '陸', '柒', '捌', '玖'],
units: ['拾', '佰', '仟', '萬'],
zero: Some('零'),
plain: LEGAL,
};
pub const SIMPLIFIED_LEGAL: Counting = Counting {
digits: ['壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'],
units: ['拾', '佰', '仟', '萬'],
zero: Some('零'),
plain: LEGAL,
};
pub const ENCLOSED_CIRCLE: [&str; 20] = [
"①", "②", "③", "④", "⑤", "⑥", "⑦", "⑧", "⑨", "⑩", "⑪", "⑫", "⑬", "⑭", "⑮", "⑯", "⑰", "⑱", "⑲",
"⑳",
];
pub const ENCLOSED_FULL_STOP: [&str; 20] = [
"⒈", "⒉", "⒊", "⒋", "⒌", "⒍", "⒎", "⒏", "⒐", "⒑", "⒒", "⒓", "⒔", "⒕", "⒖", "⒗", "⒘", "⒙", "⒚",
"⒛",
];
pub const ENCLOSED_PARENTHESES: [&str; 20] = [
"⑴", "⑵", "⑶", "⑷", "⑸", "⑹", "⑺", "⑻", "⑼", "⑽", "⑾", "⑿", "⒀", "⒁", "⒂", "⒃", "⒄", "⒅", "⒆",
"⒇",
];
pub const IDEOGRAPH_ENCLOSED_CIRCLE: [&str; 10] =
["㈠", "㈡", "㈢", "㈣", "㈤", "㈥", "㈦", "㈧", "㈨", "㈩"];
pub const STEMS: [&str; 10] = ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"];
pub const BRANCHES: [&str; 12] = [
"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戍", "亥",
];
pub const AIUEO: [&str; 46] = [
"ア", "イ", "ウ", "エ", "オ", "カ", "キ", "ク", "ケ", "コ", "サ", "シ", "ス", "セ", "ソ", "タ", "チ", "ツ", "テ",
"ト", "ナ", "ニ", "ヌ", "ネ", "ノ", "ハ", "ヒ", "フ", "ヘ", "ホ", "マ", "ミ", "ム", "メ", "モ", "ヤ", "ユ", "ヨ",
"ラ", "リ", "ル", "レ", "ロ", "ワ", "ヲ", "ン",
];
pub const AIUEO_FULL_WIDTH: [&str; 46] = [
"ア", "イ", "ウ", "エ", "オ", "カ", "キ", "ク", "ケ", "コ", "サ", "シ", "ス", "セ", "ソ", "タ",
"チ", "ツ", "テ", "ト", "ナ", "ニ", "ヌ", "ネ", "ノ", "ハ", "ヒ", "フ", "ヘ", "ホ", "マ", "ミ",
"ム", "メ", "モ", "ヤ", "ユ", "ヨ", "ラ", "リ", "ル", "レ", "ロ", "ワ", "ヲ", "ン",
];
pub const IROHA: [&str; 48] = [
"イ", "ロ", "ハ", "ニ", "ホ", "ヘ", "ト", "チ", "リ", "ヌ", "ル", "ヲ", "ワ", "カ", "ヨ", "タ", "レ", "ソ", "ツ",
"ネ", "ナ", "ラ", "ム", "ウ", "ヰ", "ノ", "オ", "ク", "ヤ", "マ", "ケ", "フ", "コ", "エ", "テ", "ア", "サ", "キ",
"ユ", "メ", "ミ", "シ", "ヱ", "ヒ", "モ", "セ", "ス", "ン",
];
pub const IROHA_FULL_WIDTH: [&str; 48] = [
"イ", "ロ", "ハ", "ニ", "ホ", "ヘ", "ト", "チ", "リ", "ヌ", "ル", "ヲ", "ワ", "カ", "ヨ", "タ",
"レ", "ソ", "ツ", "ネ", "ナ", "ラ", "ム", "ウ", "ヰ", "ノ", "オ", "ク", "ヤ", "マ", "ケ", "フ",
"コ", "エ", "テ", "ア", "サ", "キ", "ユ", "メ", "ミ", "シ", "ヱ", "ヒ", "モ", "セ", "ス", "ン",
];
pub const GANADA: [&str; 14] = [
"가", "나", "다", "라", "마", "바", "사", "아", "자", "차", "카", "타", "파", "하",
];
pub const CHOSUNG: [&str; 14] = [
"ㄱ", "ㄴ", "ㄷ", "ㄹ", "ㅁ", "ㅂ", "ㅅ", "ㅇ", "ㅈ", "ㅊ", "ㅋ", "ㅌ", "ㅍ", "ㅎ",
];
pub const RUSSIAN_LOWER: [&str; 29] = [
"а", "б", "в", "г", "д", "е", "ж", "з", "и", "к", "л", "м", "н", "о", "п", "р", "с", "т", "у",
"ф", "х", "ц", "ч", "ш", "щ", "ы", "э", "ю", "я",
];
pub const RUSSIAN_UPPER: [&str; 29] = [
"А", "Б", "В", "Г", "Д", "Е", "Ж", "З", "И", "К", "Л", "М", "Н", "О", "П", "Р", "С", "Т", "У",
"Ф", "Х", "Ц", "Ч", "Ш", "Щ", "Ы", "Э", "Ю", "Я",
];
pub const CHICAGO: [&str; 4] = ["*", "†", "‡", "§"];
pub const ARABIC_ALPHA: [&str; 28] = [
"أ", "ب", "ت", "ث", "ج", "ح", "خ", "د", "ذ", "ر", "ز", "س", "ش", "ص", "ض", "ط", "ظ", "ع", "غ",
"ف", "ق", "ك", "ل", "م", "ن", "ه", "و", "ي",
];
pub const ARABIC_ABJAD: [&str; 28] = [
"أ", "ب", "ج", "د", "ه", "و", "ز", "ح", "ط", "ي", "ك", "ل", "م", "ن", "س", "ع", "ف", "ص", "ق",
"ر", "ش", "ت", "ث", "خ", "ذ", "ض", "ظ", "غ",
];
pub const ARABIC_REPEATS: i64 = RIGHT_TO_LEFT_CYCLE / ARABIC_LETTERS;
const HEBREW_ONES: [&str; 9] = ["א", "ב", "ג", "ד", "ה", "ו", "ז", "ח", "ט"];
const HEBREW_TENS: [&str; 9] = ["י", "כ", "ל", "מ", "נ", "ס", "ע", "פ", "צ"];
const HEBREW_HUNDREDS: [&str; 4] = ["ק", "ר", "ש", "ת"];
const KOREAN_ONES: [&str; 9] = [
"하나", "둘", "셋", "넷", "다섯", "여섯", "일곱", "여덟", "아홉",
];
const KOREAN_TENS: [&str; 9] = [
"열", "스물", "서른", "마흔", "쉰", "예순", "일흔", "여든", "아흔",
];
impl Form {
pub fn write(self, value: i64) -> Option<String> {
match self {
Self::Digits(signs) => digits(value, signs),
Self::DigitsBelowTenThousand(signs) => {
if value >= TEN_THOUSAND_DIGITS_LIMIT {
Some(String::new())
} else {
digits(value, signs)
}
}
Self::WrappedDigits(signs) => {
let value = if value > DIGIT_SIGN_WRAP {
value % DIGIT_SIGN_WRAP
} else {
value
};
digits(value, signs)
}
Self::Counting(system) => system.write(value),
Self::ShortCounting(system, signs) => {
if value < SHORT_COUNTING_LIMIT {
system.write(value)
} else {
digits(value, signs)
}
}
Self::KoreanWords => korean_words(value),
Self::Listed(signs) => sign(signs, value.checked_sub(1)?).map(str::to_owned),
Self::Cycled(signs) => cycled(signs, value).map(str::to_owned),
Self::Repeated(signs, repeats) => repeated(signs, repeats, value),
Self::StemsAndBranches => {
Some([cycled(&STEMS, value)?, cycled(&BRANCHES, value)?].concat())
}
Self::Hebrew => hebrew(value),
Self::Ordinal => (value >= 0).then(|| format!("{value}{}", ordinal_suffix(value))),
Self::InDashes => Some(format!("- {value} -")),
}
}
}
fn sign(signs: &[&'static str], index: i64) -> Option<&'static str> {
usize::try_from(index)
.ok()
.and_then(|i| signs.get(i))
.copied()
}
fn cycled(signs: &[&'static str], value: i64) -> Option<&'static str> {
let length = i64::try_from(signs.len()).ok()?;
(value >= 1)
.then(|| sign(signs, (value - 1) % length))
.flatten()
}
fn digits(value: i64, signs: &[char; 10]) -> Option<String> {
(value >= 0).then(|| {
value
.to_string()
.bytes()
.filter_map(|digit| signs.get(usize::from(digit - b'0')).copied())
.collect()
})
}
fn repeated(signs: &[&'static str], repeats: i64, value: i64) -> Option<String> {
let length = i64::try_from(signs.len()).ok()?;
let place = value.checked_sub(1)?.checked_rem(length * repeats)?;
let count = usize::try_from(place / length + 1).ok()?;
sign(signs, place.checked_rem(length)?).map(|sign| sign.repeat(count))
}
impl Counting {
fn write(&self, value: i64) -> Option<String> {
if !(1..COUNTING_LIMIT).contains(&value) {
return None;
}
let (decade, _, thousand) = DECIMAL_PLACES;
let group = thousand * decade;
let (high, low) = (value / group, value % group);
let mut out = String::new();
if high > 0 {
if !(high == 1 && self.plain[3] != PlainUnit::Never) {
self.below_ten_thousand(high, false, &mut out);
}
out.push(self.units[3]);
}
self.below_ten_thousand(low, high > 0, &mut out);
Some(out)
}
fn below_ten_thousand(&self, value: i64, after: bool, out: &mut String) {
let (decade, _, thousand) = DECIMAL_PLACES;
let units = self.units.iter().zip(self.plain).rev().skip(1);
let mut place = thousand;
let mut started = after;
let mut gap = false;
for unit in units.map(Some).chain([None]) {
let digit = value / place % decade;
place /= decade;
let Some(sign) = usize::try_from(digit - 1)
.ok()
.and_then(|i| self.digits.get(i))
else {
gap |= started;
continue;
};
if gap {
out.extend(self.zero);
gap = false;
}
match unit {
None => out.push(*sign),
Some((unit, plain)) => {
let plain = match plain {
PlainUnit::Never => false,
PlainUnit::First => !started,
PlainUnit::Always => true,
};
if !(digit == 1 && plain) {
out.push(*sign);
}
out.push(*unit);
}
}
started = true;
}
}
}
fn korean_words(value: i64) -> Option<String> {
let (decade, hundred, _) = DECIMAL_PLACES;
if !(1..hundred).contains(&value) {
return KOREAN_COUNTING.write(value);
}
let tens = sign(&KOREAN_TENS, value / decade - 1).unwrap_or_default();
let ones = sign(&KOREAN_ONES, value % decade - 1).unwrap_or_default();
Some([tens, ones].concat())
}
fn hebrew(value: i64) -> Option<String> {
let value = value.checked_sub(1)?.checked_rem(RIGHT_TO_LEFT_CYCLE)? + 1;
if value < 1 {
return None;
}
let (decade, hundred, _) = DECIMAL_PLACES;
let (hundreds, rest) = (value / hundred, value % hundred);
let mut out = String::new();
out.push_str(sign(&HEBREW_HUNDREDS, hundreds - 1).unwrap_or_default());
if HEBREW_NINE_AND.contains(&rest) {
out.push_str(HEBREW_ONES.last().copied().unwrap_or_default());
out.push_str(sign(&HEBREW_ONES, rest - decade).unwrap_or_default());
} else {
out.push_str(sign(&HEBREW_TENS, rest / decade - 1).unwrap_or_default());
out.push_str(sign(&HEBREW_ONES, rest % decade - 1).unwrap_or_default());
}
Some(out)
}
fn ordinal_suffix(value: i64) -> String {
let (_, hundred, _) = DECIMAL_PLACES;
let mut words = ordinal_words(&super::english(value % hundred));
let start = words.char_indices().rev().nth(1).map_or(0, |(i, _)| i);
words.split_off(start)
}
pub fn ordinal_words(words: &str) -> String {
let split = words.rfind([' ', '-']).map_or(0, |i| i + 1);
let (head, last) = words.split_at(split);
let last = match last {
"one" => "first".to_owned(),
"two" => "second".to_owned(),
"three" => "third".to_owned(),
"five" => "fifth".to_owned(),
"eight" => "eighth".to_owned(),
"nine" => "ninth".to_owned(),
"twelve" => "twelfth".to_owned(),
word => match word.strip_suffix('y') {
Some(stem) => format!("{stem}ieth"),
None => format!("{word}th"),
},
};
format!("{head}{last}")
}