use std::borrow::Cow;
pub fn indent_by<'a, S>(number_of_spaces: usize, input: S) -> String
where
S: Into<Cow<'a, str>>,
{
indent(" ".repeat(number_of_spaces), input, false)
}
pub fn indent_with<'a, S, T>(prefix: S, input: T) -> String
where
S: Into<Cow<'a, str>>,
T: Into<Cow<'a, str>>,
{
indent(prefix, input, false)
}
pub fn indent_all_by<'a, S>(number_of_spaces: usize, input: S) -> String
where
S: Into<Cow<'a, str>>,
{
indent(" ".repeat(number_of_spaces), input, true)
}
pub fn indent_all_with<'a, S, T>(prefix: S, input: T) -> String
where
S: Into<Cow<'a, str>>,
T: Into<Cow<'a, str>>,
{
indent(prefix, input, true)
}
fn indent<'a, S, T>(prefix: S, input: T, indent_all: bool) -> String
where
S: Into<Cow<'a, str>>,
T: Into<Cow<'a, str>>,
{
let prefix = prefix.into();
let input = input.into();
let length = input.len();
let mut output = String::with_capacity(length + length / 2);
for (i, line) in input.lines().enumerate() {
if i > 0 {
output.push('\n');
if !line.is_empty() {
output.push_str(&prefix);
}
} else if indent_all && !line.is_empty() {
output.push_str(&prefix);
}
output.push_str(line);
}
if input.ends_with('\n') {
output.push('\n');
}
output
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_single_line_without_newline() {
assert_eq!(indent_by(2, "foo"), "foo")
}
#[test]
fn test_single_line_with_newline() {
assert_eq!(indent_by(2, "foo\n"), "foo\n")
}
#[test]
fn test_multiline_without_newline() {
assert_eq!(
indent_by(
2, "
foo
bar"
),
"
foo
bar"
)
}
#[test]
fn test_multiline_with_newline() {
assert_eq!(
indent_by(
2,
"
foo
bar
"
),
"
foo
bar
"
)
}
#[test]
fn test_empty_line() {
assert_eq!(
indent_by(
2,
"
foo
bar
"
),
"
foo
bar
"
)
}
#[test]
fn test_indent_all_by_empty_line() {
assert_eq!(
indent_all_by(
2,
"
foo
bar"
),
"
foo
bar"
)
}
#[test]
fn test_indent_all_by() {
assert_eq!(
indent_all_by(
2, "foo
bar"
),
" foo
bar"
)
}
#[test]
fn test_indent_with() {
assert_eq!(
indent_with(
" ",
"
foo
bar
"
),
"
foo
bar
"
)
}
#[test]
fn test_indent_all_with() {
assert_eq!(
indent_all_with(
" ", "foo
bar"
),
" foo
bar"
)
}
}