hyperlane-plugin-rewrite 23.1.0

A high-performance HTTP URL rewrite and redirect plugin for the Hyperlane framework featuring canonical host/HTTPS enforcement (X-Forwarded-Proto aware), trailing-slash and duplicate-slash normalization, O(1) XxHash3_64 static tables, segment-bounded prefix rules, and compiled regex rules.
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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
use super::*;

/// Reports whether `bytes` contains only RFC 9110 valid HTTP header field-value bytes (matching `Response::set_header`).
///
/// # Arguments
///
/// - `&[u8]` - Candidate HTTP header value byte slice.
///
/// # Returns
///
/// - `bool` - `true` iff every byte is valid on an HTTP/1.1 header value wire line.
#[inline]
pub(crate) fn is_valid_wire_header_value_bytes(bytes: &[u8]) -> bool {
    let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
    for chunk in chunks {
        let word: u64 = u64::from_ne_bytes(*chunk);
        let mut mask: u64 = word & SWAR_HI_BITS;
        mask |= word.wrapping_sub(SWAR_SPACES) & SWAR_HI_BITS;
        mask |= word.wrapping_add(SWAR_LO_BITS) & SWAR_HI_BITS;
        if mask != 0 {
            for &byte in chunk {
                if !HTTP_HEADER_VALUE_VALID_LUT[byte as usize] {
                    return false;
                }
            }
        }
    }
    for &byte in rem {
        if !HTTP_HEADER_VALUE_VALID_LUT[byte as usize] {
            return false;
        }
    }
    true
}

/// Reports whether `value` contains forbidden HTTP header CR, LF, or NUL bytes using 8-byte SWAR scanning.
///
/// # Arguments
///
/// - `&str` - Candidate header or redirect target string.
///
/// # Returns
///
/// - `bool` - `true` when CR (`\r`), LF (`\n`), or NUL (`\0`) is present.
#[inline]
pub(crate) fn has_unsafe_header_chars(value: &str) -> bool {
    let (chunks, rem): (&[[u8; 8]], &[u8]) = value.as_bytes().as_chunks::<8>();
    for chunk in chunks {
        let word: u64 = u64::from_ne_bytes(*chunk);
        let z0: u64 = word.wrapping_sub(SWAR_LO_BITS) & !word;
        let xlf: u64 = word ^ SWAR_LF_MASK;
        let zlf: u64 = xlf.wrapping_sub(SWAR_LO_BITS) & !xlf;
        let xcr: u64 = word ^ SWAR_CR_MASK;
        let zcr: u64 = xcr.wrapping_sub(SWAR_LO_BITS) & !xcr;
        let mut mask: u64 = z0;
        mask |= zlf;
        mask |= zcr;
        if (mask & SWAR_HI_BITS) != 0 {
            return true;
        }
    }
    for &b in rem {
        if b == BYTE_CR || b == BYTE_LF || b == BYTE_NUL {
            return true;
        }
    }
    false
}

/// Reports whether `text` contains no regular-expression metacharacters.
///
/// # Arguments
///
/// - `&str` - Candidate literal slice extracted from a regex pattern.
///
/// # Returns
///
/// - `bool` - `true` when `text` matches only itself as a literal byte sequence.
#[inline]
pub(crate) fn is_plain_regex_literal(text: &str) -> bool {
    !text.bytes().any(|b: u8| REGEX_META_LUT[b as usize])
}

