Skip to content

Commit

Permalink
[Perf] find min indention of the line and remove the ssame indention
Browse files Browse the repository at this point in the history
from subsequent lines
  • Loading branch information
mistricky committed Apr 25, 2024
1 parent 6b724b8 commit 6a5a756
Showing 1 changed file with 22 additions and 16 deletions.
38 changes: 22 additions & 16 deletions generator/src/code.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,25 +36,31 @@ fn replace_tab_to_space(text: &str) -> String {
str::replace(text, "\t", &spaces)
}

// If the first line have indention, remove the same indention from subsequent lines
// Find min indention of the line, and remove the same indention from subsequent lines
fn trim_space(text: &str) -> String {
let lines = text.split("\n").collect::<Vec<&str>>();
let first_line = lines.first().unwrap();
let head_spaces = Regex::new(r"^(\s*)").unwrap().find(first_line);

match head_spaces {
Some(head_spaces) => lines
.into_iter()
.map(|line| {
Regex::new(format!("^{}", head_spaces.as_str()).as_ref())
.unwrap()
.replace(line, "")
.to_string()
})
.collect::<Vec<String>>()
.join("\n"),
None => text.to_string(),
let regex = Regex::new(r"(?:^|\n)(\s*)").unwrap();
let captures_iter = regex.captures_iter(text);
let space_lengths = captures_iter
.map(|capture| capture.get(1).unwrap().as_str().len())
.collect::<Vec<usize>>();

if space_lengths.len() < lines.len() {
return text.to_string();
}

let need_to_remove_spaces = " ".repeat(space_lengths.into_iter().min().unwrap());

lines
.into_iter()
.map(|line| {
Regex::new(format!("^{}", need_to_remove_spaces).as_ref())
.unwrap()
.replace(line, "")
.to_string()
})
.collect::<Vec<String>>()
.join("\n")
}

pub fn prepare_code(code: &str) -> String {
Expand Down

0 comments on commit 6a5a756

Please sign in to comment.