Skip to main content

oicp_kit/types/
text.rs

1//! `Text` — a length-limited OICP string, and the shapes built on it.
2
3use core::fmt;
4use core::str::FromStr;
5
6use serde::{Deserialize, Deserializer, Serialize, Serializer};
7
8use super::builder::strict_builder;
9use super::validate::{Validate, Validator, ViolationCode, validate_fields};
10
11/// A string with the maximum length OICP's property table gives for its field.
12///
13/// `N` is that maximum. Over-long values **arrive** — a peer that sends a 60-character city name
14/// must not make the surrounding page undecodable — and [`Validate::validate`] reports them;
15/// [`Text::new`] refuses to build one.
16///
17/// ```
18/// use oicp_kit::types::{Text, Validate};
19///
20/// let city = Text::<50>::new("Berlin")?;
21/// assert_eq!(city.as_str(), "Berlin");
22///
23/// // Too long to construct…
24/// assert!(Text::<3>::new("Berlin").is_err());
25/// // …but it still decodes, and is reported.
26/// let arrived: Text<3> = serde_json::from_str(r#""Berlin""#)?;
27/// assert!(arrived.validate().is_err());
28/// # Ok::<(), Box<dyn std::error::Error>>(())
29/// ```
30#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
31pub struct Text<const N: usize>(String);
32
33/// Why a string could not be built.
34#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
35pub enum TextError {
36    /// The value was longer than the field's maximum.
37    #[error("the value is {actual} characters, but the maximum is {max}")]
38    TooLong {
39        /// The maximum the field allows.
40        max: usize,
41        /// The length of the offered value.
42        actual: usize,
43    },
44}
45
46impl<const N: usize> Text<N> {
47    /// The maximum length of this field, per the specification's property table.
48    pub const MAX: usize = N;
49
50    /// Builds a value, refusing one that is already out of spec.
51    ///
52    /// # Errors
53    ///
54    /// Returns [`TextError::TooLong`] when the value exceeds `N` characters.
55    pub fn new(value: impl Into<String>) -> Result<Self, TextError> {
56        let s = value.into();
57        let actual = s.chars().count();
58        if actual > N {
59            return Err(TextError::TooLong { max: N, actual });
60        }
61        Ok(Self(s))
62    }
63
64    /// Accepts `value` without checking its length; [`Validate`] reports it.
65    #[must_use]
66    pub fn new_unchecked(value: impl Into<String>) -> Self {
67        Self(value.into())
68    }
69
70    /// The text.
71    #[must_use]
72    pub fn as_str(&self) -> &str {
73        &self.0
74    }
75
76    /// The text, consuming the wrapper.
77    #[must_use]
78    pub fn into_string(self) -> String {
79        self.0
80    }
81
82    /// The length in characters.
83    #[must_use]
84    pub fn len(&self) -> usize {
85        self.0.chars().count()
86    }
87
88    /// Whether the text is empty.
89    #[must_use]
90    pub fn is_empty(&self) -> bool {
91        self.0.is_empty()
92    }
93}
94
95impl<const N: usize> fmt::Display for Text<N> {
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        f.write_str(&self.0)
98    }
99}
100
101impl<const N: usize> FromStr for Text<N> {
102    type Err = TextError;
103    fn from_str(s: &str) -> Result<Self, Self::Err> {
104        Self::new(s)
105    }
106}
107
108impl<const N: usize> Validate for Text<N> {
109    fn validate_in(&self, v: &mut Validator) {
110        let actual = self.len();
111        if actual > N {
112            v.report(
113                ViolationCode::TooLong,
114                format!("the value is {actual} characters, but the maximum is {N}"),
115            );
116        }
117    }
118}
119
120impl<const N: usize> Serialize for Text<N> {
121    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
122        s.serialize_str(&self.0)
123    }
124}
125
126impl<'de, const N: usize> Deserialize<'de> for Text<N> {
127    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
128        Ok(Self(String::deserialize(d)?))
129    }
130}
131
132impl<const N: usize> AsRef<str> for Text<N> {
133    fn as_ref(&self) -> &str {
134        &self.0
135    }
136}
137
138// These conversions are deliberately **permissive**, so a builder field can take a `&str`
139// directly. The strictness promised by "construct strictly" lives one level up: every wire type's
140// `build()` validates the finished object and returns `Err(Violations)`, so an over-long value
141// entered here is caught before the object exists. `build_unchecked()` is the escape hatch, and
142// says so in its name.
143impl<const N: usize> From<&str> for Text<N> {
144    fn from(s: &str) -> Self {
145        Self(s.to_owned())
146    }
147}
148
149impl<const N: usize> From<String> for Text<N> {
150    fn from(s: String) -> Self {
151        Self(s)
152    }
153}
154
155#[cfg(feature = "schema")]
156impl<const N: usize> schemars::JsonSchema for Text<N> {
157    fn schema_name() -> std::borrow::Cow<'static, str> {
158        format!("Text{N}").into()
159    }
160    fn json_schema(_g: &mut schemars::SchemaGenerator) -> schemars::Schema {
161        schemars::json_schema!({ "type": "string", "maxLength": N })
162    }
163}
164
165/// A partner-assigned session identifier, opaque to Hubject.
166///
167/// Both `CPOPartnerSessionID` and `EMPPartnerSessionID` are free-text, max 250 characters:
168/// *"Partner systems can use this field to link their own session handling to HBS processes."*
169pub type PartnerSessionId = Text<250>;
170
171/// Free text in a stated language, used for station names and additional information.
172///
173/// Spec: `InfoTextType`. `lang` is an ISO-639-1 or ISO-639-2/T code with optional region and
174/// script subtags; `value` is at most 150 characters.
175#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, bon::Builder)]
176#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
177#[serde(deny_unknown_fields)]
178#[builder(finish_fn = build_unchecked)]
179pub struct InfoText {
180    /// The language the text is in, e.g. `en`, `de`, `de-AT`.
181    #[builder(into)]
182    pub lang: String,
183    /// The text itself.
184    #[builder(into)]
185    pub value: Text<150>,
186}
187
188impl InfoText {
189    /// Builds a text in `lang`.
190    ///
191    /// # Errors
192    ///
193    /// Returns [`TextError::TooLong`] when `value` exceeds 150 characters.
194    pub fn new(lang: impl Into<String>, value: impl Into<String>) -> Result<Self, TextError> {
195        Ok(Self { lang: lang.into(), value: Text::new(value)? })
196    }
197
198    /// Whether `lang` matches the specification's language-code pattern.
199    ///
200    /// `^[a-z]{2,3}(?:-[A-Z]{2,3}(?:-[a-zA-Z]{4})?)?(?:-x-[a-zA-Z0-9]{1,8})?$`
201    #[must_use]
202    pub fn lang_is_well_formed(&self) -> bool {
203        let mut parts = self.lang.split('-');
204        let Some(primary) = parts.next() else { return false };
205        if !matches!(primary.len(), 2 | 3) || !primary.bytes().all(|c| c.is_ascii_lowercase()) {
206            return false;
207        }
208        let mut rest = parts.peekable();
209        if let Some(region) = rest.peek()
210            && *region != "x"
211        {
212            let region = rest.next().unwrap_or_default();
213            if !matches!(region.len(), 2 | 3) || !region.bytes().all(|c| c.is_ascii_uppercase()) {
214                return false;
215            }
216            if let Some(script) = rest.peek()
217                && *script != "x"
218            {
219                let script = rest.next().unwrap_or_default();
220                if script.len() != 4 || !script.bytes().all(|c| c.is_ascii_alphabetic()) {
221                    return false;
222                }
223            }
224        }
225        match (rest.next(), rest.next(), rest.next()) {
226            (None, _, _) => true,
227            (Some("x"), Some(private), None) => {
228                (1..=8).contains(&private.len()) && private.bytes().all(|c| c.is_ascii_alphanumeric())
229            }
230            _ => false,
231        }
232    }
233}
234
235impl Validate for InfoText {
236    fn validate_in(&self, v: &mut Validator) {
237        if !self.lang_is_well_formed() {
238            v.report_at(
239                "lang",
240                ViolationCode::PatternMismatch,
241                format!("{:?} is not an ISO-639-1 or ISO-639-2/T language code", self.lang),
242            );
243        }
244        validate_fields!(self, v, value as "value");
245    }
246}
247
248// Every builder's `build()` validates; `build_unchecked()` is the escape hatch.
249strict_builder!(InfoText, InfoTextBuilder, info_text_builder);
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254
255    #[test]
256    fn over_long_text_decodes_and_is_reported_but_cannot_be_constructed() {
257        assert!(Text::<3>::new("Berlin").is_err());
258        let arrived: Text<3> = serde_json::from_str(r#""Berlin""#).unwrap();
259        assert_eq!(arrived.validate().unwrap_err().as_slice()[0].code, ViolationCode::TooLong);
260        assert_eq!(serde_json::to_string(&arrived).unwrap(), r#""Berlin""#);
261    }
262
263    #[test]
264    fn length_is_counted_in_characters_not_bytes() {
265        // Five characters, ten bytes: a byte-length check would reject this wrongly.
266        let text = Text::<5>::new("äöüßé").unwrap();
267        assert_eq!(text.len(), 5);
268        assert!(text.validate().is_ok());
269    }
270
271    #[test]
272    fn language_codes_follow_the_spec_pattern() {
273        for good in ["en", "de", "deu", "de-AT", "zh-CN-Hans", "en-x-custom"] {
274            let t = InfoText::new(good, "x").unwrap();
275            assert!(t.lang_is_well_formed(), "{good} should be valid");
276            assert!(t.validate().is_ok());
277        }
278        for bad in ["", "E", "EN", "english", "de_AT", "de-at"] {
279            let t = InfoText::new(bad, "x").unwrap();
280            assert!(!t.lang_is_well_formed(), "{bad} should be invalid");
281        }
282    }
283}