/// Attempts to classify a regex rewrite rule into a regex-free literal or single-capture matcher.
///
/// # Arguments
///
/// - `&str` - Source regex pattern.
/// - `&str` - Replacement template.
///
/// # Returns
///
/// - `Option<CompiledRegexMatcher>` - Fast matcher when semantically identical to `regex::Regex::replace`.
pub(crate) fn try_compile_fast_regex(
    pattern: &str,
    replacement: &str,
) -> Option<CompiledRegexMatcher> {
    let inner: &str = pattern.strip_prefix('^')?.strip_suffix('$')?;
    if is_plain_regex_literal(inner) && !replacement.as_bytes().contains(&BYTE_DOLLAR) {
        return Some(CompiledRegexMatcher::ExactLiteral {
            needle: inner.to_owned(),
            replacement: replacement.to_owned(),
        });
    }
    let open: usize = inner.find('(')?;
    let close: usize = inner[open..].find(')')? + open;
    let prefix: &str = &inner[..open];
    let group: &str = &inner[open..=close];
    let suffix: &str = &inner[close + 1..];
    if !is_plain_regex_literal(prefix) || !is_plain_regex_literal(suffix) {
        return None;
    }
    let kind: CaptureKind = match group {
        CAP_PAT_DIGITS_RANGE => CaptureKind::Digits,
        CAP_PAT_NON_SLASH => CaptureKind::NonSlash,
        CAP_PAT_NON_EMPTY => CaptureKind::NonEmpty,
        CAP_PAT_ANY => CaptureKind::Any,
        _ => return None,
    };
    let (repl_prefix, repl_suffix): (&str, &str) =
        if let Some((before, after)) = replacement.split_once(REPL_CAP_1_BRACED) {
            (before, after)
        } else if let Some((before, after)) = replacement.split_once(REPL_CAP_1) {
            if after
                .as_bytes()
                .first()
                .is_some_and(|b: &u8| b.is_ascii_alphanumeric() || *b == BYTE_UNDERSCORE)
            {
                return None;
            }
            (before, after)
        } else {
            return None;
        };
    if repl_prefix.as_bytes().contains(&BYTE_DOLLAR)
        || repl_suffix.as_bytes().contains(&BYTE_DOLLAR)
    {
        return None;
    }
    Some(CompiledRegexMatcher::PrefixSuffixCapture {
        prefix: prefix.to_owned(),
        suffix: suffix.to_owned(),
        kind,
        repl_prefix: repl_prefix.to_owned(),
        repl_suffix: repl_suffix.to_owned(),
    })
}

/// Validates a captured byte slice against `kind` with exact `regex` semantics.
///
/// # Arguments
///
/// - `&str` - Captured slice between literal prefix and suffix.
/// - `CaptureKind` - Expected capture class.
///
/// # Returns
///
/// - `bool` - `true` when `captured` satisfies the capture rule.
#[inline]
pub(crate) fn matches_capture_kind(captured: &str, kind: CaptureKind) -> bool {
    let bytes: &[u8] = captured.as_bytes();
    match kind {
        CaptureKind::Any => !bytes.contains(&BYTE_LF),
        CaptureKind::NonEmpty => !bytes.is_empty() && !bytes.contains(&BYTE_LF),
        CaptureKind::NonSlash => !bytes.is_empty() && !bytes.contains(&BYTE_SLASH),
        CaptureKind::Digits => !bytes.is_empty() && bytes.iter().all(u8::is_ascii_digit),
    }
}

/// Evaluates a [`CompiledRegexMatcher`] against `path`, returning `Some(replaced)` on match.
///
/// # Arguments
///
/// - `&CompiledRegexMatcher` - Precompiled matcher.
/// - `&str` - Normalized request path.
///
/// # Returns
///
/// - `Option<String>` - Replaced path/location if matched, or `None`.
#[inline]
pub(crate) fn match_compiled_regex(matcher: &CompiledRegexMatcher, path: &str) -> Option<String> {
    match matcher {
        CompiledRegexMatcher::ExactLiteral {
            needle,
            replacement,
        } => {
            if path == needle.as_str() {
                Some(replacement.clone())
            } else {
                None
            }
        }
        CompiledRegexMatcher::PrefixSuffixCapture {
            prefix,
            suffix,
            kind,
            repl_prefix,
            repl_suffix,
        } => {
            if path.len() < prefix.len() + suffix.len() {
                return None;
            }
            let after_prefix: &str = path.strip_prefix(prefix.as_str())?;
            let captured: &str = after_prefix.strip_suffix(suffix.as_str())?;
            if !matches_capture_kind(captured, *kind) {
                return None;
            }
            let mut out: String =
                String::with_capacity(repl_prefix.len() + captured.len() + repl_suffix.len());
            out.push_str(repl_prefix);
            out.push_str(captured);
            out.push_str(repl_suffix);
            Some(out)
        }
        CompiledRegexMatcher::General {
            regex,
            replacement,
            has_expand,
        } => {
            let replaced: Cow<'_, str> = if *has_expand {
                regex.replace(path, replacement.as_str())
            } else {
                regex.replace(path, NoExpand(replacement.as_str()))
            };
            match replaced {
                Cow::Owned(s) => Some(s),
                Cow::Borrowed(_) => None,
            }
        }
    }
}

