typst_library/layout/
fragment.rs

1use std::fmt::{self, Debug, Formatter};
2
3use crate::layout::Frame;
4
5/// A partial layout result.
6#[derive(Clone)]
7pub struct Fragment(Vec<Frame>);
8
9impl Fragment {
10    /// Create a fragment from a single frame.
11    pub fn frame(frame: Frame) -> Self {
12        Self(vec![frame])
13    }
14
15    /// Create a fragment from multiple frames.
16    pub fn frames(frames: Vec<Frame>) -> Self {
17        Self(frames)
18    }
19
20    /// Return `true` if the length is 0.
21    pub fn is_empty(&self) -> bool {
22        self.0.is_empty()
23    }
24
25    /// The number of frames in the fragment.
26    pub fn len(&self) -> usize {
27        self.0.len()
28    }
29
30    /// Extract the first and only frame.
31    ///
32    /// Panics if there are multiple frames.
33    #[track_caller]
34    pub fn into_frame(self) -> Frame {
35        assert_eq!(self.0.len(), 1, "expected exactly one frame");
36        self.0.into_iter().next().unwrap()
37    }
38
39    /// Extract the frames.
40    pub fn into_frames(self) -> Vec<Frame> {
41        self.0
42    }
43
44    /// Extract a slice with the contained frames.
45    pub fn as_slice(&self) -> &[Frame] {
46        &self.0
47    }
48
49    /// Iterate over the contained frames.
50    pub fn iter(&self) -> std::slice::Iter<Frame> {
51        self.0.iter()
52    }
53
54    /// Iterate over the contained frames.
55    pub fn iter_mut(&mut self) -> std::slice::IterMut<Frame> {
56        self.0.iter_mut()
57    }
58}
59
60impl Debug for Fragment {
61    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
62        match self.0.as_slice() {
63            [frame] => frame.fmt(f),
64            frames => frames.fmt(f),
65        }
66    }
67}
68
69impl IntoIterator for Fragment {
70    type Item = Frame;
71    type IntoIter = std::vec::IntoIter<Frame>;
72
73    fn into_iter(self) -> Self::IntoIter {
74        self.0.into_iter()
75    }
76}
77
78impl<'a> IntoIterator for &'a Fragment {
79    type Item = &'a Frame;
80    type IntoIter = std::slice::Iter<'a, Frame>;
81
82    fn into_iter(self) -> Self::IntoIter {
83        self.0.iter()
84    }
85}
86
87impl<'a> IntoIterator for &'a mut Fragment {
88    type Item = &'a mut Frame;
89    type IntoIter = std::slice::IterMut<'a, Frame>;
90
91    fn into_iter(self) -> Self::IntoIter {
92        self.0.iter_mut()
93    }
94}