hyperlane-core 23.0.0

A lightweight, high-performance, and cross-platform Rust HTTP server library built on Tokio. It simplifies modern web service development by providing built-in support for middleware, WebSocket, Server-Sent Events (SSE), and raw TCP communication. With a unified and ergonomic API across Windows, Linux, and MacOS, it enables developers to build robust, scalable, and event-driven network applications with minimal overhead and maximum flexibility.
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
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
use super::*;

/// Validates and populates a framework request from HTTP/2 parts in a single header pass.
///
/// Enforces RFC 9113 §8.2.2 forbidden connection headers, parses `content-length`
/// and `expect: 100-continue`, checks authority/host equivalence, enforces header
/// and target limits, and populates pooled headers, query parameters, path,
/// method, version, and host without redundant `HeaderMap` scans.
///
/// # Arguments
///
/// - `&RequestConfig` - The parsing limits to enforce.
/// - `&mut Parts` - The decoded HTTP/2 request head parts.
/// - `bool` - Whether the request stream still carries body frames (`!is_end_stream`).
/// - `&mut Request` - The recycled framework request to populate in place.
/// - `&mut String` - The recycled buffer receiving the original wire target.
///
/// # Returns
///
/// - `Result<H2PreparedRequest, RequestError>` - Extracted framing metadata or immediate head error.
pub(crate) fn prepare_h2_request(
    config: &RequestConfig,
    parts: &mut Parts,
    has_body_stream: bool,
    request: &mut Request,
    target: &mut String,
) -> Result<H2PreparedRequest, RequestError> {
    let max_body_size: usize = config.get_max_body_size();
    let max_header_count: usize = config.get_max_header_count();
    let max_header_key_size: usize = config.get_max_header_key_size();
    let max_header_value_size: usize = config.get_max_header_value_size();
    let mut declared_content_length: Option<usize> = None;
    let mut cl_error: Option<RequestError> = None;
    let mut expect_continue: bool = false;
    let mut host_count: usize = 0;
    let mut host_val: Option<&str> = None;
    let mut host_invalid: bool = false;
    let mut colon_authority_val: Option<&str> = None;
    let mut colon_authority_invalid: bool = false;
    let mut header_count: usize = 0;
    let mut header_error: Option<RequestError> = None;
    let target_headers: &mut RequestHeaders = request.get_mut_headers();
    let forbidden_res: Result<(), RequestError> =
        PROTOCOL_HEADER_POOL.with(|pool: &RefCell<Vec<(String, VecDeque<String>)>>| {
            let mut pool_guard: RefMut<'_, Vec<(String, VecDeque<String>)>> = pool.borrow_mut();
            for (name, value) in parts.headers.iter() {
                let key: &str = name.as_str();
                if key.starts_with(PSEUDO_HEADER_PREFIX) {
                    if key == COLON_AUTHORITY
                        && colon_authority_val.is_none()
                        && !colon_authority_invalid
                    {
                        match value.to_str() {
                            Ok(val) => colon_authority_val = Some(val),
                            Err(_) => colon_authority_invalid = true,
                        }
                    }
                    continue;
                }
                if is_forbidden_h2_header(key, value.as_bytes()) {
                    return Err(RequestError::HttpRead(HttpStatus::BadRequest));
                }
                if key == CONTENT_LENGTH {
                    if declared_content_length.is_some() {
                        if cl_error.is_none() {
                            cl_error =
                                Some(RequestError::InvalidContentLength(HttpStatus::BadRequest));
                        }
                    } else if cl_error.is_none() {
                        match value.to_str() {
                            Ok(val_str) => match parse_ascii_length(val_str) {
                                Ok(parsed) => {
                                    if parsed > max_body_size
                                        && max_body_size != DEFAULT_LOW_SECURITY_MAX_BODY_SIZE
                                    {
                                        cl_error = Some(RequestError::ContentLengthTooLarge(
                                            HttpStatus::PayloadTooLarge,
                                        ));
                                    } else {
                                        declared_content_length = Some(parsed);
                                    }
                                }
                                Err(err) => cl_error = Some(err),
                            },
                            Err(_) => {
                                cl_error = Some(RequestError::InvalidContentLength(
                                    HttpStatus::BadRequest,
                                ));
                            }
                        }
                    }
                } else if key == HOST {
                    host_count += 1;
                    if host_count == 1 {
                        match value.to_str() {
                            Ok(val_str) => host_val = Some(val_str),
                            Err(_) => host_invalid = true,
                        }
                    }
                } else if has_body_stream
                    && !expect_continue
                    && key == EXPECT
                    && contains_continue_member(value.as_bytes())
                {
                    expect_continue = true;
                }
                let Ok(val_str) = value.to_str() else {
                    if header_error.is_none() {
                        header_error = Some(RequestError::HttpRead(HttpStatus::BadRequest));
                    }
                    continue;
                };
                header_count += 1;
                if header_count > max_header_count
                    && max_header_count != DEFAULT_LOW_SECURITY_MAX_HEADER_COUNT
                {
                    if header_error.is_none() {
                        header_error = Some(RequestError::TooManyHeaders(
                            HttpStatus::RequestHeaderFieldsTooLarge,
                        ));
                    }
                    continue;
                }
                if key.len() > max_header_key_size
                    && max_header_key_size != DEFAULT_LOW_SECURITY_MAX_HEADER_KEY_SIZE
                {
                    if header_error.is_none() {
                        header_error = Some(RequestError::HeaderKeyTooLong(HttpStatus::BadRequest));
                    }
                    continue;
                }
                if val_str.len() > max_header_value_size
                    && max_header_value_size != DEFAULT_LOW_SECURITY_MAX_HEADER_VALUE_SIZE
                {
                    if header_error.is_none() {
                        header_error =
                            Some(RequestError::HeaderValueTooLong(HttpStatus::BadRequest));
                    }
                    continue;
                }
                insert_pooled_map_entry(target_headers, &mut pool_guard, key, val_str);
            }
            Ok(())
        });
    forbidden_res?;
    if let Some(error) = cl_error {
        return Err(error);
    }
    let uri: &Uri = &parts.uri;
    let raw_path: &str = uri.path();
    let raw_query: Option<&str> = uri.query();
    write_request_target(raw_path, raw_query, target);
    let max_path_size: usize = config.get_max_path_size();
    let mut deferred_error: Option<RequestError> =
        if target.len() > max_path_size && max_path_size != DEFAULT_LOW_SECURITY_MAX_PATH_SIZE {
            Some(RequestError::PathTooLong(HttpStatus::URITooLong))
        } else {
            None
        };
    let authority: Option<&str> = uri
        .authority()
        .map(|authority: &Authority| authority.as_str());
    let effective_host: Option<&str> = if host_count > 0 {
        host_val
    } else {
        colon_authority_val
    };
    if deferred_error.is_none() {
        let authority_bad: bool = match authority {
            Some(val) => !is_valid_authority_value(val),
            None => false,
        };
        let effective_host_bad: bool = match effective_host {
            Some(val) => !is_valid_authority_value(val),
            None => false,
        };
        let authority_mismatch: bool = match (authority, effective_host) {
            (Some(auth), Some(host)) => !same_authority(auth, host, uri.scheme_str()),
            _ => false,
        };
        let host_bad: bool = host_count > 1
            || host_invalid
            || (host_count == 0 && colon_authority_invalid)
            || authority_bad
            || effective_host_bad
            || authority_mismatch;
        if host_bad {
            deferred_error = Some(RequestError::InvalidUrlHost(HttpStatus::BadRequest));
        } else {
            deferred_error = header_error;
        }
    }
    if deferred_error.is_none() {
        if !request.get_querys().is_empty() {
            request.get_mut_querys().clear();
        }
        let (clean_path, clean_query): (&str, &str) = match raw_path.find(HASH) {
            Some(hash_index) => (&raw_path[..hash_index], EMPTY_STR),
            None => match raw_query {
                Some(query) => match query.find(HASH) {
                    Some(hash_index) => (raw_path, &query[..hash_index]),
                    None => (raw_path, query),
                },
                None => (raw_path, EMPTY_STR),
            },
        };
        if !clean_query.is_empty() {
            fill_request_querys(clean_query, request.get_mut_querys());
        }
        let req_path: &mut String = request.get_mut_path();
        req_path.clear();
        req_path.push_str(clean_path);
        request.set_method(protocol_method(mem::take(&mut parts.method)));
        request.set_version(HttpVersion::Http2);
        let host_out: &mut String = request.get_mut_host();
        host_out.clear();
        if let Some(auth) = authority {
            host_out.push_str(auth);
        } else if let Some(host) = effective_host {
            host_out.push_str(host);
        }
    }
    Ok(H2PreparedRequest {
        declared_content_length,
        expect_continue: expect_continue && declared_content_length != Some(0),
        deferred_error,
    })
}

