feat!(buffer): use `SmolStr` to avoid bunch of heap allocations for `Cell`s

pull/644/head
rhysd 2 years ago
parent a6b25a4877
commit 8d03851f7b

@ -27,6 +27,7 @@ unicode-width = "0.1"
termion = { version = "1.5", optional = true } termion = { version = "1.5", optional = true }
crossterm = { version = "0.23", optional = true } crossterm = { version = "0.23", optional = true }
serde = { version = "1", optional = true, features = ["derive"]} serde = { version = "1", optional = true, features = ["derive"]}
smol_str = "0.1"
[dev-dependencies] [dev-dependencies]
rand = "0.8" rand = "0.8"

@ -3,6 +3,7 @@ use crate::{
style::{Color, Modifier, Style}, style::{Color, Modifier, Style},
text::{Span, Spans}, text::{Span, Spans},
}; };
use smol_str::SmolStr;
use std::cmp::min; use std::cmp::min;
use unicode_segmentation::UnicodeSegmentation; use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr; use unicode_width::UnicodeWidthStr;
@ -10,7 +11,9 @@ use unicode_width::UnicodeWidthStr;
/// A buffer cell /// A buffer cell
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub struct Cell { pub struct Cell {
pub symbol: String, /// Symbol represents single Unicode grapheme cluster in the cell. To avoid heap allocation,
/// [`SmolStr`] is used instead of [`String`].
pub symbol: SmolStr,
pub fg: Color, pub fg: Color,
pub bg: Color, pub bg: Color,
pub modifier: Modifier, pub modifier: Modifier,
@ -18,14 +21,14 @@ pub struct Cell {
impl Cell { impl Cell {
pub fn set_symbol(&mut self, symbol: &str) -> &mut Cell { pub fn set_symbol(&mut self, symbol: &str) -> &mut Cell {
self.symbol.clear(); self.symbol = SmolStr::new(symbol);
self.symbol.push_str(symbol);
self self
} }
pub fn set_char(&mut self, ch: char) -> &mut Cell { pub fn set_char(&mut self, ch: char) -> &mut Cell {
self.symbol.clear(); let mut buf = [0; 4];
self.symbol.push(ch); let ch = ch.encode_utf8(&mut buf);
self.symbol = SmolStr::new(ch);
self self
} }
@ -59,8 +62,7 @@ impl Cell {
} }
pub fn reset(&mut self) { pub fn reset(&mut self) {
self.symbol.clear(); self.symbol = SmolStr::new(" ");
self.symbol.push(' ');
self.fg = Color::Reset; self.fg = Color::Reset;
self.bg = Color::Reset; self.bg = Color::Reset;
self.modifier = Modifier::empty(); self.modifier = Modifier::empty();
@ -97,7 +99,7 @@ impl Default for Cell {
/// assert_eq!(buf.get(0, 2).symbol, "x"); /// assert_eq!(buf.get(0, 2).symbol, "x");
/// buf.set_string(3, 0, "string", Style::default().fg(Color::Red).bg(Color::White)); /// buf.set_string(3, 0, "string", Style::default().fg(Color::Red).bg(Color::White));
/// assert_eq!(buf.get(5, 0), &Cell{ /// assert_eq!(buf.get(5, 0), &Cell{
/// symbol: String::from("r"), /// symbol: "r".into(),
/// fg: Color::Red, /// fg: Color::Red,
/// bg: Color::White, /// bg: Color::White,
/// modifier: Modifier::empty() /// modifier: Modifier::empty()

Loading…
Cancel
Save