/// Looks up a header value without cloning using an `O(1)` lowercase fast path.
///
/// # Arguments
///
/// - `&'a RequestHeaders` - Incoming request header map.
/// - `&str` - Canonical lowercase header name.
///
/// # Returns
///
/// - `Option<&'a str>` - Last header value slice if present.
#[inline]
pub(crate) fn find_header_back_ref<'a>(
    headers: &'a RequestHeaders,
    lower_name: &str,
) -> Option<&'a str> {
    if let Some(vals) = headers.get(lower_name) {
        return vals.back().map(String::as_str);
    }
    headers
        .iter()
        .find(|(k, _): &(&String, &VecDeque<String>)| {
            k.len() == lower_name.len() && k.eq_ignore_ascii_case(lower_name)
        })
        .and_then(|(_, v): (&String, &VecDeque<String>)| v.back().map(String::as_str))
}

/// Detects whether the incoming request arrived over HTTPS using `X-Forwarded-Proto` or RFC 7239 `Forwarded`.
///
/// # Arguments
///
/// - `&RequestHeaders` - Request headers.
/// - `bool` - Whether forwarding headers are trusted.
///
/// # Returns
///
/// - `bool` - `true` when the request scheme is `https`.
#[inline]
pub(crate) fn is_request_https(headers: &RequestHeaders, trust_forwarded_proto: bool) -> bool {
    if !trust_forwarded_proto {
        return false;
    }
    if let Some(proto) = find_header_back_ref(headers, X_FORWARDED_PROTO) {
        let first: &str = proto.split(',').next().unwrap_or(proto).trim();
        return first.eq_ignore_ascii_case(SCHEME_HTTPS);
    }
    if let Some(fwd) = find_header_back_ref(headers, FORWARDED) {
        for element in fwd.split(',') {
            for param in element.split(';') {
                let trimmed: &str = param.trim();
                if trimmed.len() > FORWARDED_PROTO_PREFIX.len()
                    && trimmed[..FORWARDED_PROTO_PREFIX.len()]
                        .eq_ignore_ascii_case(FORWARDED_PROTO_PREFIX)
                {
                    let val: &str = trimmed[FORWARDED_PROTO_PREFIX.len()..]
                        .trim()
                        .trim_matches('"');
                    return val.eq_ignore_ascii_case(SCHEME_HTTPS);
                }
            }
        }
    }
    false
}

/// Compares incoming `Host` header against lowercased canonical host (ignoring default `:80`/`:443` suffix).
///
/// # Arguments
///
/// - `&str` - Incoming `Host` header value.
/// - `&str` - Lowercased canonical host.
///
/// # Returns
///
/// - `bool` - `true` when incoming host matches canonical host.
#[inline]
pub(crate) fn host_matches_canonical(raw_host: &str, canonical_lower: &str) -> bool {
    let trimmed: &str = raw_host.trim();
    if trimmed.eq_ignore_ascii_case(canonical_lower) {
        return true;
    }
    let stripped: &str = trimmed
        .strip_suffix(DEFAULT_HTTP_PORT)
        .or_else(|| trimmed.strip_suffix(DEFAULT_HTTPS_PORT))
        .unwrap_or(trimmed);
    stripped.eq_ignore_ascii_case(canonical_lower)
}

/// Collapses consecutive `'/'` bytes into a single `'/'` without allocating when already clean.
///
/// # Arguments
///
/// - `&str` - Candidate request path.
///
/// # Returns
///
/// - `Cow<'_, str>` - Borrowed path when already clean, or newly collapsed path.
#[inline]
pub(crate) fn collapse_slashes(path: &str) -> Cow<'_, str> {
    let bytes: &[u8] = path.as_bytes();
    let len: usize = bytes.len();
    let mut first_dup: usize = len;
    let mut idx: usize = 0;
    while idx + 1 < len {
        if bytes[idx] == BYTE_SLASH && bytes[idx + 1] == BYTE_SLASH {
            first_dup = idx;
            break;
        }
        idx += 1;
    }
    if first_dup == len {
        return Cow::Borrowed(path);
    }
    let mut out: String = String::with_capacity(len);
    out.push_str(&path[..=first_dup]);
    let mut cursor: usize = first_dup + 2;
    while cursor < len {
        while cursor < len && bytes[cursor] == BYTE_SLASH {
            cursor += 1;
        }
        let seg_start: usize = cursor;
        while cursor < len && bytes[cursor] != BYTE_SLASH {
            cursor += 1;
        }
        if cursor > seg_start {
            out.push_str(&path[seg_start..cursor]);
        }
        if cursor < len {
            out.push('/');
            cursor += 1;
        }
    }
    Cow::Owned(out)
}

