1use 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#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
31pub struct Text<const N: usize>(String);
32
33#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
35pub enum TextError {
36 #[error("the value is {actual} characters, but the maximum is {max}")]
38 TooLong {
39 max: usize,
41 actual: usize,
43 },
44}
45
46impl<const N: usize> Text<N> {
47 pub const MAX: usize = N;
49
50 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 #[must_use]
66 pub fn new_unchecked(value: impl Into<String>) -> Self {
67 Self(value.into())
68 }
69
70 #[must_use]
72 pub fn as_str(&self) -> &str {
73 &self.0
74 }
75
76 #[must_use]
78 pub fn into_string(self) -> String {
79 self.0
80 }
81
82 #[must_use]
84 pub fn len(&self) -> usize {
85 self.0.chars().count()
86 }
87
88 #[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
138impl<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
165pub type PartnerSessionId = Text<250>;
170
171#[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 #[builder(into)]
182 pub lang: String,
183 #[builder(into)]
185 pub value: Text<150>,
186}
187
188impl InfoText {
189 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 #[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
248strict_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 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}