hyperlane-plugin-static-files 23.2.0

A high-performance static file server plugin for the Hyperlane framework with canonicalized path-traversal protection, built-in FileExtension MIME detection, 64-way sharded hot-file cache, precompressed .br/.gz sidecars, ETag/304 conditional validation, RFC 9110 Range 206/416 support, and SPA fallback.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
use super::*;

/// Safely joins an untrusted relative URL path onto a canonicalized `root_dir`, rejecting traversal and dotfiles.
///
/// # Arguments
///
/// - `&Path` - Canonicalized root directory.
/// - `&str` - Raw URL relative path (after stripping mount prefix).
/// - `bool` - Whether hidden dotfiles/dotdirs (segments beginning with `.`) are permitted.
///
/// # Returns
///
/// - `Option<PathBuf>` - Validated filesystem path inside `root_dir`, or `None` on traversal/escape.
#[inline]
pub fn resolve_safe_path(
    root_dir: &Path,
    relative_url: &str,
    allow_dotfiles: bool,
) -> Option<PathBuf> {
    let (safe_rel, has_special): (Cow<'_, str>, bool) =
        validate_and_decode_relative_with_special(relative_url, allow_dotfiles)?;
    let rel_str: &str = safe_rel.as_ref();
    let mut candidate: PathBuf =
        PathBuf::with_capacity(root_dir.as_os_str().len() + rel_str.len() + 1);
    candidate.push(root_dir);
    if rel_str.is_empty() {
        return Some(candidate);
    }
    if !has_special {
        candidate.push(rel_str);
        return Some(candidate);
    }
    for component in Path::new(rel_str).components() {
        match component {
            Component::Normal(seg) => {
                let seg_str: &str = seg.to_str()?;
                if seg_str.is_empty() || (!allow_dotfiles && seg_str.as_bytes()[0] == BYTE_DOT) {
                    return None;
                }
                candidate.push(seg);
            }
            Component::CurDir => {}
            Component::ParentDir | Component::RootDir | Component::Prefix(_) => return None,
        }
    }
    Some(candidate)
}

/// Resolves the MIME `Content-Type` string for `path` with a zero-allocation fast table for common web assets.
///
/// # Arguments
///
/// - `&Path` - Target file path.
///
/// # Returns
///
/// - `&'static str` - Canonical MIME type (defaults to `application/octet-stream`).
#[inline]
pub fn mime_for_path(path: &Path) -> &'static str {
    let Some(ext_str) = path.extension().and_then(OsStr::to_str) else {
        return APPLICATION_OCTET_STREAM;
    };
    let bytes: &[u8] = ext_str.as_bytes();
    if bytes.is_empty() {
        return APPLICATION_OCTET_STREAM;
    }
    if let Some(fast_mime) = fast_web_mime(bytes) {
        return fast_mime;
    }
    let parsed: FileExtension = if !bytes.iter().any(|b: &u8| b.is_ascii_uppercase()) {
        FileExtension::parse(ext_str)
    } else if bytes.len() <= MIME_EXT_STACK_CAP {
        let mut stack_buf: [u8; MIME_EXT_STACK_CAP] = [0u8; MIME_EXT_STACK_CAP];
        for (dst, &src) in stack_buf.iter_mut().zip(bytes.iter()) {
            *dst = src.to_ascii_lowercase();
        }
        match from_utf8(&stack_buf[..bytes.len()]) {
            Ok(lower) => FileExtension::parse(lower),
            Err(_) => FileExtension::parse(ext_str.to_ascii_lowercase()),
        }
    } else {
        FileExtension::parse(ext_str.to_ascii_lowercase())
    };
    let mime: &'static str = parsed.get_content_type();
    if mime.is_empty() {
        APPLICATION_OCTET_STREAM
    } else {
        mime
    }
}

/// Checks whether an `If-None-Match` header matches `etag` (handling `*`, comma lists, and `W/` weak prefixes).
///
/// # Arguments
///
/// - `&str` - Incoming `If-None-Match` header value.
/// - `&str` - Resource strong `ETag`.
///
/// # Returns
///
/// - `bool` - `true` when the client validator matches (`304 Not Modified`).
#[inline]
pub fn if_none_match_matches(header: &str, etag: &str) -> bool {
    let trimmed: &str = header.trim();
    if trimmed == ETAG_WILDCARD || trimmed == etag {
        return true;
    }
    trimmed.split(',').any(|token: &str| {
        let candidate: &str = token.trim();
        let normalized: &str = candidate
            .strip_prefix(WEAK_ETAG_PREFIX)
            .unwrap_or(candidate);
        normalized == etag
    })
}