/// Applies [`TrailingSlashMode`] without allocating in `Strip` mode when borrowing the source path.
///
/// # Arguments
///
/// - `Cow<'a, str>` - Path after optional duplicate-slash collapsing.
/// - `TrailingSlashMode` - Desired trailing-slash policy.
///
/// # Returns
///
/// - `(Cow<'a, str>, bool)` - Normalized path and whether trailing-slash normalization modified it.
#[inline]
pub(crate) fn normalize_trailing_slash_borrowed<'a>(
    path: Cow<'a, str>,
    mode: TrailingSlashMode,
) -> (Cow<'a, str>, bool) {
    let raw: &str = path.as_ref();
    if raw.len() <= 1 {
        return (path, false);
    }
    match mode {
        TrailingSlashMode::Keep => (path, false),
        TrailingSlashMode::Strip => {
            if !raw.ends_with('/') {
                return (path, false);
            }
            match path {
                Cow::Borrowed(s) => (Cow::Borrowed(&s[..s.len() - 1]), true),
                Cow::Owned(mut s) => {
                    let _: Option<char> = s.pop();
                    (Cow::Owned(s), true)
                }
            }
        }
        TrailingSlashMode::Enforce => {
            if raw.ends_with('/') {
                return (path, false);
            }
            match path {
                Cow::Borrowed(s) => {
                    let mut out: String = String::with_capacity(s.len() + 1);
                    out.push_str(s);
                    out.push('/');
                    (Cow::Owned(out), true)
                }
                Cow::Owned(mut s) => {
                    s.push('/');
                    (Cow::Owned(s), true)
                }
            }
        }
    }
}

/// Normalizes a prefix rule path by trimming trailing slashes while preserving `"/"`.
///
/// # Arguments
///
/// - `&str` - Raw prefix path.
///
/// # Returns
///
/// - `String` - Normalized prefix.
pub(crate) fn normalize_rule_prefix(prefix: &str) -> String {
    let trimmed: &str = prefix.trim();
    if trimmed == "/" {
        return "/".to_owned();
    }
    trimmed.trim_end_matches('/').to_owned()
}

/// Checks whether `path` matches `prefix` on a segment boundary and returns the remaining suffix.
///
/// # Arguments
///
/// - `&'a str` - Incoming request path.
/// - `&str` - Normalized rule prefix.
///
/// # Returns
///
/// - `Option<&'a str>` - Remaining path suffix (`""` or starting with `'/'`), or `None` on mismatch.
#[inline]
pub(crate) fn strip_prefix_segment<'a>(path: &'a str, prefix: &str) -> Option<&'a str> {
    if prefix == "/" {
        return Some(path);
    }
    if path.len() < prefix.len() {
        return None;
    }
    let rest: &'a str = path.strip_prefix(prefix)?;
    if rest.is_empty() || rest.as_bytes()[0] == BYTE_SLASH {
        Some(rest)
    } else {
        None
    }
}

/// Joins a replacement prefix `to` with the remaining segment suffix `rest`.
///
/// # Arguments
///
/// - `&str` - Replacement prefix (may be empty for pure prefix stripping).
/// - `&str` - Remaining suffix from [`strip_prefix_segment`].
///
/// # Returns
///
/// - `String` - Rewritten path starting with `'/'` (or absolute URL when `to` has a scheme).
#[inline]
pub(crate) fn join_prefix_replacement(to: &str, rest: &str) -> String {
    if to.is_empty() {
        if rest.is_empty() {
            return "/".to_owned();
        }
        return rest.to_owned();
    }
    let mut out: String = String::with_capacity(to.len() + rest.len());
    out.push_str(to);
    out.push_str(rest);
    out
}

