f-office-docx 0.1.0

DOCX model and Word's layout rules.
Documentation
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
//! The forms of the number formats that write a number with signs of their own: digits of
//! other scripts, East Asian and Korean counting with signs of units, lists and cycles of
//! letters, Hebrew numerals and ordinals.

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,
};

/// How a format writes its numbers.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Form {
    /// Each decimal digit as a sign of its own, the sign of zero first.
    Digits(&'static [char; 10]),
    /// Each decimal digit as a sign of its own, as [`Form::Digits`], and nothing from
    /// [`TEN_THOUSAND_DIGITS_LIMIT`] on.
    DigitsBelowTenThousand(&'static [char; 10]),
    /// Each decimal digit as a sign of its own, as [`Form::Digits`], with a number above
    /// [`DIGIT_SIGN_WRAP`] taken modulo it.
    WrappedDigits(&'static [char; 10]),
    /// Counting with signs of units, as Chinese, Japanese and Korean numerals do.
    Counting(&'static Counting),
    /// Counting with signs of units below [`SHORT_COUNTING_LIMIT`], and each digit as a sign of
    /// its own from it on.
    ShortCounting(&'static Counting, &'static [char; 10]),
    /// The native Korean words below a hundred, and Sino-Korean counting from it on.
    KoreanWords,
    /// The signs of a list from 1 on, and decimal digits past its end.
    Listed(&'static [&'static str]),
    /// The signs of a list from 1 on, again from the first after the last.
    Cycled(&'static [&'static str]),
    /// The signs of a list from 1 on, and after the last the first again, two times, then
    /// three times and so on; the number is taken modulo the list's length times `repeats`.
    Repeated(&'static [&'static str], i64),
    /// The cycle of sixty: a heavenly stem and an earthly branch.
    StemsAndBranches,
    /// Hebrew numerals, with the number taken modulo [`RIGHT_TO_LEFT_CYCLE`].
    Hebrew,
    /// Decimal digits with an English ordinal suffix: 1st, 2nd, 3rd.
    Ordinal,
    /// The number in dashes: - 1 -.
    InDashes,
}

/// Where a counting format leaves out the sign of one before a unit.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PlainUnit {
    /// The sign of one always stands before the unit.
    Never,
    /// The sign of one is left out when the unit starts the number.
    First,
    /// The sign of one is always left out.
    Always,
}

/// A counting format: its signs of the digits 1 to 9, of the units ten, hundred, thousand and
/// ten thousand, of a gap of zeros between two digits, and where it leaves out the sign of one
/// before each unit.
#[derive(Debug, PartialEq, Eq)]
pub struct Counting {
    digits: [char; 9],
    units: [char; 4],
    zero: Option<char>,
    plain: [PlainUnit; 4],
}

/// The digits of `ideographDigital` and `japaneseDigitalTenThousand`.
pub const IDEOGRAPH_DIGITS: [char; 10] =
    ['〇', '一', '二', '三', '四', '五', '六', '七', '八', '九'];

/// The digits of `taiwaneseDigital`, and of `chineseCounting` and `taiwaneseCounting` from a
/// hundred on: their zero is a white circle.
pub const CIRCLE_ZERO_DIGITS: [char; 10] =
    ['○', '一', '二', '三', '四', '五', '六', '七', '八', '九'];

/// The digits of `koreanDigital`.
pub const KOREAN_DIGITS: [char; 10] = ['영', '일', '이', '삼', '사', '오', '육', '칠', '팔', '구'];

/// The digits of `koreanDigital2`.
pub const HANJA_DIGITS: [char; 10] = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];

/// The digits of `decimalFullWidth` and `decimalFullWidth2`.
pub const FULL_WIDTH_DIGITS: [char; 10] =
    ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];

/// The digits of `hindiNumbers`.
pub const DEVANAGARI_DIGITS: [char; 10] = ['०', '१', '२', '३', '४', '५', '६', '७', '८', '९'];

/// The digits of `thaiNumbers`.
pub const THAI_DIGITS: [char; 10] = ['๐', '๑', '๒', '๓', '๔', '๕', '๖', '๗', '๘', '๙'];

const CJK_ONES: [char; 9] = ['一', '二', '三', '四', '五', '六', '七', '八', '九'];

/// `chineseCountingThousand`.
pub const CHINESE_COUNTING: Counting = Counting {
    digits: CJK_ONES,
    units: ['十', '百', '千', '万'],
    zero: Some('〇'),
    plain: [
        PlainUnit::First,
        PlainUnit::Never,
        PlainUnit::Never,
        PlainUnit::Never,
    ],
};

/// `taiwaneseCountingThousand`.
pub const TAIWANESE_COUNTING: Counting = Counting {
    digits: CJK_ONES,
    units: ['十', '百', '千', '萬'],
    zero: Some('零'),
    plain: CHINESE_COUNTING.plain,
};

