Skip to main content

DocBuf

Struct DocBuf 

Source
pub struct DocBuf { /* private fields */ }
Expand description

A layout document: an arena of layout nodes, with its pools of text, children, rows, cells, columns and tables.

An emitter builds a layout document by calling the constructors (text, line, group, …), innermost parts first. Each returns the DocId of the node it creates, which the emitter passes to the constructors of the enclosing nodes; the id of the outermost node is the root that print and print_full take. The module documentation lists the constructors and describes the representation.

§Requirements

An id is meaningful only for the arena that created it, and clear makes every id given out before it meaningless; giving such an id to the printer is a caller error (see print).

§Panics

Every constructor panics if the arena or one of its pools would grow past u32::MAX entries (about four billion nodes, children, rows, cells, columns or tables, or four gigabytes of text), a size no document reaches; the panic message gives the pool.

Implementations§

Source§

impl DocBuf

Source

pub fn new() -> Self

Creates an empty layout document.

Source

pub fn clear(&mut self)

Removes every node and pool entry and keeps the allocated capacity, so that the arena can be reused for the next render. Every DocId given out before the call becomes meaningless.

Source

pub fn len(&self) -> usize

The number of nodes in the arena.

Source

pub fn is_empty(&self) -> bool

Whether the arena holds no nodes.

Source

pub fn text(&mut self, s: &str) -> DocId

Creates an atom: a text, already in its final form (escaped if the output format needs it), that the printer writes as one unit.

The printer never splits an atom at the width limit (an atom wider than the room left on the line is written whole, and the line is longer than the width) and never changes it. An atom’s width is measured in display columns (display_width).

§Requirements

An atom must not contain '\n': a line break is expressed with hardline or blocksep. It must not contain '\t' either, which has no fixed display width: an emitter expands tabs into spaces when it builds atoms, or writes text holding tabs through raw.

§Panics

In a debug build, if s contains '\n' or '\t': the requirements above are checked by a debug assertion. A release build writes such an atom as it is, and the column count of that line is then wrong. In any build, if the arena’s node or text pool would overflow (see DocBuf).

Source

pub fn line(&mut self) -> DocId

Creates a break opportunity that prints as one space if the enclosing group stays on one line (prints flat), and as a line break if the group breaks.

The space is written only when a content character follows it on the same line: an unbroken line at the end of a line leaves no trailing whitespace, and an unbroken line at the start of a line is dropped.

§Panics

If the arena’s node pool would overflow (see DocBuf).

Source

pub fn softbreak(&mut self) -> DocId

Creates a break opportunity that prints as nothing if the enclosing group stays on one line, and as a line break if the group breaks.

§Panics

If the arena’s node pool would overflow (see DocBuf).

Source

pub fn hardline(&mut self) -> DocId

Creates an unconditional line break. It also makes every enclosing group break, because a group that contains a line break cannot print on one line.

Two adjacent hardlines produce a single newline: blank lines come only from blocksep.

§Panics

If the arena’s node pool would overflow (see DocBuf).

Source

pub fn nest(&mut self, columns: u16, child: DocId) -> DocId

Indents child by columns columns more than the enclosing indentation.

The indentation applies from the next line start on: it is a unit of the printer’s indentation stack, written at the start of every line that begins inside child.

§Panics

If the arena’s node pool would overflow (see DocBuf).

Source

pub fn align(&mut self, child: DocId) -> DocId

Indents child to the column at which it starts: a hanging indent.

The second and later lines of child start under its first character. text(" • ") followed by align(body) lays out a list item whose wrapped lines start under the item’s first word. If that column is to the left of the enclosing indentation (which can happen when a deeper nest starts in the middle of a line), the enclosing indentation applies instead.

§Panics

If the arena’s node pool would overflow (see DocBuf).

Source

pub fn group(&mut self, child: DocId) -> DocId

Creates a group: a unit whose break opportunities all stay unbroken or all break.

The printer prints child flat (every line a space, every softbreak nothing) if child, together with everything that follows it on the same line, fits within the width; otherwise every break opportunity directly inside child becomes a line break (the break opportunities inside a nested group follow that group’s own decision). The printer’s module documentation describes the exact test.

§Panics

If the arena’s node pool would overflow (see DocBuf).

Source

