f-office-docx 0.2.3

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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
//! The results of `DATE` and `TIME` fields: a local date and time written with a date and time
//! picture (`\@`).

use std::fmt::Write as _;

use crate::params::{
    DAYS_PER_WEEK, FULL_NAME_LETTERS, HOURS_PER_DAY, HOURS_PER_HALF_DAY, LEAP_YEAR_CYCLES, MARCH,
    MAX_DAY_OF_MONTH, MAX_SECONDS_PER_MINUTE, MINUTES_PER_HOUR, MONTH_DAYS, MONTHS_PER_YEAR,
    SHORT_NAME_LETTERS, WEEKDAY_SHIFTS, YEAR_DIGITS, YEARS_PER_CENTURY,
};

/// The picture item of the half of the day in capitals; `am/pm` writes it in small letters.
const AM_PM: &str = "AM/PM";

/// A local date and time.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DateTime {
    /// The year, such as 2026.
    pub year: i32,
    /// The month, from 1 to 12.
    pub month: u8,
    /// The day of the month, from 1.
    pub day: u8,
    /// The hour, from 0 to 23.
    pub hour: u8,
    /// The minute, from 0 to 59.
    pub minute: u8,
    /// The second, from 0 to 59.
    pub second: u8,
}

const MONTHS: [&str; 12] = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
];

const DAYS: [&str; 7] = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
];

/// The month of an English month name or its first three letters, from 1.
fn month_of(word: &str) -> Option<u8> {
    let word = word.trim_end_matches(['.', ',']).to_lowercase();
    let index = MONTHS.iter().position(|name| {
        let name = name.to_lowercase();
        word == name || (word.len() == SHORT_NAME_LETTERS && name.starts_with(&word))
    })?;
    u8::try_from(index + 1).ok()
}

/// The days of the month `month` (1 to 12) of the year `year` in the Gregorian calendar, with
/// February's leap day; the most a month has for another month number.
fn days_in_month(year: i32, month: u8) -> u8 {
    let (leap, century, cycle) = LEAP_YEAR_CYCLES;
    let is_leap = year.rem_euclid(leap) == 0
        && (year.rem_euclid(century) != 0 || year.rem_euclid(cycle) == 0);
    let days = usize::from(month)
        .checked_sub(1)
        .and_then(|index| MONTH_DAYS.get(index).copied())
        .unwrap_or(MAX_DAY_OF_MONTH);
    let leap_day = usize::from(month) + 1 == MARCH && is_leap;
    days + u8::from(leap_day)
}

/// A day of the month, possibly followed by a comma.
fn day_of(word: &str) -> Option<u8> {
    word.trim_end_matches(',').parse().ok()
}

/// The year, month and day of an ISO 8601 date, such as `2023-04-20`.
fn iso_date(text: &str) -> Option<(i32, u8, u8)> {
    let mut parts = text.split('T').next()?.split('-');
    let year = parts.next()?.parse().ok()?;
    Some((
        year,
        parts.next()?.parse().ok()?,
        parts.next()?.parse().ok()?,
    ))
}

/// The picture of a `DATE` field without a `\@` switch.
pub const DATE_PICTURE: &str = "M/d/yyyy";

/// The picture of a `TIME` field without a `\@` switch.
pub const TIME_PICTURE: &str = "h:mm AM/PM";

/// The picture of a `SAVEDATE` or `PRINTDATE` field without a `\@` switch, on a target that
/// shows its date and time: the time of a save or print has whole minutes, so its seconds are
/// written as `00`.
pub const SAVED_DATE_PICTURE: &str = "M/d/yyyy h:mm:'00' AM/PM";

/// The picture of a date property that a `DOCPROPERTY` field without a `\@` switch shows, on a
/// target that writes such a property as its local date.
pub const PROPERTY_DATE_PICTURE: &str = "d/M/yyyy";

impl DateTime {
    /// The date of this time, taken as UTC, in a time zone `zone_minutes` east of UTC (west when
    /// it is negative), at midnight: the day before or after when the zone moves the time past
    /// midnight, by as many days as it moves it.
    #[must_use]
    pub fn local_date(self, zone_minutes: i32) -> Self {
        let per_hour = i32::from(MINUTES_PER_HOUR);
        let minutes = i32::from(self.hour) * per_hour + i32::from(self.minute);
        let days = (minutes + zone_minutes).div_euclid(i32::from(HOURS_PER_DAY) * per_hour);
        let mut date = Self {
            hour: 0,
            minute: 0,
            second: 0,
            ..self
        };
        for _ in 0..days.unsigned_abs() {
            date = if days > 0 {
                date.next_day()
            } else {
                date.day_before()
            };
        }
        date
    }

