Skip to main content

hyperlane_plugin_static_files/
fn.rs

1use super::*;
2
3/// Safely joins an untrusted relative URL path onto a canonicalized `root_dir`, rejecting traversal and dotfiles.
4///
5/// # Arguments
6///
7/// - `&Path` - Canonicalized root directory.
8/// - `&str` - Raw URL relative path (after stripping mount prefix).
9/// - `bool` - Whether hidden dotfiles/dotdirs (segments beginning with `.`) are permitted.
10///
11/// # Returns
12///
13/// - `Option<PathBuf>` - Validated filesystem path inside `root_dir`, or `None` on traversal/escape.
14#[inline]
15pub fn resolve_safe_path(
16    root_dir: &Path,
17    relative_url: &str,
18    allow_dotfiles: bool,
19) -> Option<PathBuf> {
20    let (safe_rel, has_special): (Cow<'_, str>, bool) =
21        validate_and_decode_relative_with_special(relative_url, allow_dotfiles)?;
22    let rel_str: &str = safe_rel.as_ref();
23    let mut candidate: PathBuf =
24        PathBuf::with_capacity(root_dir.as_os_str().len() + rel_str.len() + 1);
25    candidate.push(root_dir);
26    if rel_str.is_empty() {
27        return Some(candidate);
28    }
29    if !has_special {
30        candidate.push(rel_str);
31        return Some(candidate);
32    }
33    for component in Path::new(rel_str).components() {
34        match component {
35            Component::Normal(seg) => {
36                let seg_str: &str = seg.to_str()?;
37                if seg_str.is_empty() || (!allow_dotfiles && seg_str.as_bytes()[0] == BYTE_DOT) {
38                    return None;
39                }
40                candidate.push(seg);
41            }
42            Component::CurDir => {}
43            Component::ParentDir | Component::RootDir | Component::Prefix(_) => return None,
44        }
45    }
46    Some(candidate)
47}
48
49/// Resolves the MIME `Content-Type` string for `path` with a zero-allocation fast table for common web assets.
50///
51/// # Arguments
52///
53/// - `&Path` - Target file path.
54///
55/// # Returns
56///
57/// - `&'static str` - Canonical MIME type (defaults to `application/octet-stream`).
58#[inline]
59pub fn mime_for_path(path: &Path) -> &'static str {
60    let Some(ext_str) = path.extension().and_then(OsStr::to_str) else {
61        return APPLICATION_OCTET_STREAM;
62    };
63    let bytes: &[u8] = ext_str.as_bytes();
64    if bytes.is_empty() {
65        return APPLICATION_OCTET_STREAM;
66    }
67    if let Some(fast_mime) = fast_web_mime(bytes) {
68        return fast_mime;
69    }
70    let parsed: FileExtension = if !bytes.iter().any(|b: &u8| b.is_ascii_uppercase()) {
71        FileExtension::parse(ext_str)
72    } else if bytes.len() <= MIME_EXT_STACK_CAP {
73        let mut stack_buf: [u8; MIME_EXT_STACK_CAP] = [0u8; MIME_EXT_STACK_CAP];
74        for (dst, &src) in stack_buf.iter_mut().zip(bytes.iter()) {
75            *dst = src.to_ascii_lowercase();
76        }
77        match from_utf8(&stack_buf[..bytes.len()]) {
78            Ok(lower) => FileExtension::parse(lower),
79            Err(_) => FileExtension::parse(ext_str.to_ascii_lowercase()),
80        }
81    } else {
82        FileExtension::parse(ext_str.to_ascii_lowercase())
83    };
84    let mime: &'static str = parsed.get_content_type();
85    if mime.is_empty() {
86        APPLICATION_OCTET_STREAM
87    } else {
88        mime
89    }
90}
91
92/// Checks whether an `If-None-Match` header matches `etag` (handling `*`, comma lists, and `W/` weak prefixes).
93///
94/// # Arguments
95///
96/// - `&str` - Incoming `If-None-Match` header value.
97/// - `&str` - Resource strong `ETag`.
98///
99/// # Returns
100///
101/// - `bool` - `true` when the client validator matches (`304 Not Modified`).
102#[inline]
103pub fn if_none_match_matches(header: &str, etag: &str) -> bool {
104    let trimmed: &str = header.trim();
105    if trimmed == ETAG_WILDCARD || trimmed == etag {
106        return true;
107    }
108    trimmed.split(',').any(|token: &str| {
109        let candidate: &str = token.trim();
110        let normalized: &str = candidate
111            .strip_prefix(WEAK_ETAG_PREFIX)
112            .unwrap_or(candidate);
113        normalized == etag
114    })
115}
116
117/// Parses a single RFC 9110 byte `Range` header (`bytes=start-end`, `bytes=start-`, `bytes=-suffix`).
118///
119/// # Arguments
120///
121/// - `&str` - Raw `Range` header value.
122/// - `usize` - Total resource length in bytes.
123///
124/// # Returns
125///
126/// - `Option<(usize, usize)>` - Inclusive `(start, end)` byte offsets, or `None` when unsatisfiable/invalid.
127#[inline]
128pub fn parse_byte_range(header: &str, total_len: usize) -> Option<(usize, usize)> {
129    if total_len == 0 {
130        return None;
131    }
132    let trimmed: &str = header.trim();
133    let spec: &str = trimmed.strip_prefix(RANGE_BYTES_PREFIX)?;
134    if spec.as_bytes().contains(&BYTE_COMMA) {
135        return None;
136    }
137    let (start_str, end_str): (&str, &str) = spec.split_once('-')?;
138    let start_bytes: &[u8] = start_str.trim().as_bytes();
139    let end_bytes: &[u8] = end_str.trim().as_bytes();
140    if start_bytes.is_empty() {
141        let suffix: usize = parse_ascii_usize(end_bytes)?;
142        if suffix == 0 {
143            return None;
144        }
145        let start: usize = total_len.saturating_sub(suffix);
146        return Some((start, total_len - 1));
147    }
148    let start: usize = parse_ascii_usize(start_bytes)?;
149    if start >= total_len {
150        return None;
151    }
152    let end: usize = if end_bytes.is_empty() {
153        total_len - 1
154    } else {
155        parse_ascii_usize(end_bytes)?.min(total_len - 1)
156    };
157    if start > end {
158        return None;
159    }
160    Some((start, end))
161}
162
163/// Resolves common web file extensions directly without allocating or touching [`FileExtension::parse`].
164///
165/// # Arguments
166///
167/// - `&[u8]` - Raw extension bytes (case-insensitive ASCII).
168///
169/// # Returns
170///
171/// - `Option<&'static str>` - Matching canonical MIME type when present in the fast table.
172#[inline(always)]
173pub(crate) fn fast_web_mime(bytes: &[u8]) -> Option<&'static str> {
174    match bytes.len() {
175        2 => {
176            let lower: [u8; 2] = [bytes[0].to_ascii_lowercase(), bytes[1].to_ascii_lowercase()];
177            if lower == EXT_JS {
178                return Some(APPLICATION_JAVASCRIPT);
179            }
180            None
181        }
182        3 => {
183            let lower: [u8; 3] = [
184                bytes[0].to_ascii_lowercase(),
185                bytes[1].to_ascii_lowercase(),
186                bytes[2].to_ascii_lowercase(),
187            ];
188            match lower {
189                EXT_CSS => Some(TEXT_CSS),
190                EXT_PNG => Some(IMAGE_PNG),
191                EXT_JPG => Some(IMAGE_JPEG),
192                EXT_SVG => Some(IMAGE_SVG_XML),
193                EXT_GIF => Some(IMAGE_GIF),
194                EXT_ICO => Some(IMAGE_X_ICON),
195                EXT_HTM => Some(TEXT_HTML),
196                EXT_TXT => Some(TEXT_PLAIN),
197                EXT_XML => Some(APPLICATION_XML),
198                EXT_PDF => Some(APPLICATION_PDF),
199                EXT_TTF => Some(FONT_TTF),
200                EXT_OTF => Some(FONT_OTF),
201                EXT_MP4 => Some(VIDEO_MP4),
202                EXT_MP3 => Some(AUDIO_MPEG),
203                _ => None,
204            }
205        }
206        4 => {
207            let lower: [u8; 4] = [
208                bytes[0].to_ascii_lowercase(),
209                bytes[1].to_ascii_lowercase(),
210                bytes[2].to_ascii_lowercase(),
211                bytes[3].to_ascii_lowercase(),
212            ];
213            match lower {
214                EXT_HTML => Some(TEXT_HTML),
215                EXT_JSON => Some(APPLICATION_JSON),
216                EXT_WASM => Some(APPLICATION_WASM),
217                EXT_WEBP => Some(IMAGE_WEBP),
218                EXT_JPEG => Some(IMAGE_JPEG),
219                EXT_WOFF => Some(FONT_WOFF),
220                EXT_WEBM => Some(VIDEO_WEBM),
221                _ => None,
222            }
223        }
224        5 => {
225            let lower: [u8; 5] = [
226                bytes[0].to_ascii_lowercase(),
227                bytes[1].to_ascii_lowercase(),
228                bytes[2].to_ascii_lowercase(),
229                bytes[3].to_ascii_lowercase(),
230                bytes[4].to_ascii_lowercase(),
231            ];
232            if lower == EXT_WOFF2 {
233                return Some(FONT_WOFF2);
234            }
235            None
236        }
237        _ => None,
238    }
239}
240
241/// Computes the 64-way cache shard index for a normalized URL key with zero allocations.
242///
243/// # Arguments
244///
245/// - `&str` - Normalized relative URL path.
246///
247/// # Returns
248///
249/// - `usize` - Shard index in `0..STATIC_CACHE_SHARDS`.
250#[inline(always)]
251pub(crate) fn static_cache_shard_index(key: &str) -> usize {
252    let mut hasher: FxHasher = FxHasher::default();
253    hasher.write(key.as_bytes());
254    let h: u64 = hasher.finish();
255    (((h >> 32) ^ h) as usize) & (STATIC_CACHE_SHARDS - 1)
256}
257
258/// Converts an ASCII hex digit byte into its 4-bit value via 256-entry LUT.
259///
260/// # Arguments
261///
262/// - `u8` - ASCII byte.
263///
264/// # Returns
265///
266/// - `Option<u8>` - 4-bit value `0..=15`, or `None` when not hex.
267#[inline(always)]
268pub(crate) fn hex_nibble(byte: u8) -> Option<u8> {
269    let val: u8 = HEX_DECODE_LUT[byte as usize];
270    if val < 16 { Some(val) } else { None }
271}
272
273/// Percent-decodes a URL path segment while rejecting NUL bytes (`%00`) and backslashes.
274///
275/// # Arguments
276///
277/// - `&str` - Raw URL path slice.
278///
279/// # Returns
280///
281/// - `Option<String>` - Decoded UTF-8 relative path, or `None` if malformed or contains NUL/backslash.
282pub(crate) fn percent_decode_path(raw: &str) -> Option<String> {
283    let bytes: &[u8] = raw.as_bytes();
284    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
285    let mut i: usize = 0;
286    while i < bytes.len() {
287        let b: u8 = bytes[i];
288        if b == 0 || b == BYTE_BACKSLASH {
289            return None;
290        }
291        if b == BYTE_PERCENT {
292            if i + 2 >= bytes.len() {
293                return None;
294            }
295            let hi: u8 = hex_nibble(bytes[i + 1])?;
296            let lo: u8 = hex_nibble(bytes[i + 2])?;
297            let decoded: u8 = (hi << 4) | lo;
298            if decoded == 0 || decoded == BYTE_BACKSLASH {
299                return None;
300            }
301            out.push(decoded);
302            i += 3;
303        } else {
304            out.push(b);
305            i += 1;
306        }
307    }
308    String::from_utf8(out).ok()
309}
310
311/// Validates every slash-separated segment of a decoded relative path and detects `.` or `//` components.
312///
313/// # Arguments
314///
315/// - `&[u8]` - Trimmed relative URL path bytes without leading slashes.
316/// - `bool` - Whether hidden dotfiles/dotdirs are permitted.
317///
318/// # Returns
319///
320/// - `Option<bool>` - `Some(has_special)` when safe, or `None` on traversal/disallowed dotfile.
321#[inline]
322pub(crate) fn scan_decoded_segments(bytes: &[u8], allow_dotfiles: bool) -> Option<bool> {
323    if bytes.is_empty() {
324        return Some(false);
325    }
326    let mut has_special: bool = false;
327    let mut seg_start: usize = 0;
328    let len: usize = bytes.len();
329    for i in 0..=len {
330        if i < len && bytes[i] != BYTE_SLASH {
331            continue;
332        }
333        let seg: &[u8] = &bytes[seg_start..i];
334        if seg.is_empty() {
335            if i < len {
336                has_special = true;
337            }
338        } else if seg.len() == 1 && seg[0] == BYTE_DOT {
339            has_special = true;
340        } else if (seg.len() == 2 && seg[0] == BYTE_DOT && seg[1] == BYTE_DOT)
341            || (!allow_dotfiles && seg[0] == BYTE_DOT)
342        {
343            return None;
344        }
345        seg_start = i + 1;
346    }
347    Some(has_special)
348}
349
350/// Validates and percent-decodes `relative_url` in a single scan pass, returning `(path, has_special)`.
351///
352/// # Arguments
353///
354/// - `&'a str` - Raw relative URL path after stripping mount prefix.
355/// - `bool` - Whether dotfiles are allowed.
356///
357/// # Returns
358///
359/// - `Option<(Cow<'a, str>, bool)>` - Safe normalized relative path plus flag indicating `.`/`//` segments.
360#[inline]
361pub(crate) fn validate_and_decode_relative_with_special<'a>(
362    relative_url: &'a str,
363    allow_dotfiles: bool,
364) -> Option<(Cow<'a, str>, bool)> {
365    let bytes: &[u8] = relative_url.as_bytes();
366    let mut start: usize = 0;
367    while start < bytes.len() && bytes[start] == BYTE_SLASH {
368        start += 1;
369    }
370    let trimmed_bytes: &[u8] = &bytes[start..];
371    let len: usize = trimmed_bytes.len();
372    if len == 0 {
373        return Some((Cow::Borrowed(&relative_url[start..]), false));
374    }
375    let mut has_special: bool = false;
376    let mut seg_start: usize = 0;
377    for i in 0..=len {
378        if i < len {
379            let b: u8 = trimmed_bytes[i];
380            if b == 0 || b == BYTE_BACKSLASH {
381                return None;
382            }
383            if b == BYTE_PERCENT {
384                let decoded: String = percent_decode_path(relative_url)?;
385                let trimmed: &str = decoded.trim_start_matches('/');
386                let special: bool = scan_decoded_segments(trimmed.as_bytes(), allow_dotfiles)?;
387                return Some((Cow::Owned(trimmed.to_owned()), special));
388            }
389            if b != BYTE_SLASH {
390                continue;
391            }
392        }
393        let seg: &[u8] = &trimmed_bytes[seg_start..i];
394        if seg.is_empty() {
395            if i < len {
396                has_special = true;
397            }
398        } else if seg.len() == 1 && seg[0] == BYTE_DOT {
399            has_special = true;
400        } else if (seg.len() == 2 && seg[0] == BYTE_DOT && seg[1] == BYTE_DOT)
401            || (!allow_dotfiles && seg[0] == BYTE_DOT)
402        {
403            return None;
404        }
405        seg_start = i + 1;
406    }
407    Some((Cow::Borrowed(&relative_url[start..]), has_special))
408}
409
410/// Validates and percent-decodes `relative_url` without allocating when no `%` escape is present.
411///
412/// # Arguments
413///
414/// - `&'a str` - Raw relative URL path after stripping mount prefix.
415/// - `bool` - Whether dotfiles are allowed.
416///
417/// # Returns
418///
419/// - `Option<Cow<'a, str>>` - Safe normalized relative path without leading slashes, or `None` on traversal/invalid bytes.
420#[inline]
421pub(crate) fn validate_and_decode_relative<'a>(
422    relative_url: &'a str,
423    allow_dotfiles: bool,
424) -> Option<Cow<'a, str>> {
425    validate_and_decode_relative_with_special(relative_url, allow_dotfiles)
426        .map(|(cow, _): (Cow<'a, str>, bool)| cow)
427}
428
429/// Appends lowercase hexadecimal digits for `value` into `buf` at `pos` and returns the new offset.
430///
431/// # Arguments
432///
433/// - `u64` - Unsigned integer to format in lowercase hex.
434/// - `&mut [u8]` - Destination byte slice.
435/// - `usize` - Starting write offset.
436///
437/// # Returns
438///
439/// - `usize` - Updated write offset.
440#[inline]
441pub(crate) fn write_hex_u64_compact(mut value: u64, buf: &mut [u8], pos: usize) -> usize {
442    if value == 0 {
443        buf[pos] = BYTE_ZERO;
444        return pos + 1;
445    }
446    let mut tmp: [u8; 16] = [0u8; 16];
447    let mut idx: usize = 16;
448    while value > 0 {
449        idx -= 1;
450        tmp[idx] = HEX_DIGITS[(value & 0x0F) as usize];
451        value >>= 4;
452    }
453    let slice: &[u8] = &tmp[idx..];
454    buf[pos..pos + slice.len()].copy_from_slice(slice);
455    pos + slice.len()
456}
457
458/// Computes a deterministic strong `ETag` from file byte length and modification timestamp.
459///
460/// # Arguments
461///
462/// - `u64` - File size in bytes.
463/// - `u64` - Modification timestamp in milliseconds since Unix epoch.
464///
465/// # Returns
466///
467/// - `String` - Quoted strong ETag (for example `"\"400-18f123ab\""`).
468#[inline]
469pub(crate) fn compute_file_etag(size: u64, modified_ms: u64) -> String {
470    let mut buf: [u8; ETAG_STACK_CAP] = [0u8; ETAG_STACK_CAP];
471    buf[0] = BYTE_QUOTE;
472    let mut pos: usize = write_hex_u64_compact(size, &mut buf, 1);
473    buf[pos] = BYTE_DASH;
474    pos = write_hex_u64_compact(modified_ms, &mut buf, pos + 1);
475    buf[pos] = BYTE_QUOTE;
476    pos += 1;
477    from_utf8(&buf[..pos]).unwrap_or_default().to_owned()
478}
479
480/// Extracts modification time in milliseconds since Unix epoch from filesystem [`Metadata`].
481///
482/// # Arguments
483///
484/// - `&Metadata` - File metadata.
485///
486/// # Returns
487///
488/// - `u64` - Modification timestamp in milliseconds, or `0` if unavailable.
489#[inline]
490pub(crate) fn metadata_modified_ms(meta: &Metadata) -> u64 {
491    meta.modified()
492        .ok()
493        .and_then(|ts: SystemTime| ts.duration_since(UNIX_EPOCH).ok())
494        .map(|dur: Duration| dur.as_millis() as u64)
495        .unwrap_or(0)
496}
497
498/// Parses an ASCII unsigned decimal integer from `bytes` without allocating.
499///
500/// # Arguments
501///
502/// - `&[u8]` - Trimmed ASCII digit bytes.
503///
504/// # Returns
505///
506/// - `Option<usize>` - Parsed integer, or `None` on empty, non-digit, or overflow.
507#[inline]
508pub(crate) fn parse_ascii_usize(bytes: &[u8]) -> Option<usize> {
509    if bytes.is_empty() {
510        return None;
511    }
512    let mut acc: usize = 0;
513    for &b in bytes {
514        if !b.is_ascii_digit() {
515            return None;
516        }
517        acc = acc.checked_mul(10)?.checked_add((b - BYTE_ZERO) as usize)?;
518    }
519    Some(acc)
520}
521
522/// Appends decimal digits for `value` into `buf` at `pos` using a 2-digit lookup table.
523///
524/// # Arguments
525///
526/// - `usize` - Unsigned integer to format.
527/// - `&mut [u8]` - Destination byte slice.
528/// - `usize` - Starting write offset.
529///
530/// # Returns
531///
532/// - `usize` - Updated write offset.
533#[inline]
534pub(crate) fn write_usize_decimal(mut value: usize, buf: &mut [u8], pos: usize) -> usize {
535    if value < 10 {
536        buf[pos] = BYTE_ZERO + value as u8;
537        return pos + 1;
538    }
539    let mut digits: [u8; 20] = [0u8; 20];
540    let mut idx: usize = 20;
541    while value >= 100 {
542        let pair: usize = (value % 100) * 2;
543        value /= 100;
544        idx -= 2;
545        digits[idx] = DEC_DIGITS_LUT[pair];
546        digits[idx + 1] = DEC_DIGITS_LUT[pair + 1];
547    }
548    if value >= 10 {
549        let pair: usize = value * 2;
550        idx -= 2;
551        digits[idx] = DEC_DIGITS_LUT[pair];
552        digits[idx + 1] = DEC_DIGITS_LUT[pair + 1];
553    } else {
554        idx -= 1;
555        digits[idx] = BYTE_ZERO + value as u8;
556    }
557    let slice: &[u8] = &digits[idx..];
558    buf[pos..pos + slice.len()].copy_from_slice(slice);
559    pos + slice.len()
560}
561
562/// Formats `bytes <start>-<end>/<total>` into a stack buffer without heap allocation.
563///
564/// # Arguments
565///
566/// - `usize` - Inclusive range start offset.
567/// - `usize` - Inclusive range end offset.
568/// - `usize` - Total entity length in bytes.
569/// - `&mut [u8; CONTENT_RANGE_STACK_CAP]` - Stack destination buffer.
570///
571/// # Returns
572///
573/// - `&str` - Borrowed formatted `Content-Range` value.
574#[inline]
575pub(crate) fn format_content_range_stack(
576    start: usize,
577    end: usize,
578    total: usize,
579    buf: &mut [u8; CONTENT_RANGE_STACK_CAP],
580) -> &str {
581    let prefix: &[u8] = CONTENT_RANGE_BYTES_PREFIX.as_bytes();
582    buf[..prefix.len()].copy_from_slice(prefix);
583    let mut pos: usize = write_usize_decimal(start, buf, prefix.len());
584    buf[pos] = BYTE_DASH;
585    pos = write_usize_decimal(end, buf, pos + 1);
586    buf[pos] = BYTE_SLASH;
587    pos = write_usize_decimal(total, buf, pos + 1);
588    from_utf8(&buf[..pos]).unwrap_or_default()
589}
590
591/// Formats `bytes */<total>` into a stack buffer without heap allocation.
592///
593/// # Arguments
594///
595/// - `usize` - Total entity length in bytes.
596/// - `&mut [u8; CONTENT_RANGE_STACK_CAP]` - Stack destination buffer.
597///
598/// # Returns
599///
600/// - `&str` - Borrowed formatted unsatisfiable `Content-Range` value.
601#[inline]
602pub(crate) fn format_unsatisfiable_range_stack(
603    total: usize,
604    buf: &mut [u8; CONTENT_RANGE_STACK_CAP],
605) -> &str {
606    let prefix: &[u8] = CONTENT_RANGE_UNSAT_PREFIX.as_bytes();
607    buf[..prefix.len()].copy_from_slice(prefix);
608    let pos: usize = write_usize_decimal(total, buf, prefix.len());
609    from_utf8(&buf[..pos]).unwrap_or_default()
610}
611
612/// Parses `Accept-Encoding` into a two-bit sidecar acceptance mask (`ENCODING_MASK_BR | ENCODING_MASK_GZIP`) in one pass.
613///
614/// # Arguments
615///
616/// - `&str` - Incoming `Accept-Encoding` header value.
617///
618/// # Returns
619///
620/// - `u8` - Bitmask of accepted precompressed sidecar encodings.
621#[inline]
622pub(crate) fn accept_encoding_mask(accept_encoding: &str) -> u8 {
623    let mut mask: u8 = 0;
624    for part in accept_encoding.split(',') {
625        let trimmed_part: &str = part.trim();
626        if !trimmed_part.as_bytes().contains(&BYTE_SEMICOLON) {
627            if trimmed_part.eq_ignore_ascii_case(ENCODING_BR) {
628                mask |= ENCODING_MASK_BR;
629            } else if trimmed_part.eq_ignore_ascii_case(ENCODING_GZIP) {
630                mask |= ENCODING_MASK_GZIP;
631            }
632            if mask == (ENCODING_MASK_BR | ENCODING_MASK_GZIP) {
633                break;
634            }
635            continue;
636        }
637        let mut segments: Split<'_, char> = trimmed_part.split(';');
638        let coding: &str = segments.next().unwrap_or_default().trim();
639        let bit: u8 = if coding.eq_ignore_ascii_case(ENCODING_BR) {
640            ENCODING_MASK_BR
641        } else if coding.eq_ignore_ascii_case(ENCODING_GZIP) {
642            ENCODING_MASK_GZIP
643        } else {
644            continue;
645        };
646        let mut rejected: bool = false;
647        for param in segments {
648            let trimmed: &str = param.trim();
649            if let Some(qval) = trimmed
650                .strip_prefix(QUALITY_PREFIX_LOWER)
651                .or_else(|| trimmed.strip_prefix(QUALITY_PREFIX_UPPER))
652                && qval.trim().parse::<f32>().ok() == Some(0.0)
653            {
654                rejected = true;
655            }
656        }
657        if !rejected {
658            mask |= bit;
659        }
660    }
661    mask
662}
663
664/// Borrows the last value of lowercase request header `name` without allocating.
665///
666/// # Arguments
667///
668/// - `&'a Request` - Incoming HTTP request.
669/// - `&str` - Lowercase header key.
670///
671/// # Returns
672///
673/// - `Option<&'a str>` - Borrowed last header value, if present.
674#[inline]
675pub(crate) fn get_request_header_back_ref<'a>(request: &'a Request, name: &str) -> Option<&'a str> {
676    request
677        .get_headers()
678        .get(name)
679        .and_then(|values: &VecDeque<String>| values.back())
680        .map(String::as_str)
681}