/// Parses a single RFC 9110 byte `Range` header (`bytes=start-end`, `bytes=start-`, `bytes=-suffix`).
///
/// # Arguments
///
/// - `&str` - Raw `Range` header value.
/// - `usize` - Total resource length in bytes.
///
/// # Returns
///
/// - `Option<(usize, usize)>` - Inclusive `(start, end)` byte offsets, or `None` when unsatisfiable/invalid.
#[inline]
pub fn parse_byte_range(header: &str, total_len: usize) -> Option<(usize, usize)> {
    if total_len == 0 {
        return None;
    }
    let trimmed: &str = header.trim();
    let spec: &str = trimmed.strip_prefix(RANGE_BYTES_PREFIX)?;
    if spec.as_bytes().contains(&BYTE_COMMA) {
        return None;
    }
    let (start_str, end_str): (&str, &str) = spec.split_once('-')?;
    let start_bytes: &[u8] = start_str.trim().as_bytes();
    let end_bytes: &[u8] = end_str.trim().as_bytes();
    if start_bytes.is_empty() {
        let suffix: usize = parse_ascii_usize(end_bytes)?;
        if suffix == 0 {
            return None;
        }
        let start: usize = total_len.saturating_sub(suffix);
        return Some((start, total_len - 1));
    }
    let start: usize = parse_ascii_usize(start_bytes)?;
    if start >= total_len {
        return None;
    }
    let end: usize = if end_bytes.is_empty() {
        total_len - 1
    } else {
        parse_ascii_usize(end_bytes)?.min(total_len - 1)
    };
    if start > end {
        return None;
    }
    Some((start, end))
}

/// Resolves common web file extensions directly without allocating or touching [`FileExtension::parse`].
///
/// # Arguments
///
/// - `&[u8]` - Raw extension bytes (case-insensitive ASCII).
///
/// # Returns
///
/// - `Option<&'static str>` - Matching canonical MIME type when present in the fast table.
#[inline(always)]
pub(crate) fn fast_web_mime(bytes: &[u8]) -> Option<&'static str> {
    match bytes.len() {
        2 => {
            let lower: [u8; 2] = [bytes[0].to_ascii_lowercase(), bytes[1].to_ascii_lowercase()];
            if lower == EXT_JS {
                return Some(APPLICATION_JAVASCRIPT);
            }
            None
        }
        3 => {
            let lower: [u8; 3] = [
                bytes[0].to_ascii_lowercase(),
                bytes[1].to_ascii_lowercase(),
                bytes[2].to_ascii_lowercase(),
            ];
            match lower {
                EXT_CSS => Some(TEXT_CSS),
                EXT_PNG => Some(IMAGE_PNG),
                EXT_JPG => Some(IMAGE_JPEG),
                EXT_SVG => Some(IMAGE_SVG_XML),
                EXT_GIF => Some(IMAGE_GIF),
                EXT_ICO => Some(IMAGE_X_ICON),
                EXT_HTM => Some(TEXT_HTML),
                EXT_TXT => Some(TEXT_PLAIN),
                EXT_XML => Some(APPLICATION_XML),
                EXT_PDF => Some(APPLICATION_PDF),
                EXT_TTF => Some(FONT_TTF),
                EXT_OTF => Some(FONT_OTF),
                EXT_MP4 => Some(VIDEO_MP4),
                EXT_MP3 => Some(AUDIO_MPEG),
                _ => None,
            }
        }
        4 => {
            let lower: [u8; 4] = [
                bytes[0].to_ascii_lowercase(),
                bytes[1].to_ascii_lowercase(),
                bytes[2].to_ascii_lowercase(),
                bytes[3].to_ascii_lowercase(),
            ];
            match lower {
                EXT_HTML => Some(TEXT_HTML),
                EXT_JSON => Some(APPLICATION_JSON),
                EXT_WASM => Some(APPLICATION_WASM),
                EXT_WEBP => Some(IMAGE_WEBP),
                EXT_JPEG => Some(IMAGE_JPEG),
                EXT_WOFF => Some(FONT_WOFF),
                EXT_WEBM => Some(VIDEO_WEBM),
                _ => None,
            }
        }
        5 => {
            let lower: [u8; 5] = [
                bytes[0].to_ascii_lowercase(),
                bytes[1].to_ascii_lowercase(),
                bytes[2].to_ascii_lowercase(),
                bytes[3].to_ascii_lowercase(),
                bytes[4].to_ascii_lowercase(),
            ];
            if lower == EXT_WOFF2 {
                return Some(FONT_WOFF2);
            }
            None
        }
        _ => None,
    }
}

