Skip to content

Commit e1c7a1e

Browse files
authored
remove unnecessary allocations in switch_case (#12786)
1 parent 7bebe0a commit e1c7a1e

File tree

1 file changed

+35
-3
lines changed

1 file changed

+35
-3
lines changed

helix-term/src/commands.rs

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ use crate::{
6767

6868
use crate::job::{self, Jobs};
6969
use std::{
70+
char::{ToLowercase, ToUppercase},
7071
cmp::Ordering,
7172
collections::{HashMap, HashSet},
7273
error::Error,
@@ -1727,17 +1728,48 @@ where
17271728
exit_select_mode(cx);
17281729
}
17291730

1731+
enum CaseSwitcher {
1732+
Upper(ToUppercase),
1733+
Lower(ToLowercase),
1734+
Keep(Option<char>),
1735+
}
1736+
1737+
impl Iterator for CaseSwitcher {
1738+
type Item = char;
1739+
1740+
fn next(&mut self) -> Option<Self::Item> {
1741+
match self {
1742+
CaseSwitcher::Upper(upper) => upper.next(),
1743+
CaseSwitcher::Lower(lower) => lower.next(),
1744+
CaseSwitcher::Keep(ch) => ch.take(),
1745+
}
1746+
}
1747+
1748+
fn size_hint(&self) -> (usize, Option<usize>) {
1749+
match self {
1750+
CaseSwitcher::Upper(upper) => upper.size_hint(),
1751+
CaseSwitcher::Lower(lower) => lower.size_hint(),
1752+
CaseSwitcher::Keep(ch) => {
1753+
let n = if ch.is_some() { 1 } else { 0 };
1754+
(n, Some(n))
1755+
}
1756+
}
1757+
}
1758+
}
1759+
1760+
impl ExactSizeIterator for CaseSwitcher {}
1761+
17301762
fn switch_case(cx: &mut Context) {
17311763
switch_case_impl(cx, |string| {
17321764
string
17331765
.chars()
17341766
.flat_map(|ch| {
17351767
if ch.is_lowercase() {
1736-
ch.to_uppercase().collect()
1768+
CaseSwitcher::Upper(ch.to_uppercase())
17371769
} else if ch.is_uppercase() {
1738-
ch.to_lowercase().collect()
1770+
CaseSwitcher::Lower(ch.to_lowercase())
17391771
} else {
1740-
vec![ch]
1772+
CaseSwitcher::Keep(Some(ch))
17411773
}
17421774
})
17431775
.collect()

0 commit comments

Comments
 (0)