use core::fmt;
use core::str::FromStr;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use super::builder::strict_builder;
use super::validate::{Validate, Validator, ViolationCode, validate_fields};
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Text<const N: usize>(String);
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum TextError {
#[error("the value is {actual} characters, but the maximum is {max}")]
TooLong {
max: usize,
actual: usize,
},
}
impl<const N: usize> Text<N> {
pub const MAX: usize = N;
pub fn new(value: impl Into<String>) -> Result<Self, TextError> {
let s = value.into();
let actual = s.chars().count();
if actual > N {
return Err(TextError::TooLong { max: N, actual });
}
Ok(Self(s))
}
#[must_use]
pub fn new_unchecked(value: impl Into<String>) -> Self {
Self(value.into())
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn into_string(self) -> String {
self.0
}
#[must_use]
pub fn len(&self) -> usize {
self.0.chars().count()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl<const N: usize> fmt::Display for Text<N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl<const N: usize> FromStr for Text<N> {
type Err = TextError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::new(s)
}
}
impl<const N: usize> Validate for Text<N> {
fn validate_in(&self, v: &mut Validator) {
let actual = self.len();
if actual > N {
v.report(
ViolationCode::TooLong,
format!("the value is {actual} characters, but the maximum is {N}"),
);
}
}
}
impl<const N: usize> Serialize for Text<N> {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&self.0)
}
}
impl<'de, const N: usize> Deserialize<'de> for Text<N> {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
Ok(Self(String::deserialize(d)?))
}
}
impl<const N: usize> AsRef<str> for Text<N> {
fn as_ref(&self) -> &str {
&self.0
}
}
impl<const N: usize> From<&str> for Text<N> {
fn from(s: &str) -> Self {
Self(s.to_owned())
}
}
impl<const N: usize> From<String> for Text<N> {
fn from(s: String) -> Self {
Self(s)
}
}
#[cfg(feature = "schema")]
impl<const N: usize> schemars::JsonSchema for Text<N> {
fn schema_name() -> std::borrow::Cow<'static, str> {
format!("Text{N}").into()
}
fn json_schema(_g: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({ "type": "string", "maxLength": N })
}
}
pub type PartnerSessionId = Text<250>;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, bon::Builder)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[builder(finish_fn = build_unchecked)]
pub struct InfoText {
#[builder(into)]
pub lang: String,
#[builder(into)]
pub value: Text<150>,
}
impl InfoText {
pub fn new(lang: impl Into<String>, value: impl Into<String>) -> Result<Self, TextError> {
Ok(Self { lang: lang.into(), value: Text::new(value)? })
}
#[must_use]
pub fn lang_is_well_formed(&self) -> bool {
let mut parts = self.lang.split('-');
let Some(primary) = parts.next() else { return false };
if !matches!(primary.len(), 2 | 3) || !primary.bytes().all(|c| c.is_ascii_lowercase()) {
return false;
}
let mut rest = parts.peekable();
if let Some(region) = rest.peek()
&& *region != "x"
{
let region = rest.next().unwrap_or_default();
if !matches!(region.len(), 2 | 3) || !region.bytes().all(|c| c.is_ascii_uppercase()) {
return false;
}
if let Some(script) = rest.peek()
&& *script != "x"
{
let script = rest.next().unwrap_or_default();
if script.len() != 4 || !script.bytes().all(|c| c.is_ascii_alphabetic()) {
return false;
}
}
}
match (rest.next(), rest.next(), rest.next()) {
(None, _, _) => true,
(Some("x"), Some(private), None) => {
(1..=8).contains(&private.len()) && private.bytes().all(|c| c.is_ascii_alphanumeric())
}
_ => false,
}
}
}
impl Validate for InfoText {
fn validate_in(&self, v: &mut Validator) {
if !self.lang_is_well_formed() {
v.report_at(
"lang",
ViolationCode::PatternMismatch,
format!("{:?} is not an ISO-639-1 or ISO-639-2/T language code", self.lang),
);
}
validate_fields!(self, v, value as "value");
}
}
strict_builder!(InfoText, InfoTextBuilder, info_text_builder);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn over_long_text_decodes_and_is_reported_but_cannot_be_constructed() {
assert!(Text::<3>::new("Berlin").is_err());
let arrived: Text<3> = serde_json::from_str(r#""Berlin""#).unwrap();
assert_eq!(arrived.validate().unwrap_err().as_slice()[0].code, ViolationCode::TooLong);
assert_eq!(serde_json::to_string(&arrived).unwrap(), r#""Berlin""#);
}
#[test]
fn length_is_counted_in_characters_not_bytes() {
let text = Text::<5>::new("äöüßé").unwrap();
assert_eq!(text.len(), 5);
assert!(text.validate().is_ok());
}
#[test]
fn language_codes_follow_the_spec_pattern() {
for good in ["en", "de", "deu", "de-AT", "zh-CN-Hans", "en-x-custom"] {
let t = InfoText::new(good, "x").unwrap();
assert!(t.lang_is_well_formed(), "{good} should be valid");
assert!(t.validate().is_ok());
}
for bad in ["", "E", "EN", "english", "de_AT", "de-at"] {
let t = InfoText::new(bad, "x").unwrap();
assert!(!t.lang_is_well_formed(), "{bad} should be invalid");
}
}
}