Skip to main content

Buffer

Struct Buffer 

Source
pub struct Buffer {
    pub area: Rect,
    pub content: Vec<Cell>,
}
Expand description

A buffer that maps to the desired content of the terminal after the draw call

No widget in the library interacts directly with the terminal. Instead each of them is required to draw their state to an intermediate buffer. It is basically a grid where each cell contains a grapheme, a foreground color and a background color. This grid will then be used to output the appropriate escape sequences and characters to draw the UI as the user has defined it.

ยงExamples:

use ratatui::{
    buffer::{Buffer, Cell},
    layout::{Position, Rect},
    style::{Color, Style},
};

let mut buf = Buffer::empty(Rect {
    x: 0,
    y: 0,
    width: 10,
    height: 5,
});

// indexing using Position
buf[Position { x: 0, y: 0 }].set_symbol("A");
assert_eq!(buf[Position { x: 0, y: 0 }].symbol(), "A");

// indexing using (x, y) tuple (which is converted to Position)
buf[(0, 1)].set_symbol("B");
assert_eq!(buf[(0, 1)].symbol(), "x");

// getting an Option instead of panicking if the position is outside the buffer
let cell = buf.cell_mut(Position { x: 0, y: 2 })?;
cell.set_symbol("C");

let cell = buf.cell(Position { x: 0, y: 2 })?;
assert_eq!(cell.symbol(), "C");

buf.set_string(
    3,
    0,
    "string",
    Style::default().fg(Color::Red).bg(Color::White),
);
let cell = &buf[(5, 0)]; // cannot move out of buf, so we borrow it
assert_eq!(cell.symbol(), "r");
assert_eq!(cell.fg, Color::Red);
assert_eq!(cell.bg, Color::White);

Fieldsยง

ยงarea: Rect

The area represented by this buffer

ยงcontent: Vec<Cell>

The content of the buffer. The length of this Vec should always be equal to area.width * area.height

Implementationsยง

Sourceยง

impl Buffer

Source

pub fn empty(area: Rect) -> Buffer

Returns a Buffer with all cells set to the default one

Source

pub fn filled(area: Rect, cell: Cell) -> Buffer

Returns a Buffer with all cells initialized with the attributes of the given Cell

Source

pub fn with_lines<'a, Iter>(lines: Iter) -> Buffer
where Iter: IntoIterator, <Iter as IntoIterator>::Item: Into<Line<'a>>,

Returns a Buffer containing the given lines

Source

pub fn content(&self) -> &[Cell]

Returns the content of the buffer as a slice

Source

pub const fn area(&self) -> &Rect

Returns the area covered by this buffer

Source

pub fn get(&self, x: u16, y: u16) -> &Cell

๐Ÿ‘ŽDeprecated:

Use Buffer[] or Buffer::cell instead

Returns a reference to the Cell at the given coordinates

Callers should use Buffer[] or Buffer::cell instead of this method.

Note: idiomatically methods named get usually return Option<&T>, but this method panics instead. This is kept for backwards compatibility. See cell for a safe alternative.

ยงPanics

Panics if the index is out of bounds.

Source

pub fn get_mut(&mut self, x: u16, y: u16) -> &mut Cell

๐Ÿ‘ŽDeprecated:

Use Buffer[] or Buffer::cell_mut instead

Returns a mutable reference to the Cell at the given coordinates.

Callers should use Buffer[] or Buffer::cell_mut instead of this method.

Note: idiomatically methods named get_mut usually return Option<&mut T>, but this method panics instead. This is kept for backwards compatibility. See cell_mut for a safe alternative.

ยงPanics

Panics if the position is outside the Bufferโ€™s area.

Source

pub fn cell<P>(&self, position: P) -> Option<&Cell>
where P: Into<Position>,

Returns a reference to the Cell at the given position or None if the position is outside the Bufferโ€™s area.

This method accepts any value that can be converted to Position (e.g. (x, y) or Position::new(x, y)).

For a method that panics when the position is outside the buffer instead of returning None, use Buffer[].

