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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
//! The pictures of the art page borders, such as `apples`, which the caller adds beside the
//! fonts: for each art style and size, the picture that each side of a page border repeats or
//! spans and the picture of each corner, as filled outlines in the box of their part.
//!
//! The pictures come in a text form of their own, one or more styles and sizes in each file:
//!
//! ```text
//! f-office art pictures 3
//! style <name> <size in points>
//! part <top|bottom|left|right> <repeat|span>
//! part <top-left|top-right|bottom-left|bottom-right> corner
//! clip <nonzero|evenodd>
//! shape <red> <green> <blue> <nonzero|evenodd>
//! ring <x> <y> [L <x> <y> | Q <x> <y> <x> <y> | C <x> <y> <x> <y> <x> <y>] ...
//! rect <red> <green> <blue> <left> <top> <right> <bottom> <stroke width>
//! end
//! ```
//!
//! Each point is in millionths of its part's box, across from its left edge and down from its
//! top edge, in the page's own axes. A ring starts at its first point and goes on by lines
//! (`L`), quadratic curves (`Q`) and cubic curves (`C`) back to it. A shape is one filled path
//! of one or more rings. A rect is a filled rectangle with its edges in millionths of the box,
//! which the target's writer fills and strokes with an outline of the stroke width, in
//! thousandths of a point, whatever the picture's size: the writer holds its edges as it holds
//! a filled rectangle's. A clip is an outline of one or more rings: the shapes and clips after
//! its rings, up to its `end` in the same part, show only inside it, as a stroke that a picture
//! clips to its own path shows only its inner half. A `repeat` part is the picture of each
//! square along its side, a `span` part one picture from corner to corner, and a side can have
//! both.

use f_office_paint::{FillRule, Rgb};
use f_office_units::Edges;
use std::fmt;

use crate::params::ART_STROKE_UNIT;
use crate::props::ArtStyle;

pub use crate::params::{
    ART_PICTURES_BYTE_LIMIT, ART_PICTURES_CLIP_DEPTH_LIMIT, ART_PICTURES_COMMAND_LIMIT,
    ART_PICTURES_REACH_LIMIT, ART_PICTURES_SHAPE_LIMIT, ART_PICTURES_SIZE_LIMIT,
};

/// The first line of the form.
const HEADER: &str = "f-office art pictures 3";

/// One box, in the parts in which the points are given.
pub(crate) const UNIT: i32 = crate::params::ART_PICTURE_UNIT;

/// The pictures of the art page borders that a caller gives, by art style and size. An empty set,
/// the default, draws no art border: the layout leaves each side of an art style out, with a
/// warning ([`crate::Warning::ArtBorderNotDrawn`]).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ArtPictures {
    /// The pictures, in the order of their style and size, each key once.
    pictures: Vec<ArtPicture>,
}

/// The picture of one art style at one size: what each side repeats or spans, and each corner.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct ArtPicture {
    /// The art style.
    style: ArtStyle,
    /// The size, in points (`w:sz` of an art side).
    size: u32,
    /// The pictures of each side.
    pub sides: Edges<SidePicture>,
    /// The picture of each corner square.
    pub corners: Corners<Vec<ArtItem>>,
}

/// The shapes of one side of an art border.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct SidePicture {
    /// The items that each square along the side holds, in the box of the square.
    pub repeat: Vec<ArtItem>,
    /// The items that run along the whole side, in the box from corner to corner.
    pub span: Vec<ArtItem>,
}

/// A value for each corner of a page border.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct Corners<T> {
    /// The top left corner.
    pub top_left: T,
    /// The top right corner.
    pub top_right: T,
    /// The bottom left corner.
    pub bottom_left: T,
    /// The bottom right corner.
    pub bottom_right: T,
}

/// One item of a picture, in painting order.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum ArtItem {
    /// A filled path.
    Shape(ArtShape),
    /// A filled rectangle with an outline around it.
    Rect(ArtRect),
    /// The start of a clip: the items up to its [`ArtItem::End`] show only inside it.
    Clip(ArtClip),
    /// The end of the last clip that is open.
    End,
}

/// The outline of a clip of a picture.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ArtClip {
    /// The rule that decides which points lie inside the outline.
    pub fill_rule: FillRule,
    /// The outlines, each a move, its steps and a close.
    pub commands: Vec<UnitCommand>,
}

/// One filled path of a picture.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ArtShape {
    /// The fill color: black takes the side's color.
    pub color: Rgb,
    /// The rule that decides which points lie inside the path.
    pub fill_rule: FillRule,
    /// The outlines, each a move, its steps and a close.
    pub commands: Vec<UnitCommand>,
}

