ocpi_kit/types/
display_text.rs1use 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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
18#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
19#[non_exhaustive]
20pub struct DisplayText {
21 pub language: OcpiString<2>,
23 pub text: OcpiString<512>,
25 #[serde(flatten, default, skip_serializing_if = "Extensions::is_empty")]
27 pub extensions: Extensions,
28}
29
30impl DisplayText {
31 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}