/// `japaneseCounting`.
pub const JAPANESE_COUNTING: Counting = Counting {
    digits: CJK_ONES,
    units: ['十', '百', '千', '万'],
    zero: None,
    plain: [
        PlainUnit::Always,
        PlainUnit::Always,
        PlainUnit::First,
        PlainUnit::Never,
    ],
};

/// `koreanCounting`, and `koreanLegal` from a hundred on.
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];

/// `japaneseLegal`.
pub const JAPANESE_LEGAL: Counting = Counting {
    digits: ['壱', '弐', '参', '四', '伍', '六', '七', '八', '九'],
    units: ['拾', '百', '阡', '萬'],
    zero: None,
    plain: LEGAL,
};

/// `ideographLegalTraditional`.
pub const TRADITIONAL_LEGAL: Counting = Counting {
    digits: ['壹', '貳', '參', '肆', '伍', '陸', '柒', '捌', '玖'],
    units: ['拾', '佰', '仟', '萬'],
    zero: Some('零'),
    plain: LEGAL,
};

/// `chineseLegalSimplified`.
pub const SIMPLIFIED_LEGAL: Counting = Counting {
    digits: ['壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'],
    units: ['拾', '佰', '仟', '萬'],
    zero: Some('零'),
    plain: LEGAL,
};

/// `decimalEnclosedCircle`.
pub const ENCLOSED_CIRCLE: [&str; 20] = [
    "①", "②", "③", "④", "⑤", "⑥", "⑦", "⑧", "⑨", "⑩", "⑪", "⑫", "⑬", "⑭", "⑮", "⑯", "⑰", "⑱", "⑲",
    "⑳",
];

/// `decimalEnclosedFullstop`.
pub const ENCLOSED_FULL_STOP: [&str; 20] = [
    "⒈", "⒉", "⒊", "⒋", "⒌", "⒍", "⒎", "⒏", "⒐", "⒑", "⒒", "⒓", "⒔", "⒕", "⒖", "⒗", "⒘", "⒙", "⒚",
    "⒛",
];

/// `decimalEnclosedParen`.
pub const ENCLOSED_PARENTHESES: [&str; 20] = [
    "⑴", "⑵", "⑶", "⑷", "⑸", "⑹", "⑺", "⑻", "⑼", "⑽", "⑾", "⑿", "⒀", "⒁", "⒂", "⒃", "⒄", "⒅", "⒆",
    "⒇",
];

/// `ideographEnclosedCircle`.
pub const IDEOGRAPH_ENCLOSED_CIRCLE: [&str; 10] =
    ["㈠", "㈡", "㈢", "㈣", "㈤", "㈥", "㈦", "㈧", "㈨", "㈩"];

/// The heavenly stems: `ideographTraditional`, and the first sign of
/// `ideographZodiacTraditional`.
pub const STEMS: [&str; 10] = ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"];

/// The earthly branches: `ideographZodiac`, and the second sign of
/// `ideographZodiacTraditional`. The eleventh is written 戍.
pub const BRANCHES: [&str; 12] = [
    "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戍", "亥",
];

/// `aiueo`: half-width katakana in the order of the gojūon.
pub const AIUEO: [&str; 46] = [
    "ア", "イ", "ウ", "エ", "オ", "カ", "キ", "ク", "ケ", "コ", "サ", "シ", "ス", "セ", "ソ", "タ", "チ", "ツ", "テ",
    "ト", "ナ", "ニ", "ヌ", "ネ", "ノ", "ハ", "ヒ", "フ", "ヘ", "ホ", "マ", "ミ", "ム", "メ", "モ", "ヤ", "ユ", "ヨ",
    "ラ", "リ", "ル", "レ", "ロ", "ワ", "ヲ", "ン",
];

/// `aiueoFullWidth`.
pub const AIUEO_FULL_WIDTH: [&str; 46] = [
    "ア", "イ", "ウ", "エ", "オ", "カ", "キ", "ク", "ケ", "コ", "サ", "シ", "ス", "セ", "ソ", "タ",
    "チ", "ツ", "テ", "ト", "ナ", "ニ", "ヌ", "ネ", "ノ", "ハ", "ヒ", "フ", "ヘ", "ホ", "マ", "ミ",
    "ム", "メ", "モ", "ヤ", "ユ", "ヨ", "ラ", "リ", "ル", "レ", "ロ", "ワ", "ヲ", "ン",
];

/// `iroha`: half-width katakana in the order of the iroha, with wi and we in full width, which
/// have no half-width form, and n last.
pub const IROHA: [&str; 48] = [
    "イ", "ロ", "ハ", "ニ", "ホ", "ヘ", "ト", "チ", "リ", "ヌ", "ル", "ヲ", "ワ", "カ", "ヨ", "タ", "レ", "ソ", "ツ",
    "ネ", "ナ", "ラ", "ム", "ウ", "ヰ", "ノ", "オ", "ク", "ヤ", "マ", "ケ", "フ", "コ", "エ", "テ", "ア", "サ", "キ",
    "ユ", "メ", "ミ", "シ", "ヱ", "ヒ", "モ", "セ", "ス", "ン",
];