/// Computes the 64-way cache shard index for a normalized URL key with zero allocations.
///
/// # Arguments
///
/// - `&str` - Normalized relative URL path.
///
/// # Returns
///
/// - `usize` - Shard index in `0..STATIC_CACHE_SHARDS`.
#[inline(always)]
pub(crate) fn static_cache_shard_index(key: &str) -> usize {
    let mut hasher: FxHasher = FxHasher::default();
    hasher.write(key.as_bytes());
    let h: u64 = hasher.finish();
    (((h >> 32) ^ h) as usize) & (STATIC_CACHE_SHARDS - 1)
}

/// Converts an ASCII hex digit byte into its 4-bit value via 256-entry LUT.
///
/// # Arguments
///
/// - `u8` - ASCII byte.
///
/// # Returns
///
/// - `Option<u8>` - 4-bit value `0..=15`, or `None` when not hex.
#[inline(always)]
pub(crate) fn hex_nibble(byte: u8) -> Option<u8> {
    let val: u8 = HEX_DECODE_LUT[byte as usize];
    if val < 16 { Some(val) } else { None }
}

/// Percent-decodes a URL path segment while rejecting NUL bytes (`%00`) and backslashes.
///
/// # Arguments
///
/// - `&str` - Raw URL path slice.
///
/// # Returns
///
/// - `Option<String>` - Decoded UTF-8 relative path, or `None` if malformed or contains NUL/backslash.
pub(crate) fn percent_decode_path(raw: &str) -> Option<String> {
    let bytes: &[u8] = raw.as_bytes();
    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
    let mut i: usize = 0;
    while i < bytes.len() {
        let b: u8 = bytes[i];
        if b == 0 || b == BYTE_BACKSLASH {
            return None;
        }
        if b == BYTE_PERCENT {
            if i + 2 >= bytes.len() {
                return None;
            }
            let hi: u8 = hex_nibble(bytes[i + 1])?;
            let lo: u8 = hex_nibble(bytes[i + 2])?;
            let decoded: u8 = (hi << 4) | lo;
            if decoded == 0 || decoded == BYTE_BACKSLASH {
                return None;
            }
            out.push(decoded);
            i += 3;
        } else {
            out.push(b);
            i += 1;
        }
    }
    String::from_utf8(out).ok()
}

/// Validates every slash-separated segment of a decoded relative path and detects `.` or `//` components.
///
/// # Arguments
///
/// - `&[u8]` - Trimmed relative URL path bytes without leading slashes.
/// - `bool` - Whether hidden dotfiles/dotdirs are permitted.
///
/// # Returns
///
/// - `Option<bool>` - `Some(has_special)` when safe, or `None` on traversal/disallowed dotfile.
#[inline]
pub(crate) fn scan_decoded_segments(bytes: &[u8], allow_dotfiles: bool) -> Option<bool> {
    if bytes.is_empty() {
        return Some(false);
    }
    let mut has_special: bool = false;
    let mut seg_start: usize = 0;
    let len: usize = bytes.len();
    for i in 0..=len {
        if i < len && bytes[i] != BYTE_SLASH {
            continue;
        }
        let seg: &[u8] = &bytes[seg_start..i];
        if seg.is_empty() {
            if i < len {
                has_special = true;
            }
        } else if seg.len() == 1 && seg[0] == BYTE_DOT {
            has_special = true;
        } else if (seg.len() == 2 && seg[0] == BYTE_DOT && seg[1] == BYTE_DOT)
            || (!allow_dotfiles && seg[0] == BYTE_DOT)
        {
            return None;
        }
        seg_start = i + 1;
    }
    Some(has_special)
}