ยงExamples
let mut buffer = Buffer::empty(Rect::new(0, 0, 10, 10));

assert_eq!(buffer.cell(Position::new(0, 0)), Some(&Cell::default()));
assert_eq!(buffer.cell(Position::new(10, 10)), None);
assert_eq!(buffer.cell((0, 0)), Some(&Cell::default()));
assert_eq!(buffer.cell((10, 10)), None);
Source

pub fn cell_mut<P>(&mut self, position: P) -> Option<&mut Cell>
where P: Into<Position>,

Returns a mutable reference to the Cell at the given position or None if the position is outside the Bufferโ€™s area.

This method accepts any value that can be converted to Position (e.g. (x, y) or Position::new(x, y)).

For a method that panics when the position is outside the buffer instead of returning None, use Buffer[].

ยงExamples
let mut buffer = Buffer::empty(Rect::new(0, 0, 10, 10));

if let Some(cell) = buffer.cell_mut(Position::new(0, 0)) {
    cell.set_symbol("A");
}
if let Some(cell) = buffer.cell_mut((0, 0)) {
    cell.set_style(Style::default().fg(Color::Red));
}
Source

pub fn index_of(&self, x: u16, y: u16) -> usize

Returns the index in the Vec<Cell> for the given global (x, y) coordinates.

Global coordinates are offset by the Bufferโ€™s area offset (x/y).

ยงExamples
let buffer = Buffer::empty(Rect::new(200, 100, 10, 10));
// Global coordinates to the top corner of this buffer's area
assert_eq!(buffer.index_of(200, 100), 0);
ยงPanics

Panics when given an coordinate that is outside of this Bufferโ€™s area.

โ“˜
let buffer = Buffer::empty(Rect::new(200, 100, 10, 10));
// Top coordinate is outside of the buffer in global coordinate space, as the Buffer's area
// starts at (200, 100).
buffer.index_of(0, 0); // Panics
Source

pub fn pos_of(&self, i: usize) -> (u16, u16)

Returns the (global) coordinates of a cell given its index

Global coordinates are offset by the Bufferโ€™s area offset (x/y).

ยงExamples
let rect = Rect::new(200, 100, 10, 10);
let buffer = Buffer::empty(rect);
assert_eq!(buffer.pos_of(0), (200, 100));
assert_eq!(buffer.pos_of(14), (204, 101));
ยงPanics

Panics when given an index that is outside the Bufferโ€™s content.

โ“˜
let rect = Rect::new(0, 0, 10, 10); // 100 cells in total
let buffer = Buffer::empty(rect);
// Index 100 is the 101th cell, which lies outside of the area of this Buffer.
buffer.pos_of(100); // Panics
Source

pub fn set_string<T, S>(&mut self, x: u16, y: u16, string: T, style: S)
where T: AsRef<str>, S: Into<Style>,

Print a string, starting at the position (x, y)

Source

pub fn set_stringn<T, S>( &mut self, x: u16, y: u16, string: T, max_width: usize, style: S, ) -> (u16, u16)
where T: AsRef<str>, S: Into<Style>,

Print at most the first n characters of a string if enough space is available until the end of the line. Skips zero-width graphemes and control characters.

Use Buffer::set_string when the maximum amount of characters can be printed.

Source

