use std::borrow::Cow;
use crate::config::Style;
use crate::options::StyleOption;
pub fn normalized<'a>(text: &'a str, style: &Style) -> Cow<'a, str> {
let Some(rest) = text.strip_prefix("//") else {
return Cow::Borrowed(text);
};
let decorators = rest
.chars()
.take_while(|character| matches!(character, '/' | '!' | ':' | '<'))
.count();
let after_prefix = 2 + decorators;
let minimum = style.count(StyleOption::SpacesInLineCommentPrefixMinimum);
let maximum = style.number(StyleOption::SpacesInLineCommentPrefixMaximum);
let body = &text[after_prefix..];
if body.is_empty() {
return Cow::Borrowed(text);
}
let spaces = body
.chars()
.take_while(|character| *character == ' ')
.count();
let wanted = if maximum < 0 {
spaces.max(minimum)
} else {
spaces.clamp(minimum, maximum as usize)
};
if wanted == spaces {
return Cow::Borrowed(text);
}
let mut out = String::with_capacity(text.len() + wanted);
out.push_str(&text[..after_prefix]);
out.push_str(&" ".repeat(wanted));
out.push_str(&body[spaces..]);
Cow::Owned(out)
}
#[cfg(test)]
mod tests {
use super::*;
fn llvm() -> Style {
Style::default_style()
}
fn check(input: &str, expected: &str) {
assert_eq!(
normalized(input, &llvm()),
expected,
"normalising {input:?}"
);
}
#[test]
fn one_space_is_inserted_where_there_is_none() {
check("//using enum X;", "// using enum X;");
check("//NOLINT", "// NOLINT");
check("//trailing", "// trailing");
}
#[test]
fn doc_and_reference_markers_keep_their_prefix() {
check("///doc comment", "/// doc comment");
check("//!bang", "//! bang");
check("//:ref", "//: ref");
}
#[test]
fn existing_spacing_is_kept() {
check("// two spaces", "// two spaces");
check("// already spaced", "// already spaced");
}
#[test]
fn an_empty_comment_stays_empty() {
check("//", "//");
}
#[test]
fn a_block_comment_is_not_touched() {
check("/*block*/", "/*block*/");
}
}