trillium_http/headers/
known_header_name.rs

1use super::{HeaderName, HeaderNameInner};
2use std::{
3    fmt::{self, Debug, Display, Formatter},
4    hash::Hash,
5    str::FromStr,
6};
7use HeaderNameInner::{KnownHeader, UnknownHeader};
8
9impl Display for KnownHeaderName {
10    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
11        f.write_str(self.as_ref())
12    }
13}
14
15impl From<KnownHeaderName> for HeaderName<'_> {
16    fn from(khn: KnownHeaderName) -> Self {
17        Self(KnownHeader(khn))
18    }
19}
20
21impl PartialEq<HeaderName<'_>> for KnownHeaderName {
22    fn eq(&self, other: &HeaderName) -> bool {
23        match &other.0 {
24            KnownHeader(k) => self == k,
25            UnknownHeader(_) => false,
26        }
27    }
28}
29
30macro_rules! known_headers {
31    (
32        $(
33            ($capitalized:literal, $variant:tt)
34        ),+
35    ) => {
36
37        /// A short nonehaustive enum of headers that trillium can
38        /// represent as a u8. Use a `KnownHeaderName` variant instead
39        /// of a &'static str anywhere possible, as it allows trillium
40        /// to skip parsing the header entirely.
41        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
42        #[non_exhaustive]
43        #[repr(u8)]
44        pub enum KnownHeaderName {
45            $(
46                #[doc = concat!("The [", $capitalized, "](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/", $capitalized, ") header.")]
47                $variant,
48            )+
49        }
50
51
52        impl AsRef<str> for KnownHeaderName {
53            fn as_ref(&self) -> &str {
54                match self {
55                    $( Self::$variant => $capitalized, )+
56                }
57            }
58        }
59
60        impl FromStr for KnownHeaderName {
61            type Err = ();
62            fn from_str(s: &str) -> Result<Self, Self::Err> {
63                if !s.is_ascii() { return Err(()); }
64
65                $( if s.eq_ignore_ascii_case($capitalized) { Ok(Self::$variant) } else )+
66                { Err(()) }
67            }
68        }
69    }
70}
71
72/* generated with
73
74console.log($$('main > article > div > dl > dt > a > code').map(code => {
75let lowered = code.innerText.toLowerCase();
76let enum_ = lowered.replace(/(?:-|^)([a-z])/g, (_, p1) => p1.toUpperCase());
77return`("${code.innerText}", ${enum_}, "${lowered}")`
78}).join(",\n"))
79
80 on https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers
81
82
83per https://httpwg.org/specs/rfc9110.html#rfc.section.5.3,
84
85The order in which field lines with differing field names are received in a section is not
86significant. However, it is good practice to send header fields that contain additional control data
87first, such as Host on requests and Date on responses, so that implementations can decide when not
88to handle a message as early as possible.
89*/
90known_headers! {
91    ("Host", Host),
92    ("Date", Date),
93
94    ("Accept", Accept),
95    ("Accept-CH", AcceptCh),
96    ("Accept-CH-Lifetime", AcceptChLifetime),
97    ("Accept-Charset", AcceptCharset),
98    ("Accept-Encoding", AcceptEncoding),
99    ("Accept-Language", AcceptLanguage),
100    ("Accept-Push-Policy", AcceptPushPolicy),
101    ("Accept-Ranges", AcceptRanges),
102    ("Accept-Signature", AcceptSignature),
103    ("Access-Control-Allow-Credentials", AccessControlAllowCredentials),
104    ("Access-Control-Allow-Headers", AccessControlAllowHeaders),
105    ("Access-Control-Allow-Methods", AccessControlAllowMethods),
106    ("Access-Control-Allow-Origin", AccessControlAllowOrigin),
107    ("Access-Control-Expose-Headers", AccessControlExposeHeaders),
108    ("Access-Control-Max-Age", AccessControlMaxAge),
109    ("Access-Control-Request-Headers", AccessControlRequestHeaders),
110    ("Access-Control-Request-Method", AccessControlRequestMethod),
111    ("Age", Age),
112    ("Allow", Allow),
113    ("Alt-Svc", AltSvc),
114    ("Authorization", Authorization),
115    ("Cache-Control", CacheControl),
116    ("Clear-Site-Data", ClearSiteData),
117    ("Connection", Connection),
118    ("Content-DPR", ContentDpr),
119    ("Content-Disposition", ContentDisposition),
120    ("Content-Encoding", ContentEncoding),
121    ("Content-Language", ContentLanguage),
122    ("Content-Length", ContentLength),
123    ("Content-Location", ContentLocation),
124    ("Content-Range", ContentRange),
125    ("Content-Security-Policy", ContentSecurityPolicy),
126    ("Content-Security-Policy-Report-Only", ContentSecurityPolicyReportOnly),
127    ("Content-Type", ContentType),
128    ("Cookie", Cookie),
129    ("Cookie2", Cookie2),
130    ("Cross-Origin-Embedder-Policy", CrossOriginEmbedderPolicy),
131    ("Cross-Origin-Opener-Policy", CrossOriginOpenerPolicy),
132    ("Cross-Origin-Resource-Policy", CrossOriginResourcePolicy),
133    ("DNT", Dnt),
134    ("DPR", Dpr),
135    ("Device-Memory", DeviceMemory),
136    ("Downlink", Downlink),
137    ("ECT", Ect),
138    ("ETag", Etag),
139    ("Early-Data", EarlyData),
140    ("Expect", Expect),
141    ("Expect-CT", ExpectCt),
142    ("Expires", Expires),
143    ("Feature-Policy", FeaturePolicy),
144    ("Forwarded", Forwarded),
145    ("From", From),
146    ("If-Match", IfMatch),
147    ("If-Modified-Since", IfModifiedSince),
148    ("If-None-Match", IfNoneMatch),
149    ("If-Range", IfRange),
150    ("If-Unmodified-Since", IfUnmodifiedSince),
151    ("Keep-Alive", KeepAlive),
152    ("Large-Allocation", LargeAllocation),
153    ("Last-Event-ID", LastEventId),
154    ("Last-Modified", LastModified),
155    ("Link", Link),
156    ("Location", Location),
157    ("Max-Forwards", MaxForwards),
158    ("NEL", Nel),
159    ("Origin", Origin),
160    ("Origin-Isolation", OriginIsolation),
161    ("Ping-From", PingFrom),
162    ("Ping-To", PingTo),
163    ("Pragma", Pragma),
164    ("Proxy-Authenticate", ProxyAuthenticate),
165    ("Proxy-Authorization", ProxyAuthorization),
166    ("Proxy-Connection", ProxyConnection),
167    ("Public-Key-Pins", PublicKeyPins),
168    ("Public-Key-Pins-Report-Only", PublicKeyPinsReportOnly),
169    ("Push-Policy", PushPolicy),
170    ("RTT", Rtt),
171    ("Range", Range),
172    ("Referer", Referer),
173    ("Referrer-Policy", ReferrerPolicy),
174    ("Refresh-Cache", RefreshCache),
175    ("Report-To", ReportTo),
176    ("Retry-After", RetryAfter),
177    ("Save-Data", SaveData),
178    ("Sec-CH-UA", SecChUa),
179    ("Sec-CH-UA-Mobile", SecChUAMobile),
180    ("Sec-CH-UA-Platform", SecChUAPlatform),
181    ("Sec-Fetch-Dest", SecFetchDest),
182    ("Sec-Fetch-Mode", SecFetchMode),
183    ("Sec-Fetch-Site", SecFetchSite),
184    ("Sec-Fetch-User", SecFetchUser),
185    ("Sec-GPC", SecGpc),
186    ("Sec-WebSocket-Accept", SecWebsocketAccept),
187    ("Sec-WebSocket-Extensions", SecWebsocketExtensions),
188    ("Sec-WebSocket-Key", SecWebsocketKey),
189    ("Sec-WebSocket-Protocol", SecWebsocketProtocol),
190    ("Sec-WebSocket-Version", SecWebsocketVersion),
191    ("Server", Server),
192    ("Server-Timing", ServerTiming),
193    ("Service-Worker-Allowed", ServiceWorkerAllowed),
194    ("Set-Cookie", SetCookie),
195    ("Set-Cookie2", SetCookie2),
196    ("Signature", Signature),
197    ("Signed-Headers", SignedHeaders),
198    ("SourceMap", Sourcemap),
199    ("Strict-Transport-Security", StrictTransportSecurity),
200    ("TE", Te),
201    ("Timing-Allow-Origin", TimingAllowOrigin),
202    ("Trailer", Trailer),
203    ("Transfer-Encoding", TransferEncoding),
204    ("Upgrade", Upgrade),
205    ("Upgrade-Insecure-Requests", UpgradeInsecureRequests),
206    ("User-Agent", UserAgent),
207    ("Vary", Vary),
208    ("Via", Via),
209    ("Viewport-Width", ViewportWidth),
210    ("WWW-Authenticate", WwwAuthenticate),
211    ("Warning", Warning),
212    ("Width", Width),
213    ("X-Cache", Xcache),
214    ("X-Content-Type-Options", XcontentTypeOptions),
215    ("X-DNS-Prefetch-Control", XdnsPrefetchControl),
216    ("X-Download-Options", XdownloadOptions),
217    ("X-Firefox-Spdy", XfirefoxSpdy),
218    ("X-Forwarded-By", XforwardedBy),
219    ("X-Forwarded-For", XforwardedFor),
220    ("X-Forwarded-Host", XforwardedHost),
221    ("X-Forwarded-Proto", XforwardedProto),
222    ("X-Forwarded-SSL", XforwardedSsl),
223    ("X-Frame-Options", XframeOptions),
224    ("X-Permitted-Cross-Domain-Policies", XpermittedCrossDomainPolicies),
225    ("X-Pingback", Xpingback),
226    ("X-Powered-By", XpoweredBy),
227    ("X-Request-Id", XrequestId),
228    ("X-Requested-With", XrequestedWith),
229    ("X-Robots-Tag", XrobotsTag),
230    ("X-Served-By", XservedBy),
231    ("X-UA-Compatible", XuaCompatible),
232    ("X-XSS-Protection", XxssProtection)
233}