/// One filled rectangle of a picture, which the target's writer fills and strokes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct ArtRect {
    /// The fill color: black takes the side's color.
    pub color: Rgb,
    /// The top left corner, in millionths of the part's box.
    pub top_left: UnitPoint,
    /// The bottom right corner, in millionths of the part's box.
    pub bottom_right: UnitPoint,
    /// The width of the outline that the writer strokes around the rectangle, in thousandths
    /// of a point at every size of the picture.
    pub stroke: u32,
}

/// One command of a shape's outline, with points in millionths of the part's box.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum UnitCommand {
    /// Starts an outline.
    Move(UnitPoint),
    /// A straight line.
    Line(UnitPoint),
    /// A quadratic curve through a control point.
    Quad(UnitPoint, UnitPoint),
    /// A cubic curve through two control points.
    Cubic(UnitPoint, UnitPoint, UnitPoint),
    /// Back to the start of the outline.
    Close,
}

/// A point in millionths of a part's box: across from its left edge and down from its top edge.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct UnitPoint {
    /// Across.
    pub x: i32,
    /// Down.
    pub y: i32,
}

/// Why a file of art pictures does not read, and on which line.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ArtPicturesError {
    /// The line, from 1, or 0 for the file as a whole.
    pub line: usize,
    /// What is wrong.
    pub fault: ArtPicturesFault,
}

/// What is wrong with a file of art pictures.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ArtPicturesFault {
    /// The file holds more than [`ART_PICTURES_BYTE_LIMIT`] bytes.
    TooLarge,
    /// The file is not UTF-8 text.
    NotText,
    /// The first line is not the form's own.
    Header,
    /// A `style` line names no art style, or its size is no whole number from 1 to
    /// [`ART_PICTURES_SIZE_LIMIT`].
    Style,
    /// A `part` line names no part or kind, or comes before a `style` line.
    Part,
    /// A `shape` line has no color or fill rule, or comes before a `part` line.
    Shape,
    /// A `clip` line has no fill rule, or comes before a `part` line.
    Clip,
    /// A `rect` line has a color, an edge or a stroke width that does not read, an edge beyond
    /// [`ART_PICTURES_REACH_LIMIT`], a right edge left of its left edge or a bottom edge above
    /// its top edge, a stroke width wider than the largest picture, or comes before a `part`
    /// line.
    Rect,
    /// An `end` line ends no open clip, or a `style` or `part` line or the file's end comes while
    /// a clip is open.
    End,
    /// A `ring` line has a command or number that does not read, a point beyond
    /// [`ART_PICTURES_REACH_LIMIT`], or comes neither after a `shape` or `clip` line nor after
    /// one of its rings.
    Ring,
    /// A line of another kind.
    Unknown,
    /// A part holds more than [`ART_PICTURES_SHAPE_LIMIT`] items.
    TooManyShapes,
    /// A shape's or a clip's outline holds more than [`ART_PICTURES_COMMAND_LIMIT`] commands.
    TooManyCommands,
    /// More than [`ART_PICTURES_CLIP_DEPTH_LIMIT`] clips are open at once.
    TooDeep,
}

impl fmt::Display for ArtPicturesError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let what = match self.fault {
            ArtPicturesFault::TooLarge => "the file is too large",
            ArtPicturesFault::NotText => "the file is not UTF-8 text",
            ArtPicturesFault::Header => "the file does not start with the form's first line",
            ArtPicturesFault::Style => "a style line does not read",
            ArtPicturesFault::Part => "a part line does not read",
            ArtPicturesFault::Shape => "a shape line does not read",
            ArtPicturesFault::Clip => "a clip line does not read",
            ArtPicturesFault::Rect => "a rect line does not read",
            ArtPicturesFault::End => "a clip does not end where it should",
            ArtPicturesFault::Ring => "a ring line does not read",
            ArtPicturesFault::Unknown => "a line is of no kind of the form",
            ArtPicturesFault::TooManyShapes => "a part holds too many items",
            ArtPicturesFault::TooManyCommands => "an outline holds too many commands",
            ArtPicturesFault::TooDeep => "too many clips are open at once",
        };
        if self.line == 0 {
            write!(f, "the art pictures do not read: {what}")
        } else {
            write!(
                f,
                "the art pictures do not read: {what} (line {})",
                self.line
            )
        }
    }
}

impl std::error::Error for ArtPicturesError {}

