tower_http/cors/
allow_methods.rs1use std::{array, fmt};
2
3use http::{
4 header::{self, HeaderName, HeaderValue},
5 request::Parts as RequestParts,
6 Method,
7};
8
9use super::{separated_by_commas, Any, WILDCARD};
10
11#[derive(Clone, Default)]
18#[must_use]
19pub struct AllowMethods(AllowMethodsInner);
20
21impl AllowMethods {
22 pub fn any() -> Self {
28 Self(AllowMethodsInner::Const(Some(WILDCARD)))
29 }
30
31 pub fn exact(method: Method) -> Self {
37 Self(AllowMethodsInner::Const(Some(
38 HeaderValue::from_str(method.as_str()).unwrap(),
39 )))
40 }
41
42 pub fn list<I>(methods: I) -> Self
48 where
49 I: IntoIterator<Item = Method>,
50 {
51 Self(AllowMethodsInner::Const(separated_by_commas(
52 methods
53 .into_iter()
54 .map(|m| HeaderValue::from_str(m.as_str()).unwrap()),
55 )))
56 }
57
58 pub fn mirror_request() -> Self {
67 Self(AllowMethodsInner::MirrorRequest)
68 }
69
70 #[allow(clippy::borrow_interior_mutable_const)]
71 pub(super) fn is_wildcard(&self) -> bool {
72 matches!(&self.0, AllowMethodsInner::Const(Some(v)) if v == WILDCARD)
73 }
74
75 pub(super) fn to_header(&self, parts: &RequestParts) -> Option<(HeaderName, HeaderValue)> {
76 let allow_methods = match &self.0 {
77 AllowMethodsInner::Const(v) => v.clone()?,
78 AllowMethodsInner::MirrorRequest => parts
79 .headers
80 .get(header::ACCESS_CONTROL_REQUEST_METHOD)?
81 .clone(),
82 };
83
84 Some((header::ACCESS_CONTROL_ALLOW_METHODS, allow_methods))
85 }
86}
87
88impl fmt::Debug for AllowMethods {
89 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90 match &self.0 {
91 AllowMethodsInner::Const(inner) => f.debug_tuple("Const").field(inner).finish(),
92 AllowMethodsInner::MirrorRequest => f.debug_tuple("MirrorRequest").finish(),
93 }
94 }
95}
96
97impl From<Any> for AllowMethods {
98 fn from(_: Any) -> Self {
99 Self::any()
100 }
101}
102
103impl From<Method> for AllowMethods {
104 fn from(method: Method) -> Self {
105 Self::exact(method)
106 }
107}
108
109impl<const N: usize> From<[Method; N]> for AllowMethods {
110 fn from(arr: [Method; N]) -> Self {
111 #[allow(deprecated)] Self::list(array::IntoIter::new(arr))
113 }
114}
115
116impl From<Vec<Method>> for AllowMethods {
117 fn from(vec: Vec<Method>) -> Self {
118 Self::list(vec)
119 }
120}
121
122#[derive(Clone)]
123enum AllowMethodsInner {
124 Const(Option<HeaderValue>),
125 MirrorRequest,
126}
127
128impl Default for AllowMethodsInner {
129 fn default() -> Self {
130 Self::Const(None)
131 }
132}