/// Inserts a key/value entry into a pooled request header or query map using an active pool borrow.
///
/// # Arguments
///
/// - `&mut RequestHeaders` - Destination map (headers or query parameters).
/// - `&mut Vec<(String, VecDeque<String>)>` - Borrowed worker-local entry pool.
/// - `&str` - Key string to store.
/// - `&str` - Value string to append.
#[inline(always)]
pub(crate) fn insert_pooled_map_entry(
    map: &mut RequestHeaders,
    pool: &mut Vec<(String, VecDeque<String>)>,
    key: &str,
    value: &str,
) {
    let (mut pooled_key, mut pooled_values): (String, VecDeque<String>) = pool
        .pop()
        .unwrap_or_else(|| (String::new(), VecDeque::new()));
    pooled_key.clear();
    pooled_key.push_str(key);
    match map.entry(pooled_key) {
        Entry::Occupied(mut occupied) => {
            occupied.get_mut().push_back(value.to_owned());
            if pool.len() < MAX_POOLED_PROTOCOL_HEADERS {
                pool.push((String::new(), pooled_values));
            }
        }
        Entry::Vacant(vacant) => {
            if pooled_values.len() == 1 {
                pooled_values[0].clear();
                pooled_values[0].push_str(value);
            } else {
                while pooled_values.len() > 1 {
                    pooled_values.pop_back();
                }
                if let Some(slot) = pooled_values.front_mut() {
                    slot.clear();
                    slot.push_str(value);
                } else {
                    pooled_values.push_back(value.to_owned());
                }
            }
            vacant.insert(pooled_values);
        }
    }
}

