http_status_code/
lib.rs

1//! HTTP status code.
2//!
3//! See [StatusCode].
4
5/// Status code.
6#[derive(Debug, Clone, PartialEq)]
7pub struct StatusCode {
8    /// invariant: numeric code is always within `100..=999`
9    code: u16,
10}
11
12impl StatusCode {
13    /// Constructs status code from numeric representation.
14    ///
15    /// # Panics
16    ///
17    /// Panics if `code` is not within the `100..=999` range.
18    pub fn from_u16(code: u16) -> Self {
19        match code {
20            100..=999 => Self { code },
21            _ => panic!("Invalid status code: {code}"),
22        }
23    }
24
25    /// Returns status code as ASCII bytes.
26    pub fn as_text_bytes(&self) -> [u8; 3] {
27        const DIGITS_START: u8 = b'0';
28
29        let n = self.code;
30
31        let d100 = (n / 100) as u8;
32        let d10 = ((n / 10) % 10) as u8;
33        let d1 = (n % 10) as u8;
34
35        [DIGITS_START + d100, DIGITS_START + d10, DIGITS_START + d1]
36    }
37}