Skip to content

Commit

Permalink
remove unnecessary allocations in switch_case (#12786)
Browse files Browse the repository at this point in the history
  • Loading branch information
m4rch3n1ng authored Feb 27, 2025
1 parent 7bebe0a commit e1c7a1e
Showing 1 changed file with 35 additions and 3 deletions.
38 changes: 35 additions & 3 deletions helix-term/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ use crate::{

use crate::job::{self, Jobs};
use std::{
char::{ToLowercase, ToUppercase},
cmp::Ordering,
collections::{HashMap, HashSet},
error::Error,
Expand Down Expand Up @@ -1727,17 +1728,48 @@ where
exit_select_mode(cx);
}

enum CaseSwitcher {
Upper(ToUppercase),
Lower(ToLowercase),
Keep(Option<char>),
}

impl Iterator for CaseSwitcher {
type Item = char;

fn next(&mut self) -> Option<Self::Item> {
match self {
CaseSwitcher::Upper(upper) => upper.next(),
CaseSwitcher::Lower(lower) => lower.next(),
CaseSwitcher::Keep(ch) => ch.take(),
}
}

fn size_hint(&self) -> (usize, Option<usize>) {
match self {
CaseSwitcher::Upper(upper) => upper.size_hint(),
CaseSwitcher::Lower(lower) => lower.size_hint(),
CaseSwitcher::Keep(ch) => {
let n = if ch.is_some() { 1 } else { 0 };
(n, Some(n))
}
}
}
}

impl ExactSizeIterator for CaseSwitcher {}

fn switch_case(cx: &mut Context) {
switch_case_impl(cx, |string| {
string
.chars()
.flat_map(|ch| {
if ch.is_lowercase() {
ch.to_uppercase().collect()
CaseSwitcher::Upper(ch.to_uppercase())
} else if ch.is_uppercase() {
ch.to_lowercase().collect()
CaseSwitcher::Lower(ch.to_lowercase())
} else {
vec![ch]
CaseSwitcher::Keep(Some(ch))
}
})
.collect()
Expand Down

0 comments on commit e1c7a1e

Please sign in to comment.