/// Inserts a valueless key entry into a pooled request query map using an active pool borrow.
///
/// # Arguments
///
/// - `&mut RequestQuerys` - Destination query map.
/// - `&mut Vec<(String, VecDeque<String>)>` - Borrowed worker-local entry pool.
/// - `&str` - Key string to store with an empty value list.
#[inline(always)]
pub(crate) fn insert_pooled_empty_query_entry(
    map: &mut RequestQuerys,
    pool: &mut Vec<(String, VecDeque<String>)>,
    key: &str,
) {
    if map.contains_key(key) {
        return;
    }
    let (mut pooled_key, mut pooled_values): (String, VecDeque<String>) = pool
        .pop()
        .unwrap_or_else(|| (String::new(), VecDeque::new()));
    pooled_key.clear();
    pooled_key.push_str(key);
    pooled_values.clear();
    map.insert(pooled_key, pooled_values);
}

/// Writes the wire request target into a caller-owned buffer.
///
/// # Arguments
///
/// - `&str` - The request path.
/// - `Option<&str>` - The request query string, when one is present.
/// - `&mut String` - The destination buffer.
pub(crate) fn write_request_target(path: &str, query: Option<&str>, target: &mut String) {
    target.clear();
    match query {
        Some(query) => {
            target.reserve(path.len() + query.len() + 1);
            target.push_str(path);
            target.push(QUESTION_MARK);
            target.push_str(query);
        }
        None => {
            target.push_str(path);
        }
    }
}

