use crate::{FieldName, LogicalValue};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum LineEnding {
#[default]
Lf,
CrLf,
Cr,
}
impl LineEnding {
pub const fn as_str(self) -> &'static str {
match self {
Self::Lf => "\n",
Self::CrLf => "\r\n",
Self::Cr => "\r",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FormatStyle {
pub line_ending: LineEnding,
pub continuation_indent: String,
pub space_after_colon: bool,
}
impl Default for FormatStyle {
fn default() -> Self {
Self {
line_ending: LineEnding::Lf,
continuation_indent: " ".to_owned(),
space_after_colon: true,
}
}
}
pub fn field(name: &FieldName, value: &LogicalValue, style: &FormatStyle) -> String {
let mut lines = value.as_str().split('\n');
let first = lines.next().unwrap_or_default();
let mut output = format!("{name}:");
if style.space_after_colon && !first.is_empty() {
output.push(' ');
}
output.push_str(first);
for line in lines {
output.push_str(style.line_ending.as_str());
output.push_str(&style.continuation_indent);
output.push_str(if line.is_empty() { "." } else { line });
}
output
}
pub fn record(fields: &[String], style: &FormatStyle) -> String {
fields.join(style.line_ending.as_str())
}
pub fn document(records: &[String], style: &FormatStyle) -> String {
records.join(&format!("{0}{0}", style.line_ending.as_str()))
}