use std::{
borrow::Cow,
error::Error,
fmt::{self, Display, Formatter},
};
use http::header::HeaderName as HttpHeaderName;
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
use serde::{Deserialize, Deserializer, Serialize, de::Error as _};
use crate::diagnostic::{contains_control_character, count_characters};
const MAX_PARAMETER_NAME_CHARS: usize = 128;
const MAX_FIELD_NAME_BYTES: usize = 65_535;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(transparent)]
pub struct ParameterName(Cow<'static, str>);
impl ParameterName {
pub fn new(value: impl Into<String>) -> Result<Self, ParameterNameError> {
let value = value.into();
if value.is_empty() {
return Err(ParameterNameError::Empty);
}
let actual_chars = value.chars().count();
if actual_chars > MAX_PARAMETER_NAME_CHARS {
return Err(ParameterNameError::TooLong { actual_chars });
}
if let Some((character_index, _)) =
value.chars().enumerate().find(|(_, ch)| ch.is_control())
{
return Err(ParameterNameError::ControlCharacter { character_index });
}
Ok(Self(Cow::Owned(value)))
}
pub const fn from_static(value: &'static str) -> Self {
let bytes = value.as_bytes();
assert!(!bytes.is_empty(), "parameter name must not be empty");
assert!(
count_characters(bytes) <= MAX_PARAMETER_NAME_CHARS,
"parameter name exceeds its character budget"
);
assert!(
!contains_control_character(bytes),
"parameter name must not contain a control character"
);
Self(Cow::Borrowed(value))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl Display for ParameterName {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
impl<'de> Deserialize<'de> for ParameterName {
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 ParameterName {
fn schema_name() -> Cow<'static, str> {
"ParameterName".into()
}
fn json_schema(_generator: &mut SchemaGenerator) -> Schema {
json_schema!({
"type": "string",
"minLength": 1,
"maxLength": MAX_PARAMETER_NAME_CHARS,
"pattern": "^[^\\u0000-\\u001F\\u007F-\\u009F]*$"
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParameterNameError {
Empty,
TooLong {
actual_chars: usize,
},
ControlCharacter {
character_index: usize,
},
}
impl Display for ParameterNameError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::Empty => formatter.write_str("parameter name must not be empty"),
Self::TooLong { actual_chars } => write!(
formatter,
"parameter name is {actual_chars} characters; maximum is {MAX_PARAMETER_NAME_CHARS}"
),
Self::ControlCharacter { character_index } => write!(
formatter,
"parameter name contains a control character at index {character_index}"
),
}
}
}
impl Error for ParameterNameError {}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(transparent)]
pub struct HeaderName(Cow<'static, str>);
impl HeaderName {
pub fn new(value: &str) -> Result<Self, HeaderNameError> {
let parsed = HttpHeaderName::from_bytes(value.as_bytes()).map_err(|_| HeaderNameError)?;
Ok(Self(Cow::Owned(parsed.as_str().to_owned())))
}
pub const fn from_static(value: &'static str) -> Self {
let bytes = value.as_bytes();
assert!(!bytes.is_empty(), "HTTP field name must not be empty");
assert!(
bytes.len() <= MAX_FIELD_NAME_BYTES,
"HTTP field name exceeds its encoded byte budget"
);
let mut index = 0;
while index < bytes.len() {
assert!(
is_canonical_field_byte(bytes[index]),
"HTTP field name must be lowercase token syntax"
);
index += 1;
}
Self(Cow::Borrowed(value))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl Display for HeaderName {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
impl<'de> Deserialize<'de> for HeaderName {
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 HeaderName {
fn schema_name() -> Cow<'static, str> {
"HeaderName".into()
}
fn json_schema(_generator: &mut SchemaGenerator) -> Schema {
json_schema!({
"type": "string",
"pattern": "^[!#$%&'*+.^_`|~0-9A-Za-z-]+$"
})
}
}
const FIELD_NAME_SYMBOLS: &[u8] = b"!#$%&'*+-.^_`|~";
const fn is_canonical_field_byte(byte: u8) -> bool {
if byte.is_ascii_lowercase() || byte.is_ascii_digit() {
return true;
}
let mut index = 0;
while index < FIELD_NAME_SYMBOLS.len() {
if FIELD_NAME_SYMBOLS[index] == byte {
return true;
}
index += 1;
}
false
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HeaderNameError;
impl Display for HeaderNameError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str("invalid HTTP field name")
}
}
impl Error for HeaderNameError {}