Skip to main content

languagetool_rust/api/check/
mod.rs

1//! Structures for `check` requests and responses.
2
3mod data_annotations;
4mod requests;
5mod responses;
6
7pub use data_annotations::*;
8pub use requests::*;
9pub use responses::*;
10use serde::Serializer;
11
12use crate::error::{Error, Result};
13
14/// Parse `v` is valid language code.
15///
16/// A valid language code is usually
17/// - a two character string matching pattern `[a-z]{2}
18/// - a five character string matching pattern `[a-z]{2}-[A-Z]{2}
19/// - or some more complex ascii string (see below)
20///
21/// Language code is case-insensitive.
22///
23/// Therefore, a valid language code must match the following:
24///
25/// - `[a-zA-Z]{2,3}(-[a-zA-Z]{2}(-[a-zA-Z]+)*)?`
26///
27/// or
28///
29/// - "auto"
30///
31/// > Note: a valid language code does not mean that it exists.
32///
33/// # Examples
34///
35/// ```
36/// # use languagetool_rust::api::check::parse_language_code;
37/// assert!(parse_language_code("en").is_ok());
38///
39/// assert!(parse_language_code("en-US").is_ok());
40///
41/// assert!(parse_language_code("en-us").is_ok());
42///
43/// assert!(parse_language_code("ca-ES-valencia").is_ok());
44///
45/// assert!(parse_language_code("abcd").is_err());
46///
47/// assert!(parse_language_code("en_US").is_err());
48///
49/// assert!(parse_language_code("fr-french").is_err());
50///
51/// assert!(parse_language_code("some random text").is_err());
52/// ```
53#[cfg(feature = "cli")]
54pub fn parse_language_code(v: &str) -> Result<String> {
55    #[inline]
56    fn is_match(v: &str) -> bool {
57        let mut splits = v.split('-');
58
59        match splits.next() {
60            Some(s)
61                if (s.len() == 2 || s.len() == 3) && s.chars().all(|c| c.is_ascii_alphabetic()) => {
62            },
63            _ => return false,
64        }
65
66        match splits.next() {
67            Some(s) if s.len() != 2 || s.chars().any(|c| !c.is_ascii_alphabetic()) => return false,
68            Some(_) => (),
69            None => return true,
70        }
71        for s in splits {
72            if !s.chars().all(|c| c.is_ascii_alphabetic()) {
73                return false;
74            }
75        }
76        true
77    }
78
79    if v == "auto" || is_match(v) {
80        Ok(v.to_string())
81    } else {
82        Err(Error::InvalidValue(
83            "The value should be `\"auto\"` or match regex pattern: \
84             ^[a-zA-Z]{2,3}(-[a-zA-Z]{2}(-[a-zA-Z]+)*)?$"
85                .to_string(),
86        ))
87    }
88}
89
90/// Utility function to serialize a optional vector a strings
91/// into a comma separated list of strings.
92///
93/// This is required by reqwest's RequestBuilder, otherwise it
94/// will not work.
95pub(crate) fn serialize_option_vec_string<S>(
96    v: &Option<Vec<String>>,
97    serializer: S,
98) -> std::result::Result<S::Ok, S::Error>
99where
100    S: Serializer,
101{
102    match v {
103        Some(v) if v.len() == 1 => serializer.serialize_str(&v[0]),
104        Some(v) if v.len() > 1 => {
105            let size = v.iter().map(|s| s.len()).sum::<usize>() + v.len() - 1;
106            let mut string = String::with_capacity(size);
107
108            string.push_str(&v[0]);
109
110            for s in &v[1..] {
111                string.push(',');
112                string.push_str(s);
113            }
114
115            serializer.serialize_str(string.as_ref())
116        },
117        _ => serializer.serialize_none(),
118    }
119}
120
121#[cfg(test)]
122mod tests {
123    use super::*;
124
125    #[test]
126    fn test_serialize_option_vec_string() {
127        use serde::Serialize;
128
129        #[derive(Serialize)]
130        struct Foo {
131            #[serde(serialize_with = "serialize_option_vec_string")]
132            values: Option<Vec<String>>,
133        }
134
135        impl Foo {
136            fn new<I, T>(values: I) -> Self
137            where
138                I: IntoIterator<Item = T>,
139                T: ToString,
140            {
141                Self {
142                    values: Some(values.into_iter().map(|v| v.to_string()).collect()),
143                }
144            }
145            fn none() -> Self {
146                Self { values: None }
147            }
148        }
149
150        let got = serde_json::to_string(&Foo::new(vec!["en-US", "de-DE"])).unwrap();
151        assert_eq!(got, r#"{"values":"en-US,de-DE"}"#);
152
153        let got = serde_json::to_string(&Foo::new(vec!["en-US"])).unwrap();
154        assert_eq!(got, r#"{"values":"en-US"}"#);
155
156        let got = serde_json::to_string(&Foo::new(Vec::<String>::new())).unwrap();
157        assert_eq!(got, r#"{"values":null}"#);
158
159        let got = serde_json::to_string(&Foo::none()).unwrap();
160        assert_eq!(got, r#"{"values":null}"#);
161    }
162}