/// Validates and percent-decodes `relative_url` in a single scan pass, returning `(path, has_special)`.
///
/// # Arguments
///
/// - `&'a str` - Raw relative URL path after stripping mount prefix.
/// - `bool` - Whether dotfiles are allowed.
///
/// # Returns
///
/// - `Option<(Cow<'a, str>, bool)>` - Safe normalized relative path plus flag indicating `.`/`//` segments.
#[inline]
pub(crate) fn validate_and_decode_relative_with_special<'a>(
    relative_url: &'a str,
    allow_dotfiles: bool,
) -> Option<(Cow<'a, str>, bool)> {
    let bytes: &[u8] = relative_url.as_bytes();
    let mut start: usize = 0;
    while start < bytes.len() && bytes[start] == BYTE_SLASH {
        start += 1;
    }
    let trimmed_bytes: &[u8] = &bytes[start..];
    let len: usize = trimmed_bytes.len();
    if len == 0 {
        return Some((Cow::Borrowed(&relative_url[start..]), false));
    }
    let mut has_special: bool = false;
    let mut seg_start: usize = 0;
    for i in 0..=len {
        if i < len {
            let b: u8 = trimmed_bytes[i];
            if b == 0 || b == BYTE_BACKSLASH {
                return None;
            }
            if b == BYTE_PERCENT {
                let decoded: String = percent_decode_path(relative_url)?;
                let trimmed: &str = decoded.trim_start_matches('/');
                let special: bool = scan_decoded_segments(trimmed.as_bytes(), allow_dotfiles)?;
                return Some((Cow::Owned(trimmed.to_owned()), special));
            }
            if b != BYTE_SLASH {
                continue;
            }
        }
        let seg: &[u8] = &trimmed_bytes[seg_start..i];
        if seg.is_empty() {
            if i < len {
                has_special = true;
            }
        } else if seg.len() == 1 && seg[0] == BYTE_DOT {
            has_special = true;
        } else if (seg.len() == 2 && seg[0] == BYTE_DOT && seg[1] == BYTE_DOT)
            || (!allow_dotfiles && seg[0] == BYTE_DOT)
        {
            return None;
        }
        seg_start = i + 1;
    }
    Some((Cow::Borrowed(&relative_url[start..]), has_special))
}

