net_traits/
http_status.rs1#![deny(unsafe_code)]
6
7use std::ops::RangeBounds;
8
9use serde::{Deserialize, Serialize};
10
11use crate::{MallocSizeOf, StatusCode};
12
13#[derive(Clone, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
17pub struct HttpStatus {
18 code: u16,
19 message: Vec<u8>,
20}
21
22impl HttpStatus {
23 pub fn new(code: StatusCode, message: Vec<u8>) -> Self {
25 Self {
26 code: code.as_u16(),
27 message,
28 }
29 }
30
31 pub fn new_raw(code: u16, message: Vec<u8>) -> Self {
34 if !(100..=599).contains(&code) {
35 panic!(
36 "HttpStatus code must be in the range 100 to 599, inclusive, but is {}",
37 code
38 );
39 }
40
41 Self { code, message }
42 }
43
44 pub fn new_error() -> Self {
46 Self {
47 code: 0,
48 message: vec![],
49 }
50 }
51
52 pub fn code(&self) -> StatusCode {
54 StatusCode::from_u16(self.code).expect("HttpStatus code is 0, can't return a StatusCode")
55 }
56
57 pub fn try_code(&self) -> Option<StatusCode> {
59 StatusCode::from_u16(self.code).ok()
60 }
61
62 pub fn raw_code(&self) -> u16 {
65 self.code
66 }
67
68 pub fn message(&self) -> &[u8] {
70 &self.message
71 }
72
73 pub fn is_success(&self) -> bool {
75 StatusCode::from_u16(self.code).is_ok_and(|s| s.is_success())
76 }
77
78 pub fn is_error(&self) -> bool {
80 self.code == 0
81 }
82
83 pub fn in_range<T: RangeBounds<u16>>(&self, range: T) -> bool {
86 self.code != 0 && range.contains(&self.code)
87 }
88
89 pub fn is_a_range_status(&self) -> bool {
91 matches!(
92 self.code(),
93 StatusCode::PARTIAL_CONTENT | StatusCode::RANGE_NOT_SATISFIABLE
94 )
95 }
96}
97
98impl Default for HttpStatus {
99 fn default() -> Self {
101 Self {
102 code: 200,
103 message: b"OK".to_vec(),
104 }
105 }
106}
107
108impl PartialEq<StatusCode> for HttpStatus {
109 fn eq(&self, other: &StatusCode) -> bool {
110 self.code == other.as_u16()
111 }
112}
113
114impl From<StatusCode> for HttpStatus {
115 fn from(code: StatusCode) -> Self {
116 Self {
117 code: code.as_u16(),
118 message: code
119 .canonical_reason()
120 .unwrap_or_default()
121 .as_bytes()
122 .to_vec(),
123 }
124 }
125}