pub fn concat(&mut self, ids: &[DocId]) -> DocId

Creates a sequence of the nodes ids, printed in that order.

§Panics

If the arena’s node or children pool would overflow (see DocBuf).

Source

pub fn blocksep(&mut self, blank_lines: u8) -> DocId

Creates a separation between two blocks: a line break followed by blank_lines blank lines.

Adjacent requests for a line break are merged into one, which keeps the larger number of blank lines (the numbers are never added), so nested containers can each ask for the separation they need without producing runs of blank lines. A line break at the very start or end of the output is dropped.

§Panics

If the arena’s node pool would overflow (see DocBuf).

Source

pub fn prefix(&mut self, prefix: &str, child: DocId) -> DocId

Writes prefix before every line of child (> for a quotation, // for a comment block).

The prefix is a unit of the indentation stack, like an indentation written as text rather than spaces: it combines with nest and align in nesting order, and its width is subtracted from the width available for wrapping (text inside prefix("> ", ..) wraps two columns earlier). A blank line inside child is written with the prefix trimmed of trailing whitespace (>), so a quoted passage remains one quotation across its paragraphs.

§Examples

Two paragraphs inside one prefix: the blank line between them is written with the prefix trimmed of its trailing space.

use flm_core::layout::{DocBuf, Profile, print};

let mut b = DocBuf::new();
let first = b.text("one");
let gap = b.blocksep(1);
let second = b.text("two");
let body = b.concat(&[first, gap, second]);
let quoted = b.prefix("> ", body);

assert_eq!(print(&b, quoted, &Profile::new(Some(40))), "> one\n>\n> two\n");
§Requirements

Like an atom, a prefix must not contain '\n' or '\t'.

§Panics

In a debug build, if prefix contains '\n' or '\t': the requirement above is checked by a debug assertion. In any build, if the arena’s node or text pool would overflow (see DocBuf).

Source

pub fn raw(&mut self, content: &str, policy: RawPolicy) -> DocId

Creates a verbatim block: text written as it is, never reflowed, never split and never escaped.

Unlike an atom, content may contain '\n' and '\t'. A newline inside content is part of the content, not a request for a line break, so runs of blank lines inside the block are kept exactly. A newline at the end of content is treated as a request for a line break and merged with the requests around it, so raw("code\n") followed by blocksep(1) gives one blank line, not two. An empty content prints nothing. policy says whether the enclosing indentation applies to the lines of the block.

A block of several lines makes its enclosing groups break; a block of one line is measured like an atom. Tabs are written unchanged and counted as one column each. The printer never breaks a raw line, regardless of its width: a raw line longer than the line width is written as it is.

§Panics

If the arena’s node or text pool would overflow (see DocBuf).

Source

pub fn mark(&mut self, id: MarkId, child: DocId) -> DocId

Marks child, so that print_full reports where it is printed, under the identifier id.

A mark has no width and does not change the layout: the printer prints child as if the mark were not there, and records one MarkSpan in the result of print_full. Marks may be nested; a marked node that appears several times in the document (a shared node) is reported once per occurrence.

§Panics

If the arena’s node pool would overflow (see DocBuf).

Source

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

Creates a table: one ColSpec per column in cols, and the rows of cells in rows.

Each cell is a TableCell: any node of the same arena and, optionally, an alignment of its own that replaces its column’s for that cell alone. A row may be given as DocIds, which are cells that follow their columns. Rows may have fewer cells than there are columns (the missing cells at the end of a row are empty); cells beyond cols.len() are ignored. header_rows is the number of leading rows that form the header; a rule is drawn after them (0 means no header). frame is how the table is drawn around and between its cells (TableFrame): a gutter of two spaces between the columns and a rule of -, or a frame of box-drawing characters.

border_mark, when given, is the mark under which print_full reports the characters the table draws itself: one MarkSpan per maximal run of such characters on a line (a whole rule or frame line; each bar of a line of the rows on its own; the padding spaces are not part of any run), in the order they are written, after the spans of the marks opened before the table.

§How the columns are laid out

The printer lays a table out in four steps:

  1. Measure. Every cell is printed twice on its own: at width 1, where every break opportunity breaks, and with no width limit, where only unconditional line breaks break. A column’s minimum is the widest line of its cells printed at width 1 (its widest part that cannot be broken, indentation included); its maximum is the widest line printed with no limit. A cell can be wider at width 1 than with no limit (when its indentation grows as it breaks), so the maximum is raised to the minimum where it is smaller.
  2. Compute the widths. The available width is the profile’s width minus the enclosing indentation and the table’s own drawing: the gutters (two spaces between adjacent columns) under TableFrame::Gutter, three columns per column and one more under TableFrame::Box (a bar and two spaces of padding per column, and the closing bar). If the maxima of all columns fit, or the profile has no width, each column gets its maximum. Otherwise each column starts at its minimum, and the remaining width is shared out in proportion to each column’s room to grow (maximum minus minimum), in whole columns: each column first gets the whole part of its share, then the columns with the largest fractional parts get one more column each until the width is used up (on equal fractional parts, the column further left first), and no column grows past its maximum. If even the minima do not fit, every column gets its minimum and the lines are longer than the width, because atoms are never split.
  3. Print the cells. Every cell is printed at its column’s width with an empty indentation stack; the table’s own indentation applies to the assembled lines, so a table inside a list or a quotation is indented and prefixed correctly.
  4. Assemble. The rows are assembled line by line, with every cell at the top of its row: a row is as tall as its tallest cell. Each cell is padded to its column’s width in its own alignment, or in its column’s where it has none. Under TableFrame::Gutter, columns are separated by the gutter, trailing whitespace is removed from every line (the padding, and any trailing whitespace of the last cell’s own text), and the rule of - follows the header rows. Under TableFrame::Box, every line of the rows ends with its closing bar, the frame’s lines come above the first row and below the last, and its rule follows the header rows when rows follow them.

A table is a block: it starts on a line of its own and ends its last line. A table that prints nothing (no columns, no rows, or only empty cells) is not a block and leaves the surrounding line as it is.

The marks inside the cells are reported where the cells’ text lands in the table, after the spans of the marks opened before the table and after the runs of the border mark, row by row and column by column. A mark over several lines of a cell gives one span per line of the cell, because the table interleaves the cell’s lines with the rest of the row (see the printer module, section 5).

§Examples
use flm_core::layout::{ColSpec, DocBuf, Profile, TableFrame, print};

let mut b = DocBuf::new();
let name = b.text("name");
let count = b.text("count");
let alpha = b.text("alpha");
let three = b.text("3");
let t = b.table(
    &[ColSpec::left(), ColSpec::right()],
    &[&[name, count], &[alpha, three]],
    1,
    TableFrame::Gutter,
    None,
);

assert_eq!(
    print(&b, t, &Profile::new(Some(40))),
    "name   count\n-----  -----\nalpha      3\n"
);

A cell with an alignment of its own, in a left-aligned column:

use flm_core::layout::{ColAlign, ColSpec, DocBuf, Profile, TableCell, TableFrame, print};

let mut b = DocBuf::new();
let wide = b.text("a wide cell");
let right = b.text("right");
let t = b.table(
    &[ColSpec::left()],
    &[&[TableCell::new(wide)], &[TableCell::aligned(right, ColAlign::Right)]],
    0,
    TableFrame::Gutter,
    None,
);

assert_eq!(print(&b, t, &Profile::new(Some(40))), "a wide cell\n      right\n");

A framed table, with the characters it draws reported under a mark:

use flm_core::layout::{ColSpec, DocBuf, MarkId, Profile, TableFrame, print_full};

let mut b = DocBuf::new();
let name = b.text("name");
let alpha = b.text("alpha");
let t = b.table(
    &[ColSpec::left()],
    &[&[name], &[alpha]],
    1,
    TableFrame::Box,
    Some(MarkId(0)),
);

let out = print_full(&b, t, &Profile::new(Some(40)));
assert_eq!(out.text, "┌───────┐\n│ name  │\n├───────┤\n│ alpha │\n└───────┘\n");
let runs: Vec<&str> = out.marks.iter().map(|m| &out.text[m.bytes.clone()]).collect();
assert_eq!(runs, ["┌───────┐", "│", "│", "├───────┤", "│", "│", "└───────┘"]);
§Panics

If the arena’s node, column, row, cell or table pool would overflow (see DocBuf).

Source

pub fn fill_words(&mut self, s: &str) -> DocId

Creates prose: the words of s, separated by spaces that each break independently of the others.

This is a combination of the other constructors, and its exact shape matters: each space between two words is its own group(line()), so each space decides on its own whether to stay a space or become a line break. Because the printer’s test for a group looks past the group to what follows on the line, this gives correct greedy wrapping, including before a trailing text that has no break opportunity of its own. One group around a whole paragraph would instead give one line longer than the width, or a line break at every space.

s is split at breakable whitespace (is_breakable_space), which is dropped; the words become atoms. A non-breaking space (U+00A0 no-break space, U+2007 figure space, U+202F narrow no-break space) stays inside the word it joins, so an author’s request not to break there is kept. An s holding only breakable whitespace gives an empty sequence.

§Panics

If the arena’s node, text or children pool would overflow (see DocBuf).

Trait Implementations§

Source§

impl Clone for DocBuf

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DocBuf

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for DocBuf

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl Forget for DocBuf

§

impl Freeze for DocBuf

§

impl Move for DocBuf

§

impl RefUnwindSafe for DocBuf

§

impl Send for DocBuf

§

impl Sync for DocBuf

§

impl Unpin for DocBuf

§

impl UnsafeUnpin for DocBuf

§

impl UnwindSafe for DocBuf

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Az for T

Source§

fn az<Dst>(self) -> Dst
where T: Cast<Dst>,

Casts the value.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<Src, Dst> CastFrom<Src> for Dst
where Src: Cast<Dst>,

Source§

fn cast_from(src: Src) -> Dst

Casts the value.
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CheckedAs for T

Source§

fn checked_as<Dst>(self) -> Option<Dst>
where T: CheckedCast<Dst>,

Casts the value.
Source§

impl<Src, Dst> CheckedCastFrom<Src> for Dst
where Src: CheckedCast<Dst>,

Source§

fn checked_cast_from(src: Src) -> Option<Dst>

Casts the value.
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<Src, Dst> LosslessTryInto<Dst> for Src
where Dst: LosslessTryFrom<Src>,

Source§

fn lossless_try_into(self) -> Option<Dst>

Performs the conversion.
Source§

impl<Src, Dst> LossyInto<Dst> for Src
where Dst: LossyFrom<Src>,

Source§

fn lossy_into(self) -> Dst

Performs the conversion.
Source§

impl<T> OverflowingAs for T

Source§

fn overflowing_as<Dst>(self) -> (Dst, bool)
where T: OverflowingCast<Dst>,

Casts the value.
Source§

impl<Src, Dst> OverflowingCastFrom<Src> for Dst
where Src: OverflowingCast<Dst>,

Source§

fn overflowing_cast_from(src: Src) -> (Dst, bool)

Casts the value.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> SaturatingAs for T

Source§

fn saturating_as<Dst>(self) -> Dst
where T: SaturatingCast<Dst>,

Casts the value.
Source§

impl<Src, Dst> SaturatingCastFrom<Src> for Dst
where Src: SaturatingCast<Dst>,

Source§

fn saturating_cast_from(src: Src) -> Dst

Casts the value.
Source§

impl<T> StrictAs for T

Source§

fn strict_as<Dst>(self) -> Dst
where T: StrictCast<Dst>,

Casts the value.
Source§

impl<Src, Dst> StrictCastFrom<Src> for Dst
where Src: StrictCast<Dst>,

Source§

fn strict_cast_from(src: Src) -> Dst

Casts the value.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> UnwrappedAs for T

Source§

fn unwrapped_as<Dst>(self) -> Dst
where T: UnwrappedCast<Dst>,

Casts the value.
Source§

impl<Src, Dst> UnwrappedCastFrom<Src> for Dst
where Src: UnwrappedCast<Dst>,

Source§

fn unwrapped_cast_from(src: Src) -> Dst

Casts the value.
Source§

impl<T> WrappingAs for T

Source§

fn wrapping_as<Dst>(self) -> Dst
where T: WrappingCast<Dst>,

Casts the value.
Source§

impl<Src, Dst> WrappingCastFrom<Src> for Dst
where Src: WrappingCast<Dst>,

Source§

fn wrapping_cast_from(src: Src) -> Dst

Casts the value.