impl ArtPictures {
    /// No pictures.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            pictures: Vec::new(),
        }
    }

    /// Reads the pictures of a file of the form and adds them, and returns how many it read. A
    /// picture of a style and size that the set holds already takes its place. A file that does
    /// not read adds nothing.
    ///
    /// # Errors
    ///
    /// Returns the line and the fault when the file does not read.
    pub fn add(&mut self, bytes: &[u8]) -> Result<usize, ArtPicturesError> {
        let read = read(bytes)?;
        let count = read.len();
        for picture in read {
            let key = (picture.style, picture.size);
            match self
                .pictures
                .binary_search_by_key(&key, |held| (held.style, held.size))
            {
                Ok(index) => {
                    if let Some(slot) = self.pictures.get_mut(index) {
                        *slot = picture;
                    }
                }
                Err(index) => self.pictures.insert(index, picture),
            }
        }
        Ok(count)
    }

    /// How many pictures the set holds: one for each style and size.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.pictures.len()
    }

    /// Whether the set holds no picture.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.pictures.is_empty()
    }

    /// The picture of `style` at `size` points, if the set holds it.
    pub(crate) fn picture(&self, style: ArtStyle, size: u32) -> Option<&ArtPicture> {
        let index = self
            .pictures
            .binary_search_by_key(&(style, size), |held| (held.style, held.size))
            .ok()?;
        self.pictures.get(index)
    }
}

/// Where the next shapes of a file go.
#[derive(Clone, Copy)]
enum Slot {
    /// What a side repeats.
    Repeat(Side),
    /// What a side spans.
    Span(Side),
    /// A corner.
    Corner(Corner),
}

/// A side of a page border.
#[derive(Clone, Copy)]
enum Side {
    Top,
    Bottom,
    Left,
    Right,
}

/// A corner of a page border.
#[derive(Clone, Copy)]
enum Corner {
    TopLeft,
    TopRight,
    BottomLeft,
    BottomRight,
}

impl ArtPicture {
    /// The items of `slot`.
    const fn items_mut(&mut self, slot: Slot) -> &mut Vec<ArtItem> {
        match slot {
            Slot::Repeat(Side::Top) => &mut self.sides.top.repeat,
            Slot::Repeat(Side::Bottom) => &mut self.sides.bottom.repeat,
            Slot::Repeat(Side::Left) => &mut self.sides.left.repeat,
            Slot::Repeat(Side::Right) => &mut self.sides.right.repeat,
            Slot::Span(Side::Top) => &mut self.sides.top.span,
            Slot::Span(Side::Bottom) => &mut self.sides.bottom.span,
            Slot::Span(Side::Left) => &mut self.sides.left.span,
            Slot::Span(Side::Right) => &mut self.sides.right.span,
            Slot::Corner(Corner::TopLeft) => &mut self.corners.top_left,
            Slot::Corner(Corner::TopRight) => &mut self.corners.top_right,
            Slot::Corner(Corner::BottomLeft) => &mut self.corners.bottom_left,
            Slot::Corner(Corner::BottomRight) => &mut self.corners.bottom_right,
        }
    }
}

/// The pictures of a file of the form, in the order of the file.
fn read(bytes: &[u8]) -> Result<Vec<ArtPicture>, ArtPicturesError> {
    let whole = |fault| ArtPicturesError { line: 0, fault };
    if bytes.len() > ART_PICTURES_BYTE_LIMIT {
        return Err(whole(ArtPicturesFault::TooLarge));
    }
    let text = std::str::from_utf8(bytes).map_err(|_| whole(ArtPicturesFault::NotText))?;
    let mut lines = text
        .lines()
        .enumerate()
        .map(|(index, line)| (index + 1, line));
    match lines.next() {
        Some((_, line)) if line.trim_end() == HEADER => {}
        _ => {
            return Err(ArtPicturesError {
                line: 1,
                fault: ArtPicturesFault::Header,
            });
        }
    }
    let mut reading = Reading::default();
    for (number, line) in lines {
        let mut words = line.split_ascii_whitespace();
        let Some(kind) = words.next() else {
            continue;
        };
        reading
            .line(kind, &mut words)
            .map_err(|fault| ArtPicturesError {
                line: number,
                fault,
            })?;
    }
    if reading.open_clips > 0 {
        return Err(whole(ArtPicturesFault::End));
    }
    Ok(reading.pictures)
}

/// What a file has given so far.
#[derive(Default)]
struct Reading {
    /// The pictures, in the order of the file.
    pictures: Vec<ArtPicture>,
    /// Where the next items go.
    slot: Option<Slot>,
    /// The clips of the current part that have not ended.
    open_clips: usize,
}

