Skip to content

Commit

Permalink
fix: remove unneeded allocations when calling helix_view::Info::new
Browse files Browse the repository at this point in the history
  • Loading branch information
poliorcetics authored and archseer committed Oct 11, 2022
1 parent 28cb89e commit b58899b
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 17 deletions.
8 changes: 1 addition & 7 deletions helix-term/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4455,13 +4455,7 @@ fn select_textobject(cx: &mut Context, objtype: textobject::TextObject) {
(" ", "... or any character acting as a pair"),
];

cx.editor.autoinfo = Some(Info::new(
title,
help_text
.into_iter()
.map(|(col1, col2)| (col1.to_string(), col2.to_string()))
.collect(),
));
cx.editor.autoinfo = Some(Info::new(title, &help_text));
}

fn surround_add(cx: &mut Context) {
Expand Down
33 changes: 23 additions & 10 deletions helix-view/src/info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@ pub struct Info {
}

impl Info {
pub fn new(title: &str, body: Vec<(String, String)>) -> Self {
pub fn new<T, U>(title: &str, body: &[(T, U)]) -> Self
where
T: AsRef<str>,
U: AsRef<str>,
{
if body.is_empty() {
return Self {
title: title.to_string(),
Expand All @@ -26,11 +30,21 @@ impl Info {
};
}

let item_width = body.iter().map(|(item, _)| item.width()).max().unwrap();
let item_width = body
.iter()
.map(|(item, _)| item.as_ref().width())
.max()
.unwrap();
let mut text = String::new();

for (item, desc) in &body {
let _ = writeln!(text, "{:width$} {}", item, desc, width = item_width);
for (item, desc) in body {
let _ = writeln!(
text,
"{:width$} {}",
item.as_ref(),
desc.as_ref(),
width = item_width
);
}

Self {
Expand All @@ -42,33 +56,32 @@ impl Info {
}

pub fn from_keymap(title: &str, body: Vec<(&str, BTreeSet<KeyEvent>)>) -> Self {
let body = body
let body: Vec<_> = body
.into_iter()
.map(|(desc, events)| {
let events = events.iter().map(ToString::to_string).collect::<Vec<_>>();
(events.join(", "), desc.to_string())
(events.join(", "), desc)
})
.collect();

Self::new(title, body)
Self::new(title, &body)
}

pub fn from_registers(registers: &Registers) -> Self {
let body = registers
let body: Vec<_> = registers
.inner()
.iter()
.map(|(ch, reg)| {
let content = reg
.read()
.get(0)
.and_then(|s| s.lines().next())
.map(String::from)
.unwrap_or_default();
(ch.to_string(), content)
})
.collect();

let mut infobox = Self::new("Registers", body);
let mut infobox = Self::new("Registers", &body);
infobox.width = 30; // copied content could be very long
infobox
}
Expand Down

0 comments on commit b58899b

Please sign in to comment.