/// Reports whether a raw `:authority` or `host` header value has valid RFC 9110 authority syntax.
///
/// # Arguments
///
/// - `&str` - The candidate authority or host header value.
///
/// # Returns
///
/// - `bool` - `true` when the value is syntactically valid and contains no userinfo or control bytes.
pub(crate) fn is_valid_authority_value(value: &str) -> bool {
    if value.is_empty() {
        return false;
    }
    for byte in value.bytes() {
        if byte <= 0x20 || byte >= 0x7f || FORBIDDEN_AUTHORITY_BYTES.contains(&byte) {
            return false;
        }
    }
    let (host, port): (&str, Option<&str>) = split_authority_port(value);
    if host.is_empty() {
        return false;
    }
    if host.starts_with('[') {
        let Some(inner) = host
            .strip_prefix('[')
            .and_then(|s: &str| s.strip_suffix(']'))
        else {
            return false;
        };
        if inner.is_empty()
            || !inner
                .bytes()
                .all(|b: u8| b.is_ascii_hexdigit() || b == COLON_U8 || b == POINT_U8)
        {
            return false;
        }
    } else if host.contains('[') || host.contains(']') || host.contains(':') {
        return false;
    }
    if let Some(port) = port {
        let all_digits: bool = port.bytes().all(|b: u8| b.is_ascii_digit());
        if port.is_empty() || !all_digits {
            return false;
        }
        if port.parse::<u16>().is_err() {
            return false;
        }
    }
    true
}

/// Reports whether an HTTP/2 or HTTP/3 request header name/value is a forbidden connection header.
///
/// # Arguments
///
/// - `&str` - Lowercase header name.
/// - `&[u8]` - Raw header value bytes.
///
/// # Returns
///
/// - `bool` - `true` when RFC 9113 §8.2.2 forbids this header on incoming requests.
fn is_forbidden_h2_header(name: &str, value: &[u8]) -> bool {
    match name {
        CONNECTION | KEEP_ALIVE | PROXY_CONNECTION | TRANSFER_ENCODING | UPGRADE => true,
        TE => !value.eq_ignore_ascii_case(HTTP_TE_TRAILERS.as_bytes()),
        _ => false,
    }
}

/// Checks that the request authority and the host header name the same host.
///
/// HTTP/2 and HTTP/3 carry the authority in a pseudo header, and a client may
/// also send a `host` header beside it. RFC 9113 Section 8.3.1 makes a request
/// that names two different entities malformed, because a proxy that trusts
/// one value and an origin that trusts the other would route the same bytes
/// to different hosts. The pseudo header wins when only one of the two is
/// present.
///
/// The userinfo form is refused in both places, because RFC 9113 Section 8.3.1
/// forbids it in `:authority` and RFC 9110 Section 7.2 forbids it in `host`, and
/// a value that carries it names an entity other than the one it appears to.
///
/// # Arguments
///
/// - `&HeaderMap` - The protocol request headers.
/// - `&Uri` - The request target, carrying the authority.
///
/// # Returns
///
/// - `Result<(), RequestError>` - `Ok(())` when the authority is unambiguous, or
///   `RequestError::InvalidUrlHost` when it is not.
#[cfg(test)]
pub fn check_request_authority(headers: &HeaderMap, uri: &Uri) -> Result<(), RequestError> {
    let host_count: usize = headers.get_all(HOST).iter().count();
    if host_count > 1 {
        return Err(RequestError::InvalidUrlHost(HttpStatus::BadRequest));
    }
    let authority: Option<&str> = uri
        .authority()
        .map(|authority: &Authority| authority.as_str());
    let host: Option<&str> = match headers.get(HOST) {
        Some(value) => match value.to_str() {
            Ok(value) => Some(value),
            Err(_) => return Err(RequestError::InvalidUrlHost(HttpStatus::BadRequest)),
        },
        None => match headers.get(COLON_AUTHORITY) {
            Some(value) => match value.to_str() {
                Ok(value) => Some(value),
                Err(_) => return Err(RequestError::InvalidUrlHost(HttpStatus::BadRequest)),
            },
            None => None,
        },
    };
    if let Some(authority) = authority
        && !is_valid_authority_value(authority)
    {
        return Err(RequestError::InvalidUrlHost(HttpStatus::BadRequest));
    }
    if let Some(host) = host
        && !is_valid_authority_value(host)
    {
        return Err(RequestError::InvalidUrlHost(HttpStatus::BadRequest));
    }
    let (Some(authority), Some(host)) = (authority, host) else {
        return Ok(());
    };
    let scheme: Option<&str> = uri.scheme_str();
    if !same_authority(authority, host, scheme) {
        return Err(RequestError::InvalidUrlHost(HttpStatus::BadRequest));
    }
    Ok(())
}

