use std::ops::Range;
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct DocId(u32);
impl DocId {
#[inline]
pub fn index(self) -> usize {
self.0 as usize
}
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct MarkId(pub u32);
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum RawPolicy {
Indented,
Exempt,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ColAlign {
Left,
Right,
Center,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct ColSpec {
pub align: ColAlign,
}
impl ColSpec {
pub fn left() -> Self {
ColSpec {
align: ColAlign::Left,
}
}
pub fn right() -> Self {
ColSpec {
align: ColAlign::Right,
}
}
pub fn center() -> Self {
ColSpec {
align: ColAlign::Center,
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum TableFrame {
Gutter,
Box,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct TableCell {
pub doc: DocId,
pub align: Option<ColAlign>,
}
impl TableCell {
pub fn new(doc: DocId) -> Self {
TableCell { doc, align: None }
}
pub fn aligned(doc: DocId, align: ColAlign) -> Self {
TableCell {
doc,
align: Some(align),
}
}
}
impl From<DocId> for TableCell {
fn from(doc: DocId) -> Self {
TableCell::new(doc)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) struct PoolRange {
start: u32,
end: u32,
}
impl PoolRange {
#[inline]
fn as_range(self) -> Range<usize> {
self.start as usize..self.end as usize
}
}
#[inline]
fn pool_len(len: usize, pool: &str) -> u32 {
assert!(
len <= u32::MAX as usize,
"the {pool} pool of the layout document must hold at most u32::MAX entries (bytes, \
for the text pool)"
);
len as u32
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum Node {
Text(PoolRange),
Line,
SoftBreak,
HardLine,
Nest { indent: u16, child: DocId },
Align { child: DocId },
Group { child: DocId },
Concat(PoolRange),
BlockSep { blank_lines: u8 },
Prefix { prefix: PoolRange, child: DocId },
Raw { content: PoolRange, policy: RawPolicy },
Table { def: u32 },
Mark { id: MarkId, child: DocId },
FlushRight { gap: u16, child: DocId },
Ruled { def: u32 },
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) struct TableDef {
pub(crate) rows: PoolRange,
pub(crate) cols: PoolRange,
pub(crate) header_rows: u8,
pub(crate) frame: TableFrame,
pub(crate) border_mark: Option<MarkId>,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) struct RuledDef {
pub(crate) child: DocId,
pub(crate) rule: char,
pub(crate) above: bool,
pub(crate) below: bool,
pub(crate) mark: Option<MarkId>,
}
#[derive(Clone, Default, Debug)]
pub struct DocBuf {
nodes: Vec<Node>,
text: String,
children: Vec<DocId>,
rows: Vec<PoolRange>,
cells: Vec<TableCell>,
cols: Vec<ColSpec>,
tables: Vec<TableDef>,
rules: Vec<RuledDef>,
}
impl DocBuf {
pub fn new() -> Self {
Self::default()
}
pub fn clear(&mut self) {
self.nodes.clear();
self.text.clear();
self.children.clear();
self.rows.clear();
self.cells.clear();
self.cols.clear();
self.tables.clear();
self.rules.clear();
}
pub fn len(&self) -> usize {
self.nodes.len()
}
pub fn is_empty(&self) -> bool {
self.nodes.is_empty()
}
#[inline]
pub(crate) fn node(&self, id: DocId) -> Node {
self.nodes[id.0 as usize]
}
#[inline]
pub(crate) fn text_at(&self, range: PoolRange) -> &str {
&self.text[range.as_range()]
}
#[inline]
pub(crate) fn children_at(&self, range: PoolRange) -> &[DocId] {
&self.children[range.as_range()]
}
#[inline]
pub(crate) fn table_def(&self, def: u32) -> TableDef {
self.tables[def as usize]
}
#[inline]
pub(crate) fn ruled_def(&self, def: u32) -> RuledDef {
self.rules[def as usize]
}
#[inline]
pub(crate) fn rows_at(&self, range: PoolRange) -> &[PoolRange] {
&self.rows[range.as_range()]
}
#[inline]
pub(crate) fn cells_at(&self, range: PoolRange) -> &[TableCell] {
&self.cells[range.as_range()]
}
#[inline]
pub(crate) fn cols_at(&self, range: PoolRange) -> &[ColSpec] {
&self.cols[range.as_range()]
}
#[inline]
fn push(&mut self, node: Node) -> DocId {
let id = pool_len(self.nodes.len(), "node");
self.nodes.push(node);
DocId(id)
}
fn intern(&mut self, s: &str) -> PoolRange {
let start = pool_len(self.text.len(), "text");
self.text.push_str(s);
let end = pool_len(self.text.len(), "text");
PoolRange { start, end }
}
pub fn text(&mut self, s: &str) -> DocId {
debug_assert!(
!s.contains('\n'),
"text atoms must not contain newlines; use hardline()/blocksep()"
);
debug_assert!(
!s.contains('\t'),
"text atoms must not contain tabs; expand them or use raw()"
);
let range = self.intern(s);
self.push(Node::Text(range))
}
pub fn line(&mut self) -> DocId {
self.push(Node::Line)
}
pub fn softbreak(&mut self) -> DocId {
self.push(Node::SoftBreak)
}
pub fn hardline(&mut self) -> DocId {
self.push(Node::HardLine)
}
pub fn nest(&mut self, columns: u16, child: DocId) -> DocId {
self.push(Node::Nest {
indent: columns,
child,
})
}
pub fn align(&mut self, child: DocId) -> DocId {
self.push(Node::Align { child })
}
pub fn group(&mut self, child: DocId) -> DocId {
self.push(Node::Group { child })
}
pub fn concat(&mut self, ids: &[DocId]) -> DocId {
let start = pool_len(self.children.len(), "children");
self.children.extend_from_slice(ids);
let end = pool_len(self.children.len(), "children");
self.push(Node::Concat(PoolRange { start, end }))
}
pub fn blocksep(&mut self, blank_lines: u8) -> DocId {
self.push(Node::BlockSep { blank_lines })
}
pub fn prefix(&mut self, prefix: &str, child: DocId) -> DocId {
debug_assert!(
!prefix.contains('\n'),
"a line prefix must not contain newlines"
);
debug_assert!(!prefix.contains('\t'), "a line prefix must not contain tabs");
let range = self.intern(prefix);
self.push(Node::Prefix {
prefix: range,
child,
})
}
pub fn raw(&mut self, content: &str, policy: RawPolicy) -> DocId {
let range = self.intern(content);
self.push(Node::Raw {
content: range,
policy,
})
}
pub fn mark(&mut self, id: MarkId, child: DocId) -> DocId {
self.push(Node::Mark { id, child })
}
pub fn table<C>(
&mut self,
cols: &[ColSpec],
rows: &[&[C]],
header_rows: u8,
frame: TableFrame,
border_mark: Option<MarkId>,
) -> DocId
where
C: Copy + Into<TableCell>,
{
let cols_start = pool_len(self.cols.len(), "column");
self.cols.extend_from_slice(cols);
let cols_end = pool_len(self.cols.len(), "column");
let rows_start = pool_len(self.rows.len(), "row");
let mut ranges = Vec::with_capacity(rows.len());
for row in rows {
let start = pool_len(self.cells.len(), "cell");
self.cells.extend(row.iter().map(|&cell| cell.into()));
let end = pool_len(self.cells.len(), "cell");
ranges.push(PoolRange { start, end });
}
self.rows.extend_from_slice(&ranges);
let rows_end = pool_len(self.rows.len(), "row");
let def = pool_len(self.tables.len(), "table");
self.tables.push(TableDef {
rows: PoolRange {
start: rows_start,
end: rows_end,
},
cols: PoolRange {
start: cols_start,
end: cols_end,
},
header_rows,
frame,
border_mark,
});
self.push(Node::Table { def })
}
pub fn flush_right(&mut self, child: DocId, gap: u16) -> DocId {
self.push(Node::FlushRight { gap, child })
}
pub fn ruled(
&mut self,
child: DocId,
rule: char,
above: bool,
below: bool,
mark: Option<MarkId>,
) -> DocId {
debug_assert!(
!rule.is_control() && super::display_width(rule.encode_utf8(&mut [0; 4])) == 1,
"the character of a rule line must be one column wide"
);
let def = pool_len(self.rules.len(), "rule");
self.rules.push(RuledDef {
child,
rule,
above,
below,
mark,
});
self.push(Node::Ruled { def })
}
pub fn fill_words(&mut self, s: &str) -> DocId {
let mut parts: Vec<DocId> = Vec::new();
for word in s.split(is_breakable_space).filter(|word| !word.is_empty()) {
if !parts.is_empty() {
let l = self.line();
parts.push(self.group(l));
}
parts.push(self.text(word));
}
self.concat(&parts)
}
}
pub fn is_breakable_space(c: char) -> bool {
c.is_whitespace() && !matches!(c, '\u{00A0}' | '\u{2007}' | '\u{202F}')
}