    /// The same time on the next day of the Gregorian calendar.
    fn next_day(self) -> Self {
        if self.day < days_in_month(self.year, self.month) {
            Self {
                day: self.day + 1,
                ..self
            }
        } else if self.month < MONTHS_PER_YEAR {
            Self {
                month: self.month + 1,
                day: 1,
                ..self
            }
        } else {
            Self {
                year: self.year.saturating_add(1),
                month: 1,
                day: 1,
                ..self
            }
        }
    }

    /// The same time on the day before, in the Gregorian calendar.
    fn day_before(self) -> Self {
        if self.day > 1 {
            Self {
                day: self.day - 1,
                ..self
            }
        } else if self.month > 1 {
            let month = self.month - 1;
            Self {
                month,
                day: days_in_month(self.year, month),
                ..self
            }
        } else {
            let year = self.year.saturating_sub(1);
            Self {
                year,
                month: MONTHS_PER_YEAR,
                day: days_in_month(year, MONTHS_PER_YEAR),
                ..self
            }
        }
    }

    /// Reads a time in UTC written as ISO 8601, such as `2018-12-28T13:00:00Z`, the form of
    /// `vt:filetime` values.
    #[must_use]
    pub fn parse_utc(text: &str) -> Option<Self> {
        let text = text.trim().strip_suffix('Z')?;
        let (date, time) = text.split_once('T')?;
        let mut date = date.split('-');
        let mut time = time.split(':');
        let next = |part: Option<&str>| part.and_then(|p| p.split('.').next()?.parse().ok());
        let year: i32 = date.next()?.parse().ok()?;
        let parsed = Self {
            year,
            month: next(date.next())?,
            day: next(date.next())?,
            hour: next(time.next())?,
            minute: next(time.next())?,
            second: next(time.next()).unwrap_or(0),
        };
        let valid = (1..=MONTHS_PER_YEAR).contains(&parsed.month)
            && (1..=MAX_DAY_OF_MONTH).contains(&parsed.day)
            && parsed.hour < HOURS_PER_DAY
            && parsed.minute < MINUTES_PER_HOUR
            && parsed.second < MAX_SECONDS_PER_MINUTE;
        valid.then_some(parsed)
    }

    /// Reads a date written as text: "20 April 2023" or "20 Apr 2023", "April 20, 2023", or
    /// "2023-04-20". The time is midnight.
    #[must_use]
    pub fn parse_text(text: &str) -> Option<Self> {
        let words: Vec<&str> = text.split_whitespace().collect();
        let (year, month, day) = match words.as_slice() {
            [d, m, y] if day_of(d).is_some() => (y.parse().ok()?, month_of(m)?, day_of(d)?),
            [m, d, y] => (y.parse().ok()?, month_of(m)?, day_of(d)?),
            [iso] => iso_date(iso)?,
            _ => return None,
        };
        let valid = (1..=MONTHS_PER_YEAR).contains(&month) && (1..=MAX_DAY_OF_MONTH).contains(&day);
        valid.then_some(Self {
            year,
            month,
            day,
            hour: 0,
            minute: 0,
            second: 0,
        })
    }

    /// The day of the week, from 0 for Sunday, in the Gregorian calendar, also before its
    /// start, for every year of 32 bits.
    fn weekday(self) -> usize {
        // Sakamoto's method for the Gregorian calendar, in `i64`, so that the sum of a year at
        // either end of `i32` fits, with divisions that round down, so that a year before 1
        // keeps the calendar's cycle of 400 years.
        let month = usize::from(self.month.clamp(1, MONTHS_PER_YEAR));
        let year = i64::from(self.year) - i64::from(month < MARCH);
        let shift = i64::from(WEEKDAY_SHIFTS.get(month - 1).copied().unwrap_or(0));
        let (leap, century, cycle) = LEAP_YEAR_CYCLES;
        let years = |cycle: i32| year.div_euclid(i64::from(cycle));
        let day = year + years(leap) - years(century) + years(cycle) + shift + i64::from(self.day);
        usize::try_from(day.rem_euclid(i64::from(DAYS_PER_WEEK))).unwrap_or(0)
    }