impl Reading {
    /// Reads one line of the kind `kind`, with the rest of its words `words`.
    fn line<'a>(
        &mut self,
        kind: &str,
        words: &mut impl Iterator<Item = &'a str>,
    ) -> Result<(), ArtPicturesFault> {
        if matches!(kind, "style" | "part") && self.open_clips > 0 {
            return Err(ArtPicturesFault::End);
        }
        match kind {
            "style" => {
                self.pictures.push(read_style(words)?);
                self.slot = None;
            }
            "part" => {
                if self.pictures.is_empty() {
                    return Err(ArtPicturesFault::Part);
                }
                let read = match (words.next(), words.next(), words.next()) {
                    (Some(name), Some(kind), None) => part_slot(name, kind),
                    _ => None,
                };
                self.slot = Some(read.ok_or(ArtPicturesFault::Part)?);
            }
            "shape" => {
                self.items().ok_or(ArtPicturesFault::Shape)?;
                let shape = read_shape(words).ok_or(ArtPicturesFault::Shape)?;
                self.push(ArtItem::Shape(shape))?;
            }
            "rect" => {
                self.items().ok_or(ArtPicturesFault::Rect)?;
                let rect = read_rect(words).ok_or(ArtPicturesFault::Rect)?;
                self.push(ArtItem::Rect(rect))?;
            }
            "clip" => {
                self.items().ok_or(ArtPicturesFault::Clip)?;
                let clip = read_clip(words).ok_or(ArtPicturesFault::Clip)?;
                if self.open_clips >= ART_PICTURES_CLIP_DEPTH_LIMIT {
                    return Err(ArtPicturesFault::TooDeep);
                }
                self.push(ArtItem::Clip(clip))?;
                self.open_clips += 1;
            }
            "end" => {
                if self.open_clips == 0 || words.next().is_some() {
                    return Err(ArtPicturesFault::End);
                }
                self.push(ArtItem::End)?;
                self.open_clips -= 1;
            }
            "ring" => {
                let commands = match self.items().and_then(|items| items.last_mut()) {
                    Some(ArtItem::Shape(shape)) => &mut shape.commands,
                    Some(ArtItem::Clip(clip)) => &mut clip.commands,
                    _ => return Err(ArtPicturesFault::Ring),
                };
                read_ring(words, commands)?;
            }
            _ => return Err(ArtPicturesFault::Unknown),
        }
        Ok(())
    }

    /// The items of the current part, if a `part` line has given one.
    fn items(&mut self) -> Option<&mut Vec<ArtItem>> {
        let slot = self.slot?;
        Some(self.pictures.last_mut()?.items_mut(slot))
    }

    /// Adds `item` to the current part, within [`ART_PICTURES_SHAPE_LIMIT`].
    fn push(&mut self, item: ArtItem) -> Result<(), ArtPicturesFault> {
        let items = self.items().ok_or(ArtPicturesFault::Unknown)?;
        if items.len() >= ART_PICTURES_SHAPE_LIMIT {
            return Err(ArtPicturesFault::TooManyShapes);
        }
        items.push(item);
        Ok(())
    }
}

/// The picture of the rest of a `style` line: its art style and size, with no parts yet.
fn read_style<'a>(
    words: &mut impl Iterator<Item = &'a str>,
) -> Result<ArtPicture, ArtPicturesFault> {
    let style = words
        .next()
        .and_then(ArtStyle::of_name)
        .ok_or(ArtPicturesFault::Style)?;
    let size = words
        .next()
        .and_then(|size| size.parse::<u32>().ok())
        .filter(|size| (1..=ART_PICTURES_SIZE_LIMIT).contains(size))
        .ok_or(ArtPicturesFault::Style)?;
    if words.next().is_some() {
        return Err(ArtPicturesFault::Style);
    }
    Ok(ArtPicture {
        style,
        size,
        ..ArtPicture::default()
    })
}

/// The slot of a `part` line's part and kind.
fn part_slot(name: &str, kind: &str) -> Option<Slot> {
    let side = match name {
        "top" => Some(Side::Top),
        "bottom" => Some(Side::Bottom),
        "left" => Some(Side::Left),
        "right" => Some(Side::Right),
        _ => None,
    };
    let corner = match name {
        "top-left" => Some(Corner::TopLeft),
        "top-right" => Some(Corner::TopRight),
        "bottom-left" => Some(Corner::BottomLeft),
        "bottom-right" => Some(Corner::BottomRight),
        _ => None,
    };
    match (side, corner, kind) {
        (Some(side), None, "repeat") => Some(Slot::Repeat(side)),
        (Some(side), None, "span") => Some(Slot::Span(side)),
        (None, Some(corner), "corner") => Some(Slot::Corner(corner)),
        _ => None,
    }
}