/// Computes the exact query suffix byte length needed when preserving request query parameters.
///
/// # Arguments
///
/// - `&Context` - Active request context.
/// - `bool` - Whether query preservation is enabled.
/// - `bool` - Whether the base location already contains `'?'`.
///
/// # Returns
///
/// - `usize` - Total bytes required for the leading `'?'` and query parameters, or `0`.
#[inline]
pub(crate) fn query_suffix_len_from_ctx(
    ctx: &Context,
    preserve_query: bool,
    target_has_query: bool,
) -> usize {
    if !preserve_query || target_has_query {
        return 0;
    }
    if let Some(raw_target) = ctx.get_request_target()
        && let Some((_, q)) = raw_target.split_once('?')
        && !q.is_empty()
    {
        return q.len() + 1;
    }
    let querys: &RequestQuerys = ctx.get_request().get_querys();
    if querys.is_empty() {
        return 0;
    }
    let mut total: usize = 0;
    for (k, vals) in querys {
        for v in vals {
            total += 1 + k.len();
            if !v.is_empty() {
                total += 1 + v.len();
            }
        }
    }
    total
}

/// Allocates `base` plus any preserved request query parameters in a single allocation.
///
/// # Arguments
///
/// - `&str` - Base redirect location.
/// - `&Context` - Active request context.
/// - `bool` - Whether query preservation is enabled.
/// - `bool` - Whether `base` is already known to contain `'?'`.
///
/// # Returns
///
/// - `String` - Complete redirect location.
#[inline]
pub(crate) fn clone_with_query_from_ctx(
    base: &str,
    ctx: &Context,
    preserve_query: bool,
    target_has_query: bool,
) -> String {
    let q_len: usize = query_suffix_len_from_ctx(ctx, preserve_query, target_has_query);
    let mut out: String = String::with_capacity(base.len() + q_len);
    out.push_str(base);
    if q_len > 0 {
        append_query_from_ctx(&mut out, ctx, preserve_query, target_has_query);
    }
    out
}

/// Appends the original request query string directly onto `target` with exact pre-reservation.
///
/// # Arguments
///
/// - `&mut String` - Base redirect location buffer.
/// - `&Context` - Active request context.
/// - `bool` - Whether query preservation is enabled.
/// - `bool` - Whether `target` is already known to contain `'?'`.
#[inline]
pub(crate) fn append_query_from_ctx(
    target: &mut String,
    ctx: &Context,
    preserve_query: bool,
    target_has_query: bool,
) {
    if !preserve_query || target_has_query {
        return;
    }
    if let Some(raw_target) = ctx.get_request_target()
        && let Some((_, q)) = raw_target.split_once('?')
        && !q.is_empty()
    {
        target.reserve(q.len() + 1);
        target.push('?');
        target.push_str(q);
        return;
    }
    let querys: &RequestQuerys = ctx.get_request().get_querys();
    if querys.is_empty() {
        return;
    }
    let mut extra: usize = 0;
    for (k, vals) in querys {
        for v in vals {
            extra += 1 + k.len();
            if !v.is_empty() {
                extra += 1 + v.len();
            }
        }
    }
    target.reserve(extra);
    let mut first: bool = true;
    for (k, vals) in querys {
        for v in vals {
            target.push(if first { '?' } else { '&' });
            first = false;
            target.push_str(k);
            if !v.is_empty() {
                target.push('=');
                target.push_str(v);
            }
        }
    }
}