/// `irohaFullWidth`.
pub const IROHA_FULL_WIDTH: [&str; 48] = [
    "イ", "ロ", "ハ", "ニ", "ホ", "ヘ", "ト", "チ", "リ", "ヌ", "ル", "ヲ", "ワ", "カ", "ヨ", "タ",
    "レ", "ソ", "ツ", "ネ", "ナ", "ラ", "ム", "ウ", "ヰ", "ノ", "オ", "ク", "ヤ", "マ", "ケ", "フ",
    "コ", "エ", "テ", "ア", "サ", "キ", "ユ", "メ", "ミ", "シ", "ヱ", "ヒ", "モ", "セ", "ス", "ン",
];

/// `ganada`.
pub const GANADA: [&str; 14] = [
    "가", "나", "다", "라", "마", "바", "사", "아", "자", "차", "카", "타", "파", "하",
];

/// `chosung`.
pub const CHOSUNG: [&str; 14] = [
    "ㄱ", "ㄴ", "ㄷ", "ㄹ", "ㅁ", "ㅂ", "ㅅ", "ㅇ", "ㅈ", "ㅊ", "ㅋ", "ㅌ", "ㅍ", "ㅎ",
];

/// `russianLower`: the alphabet without ё, й, ъ and ь.
pub const RUSSIAN_LOWER: [&str; 29] = [
    "а", "б", "в", "г", "д", "е", "ж", "з", "и", "к", "л", "м", "н", "о", "п", "р", "с", "т", "у",
    "ф", "х", "ц", "ч", "ш", "щ", "ы", "э", "ю", "я",
];

/// `russianUpper`.
pub const RUSSIAN_UPPER: [&str; 29] = [
    "А", "Б", "В", "Г", "Д", "Е", "Ж", "З", "И", "К", "Л", "М", "Н", "О", "П", "Р", "С", "Т", "У",
    "Ф", "Х", "Ц", "Ч", "Ш", "Щ", "Ы", "Э", "Ю", "Я",
];

/// `chicago`: the signs of notes.
pub const CHICAGO: [&str; 4] = ["*", "†", "‡", "§"];

/// `arabicAlpha`: the letters in the order of the alphabet.
pub const ARABIC_ALPHA: [&str; 28] = [
    "أ", "ب", "ت", "ث", "ج", "ح", "خ", "د", "ذ", "ر", "ز", "س", "ش", "ص", "ض", "ط", "ظ", "ع", "غ",
    "ف", "ق", "ك", "ل", "م", "ن", "ه", "و", "ي",
];

/// `arabicAbjad`: the letters in the order of the abjad.
pub const ARABIC_ABJAD: [&str; 28] = [
    "أ", "ب", "ج", "د", "ه", "و", "ز", "ح", "ط", "ي", "ك", "ل", "م", "ن", "س", "ع", "ف", "ص", "ق",
    "ر", "ش", "ت", "ث", "خ", "ذ", "ض", "ظ", "غ",
];

/// The times that a letter of `arabicAlpha` and `arabicAbjad` repeats at most: the cycle of
/// the Hebrew and Arabic formats holds each of the letters this many times.
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 {
    /// The number in this form, or `None` where the form has no sign for it and the label
    /// writes decimal digits.
    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} -")),
        }
    }
}

/// The sign at `index` of `signs`.
fn sign(signs: &[&'static str], index: i64) -> Option<&'static str> {
    usize::try_from(index)
        .ok()
        .and_then(|i| signs.get(i))
        .copied()
}

/// The sign of `value` in a list that starts again after its last sign.
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()
}

/// Each decimal digit of `value` as its sign.
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()
    })
}

/// The sign of `value`, repeated once more after each round of the list, within a cycle of
/// the list's length times `repeats`.
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 {
    /// `value` in signs of digits and units, below [`COUNTING_LIMIT`].
    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)
    }

    /// Writes `value`, below ten thousand, after `out`; `after` says whether a sign comes
    /// before it in the number.
    fn below_ten_thousand(&self, value: i64, after: bool, out: &mut String) {
        let (decade, _, thousand) = DECIMAL_PLACES;
        // The units of the thousands, hundreds and tens, then the ones, which have none.
        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;
        }
    }
}

/// `koreanLegal`: the native words below a hundred, and Sino-Korean counting from it on.
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())
}

/// Hebrew numerals of `value` modulo [`RIGHT_TO_LEFT_CYCLE`]: hundreds, tens and ones, with the
/// numbers of [`HEBREW_NINE_AND`] written as nine and a sign of ones.
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)
}

/// The English ordinal suffix of `value`, st, nd, rd or th: the last two letters of the
/// ordinal in words of its last two digits.
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)
}

/// The English ordinal of the last word of the English words `words`, such as "twenty-first"
/// for "twenty-one".
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}")
}