languagetool_rust/api/check/
mod.rs1mod 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#[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
90pub(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}