/// Reports whether two authority values name the same host.
///
/// RFC 9113 Section 8.3.1 asks for the two values to be normalized before they
/// are compared, and RFC 3986 Section 6.2.3 defines the scheme based
/// normalization that a server must apply: the host is compared without regard
/// to case, and a port that is the default for the scheme is the same as no
/// port at all.
///
/// The `http` crate accepts authority values it cannot interpret, such as a
/// port that is not a number, so the values are split here instead of being
/// compared through the crate's parser.
///
/// # Arguments
///
/// - `&str` - The authority from the pseudo header.
/// - `&str` - The authority from the host header.
/// - `Option<&str>` - The scheme of the request, used to resolve the default port.
///
/// # Returns
///
/// - `bool` - `true` when both values name the same host.
pub fn same_authority(authority: &str, host: &str, scheme: Option<&str>) -> bool {
    if authority.eq_ignore_ascii_case(host) {
        return true;
    }
    let (auth_host, auth_port): (&str, Option<&str>) = split_authority_port(authority);
    let (host_host, host_port): (&str, Option<&str>) = split_authority_port(host);
    if !auth_host.eq_ignore_ascii_case(host_host) {
        return false;
    }
    let default_port: Option<&str> = match scheme {
        Some(HTTP_SCHEME) => Some(DEFAULT_HTTP_PORT_STR),
        Some(HTTPS_SCHEME) => Some(DEFAULT_HTTPS_PORT_STR),
        _ => None,
    };
    let effective_auth_port: Option<&str> = match (auth_port, default_port) {
        (Some(port), Some(default_port)) if port == default_port => None,
        (port, _) => port,
    };
    let effective_host_port: Option<&str> = match (host_port, default_port) {
        (Some(port), Some(default_port)) if port == default_port => None,
        (port, _) => port,
    };
    effective_auth_port == effective_host_port
}

/// Normalizes an authority value for comparison.
///
/// The host is lowercased and a port that is the default for the scheme is
/// dropped, so `EXAMPLE.com` and `example.com:443` name the same host for an
/// `https` request.
///
/// # Arguments
///
/// - `&str` - The authority value.
/// - `Option<&str>` - The scheme of the request, used to resolve the default port.
///
/// # Returns
///
/// - `(String, Option<String>)` - The normalized host, and the normalized port.
#[cfg(test)]
pub fn normalize_authority(authority: &str, scheme: Option<&str>) -> (String, Option<String>) {
    let (host, port): (&str, Option<&str>) = split_authority_port(authority);
    let host: String = host.to_ascii_lowercase();
    let port: Option<String> = port.map(|port: &str| port.to_owned());
    let default_port: Option<&str> = match scheme {
        Some(HTTP_SCHEME) => Some(DEFAULT_HTTP_PORT_STR),
        Some(HTTPS_SCHEME) => Some(DEFAULT_HTTPS_PORT_STR),
        _ => None,
    };
    match (port, default_port) {
        (Some(port), Some(default_port)) if port == default_port => (host, None),
        (port, _) => (host, port),
    }
}

