Skip to main content

r_dcf_syntax/
value.rs

1//! Validated semantic value types.
2
3use std::{error::Error, fmt, sync::Arc};
4
5/// A validated, case-sensitive DCF field name.
6#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
7pub struct FieldName(Arc<str>);
8
9impl FieldName {
10    /// Validates and stores `name`.
11    ///
12    /// # Errors
13    ///
14    /// Returns [`InvalidFieldName`] if the name is not valid DCF syntax.
15    pub fn new(name: impl AsRef<str>) -> Result<Self, InvalidFieldName> {
16        let name = name.as_ref();
17        if is_valid_field_name(name) {
18            Ok(Self(Arc::from(name)))
19        } else {
20            Err(InvalidFieldName)
21        }
22    }
23
24    /// Returns the field name.
25    pub fn as_str(&self) -> &str {
26        &self.0
27    }
28}
29
30impl fmt::Debug for FieldName {
31    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
32        formatter
33            .debug_tuple("FieldName")
34            .field(&self.as_str())
35            .finish()
36    }
37}
38
39impl fmt::Display for FieldName {
40    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
41        formatter.write_str(self.as_str())
42    }
43}
44
45impl TryFrom<&str> for FieldName {
46    type Error = InvalidFieldName;
47
48    fn try_from(value: &str) -> Result<Self, Self::Error> {
49        Self::new(value)
50    }
51}
52
53impl TryFrom<String> for FieldName {
54    type Error = InvalidFieldName;
55
56    fn try_from(value: String) -> Result<Self, Self::Error> {
57        Self::new(value)
58    }
59}
60
61/// Error returned for a field name outside the portable R DCF grammar.
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub struct InvalidFieldName;
64
65impl fmt::Display for InvalidFieldName {
66    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
67        formatter.write_str("invalid DCF field name")
68    }
69}
70
71impl Error for InvalidFieldName {}
72
73/// An owned logical value, with physical line endings excluded.
74#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
75pub struct LogicalValue(Arc<str>);
76
77impl LogicalValue {
78    /// Creates a logical value. LF separates logical lines; CR is rejected.
79    ///
80    /// # Errors
81    ///
82    /// Returns [`InvalidLogicalValue`] if the text cannot be represented as a
83    /// logical DCF value.
84    pub fn new(value: impl AsRef<str>) -> Result<Self, InvalidLogicalValue> {
85        let value = value.as_ref();
86        let lines_are_canonical = value.split('\n').enumerate().all(|(index, line)| {
87            line == line.trim_matches([' ', '\t']) && (index == 0 || line != ".")
88        });
89        if value.contains('\r') || value.contains('\0') || !lines_are_canonical {
90            Err(InvalidLogicalValue)
91        } else {
92            Ok(Self(Arc::from(value)))
93        }
94    }
95
96    /// Returns the unfolded logical text.
97    pub fn as_str(&self) -> &str {
98        &self.0
99    }
100}
101
102impl fmt::Display for LogicalValue {
103    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
104        formatter.write_str(self.as_str())
105    }
106}
107
108impl TryFrom<&str> for LogicalValue {
109    type Error = InvalidLogicalValue;
110
111    fn try_from(value: &str) -> Result<Self, Self::Error> {
112        Self::new(value)
113    }
114}
115
116impl TryFrom<String> for LogicalValue {
117    type Error = InvalidLogicalValue;
118
119    fn try_from(value: String) -> Result<Self, Self::Error> {
120        Self::new(value)
121    }
122}
123
124/// Error returned when logical text cannot be represented without ambiguity.
125#[derive(Debug, Clone, Copy, PartialEq, Eq)]
126pub struct InvalidLogicalValue;
127
128impl fmt::Display for InvalidLogicalValue {
129    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
130        formatter.write_str(
131            "logical DCF values cannot contain CR, NUL, surrounding horizontal whitespace, or a continued dot-only line",
132        )
133    }
134}
135
136impl Error for InvalidLogicalValue {}
137
138pub(crate) fn is_valid_field_name(name: &str) -> bool {
139    let mut chars = name.chars();
140    chars
141        .next()
142        .is_some_and(|character| character.is_ascii_alphanumeric())
143        && chars.all(|character| character.is_ascii_graphic() && character != ':')
144}