    /// Writes the date and time with a date and time picture: `d`, `dd`, `ddd` and `dddd` for
    /// the day and its name, `M` to `MMMM` for the month, `yy` and `yyyy` for the year, `h`,
    /// `hh`, `H` and `HH` for the hour, `m` and `mm` for the minute, `s` and `ss` for the
    /// second, and `AM/PM` or `am/pm`. Text in single quotes and other characters stay as they
    /// are.
    #[must_use]
    pub fn write(self, picture: &str) -> String {
        let chars: Vec<char> = picture.chars().collect();
        let mut out = String::new();
        let mut i = 0;
        while let Some(&ch) = chars.get(i) {
            let rest = chars.get(i..).unwrap_or_default();
            let run = rest.iter().take_while(|&&c| c == ch).count();
            let starts = |text: &str, lower: bool| {
                let text = text
                    .chars()
                    .map(|c| if lower { c.to_ascii_lowercase() } else { c });
                rest.iter().copied().take(AM_PM.len()).eq(text)
            };
            if ch == '\'' {
                let end = chars
                    .get(i + 1..)
                    .and_then(|tail| tail.iter().position(|&c| c == '\''))
                    .map_or(chars.len(), |p| i + 1 + p);
                out.extend(chars.get(i + 1..end).unwrap_or_default());
                i = end + 1;
                continue;
            }
            if starts(AM_PM, false) || starts(AM_PM, true) {
                let pm = self.hour >= HOURS_PER_HALF_DAY;
                let text = match (pm, ch == 'A') {
                    (true, true) => "PM",
                    (false, true) => "AM",
                    (true, false) => "pm",
                    (false, false) => "am",
                };
                out.push_str(text);
                i += AM_PM.len();
                continue;
            }
            let wrote = self.field(ch, run, &mut out);
            if wrote {
                i += run;
            } else {
                // Each letter of a run that is no picture item stays as it is. Only the last
                // one can start `AM/PM`, so the others go at once, and the last one goes
                // through the loop again: the run's letters are counted once.
                let kept = run.saturating_sub(1).max(1);
                out.extend(std::iter::repeat_n(ch, kept));
                i += kept;
            }
        }
        out
    }

    /// Writes one picture item of `count` letters `ch`, and returns whether it is one.
    fn field(self, ch: char, count: usize, out: &mut String) -> bool {
        let number = |out: &mut String, value: u32, width: usize| {
            let _ = write!(out, "{value:0width$}");
        };
        let name = |names: &[&str], index: usize, count: usize| {
            let full = names.get(index).copied().unwrap_or("");
            if count == SHORT_NAME_LETTERS {
                full.chars().take(SHORT_NAME_LETTERS).collect()
            } else {
                full.to_owned()
            }
        };
        let hour12 = match self.hour % HOURS_PER_HALF_DAY {
            0 => HOURS_PER_HALF_DAY,
            h => h,
        };
        match (ch, count) {
            ('d', 1 | 2) => number(out, u32::from(self.day), count),
            ('d', _) => out.push_str(&name(&DAYS, self.weekday(), count.min(FULL_NAME_LETTERS))),
            ('M', 1 | 2) => number(out, u32::from(self.month), count),
            ('M', _) => {
                let index = usize::from(self.month.clamp(1, MONTHS_PER_YEAR)) - 1;
                out.push_str(&name(&MONTHS, index, count.min(FULL_NAME_LETTERS)));
            }
            ('y', 1 | 2) => number(
                out,
                self.year.rem_euclid(YEARS_PER_CENTURY).unsigned_abs(),
                2,
            ),
            ('y', _) => number(out, self.year.unsigned_abs(), YEAR_DIGITS),
            ('h', _) => number(out, u32::from(hour12), count.min(2)),
            ('H', _) => number(out, u32::from(self.hour), count.min(2)),
            ('m', _) => number(out, u32::from(self.minute), count.min(2)),
            ('s', _) => number(out, u32::from(self.second), count.min(2)),
            _ => return false,
        }
        true
    }
}

#[cfg(test)]
mod tests {
    use super::DateTime;

    fn date(year: i32, month: u8, day: u8, hour: u8) -> DateTime {
        DateTime {
            year,
            month,
            day,
            hour,
            minute: 0,
            second: 0,
        }
    }

    #[test]
    fn reads_times_of_date_properties() {
        let utc = DateTime::parse_utc("2018-12-28T13:00:00Z");
        assert_eq!(utc, Some(date(2018, 12, 28, 13)));
        assert_eq!(DateTime::parse_utc("2018-12-28"), None);
        assert_eq!(DateTime::parse_utc("2018-13-28T13:00:00Z"), None);
    }

