Skip to main content

r_dcf_syntax/
make.rs

1//! Canonical text builders.
2
3use crate::{FieldName, LogicalValue};
4
5/// A physical line-ending convention.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
7pub enum LineEnding {
8    /// Line feed (`\n`).
9    #[default]
10    Lf,
11    /// Carriage return followed by line feed (`\r\n`).
12    CrLf,
13    /// A lone carriage return (`\r`).
14    Cr,
15}
16
17impl LineEnding {
18    /// Returns the physical delimiter.
19    pub const fn as_str(self) -> &'static str {
20        match self {
21            Self::Lf => "\n",
22            Self::CrLf => "\r\n",
23            Self::Cr => "\r",
24        }
25    }
26}
27
28/// Formatting choices used by canonical builders.
29#[derive(Debug, Clone, PartialEq, Eq, Hash)]
30pub struct FormatStyle {
31    /// Physical line ending.
32    pub line_ending: LineEnding,
33    /// Indentation for continuation lines.
34    pub continuation_indent: String,
35    /// Whether non-empty first lines receive one space after the colon.
36    pub space_after_colon: bool,
37}
38
39impl Default for FormatStyle {
40    fn default() -> Self {
41        Self {
42            line_ending: LineEnding::Lf,
43            continuation_indent: " ".to_owned(),
44            space_after_colon: true,
45        }
46    }
47}
48
49/// Builds one field without a trailing line ending.
50pub fn field(name: &FieldName, value: &LogicalValue, style: &FormatStyle) -> String {
51    let mut lines = value.as_str().split('\n');
52    let first = lines.next().unwrap_or_default();
53    let mut output = format!("{name}:");
54    if style.space_after_colon && !first.is_empty() {
55        output.push(' ');
56    }
57    output.push_str(first);
58    for line in lines {
59        output.push_str(style.line_ending.as_str());
60        output.push_str(&style.continuation_indent);
61        output.push_str(if line.is_empty() { "." } else { line });
62    }
63    output
64}
65
66/// Builds one record from already-built fields, without a trailing line ending.
67pub fn record(fields: &[String], style: &FormatStyle) -> String {
68    fields.join(style.line_ending.as_str())
69}
70
71/// Builds a document from already-built records, without a trailing line ending.
72pub fn document(records: &[String], style: &FormatStyle) -> String {
73    records.join(&format!("{0}{0}", style.line_ending.as_str()))
74}