/// Splits an authority value into its host and its optional port.
///
/// # Arguments
///
/// - `&str` - The authority value.
///
/// # Returns
///
/// - `(&str, Option<&str>)` - The host, and the port when the value carries one.
pub fn split_authority_port(authority: &str) -> (&str, Option<&str>) {
    let authority: &str = authority.trim();
    if authority.starts_with('[') {
        return match authority.find(']') {
            Some(end) => match authority[end + 1..].strip_prefix(':') {
                Some(port) => (&authority[..end + 1], Some(port)),
                None => (authority, None),
            },
            None => (authority, None),
        };
    }
    match authority.rsplit_once(':') {
        Some((host, port)) if !host.is_empty() && !host.contains(':') => (host, Some(port)),
        _ => (authority, None),
    }
}

/// Parses a query string into the request's query map.
///
/// A key that repeats keeps every value, because a single valued map would
/// discard all but the last occurrence without reporting anything.
///
/// # Arguments
///
/// - `&str` - The query string.
/// - `&mut RequestQuerys` - The map to fill.
pub fn fill_request_querys(query: &str, querys: &mut RequestQuerys) {
    if query.is_empty() {
        return;
    }
    PROTOCOL_HEADER_POOL.with(|pool: &RefCell<Vec<(String, VecDeque<String>)>>| {
        let mut pool_guard: RefMut<'_, Vec<(String, VecDeque<String>)>> = pool.borrow_mut();
        let mut param_count: usize = 0;
        for pair in query.split(AND) {
            if param_count >= PROTOCOL_MAX_QUERY_PARAM_COUNT {
                break;
            }
            if let Some((key, value)) = pair.split_once(EQUAL) {
                if !key.is_empty() {
                    param_count += 1;
                    insert_pooled_map_entry(querys, &mut pool_guard, key, value);
                }
            } else if !pair.is_empty() {
                param_count += 1;
                insert_pooled_empty_query_entry(querys, &mut pool_guard, pair);
            }
        }
    });
}

/// Decodes a protocol method into the framework method enum.
///
/// # Arguments
///
/// - `http::Method` - The method decoded by the protocol library.
///
/// # Returns
///
/// - `Method` - The framework method.
pub fn protocol_method(method: http::Method) -> Method {
    if method == http::Method::GET {
        return Method::Get;
    }
    if method == http::Method::POST {
        return Method::Post;
    }
    if method == http::Method::PUT {
        return Method::Put;
    }
    if method == http::Method::DELETE {
        return Method::Delete;
    }
    if method == http::Method::PATCH {
        return Method::Patch;
    }
    if method == http::Method::HEAD {
        return Method::Head;
    }
    if method == http::Method::OPTIONS {
        return Method::Options;
    }
    if method == http::Method::CONNECT {
        return Method::Connect;
    }
    if method == http::Method::TRACE {
        return Method::Trace;
    }
    Method::Unknown(method.as_str().to_owned())
}

/// Reports whether a header is hop by hop for the HTTP/2 and HTTP/3 framing.
///
/// # Arguments
///
/// - `&str` - The lowercased header name.
///
/// # Returns
///
/// - `bool` - `true` when the header must not cross the protocol boundary.
pub fn is_hop_by_hop(name: &str) -> bool {
    matches!(
        name,
        CONNECTION
            | KEEP_ALIVE
            | PROXY_AUTHENTICATE
            | PROXY_AUTHORIZATION
            | TE
            | TRAILER_HEADER
            | TRANSFER_ENCODING
            | UPGRADE
    )
}

/// Matches a bare list member without splitting quoted extension values.
///
/// # Arguments
///
/// - `&[u8]` - One Expect field value.
///
/// # Returns
///
/// - `bool` - Whether the field contains the continue token.
pub(crate) fn contains_continue_member(value: &[u8]) -> bool {
    let token: &[u8] = CONTINUE_EXPECT.as_bytes();
    let mut start: usize = 0;
    let mut quoted: bool = false;
    let mut escaped: bool = false;
    for (offset, byte) in value.iter().copied().enumerate() {
        match byte {
            _ if escaped => escaped = false,
            HTTP_QUOTED_FIELD_ESCAPE if quoted => escaped = true,
            HTTP_QUOTED_FIELD_QUOTE => quoted = !quoted,
            COMMA_U8 if !quoted => {
                if value[start..offset]
                    .trim_ascii()
                    .eq_ignore_ascii_case(token)
                {
                    return true;
                }
                start = offset + 1;
            }
            _ => {}
        }
    }
    value[start..].trim_ascii().eq_ignore_ascii_case(token)
}