/// The color that the next three words give, red, green and blue, each from 0 to 255.
fn read_color<'a>(words: &mut impl Iterator<Item = &'a str>) -> Option<Rgb> {
    let mut channel = || words.next().and_then(|word| word.parse::<u8>().ok());
    let (r, g, b) = (channel()?, channel()?, channel()?);
    Some(Rgb { r, g, b })
}

/// The shape of the rest of a `shape` line: its color and fill rule, with no outline yet.
fn read_shape<'a>(words: &mut impl Iterator<Item = &'a str>) -> Option<ArtShape> {
    let color = read_color(words)?;
    let fill_rule = read_fill_rule(words)?;
    Some(ArtShape {
        color,
        fill_rule,
        commands: Vec::new(),
    })
}

/// The rectangle of the rest of a `rect` line: its color, its edges within
/// [`ART_PICTURES_REACH_LIMIT`], each right or bottom edge at or after its left or top edge,
/// and its stroke width, at most the side of the largest picture.
fn read_rect<'a>(words: &mut impl Iterator<Item = &'a str>) -> Option<ArtRect> {
    let color = read_color(words)?;
    let mut edge = || {
        words
            .next()
            .and_then(|word| word.parse::<i32>().ok())
            .filter(|value| value.abs() <= ART_PICTURES_REACH_LIMIT)
    };
    let top_left = UnitPoint {
        x: edge()?,
        y: edge()?,
    };
    let bottom_right = UnitPoint {
        x: edge()?,
        y: edge()?,
    };
    let stroke = words
        .next()
        .and_then(|word| word.parse::<u32>().ok())
        .filter(|stroke| *stroke <= ART_PICTURES_SIZE_LIMIT.saturating_mul(ART_STROKE_UNIT))?;
    let ordered = top_left.x <= bottom_right.x && top_left.y <= bottom_right.y;
    (ordered && words.next().is_none()).then_some(ArtRect {
        color,
        top_left,
        bottom_right,
        stroke,
    })
}

/// The clip of the rest of a `clip` line: its fill rule, with no outline yet.
fn read_clip<'a>(words: &mut impl Iterator<Item = &'a str>) -> Option<ArtClip> {
    Some(ArtClip {
        fill_rule: read_fill_rule(words)?,
        commands: Vec::new(),
    })
}

/// The fill rule that ends a `shape` or `clip` line, the line's last word.
fn read_fill_rule<'a>(words: &mut impl Iterator<Item = &'a str>) -> Option<FillRule> {
    let fill_rule = match words.next()? {
        "nonzero" => FillRule::NonZero,
        "evenodd" => FillRule::EvenOdd,
        _ => return None,
    };
    words.next().is_none().then_some(fill_rule)
}

/// Adds the outline of the rest of a `ring` line to `commands`: a move to its first point, its
/// steps and a close.
fn read_ring<'a>(
    words: &mut impl Iterator<Item = &'a str>,
    commands: &mut Vec<UnitCommand>,
) -> Result<(), ArtPicturesFault> {
    let mut next = vec![UnitCommand::Move(read_point(words)?)];
    loop {
        let command = match words.next() {
            None => break,
            Some("L") => UnitCommand::Line(read_point(words)?),
            Some("Q") => UnitCommand::Quad(read_point(words)?, read_point(words)?),
            Some("C") => {
                UnitCommand::Cubic(read_point(words)?, read_point(words)?, read_point(words)?)
            }
            Some(_) => return Err(ArtPicturesFault::Ring),
        };
        next.push(command);
        if commands.len() + next.len() >= ART_PICTURES_COMMAND_LIMIT {
            return Err(ArtPicturesFault::TooManyCommands);
        }
    }
    next.push(UnitCommand::Close);
    commands.append(&mut next);
    Ok(())
}

/// The next point of a `ring` line: two whole numbers within [`ART_PICTURES_REACH_LIMIT`].
fn read_point<'a>(
    words: &mut impl Iterator<Item = &'a str>,
) -> Result<UnitPoint, ArtPicturesFault> {
    let mut number = || {
        words
            .next()
            .and_then(|word| word.parse::<i32>().ok())
            .filter(|value| value.abs() <= ART_PICTURES_REACH_LIMIT)
            .ok_or(ArtPicturesFault::Ring)
    };
    let x = number()?;
    Ok(UnitPoint { x, y: number()? })
}

#[cfg(test)]
mod tests;