#[derive(Debug, Clone, PartialEq, Eq)]
pub(in crate::types::json) struct Indent(String);
impl Indent {
pub(in crate::types::json) fn detect(text: &str) -> Self {
let Some(line) = text
.split('\n')
.skip(1)
.find(|line| line.starts_with([' ', '\t']))
else {
return Self::two_spaces();
};
let run = &line[..line.len() - line.trim_start_matches([' ', '\t']).len()];
if run == "\t" || run.bytes().all(|byte| byte == b' ') {
Self(run.to_owned())
} else {
Self::two_spaces()
}
}
fn two_spaces() -> Self {
Self(" ".to_owned())
}
pub(in crate::types::json) const fn as_bytes(&self) -> &[u8] {
self.0.as_bytes()
}
}
#[cfg(test)]
mod tests {
use super::*;
const SOURCE: &str = "{\n \"permissions\": {\n \"allow\": [\n \"Bash(x:*)\"\n ]\n },\n \"zeta\": 1,\n \"alpha\": 12345678901234567890123,\n \"d\": 0.10,\n \"hooks\": {}\n}";
fn detected(text: &str) -> Vec<u8> {
Indent::detect(text).as_bytes().to_vec()
}
#[test]
fn indent_takes_two_spaces_from_the_first_indented_line() {
assert_eq!(detected("{\n \"a\": 1\n}"), b" ");
}
#[test]
fn indent_takes_four_spaces_from_the_first_indented_line() {
assert_eq!(detected(SOURCE), b" ");
}
#[test]
fn indent_takes_one_tab_from_the_first_indented_line() {
assert_eq!(detected("{\n\t\"a\": 1\n}"), b"\t");
}
#[test]
fn indent_falls_back_to_two_spaces_for_mixed_whitespace() {
assert_eq!(detected("{\n\t \"a\": 1\n}"), b" ");
assert_eq!(detected("{\n \t\"a\": 1\n}"), b" ");
}
#[test]
fn indent_falls_back_to_two_spaces_for_two_tabs() {
assert_eq!(detected("{\n\t\t\"a\": 1\n}"), b" ");
}
#[test]
fn indent_falls_back_to_two_spaces_without_an_indented_line() {
assert_eq!(detected("{\"a\":1}"), b" ");
assert_eq!(detected(""), b" ");
assert_eq!(detected("{\n\"a\": 1\n}"), b" ");
}
#[test]
fn indent_ignores_the_first_line() {
assert_eq!(detected(" {\n \"a\": 1\n}"), b" ");
}
#[test]
fn indent_reads_crlf_text_like_lf_text() {
assert_eq!(detected(&SOURCE.replace('\n', "\r\n")), b" ");
}
}