use crate::errors::ValidationError;
use crate::traits::ValueObject;
pub type HttpStatusCodeInput = u16;
pub type HttpStatusCodeOutput = u16;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct HttpStatusCode(u16);
impl ValueObject for HttpStatusCode {
type Input = HttpStatusCodeInput;
type Output = HttpStatusCodeOutput;
type Error = ValidationError;
fn new(value: Self::Input) -> Result<Self, Self::Error> {
if !(100..=599).contains(&value) {
return Err(ValidationError::invalid(
"HttpStatusCode",
&value.to_string(),
));
}
Ok(Self(value))
}
fn value(&self) -> &Self::Output {
&self.0
}
fn into_inner(self) -> Self::Input {
self.0
}
}
impl HttpStatusCode {
pub fn is_informational(&self) -> bool {
(100..=199).contains(&self.0)
}
pub fn is_success(&self) -> bool {
(200..=299).contains(&self.0)
}
pub fn is_redirection(&self) -> bool {
(300..=399).contains(&self.0)
}
pub fn is_client_error(&self) -> bool {
(400..=499).contains(&self.0)
}
pub fn is_server_error(&self) -> bool {
(500..=599).contains(&self.0)
}
}
impl std::fmt::Display for HttpStatusCode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_200() {
let code = HttpStatusCode::new(200).unwrap();
assert_eq!(*code.value(), 200);
}
#[test]
fn accepts_boundaries() {
assert!(HttpStatusCode::new(100).is_ok());
assert!(HttpStatusCode::new(599).is_ok());
}
#[test]
fn rejects_below_100() {
assert!(HttpStatusCode::new(99).is_err());
}
#[test]
fn rejects_600_and_above() {
assert!(HttpStatusCode::new(600).is_err());
}
#[test]
fn category_helpers() {
assert!(HttpStatusCode::new(100).unwrap().is_informational());
assert!(HttpStatusCode::new(200).unwrap().is_success());
assert!(HttpStatusCode::new(301).unwrap().is_redirection());
assert!(HttpStatusCode::new(404).unwrap().is_client_error());
assert!(HttpStatusCode::new(500).unwrap().is_server_error());
}
#[test]
fn display() {
let code = HttpStatusCode::new(404).unwrap();
assert_eq!(code.to_string(), "404");
}
#[test]
fn into_inner_roundtrip() {
let code = HttpStatusCode::new(201).unwrap();
assert_eq!(code.into_inner(), 201);
}
}