Skip to main content

fastapi_types/
lib.rs

1//! Shared types for the FastAPI Rust framework.
2//!
3//! This crate provides fundamental types used across multiple fastapi crates,
4//! enabling clean dependency ordering without cycles.
5
6#![forbid(unsafe_code)]
7
8use std::fmt;
9
10/// HTTP method.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
12pub enum Method {
13    /// GET method.
14    Get,
15    /// POST method.
16    Post,
17    /// PUT method.
18    Put,
19    /// DELETE method.
20    Delete,
21    /// PATCH method.
22    Patch,
23    /// OPTIONS method.
24    Options,
25    /// HEAD method.
26    Head,
27    /// TRACE method.
28    Trace,
29}
30
31impl Method {
32    /// Parse method from bytes.
33    #[must_use]
34    pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
35        match bytes {
36            b"GET" => Some(Self::Get),
37            b"POST" => Some(Self::Post),
38            b"PUT" => Some(Self::Put),
39            b"DELETE" => Some(Self::Delete),
40            b"PATCH" => Some(Self::Patch),
41            b"OPTIONS" => Some(Self::Options),
42            b"HEAD" => Some(Self::Head),
43            b"TRACE" => Some(Self::Trace),
44            _ => None,
45        }
46    }
47
48    /// Return the canonical uppercase method name.
49    #[must_use]
50    pub const fn as_str(self) -> &'static str {
51        match self {
52            Self::Get => "GET",
53            Self::Post => "POST",
54            Self::Put => "PUT",
55            Self::Delete => "DELETE",
56            Self::Patch => "PATCH",
57            Self::Options => "OPTIONS",
58            Self::Head => "HEAD",
59            Self::Trace => "TRACE",
60        }
61    }
62}
63
64impl fmt::Display for Method {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        f.write_str(self.as_str())
67    }
68}