pub fn set_line( &mut self, x: u16, y: u16, line: &Line<'_>, max_width: u16, ) -> (u16, u16)

Print a line, starting at the position (x, y)

Source

pub fn set_span( &mut self, x: u16, y: u16, span: &Span<'_>, max_width: u16, ) -> (u16, u16)

Print a span, starting at the position (x, y)

Source

pub fn set_style<S>(&mut self, area: Rect, style: S)
where S: Into<Style>,

Set the style of all cells in the given area.

style accepts any type that is convertible to Style (e.g. Style, Color, or your own type that implements Into<Style>).

Source

pub fn resize(&mut self, area: Rect)

Resize the buffer so that the mapped area matches the given area and that the buffer length is equal to area.width * area.height

Source

pub fn reset(&mut self)

Reset all cells in the buffer

Source

pub fn merge(&mut self, other: &Buffer)

Merge an other buffer into this one

Source

pub fn diff<'a>(&self, other: &'a Buffer) -> Vec<(u16, u16, &'a Cell)>

Builds a minimal sequence of coordinates and Cells necessary to update the UI from self to other.

Weโ€™re assuming that buffers are well-formed, that is no double-width cell is followed by a non-blank cell.

ยงMulti-width characters handling:
(Index:) `01`
Prev:    `ใ‚ณ`
Next:    `aa`
Updates: `0: a, 1: a'
(Index:) `01`
Prev:    `a `
Next:    `ใ‚ณ`
Updates: `0: ใ‚ณ` (double width symbol at index 0 - skip index 1)
(Index:) `012`
Prev:    `aaa`
Next:    `aใ‚ณ`
Updates: `0: a, 1: ใ‚ณ` (double width symbol at index 1 - skip index 2)

Trait Implementationsยง

Sourceยง

impl Clone for Buffer

Sourceยง

fn clone(&self) -> Buffer

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 Buffer

Sourceยง

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

Writes a debug representation of the buffer to the given formatter.

The format is like a pretty printed struct, with the following fields:

  • area: displayed as Rect { x: 1, y: 2, width: 3, height: 4 }
  • content: displayed as a list of strings representing the content of the buffer
  • styles: displayed as a list of: { x: 1, y: 2, fg: Color::Red, bg: Color::Blue, modifier: Modifier::BOLD } only showing a value when there is a change in style.
Sourceยง

impl Default for Buffer

Sourceยง

fn default() -> Buffer

Returns the โ€œdefault valueโ€ for a type. Read more
Sourceยง

impl Eq for Buffer

Sourceยง

impl Hash for Buffer

Sourceยง

fn hash<__H>(&self, state: &mut __H)
where __H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 ยท Sourceยง

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Sourceยง

impl<P> Index<P> for Buffer
where P: Into<Position>,

Sourceยง

fn index(&self, position: P) -> &<Buffer as Index<P>>::Output

Returns a reference to the Cell at the given position.

This method accepts any value that can be converted to Position (e.g. (x, y) or Position::new(x, y)).

ยงPanics

May panic if the given position is outside the bufferโ€™s area. For a method that returns None instead of panicking, use Buffer::cell.

ยงExamples
let buf = Buffer::empty(Rect::new(0, 0, 10, 10));
let cell = &buf[(0, 0)];
let cell = &buf[Position::new(0, 0)];
Sourceยง

type Output = Cell

The returned type after indexing.
Sourceยง

impl<P> IndexMut<P> for Buffer
where P: Into<Position>,

Sourceยง

fn index_mut(&mut self, position: P) -> &mut <Buffer as Index<P>>::Output

Returns a mutable reference to the Cell at the given position.

This method accepts any value that can be converted to Position (e.g. (x, y) or Position::new(x, y)).

ยงPanics

May panic if the given position is outside the bufferโ€™s area. For a method that returns None instead of panicking, use Buffer::cell_mut.

ยงExamples
let mut buf = Buffer::empty(Rect::new(0, 0, 10, 10));
buf[(0, 0)].set_symbol("A");
buf[Position::new(0, 0)].set_symbol("B");
Sourceยง

impl PartialEq for Buffer

Sourceยง

fn eq(&self, other: &Buffer) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) ยท Sourceยง

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Sourceยง

impl StructuralPartialEq for Buffer

Auto Trait Implementationsยง

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> 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<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> Downcast for T
where T: Any,

Sourceยง

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Sourceยง

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Sourceยง

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Anyโ€™s vtable from &Traitโ€™s.
Sourceยง

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Anyโ€™s vtable from &mut Traitโ€™s.
Sourceยง

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Sourceยง

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send> โ“˜

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Sourceยง

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Sourceยง

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
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<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.