Skip to main content

ocpi_kit/types/
display_text.rs

1//! `DisplayText` — a string with the language it is written in.
2
3use serde::{Deserialize, Serialize};
4
5use super::extensions::Extensions;
6use super::string::OcpiString;
7use super::text::InvalidString;
8use super::validate::{Validate, Validator};
9use super::validate_fields;
10
11/// Text to be shown to an end user, tagged with its language.
12///
13/// > *`language`: Language Code ISO 639-1. `text`: Text to be displayed to a end user. No markup,
14/// > html etc. allowed.*
15///
16/// Spec: 2.3.0 §types_displaytext_class
17#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
18#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
19#[non_exhaustive]
20pub struct DisplayText {
21    /// Language Code ISO 639-1.
22    pub language: OcpiString<2>,
23    /// Text to be displayed to an end user. No markup, HTML etc. allowed.
24    pub text: OcpiString<512>,
25    /// Undocumented JSON fields, preserved verbatim.
26    #[serde(flatten, default, skip_serializing_if = "Extensions::is_empty")]
27    pub extensions: Extensions,
28}
29
30impl DisplayText {
31    /// Creates a `DisplayText`.
32    ///
33    /// # Errors
34    ///
35    /// Returns [`InvalidString`] if the language code is not two characters or the text is
36    /// longer than 512 characters, or if either contains a control character.
37    pub fn new(language: impl Into<String>, text: impl Into<String>) -> Result<Self, InvalidString> {
38        Ok(Self {
39            language: OcpiString::new(language)?,
40            text: OcpiString::new(text)?,
41            extensions: Extensions::new(),
42        })
43    }
44}
45
46impl Validate for DisplayText {
47    fn validate_in(&self, v: &mut Validator) {
48        validate_fields!(self, v, language, text);
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55
56    #[test]
57    fn round_trips_and_keeps_extensions() {
58        let json = r#"{"language":"en","text":"2 euro per hour","nltnm_source":"cms"}"#;
59        let dt: DisplayText = serde_json::from_str(json).unwrap();
60        assert_eq!(dt.text.as_str(), "2 euro per hour");
61        assert_eq!(serde_json::to_string(&dt).unwrap(), json);
62    }
63
64    #[test]
65    fn constructor_enforces_the_language_code_length() {
66        assert!(DisplayText::new("en", "hello").is_ok());
67        assert!(DisplayText::new("english", "hello").is_err());
68    }
69}