use std::{
borrow::Cow,
error::Error,
fmt::{self, Display, Formatter},
};
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
use serde::{Deserialize, Deserializer, Serialize, de::Error as _};
pub const DEFAULT_PUBLIC_TEXT_CHARS: usize = 1_024;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(transparent)]
pub struct PublicText(Cow<'static, str>);
impl PublicText {
pub fn new(value: impl Into<String>) -> Result<Self, PublicTextError> {
Self::with_max_chars(value, DEFAULT_PUBLIC_TEXT_CHARS)
}
pub const fn from_static(value: &'static str) -> Self {
let bytes = value.as_bytes();
assert!(!bytes.is_empty(), "public text must not be empty");
assert!(
count_characters(bytes) <= DEFAULT_PUBLIC_TEXT_CHARS,
"public text exceeds its character budget"
);
assert!(
!contains_control_character(bytes),
"public text must not contain a control character"
);
Self(Cow::Borrowed(value))
}
pub fn with_max_chars(
value: impl Into<String>,
max_chars: usize,
) -> Result<Self, PublicTextError> {
let value = value.into();
if max_chars == 0 {
return Err(PublicTextError::ZeroLimit);
}
if value.is_empty() {
return Err(PublicTextError::Empty);
}
let actual_chars = value.chars().count();
if actual_chars > max_chars {
return Err(PublicTextError::TooLong {
actual_chars,
max_chars,
});
}
if let Some((character_index, _)) =
value.chars().enumerate().find(|(_, ch)| ch.is_control())
{
return Err(PublicTextError::ControlCharacter { character_index });
}
Ok(Self(Cow::Owned(value)))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl Display for PublicText {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
impl AsRef<str> for PublicText {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl<'de> Deserialize<'de> for PublicText {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
Self::new(value).map_err(D::Error::custom)
}
}
impl JsonSchema for PublicText {
fn schema_name() -> Cow<'static, str> {
"PublicText".into()
}
fn json_schema(_generator: &mut SchemaGenerator) -> Schema {
json_schema!({
"type": "string",
"minLength": 1,
"maxLength": DEFAULT_PUBLIC_TEXT_CHARS,
"pattern": "^[^\\u0000-\\u001F\\u007F-\\u009F]*$"
})
}
}
pub(crate) const fn contains_control_character(bytes: &[u8]) -> bool {
let mut index = 0;
while index < bytes.len() {
let byte = bytes[index];
if byte < 0x20 || byte == 0x7f {
return true;
}
if byte == 0xc2 && index + 1 < bytes.len() && matches!(bytes[index + 1], 0x80..=0x9f) {
return true;
}
index += 1;
}
false
}
pub(crate) const fn count_characters(bytes: &[u8]) -> usize {
let mut index = 0;
let mut count = 0;
while index < bytes.len() {
if !matches!(bytes[index], 0x80..=0xbf) {
count += 1;
}
index += 1;
}
count
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PublicTextError {
ZeroLimit,
Empty,
TooLong {
actual_chars: usize,
max_chars: usize,
},
ControlCharacter {
character_index: usize,
},
}
impl Display for PublicTextError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::ZeroLimit => formatter.write_str("public text character limit must be positive"),
Self::Empty => formatter.write_str("public text must not be empty"),
Self::TooLong {
actual_chars,
max_chars,
} => write!(
formatter,
"public text is {actual_chars} characters; maximum is {max_chars}"
),
Self::ControlCharacter { character_index } => write!(
formatter,
"public text contains a control character at index {character_index}"
),
}
}
}
impl Error for PublicTextError {}