    #[test]
    fn takes_the_date_of_a_utc_time_in_a_zone_at_midnight() {
        let at = |year, month, day, hour, minute| DateTime {
            year,
            month,
            day,
            hour,
            minute,
            second: 30,
        };
        let day = |year, month, day| date(year, month, day, 0);
        let cases = [
            // Two times early in a UTC day and one late in it, 8 hours east of UTC.
            (at(2026, 1, 15, 3, 30), 480, day(2026, 1, 15)),
            (at(2026, 7, 15, 3, 30), 480, day(2026, 7, 15)),
            (at(2026, 1, 15, 23, 30), 480, day(2026, 1, 16)),
            // The next day ends a month, a year, and February in leap and common years.
            (at(2026, 12, 31, 20, 0), 480, day(2027, 1, 1)),
            (at(2024, 2, 28, 16, 0), 480, day(2024, 2, 29)),
            (at(2023, 2, 28, 16, 0), 480, day(2023, 3, 1)),
            (at(1900, 2, 28, 16, 0), 480, day(1900, 3, 1)),
            (at(2000, 2, 28, 16, 0), 480, day(2000, 2, 29)),
            (at(2026, 4, 30, 15, 59), 480, day(2026, 4, 30)),
            // West of UTC, the day before.
            (at(2026, 3, 1, 2, 0), -300, day(2026, 2, 28)),
            (at(2024, 3, 1, 2, 0), -300, day(2024, 2, 29)),
            (at(2026, 1, 1, 1, 0), -300, day(2025, 12, 31)),
            (at(2026, 5, 1, 4, 59), -300, day(2026, 4, 30)),
            (at(2026, 5, 1, 5, 0), -300, day(2026, 5, 1)),
            // UTC itself drops the time only.
            (at(2026, 1, 15, 23, 59), 0, day(2026, 1, 15)),
        ];
        for (utc, zone, local) in cases {
            assert_eq!(utc.local_date(zone), local, "{utc:?} {zone}");
        }
        assert_eq!(
            day(2026, 1, 15)
                .local_date(480)
                .write(super::PROPERTY_DATE_PICTURE),
            "15/1/2026"
        );
    }

    #[test]
    fn reads_dates_written_as_text() {
        for text in [
            "20 April 2023",
            "20 Apr 2023",
            "April 20, 2023",
            "2023-04-20",
        ] {
            assert_eq!(
                DateTime::parse_text(text),
                Some(date(2023, 4, 20, 0)),
                "{text}"
            );
        }
        for text in ["Unknown", "20 Avril 2023", "32 April 2023", "April"] {
            assert_eq!(DateTime::parse_text(text), None, "{text}");
        }
        assert_eq!(date(2023, 4, 20, 0).write("dd/MM/yyyy"), "20/04/2023");
    }

    const PRINTED: DateTime = DateTime {
        year: 2026,
        month: 9,
        day: 25,
        hour: 14,
        minute: 33,
        second: 2,
    };

    #[test]
    fn writes_dates_and_times_with_pictures() {
        let cases = [
            ("dddd, MMMM d, yyyy", "Friday, September 25, 2026"),
            ("d MMMM yyyy", "25 September 2026"),
            ("yyyy", "2026"),
            ("M/d/yyyy", "9/25/2026"),
            ("dd/MM/yy", "25/09/26"),
            ("ddd d MMM", "Fri 25 Sep"),
            ("dd/MM/yyyy H:mm:ss", "25/09/2026 14:33:02"),
            ("d/M/yyyy h:mm AM/PM", "25/9/2026 2:33 PM"),
            ("h:mm am/pm", "2:33 pm"),
            ("'Week of' d MMMM", "Week of 25 September"),
            ("d.M.yyyy", "25.9.2026"),
            // Letters that are no picture item stay, and the last of a run can start AM/PM.
            ("xxAAAM/PM zz", "xxAAPM zz"),
            ("aaam/pm aAM/PM", "aapm aPM"),
            ("AAM/P", "AA9/P"),
            // A save or print date without a picture, in whole minutes.
            (super::SAVED_DATE_PICTURE, "9/25/2026 2:33:00 PM"),
        ];
        for (picture, text) in cases {
            assert_eq!(PRINTED.write(picture), text, "{picture}");
        }
    }

    #[test]
    fn finds_the_day_of_the_week() {
        let day = |year, month, day| DateTime {
            year,
            month,
            day,
            hour: 0,
            minute: 0,
            second: 0,
        };
        assert_eq!(day(2026, 9, 25).write("dddd"), "Friday");
        assert_eq!(day(2000, 1, 1).write("dddd"), "Saturday");
        assert_eq!(day(2024, 2, 29).write("dddd"), "Thursday");
        assert_eq!(day(2026, 11, 5).write("dddd"), "Thursday");
    }

    #[test]
    fn finds_the_day_of_the_week_at_the_ends_of_32_bits_and_before_the_year_1() {
        let day = |year, month, day| DateTime {
            year,
            month,
            day,
            hour: 0,
            minute: 0,
            second: 0,
        };
        // The calendar repeats every 400 years: these are the days of 1 January 47, 1 January
        // 352, 31 December 47, and 1 January and 1 March 399.
        assert_eq!(day(i32::MAX, 1, 1).write("dddd"), "Tuesday");
        assert_eq!(day(i32::MIN, 1, 1).write("dddd"), "Tuesday");
        assert_eq!(day(i32::MAX, 12, 31).write("dddd"), "Tuesday");
        assert_eq!(day(-1, 1, 1).write("dddd"), "Friday");
        assert_eq!(day(-1, 3, 1).write("dddd"), "Monday");
    }
}