/// Validates and percent-decodes `relative_url` without allocating when no `%` escape is present.
///
/// # Arguments
///
/// - `&'a str` - Raw relative URL path after stripping mount prefix.
/// - `bool` - Whether dotfiles are allowed.
///
/// # Returns
///
/// - `Option<Cow<'a, str>>` - Safe normalized relative path without leading slashes, or `None` on traversal/invalid bytes.
#[inline]
pub(crate) fn validate_and_decode_relative<'a>(
    relative_url: &'a str,
    allow_dotfiles: bool,
) -> Option<Cow<'a, str>> {
    validate_and_decode_relative_with_special(relative_url, allow_dotfiles)
        .map(|(cow, _): (Cow<'a, str>, bool)| cow)
}

/// Appends lowercase hexadecimal digits for `value` into `buf` at `pos` and returns the new offset.
///
/// # Arguments
///
/// - `u64` - Unsigned integer to format in lowercase hex.
/// - `&mut [u8]` - Destination byte slice.
/// - `usize` - Starting write offset.
///
/// # Returns
///
/// - `usize` - Updated write offset.
#[inline]
pub(crate) fn write_hex_u64_compact(mut value: u64, buf: &mut [u8], pos: usize) -> usize {
    if value == 0 {
        buf[pos] = BYTE_ZERO;
        return pos + 1;
    }
    let mut tmp: [u8; 16] = [0u8; 16];
    let mut idx: usize = 16;
    while value > 0 {
        idx -= 1;
        tmp[idx] = HEX_DIGITS[(value & 0x0F) as usize];
        value >>= 4;
    }
    let slice: &[u8] = &tmp[idx..];
    buf[pos..pos + slice.len()].copy_from_slice(slice);
    pos + slice.len()
}

/// Computes a deterministic strong `ETag` from file byte length and modification timestamp.
///
/// # Arguments
///
/// - `u64` - File size in bytes.
/// - `u64` - Modification timestamp in milliseconds since Unix epoch.
///
/// # Returns
///
/// - `String` - Quoted strong ETag (for example `"\"400-18f123ab\""`).
#[inline]
pub(crate) fn compute_file_etag(size: u64, modified_ms: u64) -> String {
    let mut buf: [u8; ETAG_STACK_CAP] = [0u8; ETAG_STACK_CAP];
    buf[0] = BYTE_QUOTE;
    let mut pos: usize = write_hex_u64_compact(size, &mut buf, 1);
    buf[pos] = BYTE_DASH;
    pos = write_hex_u64_compact(modified_ms, &mut buf, pos + 1);
    buf[pos] = BYTE_QUOTE;
    pos += 1;
    from_utf8(&buf[..pos]).unwrap_or_default().to_owned()
}

/// Extracts modification time in milliseconds since Unix epoch from filesystem [`Metadata`].
///
/// # Arguments
///
/// - `&Metadata` - File metadata.
///
/// # Returns
///
/// - `u64` - Modification timestamp in milliseconds, or `0` if unavailable.
#[inline]
pub(crate) fn metadata_modified_ms(meta: &Metadata) -> u64 {
    meta.modified()
        .ok()
        .and_then(|ts: SystemTime| ts.duration_since(UNIX_EPOCH).ok())
        .map(|dur: Duration| dur.as_millis() as u64)
        .unwrap_or(0)
}

/// Parses an ASCII unsigned decimal integer from `bytes` without allocating.
///
/// # Arguments
///
/// - `&[u8]` - Trimmed ASCII digit bytes.
///
/// # Returns
///
/// - `Option<usize>` - Parsed integer, or `None` on empty, non-digit, or overflow.
#[inline]
pub(crate) fn parse_ascii_usize(bytes: &[u8]) -> Option<usize> {
    if bytes.is_empty() {
        return None;
    }
    let mut acc: usize = 0;
    for &b in bytes {
        if !b.is_ascii_digit() {
            return None;
        }
        acc = acc.checked_mul(10)?.checked_add((b - BYTE_ZERO) as usize)?;
    }
    Some(acc)
}

/// Appends decimal digits for `value` into `buf` at `pos` using a 2-digit lookup table.
///
/// # Arguments
///
/// - `usize` - Unsigned integer to format.
/// - `&mut [u8]` - Destination byte slice.
/// - `usize` - Starting write offset.
///
/// # Returns
///
/// - `usize` - Updated write offset.
#[inline]
pub(crate) fn write_usize_decimal(mut value: usize, buf: &mut [u8], pos: usize) -> usize {
    if value < 10 {
        buf[pos] = BYTE_ZERO + value as u8;
        return pos + 1;
    }
    let mut digits: [u8; 20] = [0u8; 20];
    let mut idx: usize = 20;
    while value >= 100 {
        let pair: usize = (value % 100) * 2;
        value /= 100;
        idx -= 2;
        digits[idx] = DEC_DIGITS_LUT[pair];
        digits[idx + 1] = DEC_DIGITS_LUT[pair + 1];
    }
    if value >= 10 {
        let pair: usize = value * 2;
        idx -= 2;
        digits[idx] = DEC_DIGITS_LUT[pair];
        digits[idx + 1] = DEC_DIGITS_LUT[pair + 1];
    } else {
        idx -= 1;
        digits[idx] = BYTE_ZERO + value as u8;
    }
    let slice: &[u8] = &digits[idx..];
    buf[pos..pos + slice.len()].copy_from_slice(slice);
    pos + slice.len()
}

/// Formats `bytes <start>-<end>/<total>` into a stack buffer without heap allocation.
///
/// # Arguments
///
/// - `usize` - Inclusive range start offset.
/// - `usize` - Inclusive range end offset.
/// - `usize` - Total entity length in bytes.
/// - `&mut [u8; CONTENT_RANGE_STACK_CAP]` - Stack destination buffer.
///
/// # Returns
///
/// - `&str` - Borrowed formatted `Content-Range` value.
#[inline]
pub(crate) fn format_content_range_stack(
    start: usize,
    end: usize,
    total: usize,
    buf: &mut [u8; CONTENT_RANGE_STACK_CAP],
) -> &str {
    let prefix: &[u8] = CONTENT_RANGE_BYTES_PREFIX.as_bytes();
    buf[..prefix.len()].copy_from_slice(prefix);
    let mut pos: usize = write_usize_decimal(start, buf, prefix.len());
    buf[pos] = BYTE_DASH;
    pos = write_usize_decimal(end, buf, pos + 1);
    buf[pos] = BYTE_SLASH;
    pos = write_usize_decimal(total, buf, pos + 1);
    from_utf8(&buf[..pos]).unwrap_or_default()
}

/// Formats `bytes */<total>` into a stack buffer without heap allocation.
///
/// # Arguments
///
/// - `usize` - Total entity length in bytes.
/// - `&mut [u8; CONTENT_RANGE_STACK_CAP]` - Stack destination buffer.
///
/// # Returns
///
/// - `&str` - Borrowed formatted unsatisfiable `Content-Range` value.
#[inline]
pub(crate) fn format_unsatisfiable_range_stack(
    total: usize,
    buf: &mut [u8; CONTENT_RANGE_STACK_CAP],
) -> &str {
    let prefix: &[u8] = CONTENT_RANGE_UNSAT_PREFIX.as_bytes();
    buf[..prefix.len()].copy_from_slice(prefix);
    let pos: usize = write_usize_decimal(total, buf, prefix.len());
    from_utf8(&buf[..pos]).unwrap_or_default()
}

/// Parses `Accept-Encoding` into a two-bit sidecar acceptance mask (`ENCODING_MASK_BR | ENCODING_MASK_GZIP`) in one pass.
///
/// # Arguments
///
/// - `&str` - Incoming `Accept-Encoding` header value.
///
/// # Returns
///
/// - `u8` - Bitmask of accepted precompressed sidecar encodings.
#[inline]
pub(crate) fn accept_encoding_mask(accept_encoding: &str) -> u8 {
    let mut mask: u8 = 0;
    for part in accept_encoding.split(',') {
        let trimmed_part: &str = part.trim();
        if !trimmed_part.as_bytes().contains(&BYTE_SEMICOLON) {
            if trimmed_part.eq_ignore_ascii_case(ENCODING_BR) {
                mask |= ENCODING_MASK_BR;
            } else if trimmed_part.eq_ignore_ascii_case(ENCODING_GZIP) {
                mask |= ENCODING_MASK_GZIP;
            }
            if mask == (ENCODING_MASK_BR | ENCODING_MASK_GZIP) {
                break;
            }
            continue;
        }
        let mut segments: Split<'_, char> = trimmed_part.split(';');
        let coding: &str = segments.next().unwrap_or_default().trim();
        let bit: u8 = if coding.eq_ignore_ascii_case(ENCODING_BR) {
            ENCODING_MASK_BR
        } else if coding.eq_ignore_ascii_case(ENCODING_GZIP) {
            ENCODING_MASK_GZIP
        } else {
            continue;
        };
        let mut rejected: bool = false;
        for param in segments {
            let trimmed: &str = param.trim();
            if let Some(qval) = trimmed
                .strip_prefix(QUALITY_PREFIX_LOWER)
                .or_else(|| trimmed.strip_prefix(QUALITY_PREFIX_UPPER))
                && qval.trim().parse::<f32>().ok() == Some(0.0)
            {
                rejected = true;
            }
        }
        if !rejected {
            mask |= bit;
        }
    }
    mask
}

/// Borrows the last value of lowercase request header `name` without allocating.
///
/// # Arguments
///
/// - `&'a Request` - Incoming HTTP request.
/// - `&str` - Lowercase header key.
///
/// # Returns
///
/// - `Option<&'a str>` - Borrowed last header value, if present.
#[inline]
pub(crate) fn get_request_header_back_ref<'a>(request: &'a Request, name: &str) -> Option<&'a str> {
    request
        .get_headers()
        .get(name)
        .and_then(|values: &VecDeque<String>| values.back())
        .map(String::as_str)
}