From ec42b42ce601808070462111c0c28edb0e89babb Mon Sep 17 00:00:00 2001 From: Christian Duerr Date: Thu, 5 Nov 2020 04:45:14 +0000 Subject: 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>), 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. --- alacritty_terminal/src/grid/mod.rs | 95 +++-- alacritty_terminal/src/grid/resize.rs | 47 ++- alacritty_terminal/src/grid/row.rs | 54 ++- alacritty_terminal/src/grid/storage.rs | 415 +++++++++------------ alacritty_terminal/src/grid/tests.rs | 42 +-- alacritty_terminal/src/index.rs | 4 +- alacritty_terminal/src/term/cell.rs | 151 ++++---- alacritty_terminal/src/term/mod.rs | 169 +++++---- alacritty_terminal/src/term/search.rs | 39 +- alacritty_terminal/src/vi_mode.rs | 8 +- alacritty_terminal/tests/ref.rs | 6 +- alacritty_terminal/tests/ref/alt_reset/grid.json | 2 +- .../tests/ref/clear_underline/grid.json | 2 +- .../tests/ref/colored_reset/grid.json | 2 +- alacritty_terminal/tests/ref/csi_rep/grid.json | 2 +- .../tests/ref/decaln_reset/grid.json | 2 +- .../tests/ref/deccolm_reset/grid.json | 2 +- .../tests/ref/delete_chars_reset/grid.json | 2 +- .../tests/ref/delete_lines/grid.json | 2 +- .../tests/ref/erase_chars_reset/grid.json | 2 +- alacritty_terminal/tests/ref/fish_cc/grid.json | 2 +- alacritty_terminal/tests/ref/grid_reset/grid.json | 2 +- alacritty_terminal/tests/ref/history/grid.json | 2 +- .../tests/ref/indexed_256_colors/grid.json | 2 +- .../tests/ref/insert_blank_reset/grid.json | 2 +- alacritty_terminal/tests/ref/issue_855/grid.json | 2 +- alacritty_terminal/tests/ref/ll/grid.json | 2 +- .../grid.json | 2 +- .../tests/ref/region_scroll_down/grid.json | 2 +- alacritty_terminal/tests/ref/row_reset/grid.json | 2 +- .../tests/ref/saved_cursor/grid.json | 2 +- .../tests/ref/saved_cursor_alt/grid.json | 2 +- .../tests/ref/scroll_up_reset/grid.json | 2 +- .../tests/ref/selective_erasure/grid.json | 2 +- alacritty_terminal/tests/ref/sgr/grid.json | 2 +- .../tests/ref/tab_rendering/grid.json | 2 +- .../tests/ref/tmux_git_log/grid.json | 2 +- alacritty_terminal/tests/ref/tmux_htop/grid.json | 2 +- alacritty_terminal/tests/ref/underline/grid.json | 2 +- .../tests/ref/vim_24bitcolors_bce/grid.json | 2 +- .../tests/ref/vim_large_window_scroll/grid.json | 2 +- .../tests/ref/vim_simple_edit/grid.json | 2 +- .../tests/ref/vttest_cursor_movement_1/grid.json | 2 +- .../tests/ref/vttest_insert/grid.json | 2 +- .../tests/ref/vttest_origin_mode_1/grid.json | 2 +- .../tests/ref/vttest_origin_mode_2/grid.json | 2 +- .../tests/ref/vttest_scroll/grid.json | 2 +- .../tests/ref/vttest_tab_clear_set/grid.json | 2 +- .../tests/ref/wrapline_alt_toggle/grid.json | 2 +- .../tests/ref/zerowidth/alacritty.recording | 4 +- alacritty_terminal/tests/ref/zerowidth/config.json | 2 +- alacritty_terminal/tests/ref/zerowidth/grid.json | 2 +- alacritty_terminal/tests/ref/zerowidth/size.json | 2 +- .../tests/ref/zsh_tab_completion/grid.json | 2 +- 54 files changed, 579 insertions(+), 539 deletions(-) (limited to 'alacritty_terminal') 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 ::std::cmp::PartialEq for Grid { } } -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 { /// 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 for Charsets { pub struct Grid { /// Current cursor for writing data. #[serde(skip)] - pub cursor: Cursor, + pub cursor: Cursor, /// Last saved cursor. #[serde(skip)] - pub saved_cursor: Cursor, + pub saved_cursor: Cursor, /// 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 Grid { - pub fn new(lines: Line, cols: Column, max_scroll_limit: usize, template: T) -> Grid { +impl Grid { + pub fn new(lines: Line, cols: Column, max_scroll_limit: usize) -> Grid { 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 Grid { }; } - 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 Grid { } #[inline] - pub fn scroll_down(&mut self, region: &Range, positions: Line, template: T) { + pub fn scroll_down(&mut self, region: &Range, positions: Line) + where + T: ResetDiscriminant, + 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 Grid { // 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 Grid { } 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 Grid { /// Move lines at the bottom toward the top. /// /// This is the performance-sensitive part of scrolling. - pub fn scroll_up(&mut self, region: &Range, positions: Line, template: T) { + pub fn scroll_up(&mut self, region: &Range, positions: Line) + where + T: ResetDiscriminant, + D: PartialEq, + { let num_lines = self.screen_lines().0; if region.start == Line(0) { @@ -264,7 +271,7 @@ impl Grid { 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 Grid { // // 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 Grid { // 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(&mut self) + where + T: ResetDiscriminant, + 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 Grid { self.display_offset = 0; // Clear the viewport. - self.scroll_up(®ion, positions, template); + self.scroll_up(®ion, 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(&mut self) + where + T: ResetDiscriminant, + 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 Grid { /// 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; +impl<'a, T: 'a> Iterator for DisplayIter<'a, T> { + type Item = Indexed<&'a T>; #[inline] fn next(&mut self) -> Option { @@ -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 Grid { +impl Grid { /// Resize the grid's width and/or height. - pub fn resize(&mut self, reflow: bool, lines: Line, cols: Column) { + pub fn resize(&mut self, reflow: bool, lines: Line, cols: Column) + where + T: ResetDiscriminant, + 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 Grid { 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 Grid { /// 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(&mut self, new_line_count: Line) + where + T: ResetDiscriminant, + 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 Grid { // 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 Grid { /// of the terminal window. /// /// Alacritty takes the same approach. - fn shrink_lines(&mut self, target: Line) { + fn shrink_lines(&mut self, target: Line) + where + T: ResetDiscriminant, + 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 Grid { 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 Grid { 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 Grid { // 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 Grid { // 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 PartialEq for Row { } } -impl Row { - pub fn new(columns: Column, template: T) -> Row - where - T: GridCell, - { - let occ = if template.is_empty() { 0 } else { columns.0 }; - Row { inner: vec![template; columns.0], occ } +impl Row { + /// Create a new terminal row. + /// + /// Ideally the `template` should be `Copy` in all performance sensitive scenarios. + pub fn new(columns: Column) -> Row { + debug_assert!(columns.0 >= 1); + + let mut inner: Vec = 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> where T: GridCell, @@ -69,21 +92,22 @@ impl Row { /// Reset all cells in the row to the `template` cell. #[inline] - pub fn reset(&mut self, template: T) + pub fn reset(&mut self, template: &T) where - T: GridCell + PartialEq, + T: ResetDiscriminant + 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 { inner: Vec>, @@ -62,57 +61,35 @@ impl PartialEq for Storage { impl Storage { #[inline] - pub fn with_capacity(visible_lines: Line, template: Row) -> Storage + pub fn with_capacity(visible_lines: Line, cols: Column) -> Storage 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) + #[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) - 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 Storage { } /// 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 Storage { } /// 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 Storage { 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 Storage { 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 Index for Storage { @@ -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::::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::::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::::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::::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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 { + 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::::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::::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::::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::(&(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::::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::(&(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::::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::::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::::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::::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::::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::::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::::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::::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'); diff --git a/alacritty_terminal/src/index.rs b/alacritty_terminal/src/index.rs index 2c28bec2..2ee679db 100644 --- a/alacritty_terminal/src/index.rs +++ b/alacritty_terminal/src/index.rs @@ -190,8 +190,8 @@ impl From for Point { } } -impl From for Point { - fn from(cell: RenderableCell) -> Self { +impl From<&RenderableCell> for Point { + fn from(cell: &RenderableCell) -> Self { Point::new(cell.line, cell.column) } } diff --git a/alacritty_terminal/src/term/cell.rs b/alacritty_terminal/src/term/cell.rs index ee95fcba..8ac3edd0 100644 --- a/alacritty_terminal/src/term/cell.rs +++ b/alacritty_terminal/src/term/cell.rs @@ -1,14 +1,12 @@ -use bitflags::bitflags; +use std::boxed::Box; +use bitflags::bitflags; use serde::{Deserialize, Serialize}; use crate::ansi::{Color, NamedColor}; use crate::grid::{self, GridCell}; use crate::index::Column; -/// Maximum number of zerowidth characters which will be stored per cell. -pub const MAX_ZEROWIDTH_CHARS: usize = 5; - bitflags! { #[derive(Serialize, Deserialize)] pub struct Flags: u16 { @@ -29,23 +27,77 @@ bitflags! { } } -const fn default_extra() -> [char; MAX_ZEROWIDTH_CHARS] { - [' '; MAX_ZEROWIDTH_CHARS] +/// Trait for determining if a reset should be performed. +pub trait ResetDiscriminant { + /// Value based on which equality for the reset will be determined. + fn discriminant(&self) -> T; +} + +impl ResetDiscriminant for T { + fn discriminant(&self) -> T { + *self + } +} + +impl ResetDiscriminant for Cell { + fn discriminant(&self) -> Color { + self.bg + } +} + +/// Dynamically allocated cell content. +/// +/// This storage is reserved for cell attributes which are rarely set. This allows reducing the +/// allocation required ahead of time for every cell, with some additional overhead when the extra +/// storage is actually required. +#[derive(Serialize, Deserialize, Default, Debug, Clone, Eq, PartialEq)] +struct CellExtra { + zerowidth: Vec, } -#[derive(Copy, Clone, Debug, Serialize, Deserialize, Eq, PartialEq)] +/// Content and attributes of a single cell in the terminal grid. +#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)] pub struct Cell { pub c: char, pub fg: Color, pub bg: Color, pub flags: Flags, - #[serde(default = "default_extra")] - pub extra: [char; MAX_ZEROWIDTH_CHARS], + #[serde(default)] + extra: Option>, } impl Default for Cell { + #[inline] fn default() -> Cell { - Cell::new(' ', Color::Named(NamedColor::Foreground), Color::Named(NamedColor::Background)) + Cell { + c: ' ', + bg: Color::Named(NamedColor::Background), + fg: Color::Named(NamedColor::Foreground), + flags: Flags::empty(), + extra: None, + } + } +} + +impl Cell { + /// Zerowidth characters stored in this cell. + #[inline] + pub fn zerowidth(&self) -> Option<&[char]> { + self.extra.as_ref().map(|extra| extra.zerowidth.as_slice()) + } + + /// Write a new zerowidth character to this cell. + #[inline] + pub fn push_zerowidth(&mut self, c: char) { + self.extra.get_or_insert_with(Default::default).zerowidth.push(c); + } + + /// Free all dynamically allocated cell storage. + #[inline] + pub fn drop_extra(&mut self) { + if self.extra.is_some() { + self.extra = None; + } } } @@ -53,7 +105,6 @@ impl GridCell for Cell { #[inline] fn is_empty(&self) -> bool { (self.c == ' ' || self.c == '\t') - && self.extra[0] == ' ' && self.bg == Color::Named(NamedColor::Background) && self.fg == Color::Named(NamedColor::Foreground) && !self.flags.intersects( @@ -65,6 +116,7 @@ impl GridCell for Cell { | Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER, ) + && self.extra.as_ref().map(|extra| extra.zerowidth.is_empty()) != Some(false) } #[inline] @@ -78,8 +130,15 @@ impl GridCell for Cell { } #[inline] - fn fast_eq(&self, other: Self) -> bool { - self.bg == other.bg + fn reset(&mut self, template: &Self) { + *self = Cell { bg: template.bg, ..Cell::default() }; + } +} + +impl From for Cell { + #[inline] + fn from(color: Color) -> Self { + Self { bg: color, ..Cell::default() } } } @@ -98,7 +157,9 @@ impl LineLength for grid::Row { } for (index, cell) in self[..].iter().rev().enumerate() { - if cell.c != ' ' || cell.extra[0] != ' ' { + if cell.c != ' ' + || cell.extra.as_ref().map(|extra| extra.zerowidth.is_empty()) == Some(false) + { length = Column(self.len() - index); break; } @@ -108,57 +169,6 @@ impl LineLength for grid::Row { } } -impl Cell { - #[inline] - pub fn bold(&self) -> bool { - self.flags.contains(Flags::BOLD) - } - - #[inline] - pub fn inverse(&self) -> bool { - self.flags.contains(Flags::INVERSE) - } - - #[inline] - pub fn dim(&self) -> bool { - self.flags.contains(Flags::DIM) - } - - pub fn new(c: char, fg: Color, bg: Color) -> Cell { - Cell { extra: [' '; MAX_ZEROWIDTH_CHARS], c, bg, fg, flags: Flags::empty() } - } - - #[inline] - pub fn reset(&mut self, template: &Cell) { - // memcpy template to self. - *self = Cell { c: template.c, bg: template.bg, ..Cell::default() }; - } - - #[inline] - pub fn chars(&self) -> [char; MAX_ZEROWIDTH_CHARS + 1] { - unsafe { - let mut chars = [std::mem::MaybeUninit::uninit(); MAX_ZEROWIDTH_CHARS + 1]; - std::ptr::write(chars[0].as_mut_ptr(), self.c); - std::ptr::copy_nonoverlapping( - self.extra.as_ptr() as *mut std::mem::MaybeUninit, - chars.as_mut_ptr().offset(1), - self.extra.len(), - ); - std::mem::transmute(chars) - } - } - - #[inline] - pub fn push_extra(&mut self, c: char) { - for elem in self.extra.iter_mut() { - if elem == &' ' { - *elem = c; - break; - } - } - } -} - #[cfg(test)] mod tests { use super::{Cell, LineLength}; @@ -168,8 +178,7 @@ mod tests { #[test] fn line_length_works() { - let template = Cell::default(); - let mut row = Row::new(Column(10), template); + let mut row = Row::::new(Column(10)); row[Column(5)].c = 'a'; assert_eq!(row.line_length(), Column(6)); @@ -177,8 +186,7 @@ mod tests { #[test] fn line_length_works_with_wrapline() { - let template = Cell::default(); - let mut row = Row::new(Column(10), template); + let mut row = Row::::new(Column(10)); row[Column(9)].flags.insert(super::Flags::WRAPLINE); assert_eq!(row.line_length(), Column(10)); @@ -188,7 +196,8 @@ mod tests { #[cfg(all(test, feature = "bench"))] mod benches { extern crate test; - use super::Cell; + + use super::*; #[bench] fn cell_reset(b: &mut test::Bencher) { @@ -196,7 +205,7 @@ mod benches { let mut cell = Cell::default(); for _ in 0..100 { - cell.reset(test::black_box(&Cell::default())); + cell = test::black_box(Color::Named(NamedColor::Foreground).into()); } test::black_box(cell); diff --git a/alacritty_terminal/src/term/mod.rs b/alacritty_terminal/src/term/mod.rs index 59549106..af64cb5e 100644 --- a/alacritty_terminal/src/term/mod.rs +++ b/alacritty_terminal/src/term/mod.rs @@ -218,7 +218,7 @@ impl<'a, C> RenderableCellsIter<'a, C> { // Convert to absolute coordinates to adjust for the display offset. let buffer_point = self.grid.visible_to_buffer(point); - let cell = self.grid[buffer_point]; + let cell = &self.grid[buffer_point]; // Check if wide char's spacers are selected. if cell.flags.contains(Flags::WIDE_CHAR) { @@ -249,13 +249,13 @@ impl<'a, C> RenderableCellsIter<'a, C> { } } -#[derive(Copy, Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq)] pub enum RenderableCellContent { - Chars([char; cell::MAX_ZEROWIDTH_CHARS + 1]), + Chars((char, Option>)), Cursor(CursorKey), } -#[derive(Copy, Clone, Debug)] +#[derive(Clone, Debug)] pub struct RenderableCell { /// A _Display_ line (not necessarily an _Active_ line). pub line: Line, @@ -268,14 +268,14 @@ pub struct RenderableCell { } impl RenderableCell { - fn new<'a, C>(iter: &mut RenderableCellsIter<'a, C>, cell: Indexed) -> Self { + fn new<'a, C>(iter: &mut RenderableCellsIter<'a, C>, cell: Indexed<&Cell>) -> Self { let point = Point::new(cell.line, cell.column); // Lookup RGB values. let mut fg_rgb = Self::compute_fg_rgb(iter.config, iter.colors, cell.fg, cell.flags); let mut bg_rgb = Self::compute_bg_rgb(iter.colors, cell.bg); - let mut bg_alpha = if cell.inverse() { + let mut bg_alpha = if cell.flags.contains(Flags::INVERSE) { mem::swap(&mut fg_rgb, &mut bg_rgb); 1.0 } else { @@ -308,10 +308,12 @@ impl RenderableCell { } } + let zerowidth = cell.zerowidth().map(|zerowidth| zerowidth.to_vec()); + RenderableCell { line: cell.line, column: cell.column, - inner: RenderableCellContent::Chars(cell.chars()), + inner: RenderableCellContent::Chars((cell.c, zerowidth)), fg: fg_rgb, bg: bg_rgb, bg_alpha, @@ -322,7 +324,7 @@ impl RenderableCell { fn is_empty(&self) -> bool { self.bg_alpha == 0. && !self.flags.intersects(Flags::UNDERLINE | Flags::STRIKEOUT | Flags::DOUBLE_UNDERLINE) - && self.inner == RenderableCellContent::Chars([' '; cell::MAX_ZEROWIDTH_CHARS + 1]) + && self.inner == RenderableCellContent::Chars((' ', None)) } fn compute_fg_rgb(config: &Config, colors: &color::List, fg: Color, flags: Flags) -> Rgb { @@ -425,7 +427,7 @@ impl<'a, C> Iterator for RenderableCellsIter<'a, C> { let buffer_point = self.grid.visible_to_buffer(self.cursor.point); let cell = Indexed { - inner: self.grid[buffer_point.line][buffer_point.col], + inner: &self.grid[buffer_point.line][buffer_point.col], column: self.cursor.point.col, line: self.cursor.point.line, }; @@ -851,8 +853,8 @@ impl Term { let num_lines = size.screen_lines; let history_size = config.scrolling.history() as usize; - let grid = Grid::new(num_lines, num_cols, history_size, Cell::default()); - let alt = Grid::new(num_lines, num_cols, 0 /* scroll history */, Cell::default()); + let grid = Grid::new(num_lines, num_cols, history_size); + let alt = Grid::new(num_lines, num_cols, 0); let tabs = TabStops::new(grid.cols()); @@ -979,7 +981,7 @@ impl Term { let mut tab_mode = false; for col in IndexRange::from(cols.start..line_length) { - let cell = grid_line[col]; + let cell = &grid_line[col]; // Skip over cells until next tab-stop once a tab was found. if tab_mode { @@ -999,7 +1001,7 @@ impl Term { text.push(cell.c); // Push zero-width characters. - for c in (&cell.chars()[1..]).iter().take_while(|c| **c != ' ') { + for c in cell.zerowidth().into_iter().flatten() { text.push(*c); } } @@ -1111,14 +1113,14 @@ impl Term { pub fn swap_alt(&mut self) { if !self.mode.contains(TermMode::ALT_SCREEN) { // Set alt screen cursor to the current primary screen cursor. - self.inactive_grid.cursor = self.grid.cursor; + self.inactive_grid.cursor = self.grid.cursor.clone(); // Drop information about the primary screens saved cursor. - self.grid.saved_cursor = self.grid.cursor; + self.grid.saved_cursor = self.grid.cursor.clone(); // Reset alternate screen contents. - let template = self.inactive_grid.cursor.template; - self.inactive_grid.region_mut(..).each(|c| c.reset(&template)); + let bg = self.inactive_grid.cursor.template.bg; + self.inactive_grid.region_mut(..).each(|cell| *cell = bg.into()); } mem::swap(&mut self.grid, &mut self.inactive_grid); @@ -1149,8 +1151,7 @@ impl Term { .and_then(|s| s.rotate(self, &absolute_region, -(lines.0 as isize))); // Scroll between origin and bottom - let template = Cell { bg: self.grid.cursor.template.bg, ..Cell::default() }; - self.grid.scroll_down(®ion, lines, template); + self.grid.scroll_down(®ion, lines); } /// Scroll screen up @@ -1173,8 +1174,7 @@ impl Term { self.se