/// Parses a declared body length from one header field value.
///
/// The length is a run of ASCII digits and nothing else. `str::parse` accepts
/// a leading `+`, so a header announcing `+1` would otherwise be read as `1` —
/// a value the sender could not have meant, and one that makes the declared
/// length disagree with the bytes that follow. An empty value is refused for
/// the same reason: it is not a length at all, and treating it as zero would
/// turn a malformed head into a truncated-but-successful request.
///
/// # Arguments
///
/// - `&str` - The raw header field value.
///
/// # Returns
///
/// - `Result<usize, RequestError>` - The declared length, or the refusal.
pub(crate) fn parse_ascii_length(value: &str) -> Result<usize, RequestError> {
    let digits: &str = value.trim();
    if digits.is_empty() || !digits.bytes().all(|byte: u8| byte.is_ascii_digit()) {
        return Err(RequestError::InvalidContentLength(HttpStatus::BadRequest));
    }
    digits
        .parse::<usize>()
        .map_err(|_: ParseIntError| RequestError::InvalidContentLength(HttpStatus::BadRequest))
}

/// Reports whether a status code forbids a response body.
///
/// A `HEAD` response carries the length the matching `GET` would have but no
/// bytes, and the no-content statuses carry none either.
///
/// # Arguments
///
/// - `usize` - The response status code.
/// - `bool` - Whether the request method was `HEAD`.
///
/// # Returns
///
/// - `bool` - `true` when no body bytes may be emitted.
pub fn is_bodyless_status(status_code: usize, is_head: bool) -> bool {
    is_head
        || status_code < 200
        || status_code == HttpStatus::NoContent.code()
        || status_code == HttpStatus::ResetContent.code()
        || status_code == HttpStatus::NotModified.code()
}

/// Collects a protocol request body into a bounded buffer.
///
/// The framework request carries its body as bytes, so the stream is drained
/// into a single buffer. The cap is enforced as the body grows rather than
/// after it is complete, so an oversized upload is rejected while it is being
/// read instead of after it has already been buffered.
///
/// # Arguments
///
/// - `usize` - The maximum number of body bytes to accept.
/// - `&mut Vec<u8>` - The buffer to append into.
/// - `Bytes` - The incoming body chunk.
///
/// # Returns
///
/// - `Result<(), RequestError>` - `Ok(())` while the body stays within the cap, or payload-too-large error.
pub fn push_bounded_body(
    limit: usize,
    body: &mut Vec<u8>,
    chunk: Bytes,
) -> Result<(), RequestError> {
    if limit != DEFAULT_LOW_SECURITY_MAX_BODY_SIZE && chunk.len() > limit.saturating_sub(body.len())
    {
        return Err(RequestError::ContentLengthTooLarge(
            HttpStatus::PayloadTooLarge,
        ));
    }
    body.extend_from_slice(chunk.as_ref());
    Ok(())
}

/// Joins a request path and its query into the target carried on the wire.
///
/// # Arguments
///
/// - `&str` - The request path.
/// - `Option<&str>` - The request query string, when one is present.
///
/// # Returns
///
/// - `String` - The target including its query string and query separator.
#[cfg(test)]
pub fn request_target(path: &str, query: Option<&str>) -> String {
    match query {
        Some(query) => {
            let mut target: String = String::with_capacity(path.len() + query.len() + 1);
            target.push_str(path);
            target.push(QUESTION_MARK);
            target.push_str(query);
            target
        }
        None => path.to_owned(),
    }
}