aboutsummaryrefslogtreecommitdiff
path: root/alacritty_terminal/src/grid
diff options
context:
space:
mode:
authorChristian Duerr <contact@christianduerr.com>2020-11-05 04:45:14 +0000
committerGitHub <noreply@github.com>2020-11-05 04:45:14 +0000
commitec42b42ce601808070462111c0c28edb0e89babb (patch)
tree48006abca4497f66307f3b4d485bb1f162f4bf32 /alacritty_terminal/src/grid
parent9028fb451a967d69a9e258a083ba64b052a9a5dd (diff)
downloadr-alacritty-ec42b42ce601808070462111c0c28edb0e89babb.tar.gz
r-alacritty-ec42b42ce601808070462111c0c28edb0e89babb.tar.bz2
r-alacritty-ec42b42ce601808070462111c0c28edb0e89babb.zip
Use dynamic storage for zerowidth characters
The zerowidth characters were conventionally stored in a [char; 5]. This creates problems both by limiting the maximum number of zerowidth characters and by increasing the cell size beyond what is necessary even when no zerowidth characters are used. Instead of storing zerowidth characters as a slice, a new CellExtra struct is introduced which can store arbitrary optional cell data that is rarely required. Since this is stored behind an optional pointer (Option<Box<CellExtra>>), the initialization and dropping in the case of no extra data are extremely cheap and the size penalty to cells without this extra data is limited to 8 instead of 20 bytes. The most noticible difference with this PR should be a reduction in memory size of up to at least 30% (1.06G -> 733M, 100k scrollback, 72 lines, 280 columns). Since the zerowidth characters are now stored dynamically, the limit of 5 per cell is also no longer present.
Diffstat (limited to 'alacritty_terminal/src/grid')
-rw-r--r--alacritty_terminal/src/grid/mod.rs95
-rw-r--r--alacritty_terminal/src/grid/resize.rs47
-rw-r--r--alacritty_terminal/src/grid/row.rs54
-rw-r--r--alacritty_terminal/src/grid/storage.rs415
-rw-r--r--alacritty_terminal/src/grid/tests.rs42
5 files changed, 333 insertions, 320 deletions
diff --git a/alacritty_terminal/src/grid/mod.rs b/alacritty_terminal/src/grid/mod.rs
index 5ab25c78..70dbc936 100644
--- a/alacritty_terminal/src/grid/mod.rs
+++ b/alacritty_terminal/src/grid/mod.rs
@@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize};
use crate::ansi::{CharsetIndex, StandardCharset};
use crate::index::{Column, IndexRange, Line, Point};
-use crate::term::cell::{Cell, Flags};
+use crate::term::cell::{Flags, ResetDiscriminant};
pub mod resize;
mod row;
@@ -49,25 +49,24 @@ impl<T: PartialEq> ::std::cmp::PartialEq for Grid<T> {
}
}
-pub trait GridCell {
+pub trait GridCell: Sized {
+ /// Check if the cell contains any content.
fn is_empty(&self) -> bool;
+
+ /// Perform an opinionated cell reset based on a template cell.
+ fn reset(&mut self, template: &Self);
+
fn flags(&self) -> &Flags;
fn flags_mut(&mut self) -> &mut Flags;
-
- /// Fast equality approximation.
- ///
- /// This is a faster alternative to [`PartialEq`],
- /// but might report unequal cells as equal.
- fn fast_eq(&self, other: Self) -> bool;
}
-#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
-pub struct Cursor {
+#[derive(Debug, Default, Clone, PartialEq, Eq)]
+pub struct Cursor<T> {
/// The location of this cursor.
pub point: Point,
/// Template cell when using this cursor.
- pub template: Cell,
+ pub template: T,
/// Currently configured graphic character sets.
pub charsets: Charsets,
@@ -131,11 +130,11 @@ impl IndexMut<CharsetIndex> for Charsets {
pub struct Grid<T> {
/// Current cursor for writing data.
#[serde(skip)]
- pub cursor: Cursor,
+ pub cursor: Cursor<T>,
/// Last saved cursor.
#[serde(skip)]
- pub saved_cursor: Cursor,
+ pub saved_cursor: Cursor<T>,
/// Lines in the grid. Each row holds a list of cells corresponding to the
/// columns in that row.
@@ -167,10 +166,10 @@ pub enum Scroll {
Bottom,
}
-impl<T: GridCell + Default + PartialEq + Copy> Grid<T> {
- pub fn new(lines: Line, cols: Column, max_scroll_limit: usize, template: T) -> Grid<T> {
+impl<T: GridCell + Default + PartialEq + Clone> Grid<T> {
+ pub fn new(lines: Line, cols: Column, max_scroll_limit: usize) -> Grid<T> {
Grid {
- raw: Storage::with_capacity(lines, Row::new(cols, template)),
+ raw: Storage::with_capacity(lines, cols),
max_scroll_limit,
display_offset: 0,
saved_cursor: Cursor::default(),
@@ -203,10 +202,10 @@ impl<T: GridCell + Default + PartialEq + Copy> Grid<T> {
};
}
- fn increase_scroll_limit(&mut self, count: usize, template: T) {
+ fn increase_scroll_limit(&mut self, count: usize) {
let count = min(count, self.max_scroll_limit - self.history_size());
if count != 0 {
- self.raw.initialize(count, template, self.cols);
+ self.raw.initialize(count, self.cols);
}
}
@@ -219,7 +218,11 @@ impl<T: GridCell + Default + PartialEq + Copy> Grid<T> {
}
#[inline]
- pub fn scroll_down(&mut self, region: &Range<Line>, positions: Line, template: T) {
+ pub fn scroll_down<D>(&mut self, region: &Range<Line>, positions: Line)
+ where
+ T: ResetDiscriminant<D>,
+ D: PartialEq,
+ {
// Whether or not there is a scrolling region active, as long as it
// starts at the top, we can do a full rotation which just involves
// changing the start index.
@@ -238,7 +241,7 @@ impl<T: GridCell + Default + PartialEq + Copy> Grid<T> {
// Finally, reset recycled lines.
for i in IndexRange(Line(0)..positions) {
- self.raw[i].reset(template);
+ self.raw[i].reset(&self.cursor.template);
}
} else {
// Subregion rotation.
@@ -247,7 +250,7 @@ impl<T: GridCell + Default + PartialEq + Copy> Grid<T> {
}
for line in IndexRange(region.start..(region.start + positions)) {
- self.raw[line].reset(template);
+ self.raw[line].reset(&self.cursor.template);
}
}
}
@@ -255,7 +258,11 @@ impl<T: GridCell + Default + PartialEq + Copy> Grid<T> {
/// Move lines at the bottom toward the top.
///
/// This is the performance-sensitive part of scrolling.
- pub fn scroll_up(&mut self, region: &Range<Line>, positions: Line, template: T) {
+ pub fn scroll_up<D>(&mut self, region: &Range<Line>, positions: Line)
+ where
+ T: ResetDiscriminant<D>,
+ D: PartialEq,
+ {
let num_lines = self.screen_lines().0;
if region.start == Line(0) {
@@ -264,7 +271,7 @@ impl<T: GridCell + Default + PartialEq + Copy> Grid<T> {
self.display_offset = min(self.display_offset + *positions, self.max_scroll_limit);
}
- self.increase_scroll_limit(*positions, template);
+ self.increase_scroll_limit(*positions);
// Rotate the entire line buffer. If there's a scrolling region
// active, the bottom lines are restored in the next step.
@@ -284,7 +291,7 @@ impl<T: GridCell + Default + PartialEq + Copy> Grid<T> {
//
// Recycled lines are just above the end of the scrolling region.
for i in 0..*positions {
- self.raw[i + fixed_lines].reset(template);
+ self.raw[i + fixed_lines].reset(&self.cursor.template);
}
} else {
// Subregion rotation.
@@ -294,12 +301,16 @@ impl<T: GridCell + Default + PartialEq + Copy> Grid<T> {
// Clear reused lines.
for line in IndexRange((region.end - positions)..region.end) {
- self.raw[line].reset(template);
+ self.raw[line].reset(&self.cursor.template);
}
}
}
- pub fn clear_viewport(&mut self, template: T) {
+ pub fn clear_viewport<D>(&mut self)
+ where
+ T: ResetDiscriminant<D>,
+ D: PartialEq,
+ {
// Determine how many lines to scroll up by.
let end = Point { line: 0, col: self.cols() };
let mut iter = self.iter_from(end);
@@ -316,26 +327,30 @@ impl<T: GridCell + Default + PartialEq + Copy> Grid<T> {
self.display_offset = 0;
// Clear the viewport.
- self.scroll_up(&region, positions, template);
+ self.scroll_up(&region, positions);
// Reset rotated lines.
for i in positions.0..self.lines.0 {
- self.raw[i].reset(template);
+ self.raw[i].reset(&self.cursor.template);
}
}
/// Completely reset the grid state.
- pub fn reset(&mut self, template: T) {
+ pub fn reset<D>(&mut self)
+ where
+ T: ResetDiscriminant<D>,
+ D: PartialEq,
+ {
self.clear_history();
- // Reset all visible lines.
- for row in 0..self.raw.len() {
- self.raw[row].reset(template);
- }
-
self.saved_cursor = Cursor::default();
self.cursor = Cursor::default();
self.display_offset = 0;
+
+ // Reset all visible lines.
+ for row in 0..self.raw.len() {
+ self.raw[row].reset(&self.cursor.template);
+ }
}
}
@@ -372,15 +387,15 @@ impl<T> Grid<T> {
/// This is used only for initializing after loading ref-tests.
#[inline]
- pub fn initialize_all(&mut self, template: T)
+ pub fn initialize_all(&mut self)
where
- T: Copy + GridCell,
+ T: GridCell + Clone + Default,
{
// Remove all cached lines to clear them of any content.
self.truncate();
// Initialize everything with empty new lines.
- self.raw.initialize(self.max_scroll_limit - self.history_size(), template, self.cols);
+ self.raw.initialize(self.max_scroll_limit - self.history_size(), self.cols);
}
/// This is used only for truncating before saving ref-tests.
@@ -753,8 +768,8 @@ impl<'a, T: 'a> DisplayIter<'a, T> {
}
}
-impl<'a, T: Copy + 'a> Iterator for DisplayIter<'a, T> {
- type Item = Indexed<T>;
+impl<'a, T: 'a> Iterator for DisplayIter<'a, T> {
+ type Item = Indexed<&'a T>;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
@@ -765,7 +780,7 @@ impl<'a, T: Copy + 'a> Iterator for DisplayIter<'a, T> {
// Get the next item.
let item = Some(Indexed {
- inner: self.grid.raw[self.offset][self.col],
+ inner: &self.grid.raw[self.offset][self.col],
line: self.line,
column: self.col,
});
diff --git a/alacritty_terminal/src/grid/resize.rs b/alacritty_terminal/src/grid/resize.rs
index acdc040e..1a16e09e 100644
--- a/alacritty_terminal/src/grid/resize.rs
+++ b/alacritty_terminal/src/grid/resize.rs
@@ -1,16 +1,24 @@
//! Grid resize and reflow.
use std::cmp::{min, Ordering};
+use std::mem;
use crate::index::{Column, Line};
-use crate::term::cell::Flags;
+use crate::term::cell::{Flags, ResetDiscriminant};
use crate::grid::row::Row;
use crate::grid::{Dimensions, Grid, GridCell};
-impl<T: GridCell + Default + PartialEq + Copy> Grid<T> {
+impl<T: GridCell + Default + PartialEq + Clone> Grid<T> {
/// Resize the grid's width and/or height.
- pub fn resize(&mut self, reflow: bool, lines: Line, cols: Column) {
+ pub fn resize<D>(&mut self, reflow: bool, lines: Line, cols: Column)
+ where
+ T: ResetDiscriminant<D>,
+ D: PartialEq,
+ {
+ // Use empty template cell for resetting cells due to resize.
+ let template = mem::take(&mut self.cursor.template);
+
match self.lines.cmp(&lines) {
Ordering::Less => self.grow_lines(lines),
Ordering::Greater => self.shrink_lines(lines),
@@ -22,6 +30,9 @@ impl<T: GridCell + Default + PartialEq + Copy> Grid<T> {
Ordering::Greater => self.shrink_cols(reflow, cols),
Ordering::Equal => (),
}
+
+ // Restore template cell.
+ self.cursor.template = template;
}
/// Add lines to the visible area.
@@ -29,11 +40,15 @@ impl<T: GridCell + Default + PartialEq + Copy> Grid<T> {
/// Alacritty keeps the cursor at the bottom of the terminal as long as there
/// is scrollback available. Once scrollback is exhausted, new lines are
/// simply added to the bottom of the screen.
- fn grow_lines(&mut self, new_line_count: Line) {
+ fn grow_lines<D>(&mut self, new_line_count: Line)
+ where
+ T: ResetDiscriminant<D>,
+ D: PartialEq,
+ {
let lines_added = new_line_count - self.lines;
// Need to resize before updating buffer.
- self.raw.grow_visible_lines(new_line_count, Row::new(self.cols, T::default()));
+ self.raw.grow_visible_lines(new_line_count);
self.lines = new_line_count;
let history_size = self.history_size();
@@ -42,7 +57,7 @@ impl<T: GridCell + Default + PartialEq + Copy> Grid<T> {
// Move existing lines up for every line that couldn't be pulled from history.
if from_history != lines_added.0 {
let delta = lines_added - from_history;
- self.scroll_up(&(Line(0)..new_line_count), delta, T::default());
+ self.scroll_up(&(Line(0)..new_line_count), delta);
}
// Move cursor down for every line pulled from history.
@@ -60,11 +75,15 @@ impl<T: GridCell + Default + PartialEq + Copy> Grid<T> {
/// of the terminal window.
///
/// Alacritty takes the same approach.
- fn shrink_lines(&mut self, target: Line) {
+ fn shrink_lines<D>(&mut self, target: Line)
+ where
+ T: ResetDiscriminant<D>,
+ D: PartialEq,
+ {
// Scroll up to keep content inside the window.
let required_scrolling = (self.cursor.point.line + 1).saturating_sub(target.0);
if required_scrolling > 0 {
- self.scroll_up(&(Line(0)..self.lines), Line(required_scrolling), T::default());
+ self.scroll_up(&(Line(0)..self.lines), Line(required_scrolling));
// Clamp cursors to the new viewport size.
self.cursor.point.line = min(self.cursor.point.line, target - 1);
@@ -194,7 +213,7 @@ impl<T: GridCell + Default + PartialEq + Copy> Grid<T> {
if reversed.len() < self.lines.0 {
let delta = self.lines.0 - reversed.len();
self.cursor.point.line.0 = self.cursor.point.line.saturating_sub(delta);
- reversed.append(&mut vec![Row::new(cols, T::default()); delta]);
+ reversed.resize_with(self.lines.0, || Row::new(cols));
}
// Pull content down to put cursor in correct position, or move cursor up if there's no
@@ -211,7 +230,7 @@ impl<T: GridCell + Default + PartialEq + Copy> Grid<T> {
let mut new_raw = Vec::with_capacity(reversed.len());
for mut row in reversed.drain(..).rev() {
if row.len() < cols.0 {
- row.grow(cols, T::default());
+ row.grow(cols);
}
new_raw.push(row);
}
@@ -269,11 +288,11 @@ impl<T: GridCell + Default + PartialEq + Copy> Grid<T> {
// Insert spacer if a wide char would be wrapped into the last column.
if row.len() >= cols.0 && row[cols - 1].flags().contains(Flags::WIDE_CHAR) {
- wrapped.insert(0, row[cols - 1]);
-
let mut spacer = T::default();
spacer.flags_mut().insert(Flags::LEADING_WIDE_CHAR_SPACER);
- row[cols - 1] = spacer;
+
+ let wide_char = mem::replace(&mut row[cols - 1], spacer);
+ wrapped.insert(0, wide_char);
}
// Remove wide char spacer before shrinking.
@@ -330,7 +349,7 @@ impl<T: GridCell + Default + PartialEq + Copy> Grid<T> {
// Make sure new row is at least as long as new width.
let occ = wrapped.len();
if occ < cols.0 {
- wrapped.append(&mut vec![T::default(); cols.0 - occ]);
+ wrapped.resize_with(cols.0, T::default);
}
row = Row::from_vec(wrapped, occ);
}
diff --git a/alacritty_terminal/src/grid/row.rs b/alacritty_terminal/src/grid/row.rs
index 7846a7ae..5b1be31c 100644
--- a/alacritty_terminal/src/grid/row.rs
+++ b/alacritty_terminal/src/grid/row.rs
@@ -3,12 +3,14 @@
use std::cmp::{max, min};
use std::ops::{Index, IndexMut};
use std::ops::{Range, RangeFrom, RangeFull, RangeTo, RangeToInclusive};
+use std::ptr;
use std::slice;
use serde::{Deserialize, Serialize};
use crate::grid::GridCell;
use crate::index::Column;
+use crate::term::cell::ResetDiscriminant;
/// A row in the grid.
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
@@ -28,23 +30,44 @@ impl<T: PartialEq> PartialEq for Row<T> {
}
}
-impl<T: Copy> Row<T> {
- pub fn new(columns: Column, template: T) -> Row<T>
- where
- T: GridCell,
- {
- let occ = if template.is_empty() { 0 } else { columns.0 };
- Row { inner: vec![template; columns.0], occ }
+impl<T: Clone + Default> Row<T> {
+ /// Create a new terminal row.
+ ///
+ /// Ideally the `template` should be `Copy` in all performance sensitive scenarios.
+ pub fn new(columns: Column) -> Row<T> {
+ debug_assert!(columns.0 >= 1);
+
+ let mut inner: Vec<T> = Vec::with_capacity(columns.0);
+
+ // This is a slightly optimized version of `std::vec::Vec::resize`.
+ unsafe {
+ let mut ptr = inner.as_mut_ptr();
+
+ for _ in 1..columns.0 {
+ ptr::write(ptr, T::default());
+ ptr = ptr.offset(1);
+ }
+ ptr::write(ptr, T::default());
+
+ inner.set_len(columns.0);
+ }
+
+ Row { inner, occ: 0 }
}
- pub fn grow(&mut self, cols: Column, template: T) {
+ /// Increase the number of columns in the row.
+ #[inline]
+ pub fn grow(&mut self, cols: Column) {
if self.inner.len() >= cols.0 {
return;
}
- self.inner.append(&mut vec![template; cols.0 - self.len()]);
+ self.inner.resize_with(cols.0, T::default);
}
+ /// Reduce the number of columns in the row.
+ ///
+ /// This will return all non-empty cells that were removed.
pub fn shrink(&mut self, cols: Column) -> Option<Vec<T>>
where
T: GridCell,
@@ -69,21 +92,22 @@ impl<T: Copy> Row<T> {
/// Reset all cells in the row to the `template` cell.
#[inline]
- pub fn reset(&mut self, template: T)
+ pub fn reset<D>(&mut self, template: &T)
where
- T: GridCell + PartialEq,
+ T: ResetDiscriminant<D> + GridCell,
+ D: PartialEq,
{
debug_assert!(!self.inner.is_empty());
// Mark all cells as dirty if template cell changed.
let len = self.inner.len();
- if !self.inner[len - 1].fast_eq(template) {
+ if self.inner[len - 1].discriminant() != template.discriminant() {
self.occ = len;
}
- // Reset every dirty in the row.
- for item in &mut self.inner[..self.occ] {
- *item = template;
+ // Reset every dirty cell in the row.
+ for item in &mut self.inner[0..self.occ] {
+ item.reset(template);
}
self.occ = 0;
diff --git a/alacritty_terminal/src/grid/storage.rs b/alacritty_terminal/src/grid/storage.rs
index a025a99c..dd8dbb22 100644
--- a/alacritty_terminal/src/grid/storage.rs
+++ b/alacritty_terminal/src/grid/storage.rs
@@ -5,7 +5,6 @@ use std::ops::{Index, IndexMut};
use serde::{Deserialize, Serialize};
use super::Row;
-use crate::grid::GridCell;
use crate::index::{Column, Line};
/// Maximum number of buffered lines outside of the grid for performance optimization.
@@ -27,7 +26,7 @@ const MAX_CACHE_SIZE: usize = 1_000;
/// [`slice::rotate_left`]: https://doc.rust-lang.org/std/primitive.slice.html#method.rotate_left
/// [`Deref`]: std::ops::Deref
/// [`zero`]: #structfield.zero
-#[derive(Clone, Debug, Deserialize, Serialize)]
+#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct Storage<T> {
inner: Vec<Row<T>>,
@@ -62,57 +61,35 @@ impl<T: PartialEq> PartialEq for Storage<T> {
impl<T> Storage<T> {
#[inline]
- pub fn with_capacity(visible_lines: Line, template: Row<T>) -> Storage<T>
+ pub fn with_capacity(visible_lines: Line, cols: Column) -> Storage<T>
where
- T: Clone,
+ T: Clone + Default,
{
- // Initialize visible lines, the scrollback buffer is initialized dynamically.
- let inner = vec![template; visible_lines.0];
+ // Initialize visible lines; the scrollback buffer is initialized dynamically.
+ let mut inner = Vec::with_capacity(visible_lines.0);
+ inner.resize_with(visible_lines.0, || Row::new(cols));
Storage { inner, zero: 0, visible_lines, len: visible_lines.0 }
}
/// Increase the number of lines in the buffer.
- pub fn grow_visible_lines(&mut self, next: Line, template_row: Row<T>)
+ #[inline]
+ pub fn grow_visible_lines(&mut self, next: Line)
where
- T: Clone,
+ T: Clone + Default,
{
// Number of lines the buffer needs to grow.
let growage = next - self.visible_lines;
- self.grow_lines(growage.0, template_row);
+
+ let cols = self[0].len();
+ self.initialize(growage.0, Column(cols));
// Update visible lines.
self.visible_lines = next;
}
- /// Grow the number of lines in the buffer, filling new lines with the template.
- fn grow_lines(&mut self, growage: usize, template_row: Row<T>)
- where
- T: Clone,
- {
- // Only grow if there are not enough lines still hidden.
- let mut new_growage = 0;
- if growage > (self.inner.len() - self.len) {
- // Lines to grow additionally to invisible lines.
- new_growage = growage - (self.inner.len() - self.len);
-
- // Split off the beginning of the raw inner buffer.
- let mut start_buffer = self.inner.split_off(self.zero);
-
- // Insert new template rows at the end of the raw inner buffer.
- let mut new_lines = vec![template_row; new_growage];
- self.inner.append(&mut new_lines);
-
- // Add the start to the raw inner buffer again.
- self.inner.append(&mut start_buffer);
- }
-
- // Update raw buffer length and zero offset.
- self.zero += new_growage;
- self.len += growage;
- }
-
/// Decrease the number of lines in the buffer.
+ #[inline]
pub fn shrink_visible_lines(&mut self, next: Line) {
// Shrink the size without removing any lines.
let shrinkage = self.visible_lines - next;
@@ -123,6 +100,7 @@ impl<T> Storage<T> {
}
/// Shrink the number of lines in the buffer.
+ #[inline]
pub fn shrink_lines(&mut self, shrinkage: usize) {
self.len -= shrinkage;
@@ -133,26 +111,24 @@ impl<T> Storage<T> {
}
/// Truncate the invisible elements from the raw buffer.
+ #[inline]
pub fn truncate(&mut self) {
- self.inner.rotate_left(self.zero);
- self.inner.truncate(self.len);
+ self.rezero();
- self.zero = 0;
+ self.inner.truncate(self.len);
}
/// Dynamically grow the storage buffer at runtime.
#[inline]
- pub fn initialize(&mut self, additional_rows: usize, template: T, cols: Column)
+ pub fn initialize(&mut self, additional_rows: usize, cols: Column)
where
- T: GridCell + Copy,
+ T: Clone + Default,
{
if self.len + additional_rows > self.inner.len() {
- let realloc_size = max(additional_rows, MAX_CACHE_SIZE);
- let mut new = vec![Row::new(cols, template); realloc_size];
- let mut split = self.inner.split_off(self.zero);
- self.inner.append(&mut new);
- self.inner.append(&mut split);
- self.zero += realloc_size;
+ self.rezero();
+
+ let realloc_size = self.inner.len() + max(additional_rows, MAX_CACHE_SIZE);
+ self.inner.resize_with(realloc_size, || Row::new(cols));
}
self.len += additional_rows;
@@ -163,24 +139,7 @@ impl<T> Storage<T> {
self.len
}
- /// Compute actual index in underlying storage given the requested index.
#[inline]
- fn compute_index(&self, requested: usize) -> usize {
- debug_assert!(requested < self.len);
-
- let zeroed = self.zero + requested;
-
- // Use if/else instead of remainder here to improve performance.
- //
- // Requires `zeroed` to be smaller than `self.inner.len() * 2`,
- // but both `self.zero` and `requested` are always smaller than `self.inner.len()`.
- if zeroed >= self.inner.len() {
- zeroed - self.inner.len()
- } else {
- zeroed
- }
- }
-
pub fn swap_lines(&mut self, a: Line, b: Line) {
let offset = self.inner.len() + self.zero + *self.visible_lines - 1;
let a = (offset - *a) % self.inner.len();
@@ -256,11 +215,39 @@ impl<T> Storage<T> {
let mut buffer = Vec::new();
mem::swap(&mut buffer, &mut self.inner);
- self.zero = 0;
self.len = 0;
buffer
}
+
+ /// Compute actual index in underlying storage given the requested index.
+ #[inline]
+ fn compute_index(&self, requested: usize) -> usize {
+ debug_assert!(requested < self.len);
+
+ let zeroed = self.zero + requested;
+
+ // Use if/else instead of remainder here to improve performance.
+ //
+ // Requires `zeroed` to be smaller than `self.inner.len() * 2`,
+ // but both `self.zero` and `requested` are always smaller than `self.inner.len()`.
+ if zeroed >= self.inner.len() {
+ zeroed - self.inner.len()
+ } else {
+ zeroed
+ }
+ }
+
+ /// Rotate the ringbuffer to reset `self.zero` back to index `0`.
+ #[inline]
+ fn rezero(&mut self) {
+ if self.zero == 0 {
+ return;
+ }
+
+ self.inner.rotate_left(self.zero);
+ self.zero = 0;
+ }
}
impl<T> Index<usize> for Storage<T> {
@@ -311,6 +298,10 @@ mod tests {
*self == ' ' || *self == '\t'
}
+ fn reset(&mut self, template: &Self) {
+ *self = *template;
+ }
+
fn flags(&self) -> &Flags {
unimplemented!();
}
@@ -318,15 +309,11 @@ mod tests {
fn flags_mut(&mut self) -> &mut Flags {
unimplemented!();
}
-
- fn fast_eq(&self, other: Self) -> bool {
- self == &other
- }
}
#[test]
fn with_capacity() {
- let storage = Storage::with_capacity(Line(3), Row::new(Column(0), ' '));
+ let storage = Storage::<char>::with_capacity(Line(3), Column(1));
assert_eq!(storage.inner.len(), 3);
assert_eq!(storage.len, 3);
@@ -336,33 +323,33 @@ mod tests {
#[test]
fn indexing() {
- let mut storage = Storage::with_capacity(Line(3), Row::new(Column(0), ' '));
+ let mut storage = Storage::<char>::with_capacity(Line(3), Column(1));
- storage[0] = Row::new(Column(1), '0');
- storage[1] = Row::new(Column(1), '1');
- storage[2] = Row::new(Column(1), '2');
+ storage[0] = filled_row('0');
+ storage[1] = filled_row('1');
+ storage[2] = filled_row('2');
- assert_eq!(storage[0], Row::new(Column(1), '0'));
- assert_eq!(storage[1], Row::new(Column(1), '1'));
- assert_eq!(storage[2], Row::new(Column(1), '2'));
+ assert_eq!(storage[0], filled_row('0'));
+ assert_eq!(storage[1], filled_row('1'));
+ assert_eq!(storage[2], filled_row('2'));
storage.zero += 1;
- assert_eq!(storage[0], Row::new(Column(1), '1'));
- assert_eq!(storage[1], Row::new(Column(1), '2'));
- assert_eq!(storage[2], Row::new(Column(1), '0'));
+ assert_eq!(storage[0], filled_row('1'));
+ assert_eq!(storage[1], filled_row('2'));
+ assert_eq!(storage[2], filled_row('0'));
}
#[test]
#[should_panic]
fn indexing_above_inner_len() {
- let storage = Storage::with_capacity(Line(1), Row::new(Column(0), ' '));
+ let storage = Storage::<char>::with_capacity(Line(1), Column(1));
let _ = &storage[2];
}
#[test]
fn rotate() {
- let mut storage = Storage::with_capacity(Line(3), Row::new(Column(0), ' '));
+ let mut storage = Storage::<char>::with_capacity(Line(3), Column(1));
storage.rotate(2);
assert_eq!(storage.zero, 2);
storage.shrink_lines(2);
@@ -378,39 +365,34 @@ mod tests {
/// 1: 1
/// 2: -
/// After:
- /// 0: -
- /// 1: 0 <- Zero
- /// 2: 1
- /// 3: -
+ /// 0: 0 <- Zero
+ /// 1: 1
+ /// 2: -
+ /// 3: \0
+ /// ...
+ /// MAX_CACHE_SIZE: \0
#[test]
fn grow_after_zero() {
- // Setup storage area
- let mut storage = Storage {
- inner: vec![
- Row::new(Column(1), '0'),
- Row::new(Column(1), '1'),
- Row::new(Column(1), '-'),
- ],
+ // Setup storage area.
+ let mut storage: Storage<char> = Storage {
+ inner: vec![filled_row('0'), filled_row('1'), filled_row('-')],
zero: 0,
visible_lines: Line(3),
len: 3,
};
- // Grow buffer
- storage.grow_visible_lines(Line(4), Row::new(Column(1), '-'));
+ // Grow buffer.
+ storage.grow_visible_lines(Line(4));
- // Make sure the result is correct
- let expected = Storage {
- inner: vec![
- Row::new(Column(1), '-'),
- Row::new(Column(1), '0'),
- Row::new(Column(1), '1'),
- Row::new(Column(1), '-'),
- ],
- zero: 1,
+ // Make sure the result is correct.
+ let mut expected = Storage {
+ inner: vec![filled_row('0'), filled_row('1'), filled_row('-')],
+ zero: 0,
visible_lines: Line(4),
len: 4,
};
+ expected.inner.append(&mut vec![filled_row('\0'); MAX_CACHE_SIZE]);
+
assert_eq!(storage.visible_lines, expected.visible_lines);
assert_eq!(storage.inner, expected.inner);
assert_eq!(storage.zero, expected.zero);
@@ -424,39 +406,34 @@ mod tests {
/// 1: 0 <- Zero
/// 2: 1
/// After:
- /// 0: -
- /// 1: -
- /// 2: 0 <- Zero
- /// 3: 1
+ /// 0: 0 <- Zero
+ /// 1: 1
+ /// 2: -
+ /// 3: \0
+ /// ...
+ /// MAX_CACHE_SIZE: \0
#[test]
fn grow_before_zero() {
// Setup storage area.
- let mut storage = Storage {
- inner: vec![
- Row::new(Column(1), '-'),
- Row::new(Column(1), '0'),
- Row::new(Column(1), '1'),
- ],
+ let mut storage: Storage<char> = Storage {
+ inner: vec![filled_row('-'), filled_row('0'), filled_row('1')],
zero: 1,
visible_lines: Line(3),
len: 3,
};
// Grow buffer.
- storage.grow_visible_lines(Line(4), Row::new(Column(1), '-'));
+ storage.grow_visible_lines(Line(4));
// Make sure the result is correct.
- let expected = Storage {
- inner: vec![
- Row::new(Column(1), '-'),
- Row::new(Column(1), '-'),
- Row::new(Column(1), '0'),
- Row::new(Column(1), '1'),
- ],
- zero: 2,
+ let mut expected = Storage {
+ inner: vec![filled_row('0'), filled_row('1'), filled_row('-')],
+ zero: 0,
visible_lines: Line(4),
len: 4,
};
+ expected.inner.append(&mut vec![filled_row('\0'); MAX_CACHE_SIZE]);
+
assert_eq!(storage.visible_lines, expected.visible_lines);
assert_eq!(storage.inner, expected.inner);
assert_eq!(storage.zero, expected.zero);
@@ -476,12 +453,8 @@ mod tests {
#[test]
fn shrink_before_zero() {
// Setup storage area.
- let mut storage = Storage {
- inner: vec![
- Row::new(Column(1), '2'),
- Row::new(Column(1), '0'),
- Row::new(Column(1), '1'),
- ],
+ let mut storage: Storage<char> = Storage {
+ inner: vec![filled_row('2'), filled_row('0'), filled_row('1')],
zero: 1,
visible_lines: Line(3),
len: 3,
@@ -492,11 +465,7 @@ mod tests {
// Make sure the result is correct.
let expected = Storage {
- inner: vec![
- Row::new(Column(1), '2'),
- Row::new(Column(1), '0'),
- Row::new(Column(1), '1'),
- ],
+ inner: vec![filled_row('2'), filled_row('0'), filled_row('1')],
zero: 1,
visible_lines: Line(2),
len: 2,
@@ -520,12 +489,8 @@ mod tests {
#[test]
fn shrink_after_zero() {
// Setup storage area.
- let mut storage = Storage {
- inner: vec![
- Row::new(Column(1), '0'),
- Row::new(Column(1), '1'),
- Row::new(Column(1), '2'),
- ],
+ let mut storage: Storage<char> = Storage {
+ inner: vec![filled_row('0'), filled_row('1'), filled_row('2')],
zero: 0,
visible_lines: Line(3),
len: 3,
@@ -536,11 +501,7 @@ mod tests {
// Make sure the result is correct.
let expected = Storage {
- inner: vec![
- Row::new(Column(1), '0'),
- Row::new(Column(1), '1'),
- Row::new(Column(1), '2'),
- ],
+ inner: vec![filled_row('0'), filled_row('1'), filled_row('2')],
zero: 0,
visible_lines: Line(2),
len: 2,
@@ -570,14 +531,14 @@ mod tests {
#[test]
fn shrink_before_and_after_zero() {
// Setup storage area.
- let mut storage = Storage {
+ let mut storage: Storage<char> = Storage {
inner: vec![
- Row::new(Column(1), '4'),
- Row::new(Column(1), '5'),
- Row::new(Column(1), '0'),
- Row::new(Column(1), '1'),
- Row::new(Column(1), '2'),
- Row::new(Column(1), '3'),
+ filled_row('4'),
+ filled_row('5'),
+ filled_row('0'),
+ filled_row('1'),
+ filled_row('2'),
+ filled_row('3'),
],
zero: 2,
visible_lines: Line(6),
@@ -590,12 +551,12 @@ mod tests {
// Make sure the result is correct.
let expected = Storage {
inner: vec![
- Row::new(Column(1), '4'),
- Row::new(Column(1), '5'),
- Row::new(Column(1), '0'),
- Row::new(Column(1), '1'),
- Row::new(Column(1), '2'),
- Row::new(Column(1), '3'),
+ filled_row('4'),
+ filled_row('5'),
+ filled_row('0'),
+ filled_row('1'),
+ filled_row('2'),
+ filled_row('3'),
],
zero: 2,
visible_lines: Line(2),
@@ -622,14 +583,14 @@ mod tests {
#[test]
fn truncate_invisible_lines() {
// Setup storage area.
- let mut storage = Storage {
+ let mut storage: Storage<char> = Storage {
inner: vec![
- Row::new(Column(1), '4'),
- Row::new(Column(1), '5'),
- Row::new(Column(1), '0'),
- Row::new(Column(1), '1'),
- Row::new(Column(1), '2'),
- Row::new(Column(1), '3'),
+ filled_row('4'),
+ filled_row('5'),
+ filled_row('0'),
+ filled_row('1'),
+ filled_row('2'),
+ filled_row('3'),
],
zero: 2,
visible_lines: Line(1),
@@ -641,7 +602,7 @@ mod tests {
// Make sure the result is correct.
let expected = Storage {
- inner: vec![Row::new(Column(1), '0'), Row::new(Column(1), '1')],
+ inner: vec![filled_row('0'), filled_row('1')],
zero: 0,
visible_lines: Line(1),
len: 2,
@@ -664,12 +625,8 @@ mod tests {
#[test]
fn truncate_invisible_lines_beginning() {
// Setup storage area.
- let mut storage = Storage {
- inner: vec![
- Row::new(Column(1), '1'),
- Row::new(Column(1), '2'),
- Row::new(Column(1), '0'),
- ],
+ let mut storage: Storage<char> = Storage {
+ inner: vec![filled_row('1'), filled_row('2'), filled_row('0')],
zero: 2,
visible_lines: Line(1),
len: 2,
@@ -680,7 +637,7 @@ mod tests {
// Make sure the result is correct.
let expected = Storage {
- inner: vec![Row::new(Column(1), '0'), Row::new(Column(1), '1')],
+ inner: vec![filled_row('0'), filled_row('1')],
zero: 0,
visible_lines: Line(1),
len: 2,
@@ -718,14 +675,14 @@ mod tests {
#[test]
fn shrink_then_grow() {
// Setup storage area.
- let mut storage = Storage {
+ let mut storage: Storage<char> = Storage {
inner: vec![
- Row::new(Column(1), '4'),
- Row::new(Column(1), '5'),
- Row::new(Column(1), '0'),
- Row::new(Column(1), '1'),
- Row::new(Column(1), '2'),
- Row::new(Column(1), '3'),
+ filled_row('4'),
+ filled_row('5'),
+ filled_row('0'),
+ filled_row('1'),
+ filled_row('2'),
+ filled_row('3'),
],
zero: 2,
visible_lines: Line(0),
@@ -738,12 +695,12 @@ mod tests {
// Make sure the result after shrinking is correct.
let shrinking_expected = Storage {
inner: vec![
- Row::new(Column(1), '4'),
- Row::new(Column(1), '5'),
- Row::new(Column(1), '0'),
- Row::new(Column(1), '1'),
- Row::new(Column(1), '2'),
- Row::new(Column(1), '3'),
+ filled_row('4'),
+ filled_row('5'),
+ filled_row('0'),
+ filled_row('1'),
+ filled_row('2'),
+ filled_row('3'),
],
zero: 2,
visible_lines: Line(0),
@@ -754,23 +711,23 @@ mod tests {
assert_eq!(storage.len, shrinking_expected.len);
// Grow buffer.
- storage.grow_lines(4, Row::new(Column(1), '-'));
+ storage.initialize(1, Column(1));
- // Make sure the result after shrinking is correct.
+ // Make sure the previously freed elements are reused.
let growing_expected = Storage {
inner: vec![
- Row::new(Column(1), '4'),
- Row::new(Column(1), '5'),
- Row::new(Column(1), '-'),
- Row::new(Column(1), '0'),
- Row::new(Column(1), '1'),
- Row::new(Column(1), '2'),
- Row::new(Column(1), '3'),
+ filled_row('4'),
+ filled_row('5'),
+ filled_row('0'),
+ filled_row('1'),
+ filled_row('2'),
+ filled_row('3'),
],
- zero: 3,
+ zero: 2,
visible_lines: Line(0),
- len: 7,
+ len: 4,
};
+
assert_eq!(storage.inner, growing_expected.inner);
assert_eq!(storage.zero, growing_expected.zero);
assert_eq!(storage.len, growing_expected.len);
@@ -779,14 +736,14 @@ mod tests {
#[test]
fn initialize() {
// Setup storage area.
- let mut storage = Storage {
+ let mut storage: Storage<char> = Storage {
inner: vec![
- Row::new(Column(1), '4'),
- Row::new(Column(1), '5'),
- Row::new(Column(1), '0'),
- Row::new(Column(1), '1'),
- Row::new(Column(1), '2'),
- Row::new(Column(1), '3'),
+ filled_row('4'),
+ filled_row('5'),
+ filled_row('0'),
+ filled_row('1'),
+ filled_row('2'),
+ filled_row('3'),
],
zero: 2,
visible_lines: Line(0),
@@ -795,39 +752,31 @@ mod tests {
// Initialize additional lines.
let init_size = 3;
- storage.initialize(init_size, '-', Column(1));
-
- // Make sure the lines are present and at the right location.
-
+ storage.initialize(init_size, Column(1));
+
+ // Generate expected grid.
+ let mut expected_inner = vec![
+ filled_row('0'),
+ filled_row('1'),
+ filled_row('2'),
+ filled_row('3'),
+ filled_row('4'),
+ filled_row('5'),
+ ];
let expected_init_size = std::cmp::max(init_size, MAX_CACHE_SIZE);
- let mut expected_inner = vec![Row::new(Column(1), '4'), Row::new(Column(1), '5')];
- expected_inner.append(&mut vec![Row::new(Column(1), '-'); expected_init_size]);
- expected_inner.append(&mut vec![
- Row::new(Column(1), '0'),
- Row::new(Column(1), '1'),
- Row::new(Column(1), '2'),
- Row::new(Column(1), '3'),
- ]);
- let expected_storage = Storage {
- inner: expected_inner,
- zero: 2 + expected_init_size,
- visible_lines: Line(0),
- len: 9,
- };
+ expected_inner.append(&mut vec![filled_row('\0'); expected_init_size]);
+ let expected_storage =
+ Storage { inner: expected_inner, zero: 0, visible_lines: Line(0), len: 9 };
- assert_eq!(storage.inner, expected_storage.inner);
- assert_eq!(storage.zero, expected_storage.zero);
assert_eq!(storage.len, expected_storage.len);
+ assert_eq!(storage.zero, expected_storage.zero);
+ assert_eq!(storage.inner, expected_storage.inner);
}
#[test]
fn rotate_wrap_zero() {
- let mut storage = Storage {
- inner: vec![
- Row::new(Column(1), '-'),
- Row::new(Column(1), '-'),
- Row::new(Column(1), '-'),
- ],
+ let mut storage: Storage<char> = Storage {
+ inner: vec![filled_row('-'), filled_row('-'), filled_row('-')],
zero: 2,
visible_lines: Line(0),
len: 3,
@@ -837,4 +786,10 @@ mod tests {
assert!(storage.zero < storage.inner.len());
}
+
+ fn filled_row(content: char) -> Row<char> {
+ let mut row = Row::new(Column(1));
+ row[Column(0)] = content;
+ row
+ }
}
diff --git a/alacritty_terminal/src/grid/tests.rs b/alacritty_terminal/src/grid/tests.rs
index f86c77b5..eac19828 100644
--- a/alacritty_terminal/src/grid/tests.rs
+++ b/alacritty_terminal/src/grid/tests.rs
@@ -1,14 +1,18 @@
//! Tests for the Grid.
-use super::{BidirectionalIterator, Dimensions, Grid, GridCell};
-use crate::index::{Column, Line, Point};
-use crate::term::cell::{Cell, Flags};
+use super::*;
+
+use crate::term::cell::Cell;
impl GridCell for usize {
fn is_empty(&self) -> bool {
*self == 0
}
+ fn reset(&mut self, template: &Self) {
+ *self = *template;
+ }
+
fn flags(&self) -> &Flags {
unimplemented!();
}
@@ -16,15 +20,11 @@ impl GridCell for usize {
fn flags_mut(&mut self) -> &mut Flags {
unimplemented!();
}
-
- fn fast_eq(&self, other: Self) -> bool {
- self == &other
- }
}
#[test]
fn grid_clamp_buffer_point() {
- let mut grid = Grid::new(Line(10), Column(10), 1_000, 0);
+ let mut grid = Grid::<usize>::new(Line(10), Column(10), 1_000);
grid.display_offset = 5;
let point = grid.clamp_buffer_to_visible(Point::new(10, Column(3)));
@@ -44,7 +44,7 @@ fn grid_clamp_buffer_point() {
#[test]
fn visible_to_buffer() {
- let mut grid = Grid::new(Line(10), Column(10), 1_000, 0);
+ let mut grid = Grid::<usize>::new(Line(10), Column(10), 1_000);
grid.display_offset = 5;
let point = grid.visible_to_buffer(Point::new(Line(4), Column(3)));
@@ -59,12 +59,12 @@ fn visible_to_buffer() {
// Scroll up moves lines upward.
#[test]
fn scroll_up() {
- let mut grid = Grid::new(Line(10), Column(1), 0, 0);
+ let mut grid = Grid::<usize>::new(Line(10), Column(1), 0);
for i in 0..10 {
grid[Line(i)][Column(0)] = i;
}
- grid.scroll_up(&(Line(0)..Line(10)), Line(2), 0);
+ grid.scroll_up::<usize>(&(Line(0)..Line(10)), Line(2));
assert_eq!(grid[Line(0)][Column(0)], 2);
assert_eq!(grid[Line(0)].occ, 1);
@@ -91,12 +91,12 @@ fn scroll_up() {
// Scroll down moves lines downward.
#[test]
fn scroll_down() {
- let mut grid = Grid::new(Line(10), Column(1), 0, 0);
+ let mut grid = Grid::<usize>::new(Line(10), Column(1), 0);
for i in 0..10 {
grid[Line(i)][Column(0)] = i;
}
- grid.scroll_down(&(Line(0)..Line(10)), Line(2), 0);
+ grid.scroll_down::<usize>(&(Line(0)..Line(10)), Line(2));
assert_eq!(grid[Line(0)][Column(0)], 0); // was 8.
assert_eq!(grid[Line(0)].occ, 0);
@@ -123,7 +123,7 @@ fn scroll_down() {
// Test that GridIterator works.
#[test]
fn test_iter() {
- let mut grid = Grid::new(Line(5), Column(5), 0, 0);
+ let mut grid = Grid::<usize>::new(Line(5), Column(5), 0);
for i in 0..5 {
for j in 0..5 {
grid[Line(i)][Column(j)] = i * 5 + j;
@@ -161,7 +161,7 @@ fn test_iter() {
#[test]
fn shrink_reflow() {
- let mut grid = Grid::new(Line(1), Column(5), 2, cell('x'));
+ let mut grid = Grid::<Cell>::new(Line(1), Column(5), 2);
grid[Line(0)][Column(0)] = cell('1');
grid[Line(0)][Column(1)] = cell('2');
grid[Line(0)][Column(2)] = cell('3');
@@ -187,7 +187,7 @@ fn shrink_reflow() {
#[test]
fn shrink_reflow_twice() {
- let mut grid = Grid::new(Line(1), Column(5), 2, cell('x'));
+ let mut grid = Grid::<Cell>::new(Line(1), Column(5), 2);
grid[Line(0)][Column(0)] = cell('1');
grid[Line(0)][Column(1)] = cell('2');
grid[Line(0)][Column(2)] = cell('3');
@@ -214,7 +214,7 @@ fn shrink_reflow_twice() {
#[test]
fn shrink_reflow_empty_cell_inside_line() {
- let mut grid = Grid::new(Line(1), Column(5), 3, cell('x'));
+ let mut grid = Grid::<Cell>::new(Line(1), Column(5), 3);
grid[Line(0)][Column(0)] = cell('1');
grid[Line(0)][Column(1)] = Cell::default();
grid[Line(0)][Column(2)] = cell('3');
@@ -252,7 +252,7 @@ fn shrink_reflow_empty_cell_inside_line() {
#[test]
fn grow_reflow() {
- let mut grid = Grid::new(Line(2), Column(2), 0, cell('x'));
+ let mut grid = Grid::<Cell>::new(Line(2), Column(2), 0);
grid[Line(0)][Column(0)] = cell('1');
grid[Line(0)][Column(1)] = wrap_cell('2');
grid[Line(1)][Column(0)] = cell('3');
@@ -276,7 +276,7 @@ fn grow_reflow() {
#[test]
fn grow_reflow_multiline() {
- let mut grid = Grid::new(Line(3), Column(2), 0, cell('x'));
+ let mut grid = Grid::<Cell>::new(Line(3), Column(2), 0);
grid[Line(0)][Column(0)] = cell('1');
grid[Line(0)][Column(1)] = wrap_cell('2');
grid[Line(1)][Column(0)] = cell('3');
@@ -309,7 +309,7 @@ fn grow_reflow_multiline() {
#[test]
fn grow_reflow_disabled() {
- let mut grid = Grid::new(Line(2), Column(2), 0, cell('x'));
+ let mut grid = Grid::<Cell>::new(Line(2), Column(2), 0);
grid[Line(0)][Column(0)] = cell('1');
grid[Line(0)][Column(1)] = wrap_cell('2');
grid[Line(1)][Column(0)] = cell('3');
@@ -332,7 +332,7 @@ fn grow_reflow_disabled() {
#[test]
fn shrink_reflow_disabled() {
- let mut grid = Grid::new(Line(1), Column(5), 2, cell('x'));
+ let mut grid = Grid::<Cell>::new(Line(1), Column(5), 2);
grid[Line(0)][Column(0)] = cell('1');
grid[Line(0)][Column(1)] = cell('2');
grid[Line(0)][Column(2)] = cell('3');