/// Appends the original request query string directly onto a raw byte stack buffer.
///
/// # Arguments
///
/// - `&mut [u8]` - Destination stack byte buffer.
/// - `usize` - Current write offset inside `buf`.
/// - `&Context` - Active request context.
/// - `bool` - Whether query preservation is enabled.
/// - `bool` - Whether the location prefix already contains `'?'`.
///
/// # Returns
///
/// - `Option<usize>` - Updated offset on success, or `None` on stack overflow.
#[inline]
pub(crate) fn write_query_bytes_from_ctx(
    buf: &mut [u8],
    mut pos: usize,
    ctx: &Context,
    preserve_query: bool,
    target_has_query: bool,
) -> Option<usize> {
    if !preserve_query || target_has_query {
        return Some(pos);
    }
    if let Some(raw_target) = ctx.get_request_target()
        && let Some((_, q)) = raw_target.split_once('?')
        && !q.is_empty()
    {
        let qb: &[u8] = q.as_bytes();
        if pos + 1 + qb.len() > buf.len() {
            return None;
        }
        buf[pos] = BYTE_QUESTION;
        pos += 1;
        buf[pos..pos + qb.len()].copy_from_slice(qb);
        return Some(pos + qb.len());
    }
    let querys: &RequestQuerys = ctx.get_request().get_querys();
    if querys.is_empty() {
        return Some(pos);
    }
    let mut first: bool = true;
    for (k, vals) in querys {
        let kb: &[u8] = k.as_bytes();
        for v in vals {
            let vb: &[u8] = v.as_bytes();
            let extra: usize = 1 + kb.len() + if vb.is_empty() { 0 } else { 1 + vb.len() };
            if pos + extra > buf.len() {
                return None;
            }
            buf[pos] = if first { BYTE_QUESTION } else { BYTE_AMP };
            first = false;
            pos += 1;
            buf[pos..pos + kb.len()].copy_from_slice(kb);
            pos += kb.len();
            if !vb.is_empty() {
                buf[pos] = BYTE_EQ;
                pos += 1;
                buf[pos..pos + vb.len()].copy_from_slice(vb);
                pos += vb.len();
            }
        }
    }
    Some(pos)
}

/// Returns the prebuilt HTTP/1.1 wire prefix for `status` up to the `Location` value.
///
/// # Arguments
///
/// - `RedirectStatus` - Redirect status variant.
///
/// # Returns
///
/// - `&'static [u8]` - Static HTTP/1.1 header prefix bytes.
#[inline(always)]
pub(crate) fn redirect_wire_prefix(status: RedirectStatus) -> &'static [u8] {
    match status {
        RedirectStatus::MovedPermanently301 => WIRE_301_PREFIX,
        RedirectStatus::Found302 => WIRE_302_PREFIX,
        RedirectStatus::Temporary307 => WIRE_307_PREFIX,
        RedirectStatus::Permanent308 => WIRE_308_PREFIX,
    }
}

/// Stores the pre-rewrite request path attribute in-place, returning any previous `String` buffer for reuse.
///
/// # Arguments
///
/// - `&mut Context` - Active request context.
/// - `String` - Original request path prior to rewrite.
///
/// # Returns
///
/// - `Option<String>` - Recycled previous attribute `String` buffer when updated in-place.
#[inline]
pub(crate) fn store_original_path_attr(ctx: &mut Context, original: String) -> Option<String> {
    if let Some(slot) = ctx.get_mut_attributes().get_mut(ATTR_ORIGINAL_PATH_MAP_KEY) {
        if let Some(any_mut) = Arc::get_mut(slot)
            && let Some(existing) = any_mut.downcast_mut::<String>()
        {
            return Some(mem::replace(existing, original));
        }
        *slot = Arc::new(original);
    } else {
        ctx.get_mut_attributes()
            .insert(ATTR_ORIGINAL_PATH_MAP_KEY.to_owned(), Arc::new(original));
    }
    None
}

/// Applies an internal path rewrite while recycling the previous path and attribute buffers without extra clones.
///
/// # Arguments
///
/// - `&mut Context` - Active request context.
/// - `&str` - New rewritten request path.
#[inline]
pub(crate) fn apply_internal_rewrite_copy(ctx: &mut Context, target: &str) {
    let old_path: String = mem::take(ctx.get_mut_request().get_mut_path());
    let next_path: String = if let Some(mut recycled) = store_original_path_attr(ctx, old_path) {
        recycled.clear();
        recycled.push_str(target);
        recycled
    } else {
        target.to_owned()
    };
    ctx.get_mut_request().set_path(next_path);
}

/// Applies an internal path rewrite moving `target` directly into the request without cloning.
///
/// # Arguments
///
/// - `&mut Context` - Active request context.
/// - `String` - Owned rewritten request path.
#[inline]
pub(crate) fn apply_internal_rewrite_owned(ctx: &mut Context, target: String) {
    let old_path: String = mem::replace(ctx.get_mut_request().get_mut_path(), target);
    let _: Option<String> = store_original_path_attr(ctx, old_path);
}