hyperlane-core 23.4.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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
use super::*;

/// Removes the inline registry entry when the owning hook handler is dropped.
impl Drop for InlineHookGuard {
    /// Unregisters the associated handler address from the global inline registry.
    fn drop(&mut self) {
        let Self { key } = self;
        let value: usize = key.load(sync::atomic::Ordering::Relaxed);
        unregister_inline_hook(value);
    }
}

/// Drops an initialized inline future on normal completion or unwind.
impl<F> Drop for InlineDropGuard<F> {
    /// Drops the pointed-to future in place.
    #[inline(always)]
    fn drop(&mut self) {
        let Self { ptr } = self;
        // SAFETY: Guard owns the initialized `F` in inline storage until forgotten on `Pending`.
        unsafe {
            ptr::drop_in_place(*ptr);
        }
    }
}

/// Inherent implementation of [`RouteTrie`].
impl RouteTrie {
    /// Inserts one parsed [`RoutePattern`] and its [`CompiledHook`] into the trie.
    ///
    /// # Arguments
    ///
    /// - `&RoutePattern` - The parsed pattern segments to index.
    /// - `CompiledHook` - The compiled route handler.
    pub(super) fn insert(&mut self, pattern: &RoutePattern, hook: CompiledHook) {
        let Self { nodes } = self;
        if nodes.is_empty() {
            nodes.push(RouteTrieNode::default());
        }
        let mut node_idx: usize = 0;
        for segment in pattern.get_0().iter() {
            node_idx = match segment {
                RouteSegment::Static(literal) => {
                    let existing: Option<usize> = nodes[node_idx]
                        .small_static
                        .iter()
                        .find(|(lit, _): &&(String, usize)| lit == literal)
                        .map(|(_, child): &(String, usize)| *child);
                    if let Some(child) = existing {
                        child
                    } else {
                        let next_idx: usize = nodes.len();
                        nodes.push(RouteTrieNode::default());
                        nodes[node_idx]
                            .small_static
                            .push((literal.clone(), next_idx));
                        next_idx
                    }
                }
                RouteSegment::Dynamic(param_name) => {
                    let existing: Option<usize> = nodes[node_idx]
                        .dynamic_children
                        .iter()
                        .find(|(name, _): &&(String, usize)| name == param_name)
                        .map(|(_, child): &(String, usize)| *child);
                    if let Some(child) = existing {
                        child
                    } else {
                        let next_idx: usize = nodes.len();
                        nodes.push(RouteTrieNode::default());
                        nodes[node_idx]
                            .dynamic_children
                            .push((param_name.clone(), next_idx));
                        next_idx
                    }
                }
                RouteSegment::Regex(param_name, regex) => {
                    let existing: Option<usize> = nodes[node_idx]
                        .regex_children
                        .iter()
                        .find(|(name, rx, _): &&(String, Regex, usize)| {
                            name == param_name && rx.as_str() == regex.as_str()
                        })
                        .map(|(_, _, child): &(String, Regex, usize)| *child);
                    if let Some(child) = existing {
                        child
                    } else {
                        let next_idx: usize = nodes.len();
                        nodes.push(RouteTrieNode::default());
                        nodes[node_idx].regex_children.push((
                            param_name.clone(),
                            regex.clone(),
                            next_idx,
                        ));
                        next_idx
                    }
                }
            };
        }
        if nodes[node_idx].leaf.is_none() {
            nodes[node_idx].leaf = Some(hook);
        }
    }

    /// Promotes nodes with large static fan-out from linear scan to hash-map lookup.
    pub(super) fn finalize(&mut self) {
        let Self { nodes } = self;
        for node in nodes {
            if node.small_static.len() > SMALL_TRIE_STATIC_LIMIT {
                let mut map: HashMapXxHash3_64<String, usize> = hash_map_xx_hash3_64();
                map.reserve(node.small_static.len());
                for (literal, child_idx) in node.small_static.drain(..) {
                    map.insert(literal, child_idx);
                }
                node.static_map = map;
            }
        }
    }

    /// Matches pre-split non-empty path segments recursively, recording captured parameters in `captured`.
    ///
    /// # Arguments
    ///
    /// - `&'a self` - The route trie being traversed.
    /// - `usize` - Current node index inside `self.nodes`.
    /// - `&[&'p str]` - Non-empty path segments.
    /// - `usize` - Current segment depth.
    /// - `&mut [MaybeUninit<(&'a str, &'p str)>; MAX_STACK_ROUTE_SEGS]` - Stack capture buffer.
    /// - `&mut usize` - Active count of initialized stack captures.
    /// - `&mut Option<Vec<(&'a str, &'p str)>>` - Overflow captures when depth exceeds stack capacity.
    ///
    /// # Returns
    ///
    /// - `Option<&'a CompiledHook>` - The matched hook when a complete path reaches a leaf.
    fn match_node<'a, 'p>(
        &'a self,
        node_idx: usize,
        segments: &[&'p str],
        depth: usize,
        captured: &mut [MaybeUninit<(&'a str, &'p str)>; MAX_STACK_ROUTE_SEGS],
        captured_len: &mut usize,
        overflow: &mut Option<Vec<(&'a str, &'p str)>>,
    ) -> Option<&'a CompiledHook> {
        let Self { nodes } = self;
        let node: &RouteTrieNode = &nodes[node_idx];
        if depth == segments.len() {
            return node.leaf.as_ref();
        }
        let part: &'p str = segments[depth];
        if !node.small_static.is_empty() {
            let part_bytes: &[u8] = part.as_bytes();
            for (literal, child_idx) in &node.small_static {
                if literal.as_bytes() == part_bytes {
                    if let Some(hook) = self.match_node(
                        *child_idx,
                        segments,
                        depth + 1,
                        captured,
                        captured_len,
                        overflow,
                    ) {
                        return Some(hook);
                    }
                    break;
                }
            }
        } else if !node.static_map.is_empty()
            && let Some(&child_idx) = node.static_map.get(part)
            && let Some(hook) = self.match_node(
                child_idx,
                segments,
                depth + 1,
                captured,
                captured_len,
                overflow,
            )
        {
            return Some(hook);
        }
        for (param_name, child_idx) in &node.dynamic_children {
            let prev_len: usize = *captured_len;
            let prev_overflow_len: usize = overflow.as_ref().map_or(0, Vec::len);
            if *captured_len < MAX_STACK_ROUTE_SEGS {
                captured[*captured_len].write((param_name.as_str(), part));
                *captured_len += 1;
            } else {
                overflow
                    .get_or_insert_with(Vec::new)
                    .push((param_name.as_str(), part));
            }
            if let Some(hook) = self.match_node(
                *child_idx,
                segments,
                depth + 1,
                captured,
                captured_len,
                overflow,
            ) {
                return Some(hook);
            }
            *captured_len = prev_len;
            if let Some(extra) = overflow.as_mut() {
                extra.truncate(prev_overflow_len);
            }
        }
        for (param_name, regex, child_idx) in &node.regex_children {
            if !regex.is_match(part) {
                continue;
            }
            let prev_len: usize = *captured_len;
            let prev_overflow_len: usize = overflow.as_ref().map_or(0, Vec::len);
            if *captured_len < MAX_STACK_ROUTE_SEGS {
                captured[*captured_len].write((param_name.as_str(), part));
                *captured_len += 1;
            } else {
                overflow
                    .get_or_insert_with(Vec::new)
                    .push((param_name.as_str(), part));
            }
            if let Some(hook) = self.match_node(
                *child_idx,
                segments,
                depth + 1,
                captured,
                captured_len,
                overflow,
            ) {
                return Some(hook);
            }
            *captured_len = prev_len;
            if let Some(extra) = overflow.as_mut() {
                extra.truncate(prev_overflow_len);
            }
        }
        None
    }

    /// Resolves pre-split non-empty path segments and fills `params` in place on match.
    ///
    /// # Arguments
    ///
    /// - `&'a self` - The route trie being queried.
    /// - `&[&str]` - Pre-split non-empty path segments.
    /// - `&mut HashMapXxHash3_64<String, String>` - Recycled parameter map populated on match.
    ///
    /// # Returns
    ///
    /// - `Option<&'a CompiledHook>` - The matched compiled hook, if any.
    #[inline(always)]
    pub(super) fn try_match_segments<'a>(
        &'a self,
        segments: &[&str],
        params: &mut HashMapXxHash3_64<String, String>,
    ) -> Option<&'a CompiledHook> {
        let Self { nodes } = self;
        if nodes.is_empty() {
            return None;
        }
        let mut captured: [MaybeUninit<(&str, &str)>; MAX_STACK_ROUTE_SEGS] =
            [const { MaybeUninit::uninit() }; MAX_STACK_ROUTE_SEGS];
        let mut captured_len: usize = 0;
        let mut overflow: Option<Vec<(&str, &str)>> = None;
        let hook: &CompiledHook = self.match_node(
            0,
            segments,
            0,
            &mut captured,
            &mut captured_len,
            &mut overflow,
        )?;
        if !params.is_empty() {
            return_route_param_entries(params.drain());
        }
        if captured_len > 0 || overflow.is_some() {
            ROUTE_PARAM_POOL.with(|pool: &RefCell<Vec<(String, String)>>| {
                let mut pool: RefMut<'_, Vec<(String, String)>> = pool.borrow_mut();
                for slot in &captured[..captured_len] {
                    // SAFETY: Every slot in `0..captured_len` was initialized via `MaybeUninit::write`.
                    let (param_name, part): (&str, &str) = unsafe { slot.assume_init() };
                    let (mut key, mut val): (String, String) = pool.pop().unwrap_or_default();
                    key.clear();
                    val.clear();
                    key.push_str(param_name);
                    val.push_str(part);
                    params.insert(key, val);
                }
                if let Some(extra) = overflow {
                    for (param_name, part) in extra {
                        let (mut key, mut val): (String, String) = pool.pop().unwrap_or_default();
                        key.clear();
                        val.clear();
                        key.push_str(param_name);
                        val.push_str(part);
                        params.insert(key, val);
                    }
                }
            });
        }
        Some(hook)
    }
}

/// SAFETY: `InlineRequestFuture` only stores `Send` references, `Send + Sync` hooks,
/// and `Send` futures constructed via `start_inline_future` or `ServerHookHandler`.
unsafe impl Send for InlineRequestFuture<'_> {}

/// Drops any active suspended inline future if the request pipeline is cancelled or unwound.
impl Drop for InlineRequestFuture<'_> {
    /// Drops the in-place future when active.
    #[inline(always)]
    fn drop(&mut self) {
        let Self { state, storage, .. } = self;
        if matches!(state, InlinePollState::Uninit | InlinePollState::Done) {
            return;
        }
        let previous: InlinePollState = mem::replace(state, InlinePollState::Done);
        if let InlinePollState::Inline { drop_fn, .. } = previous {
            let ptr: *mut u8 = storage.as_mut_ptr().cast::<u8>();
            // SAFETY: `state` was `Inline`, so `storage` holds an initialized future dropped once.
            unsafe {
                drop_fn(ptr);
            }
        }
    }
}

/// Drives request middleware, route matching/execution, and response middleware in one inline slot.
impl Future for InlineRequestFuture<'_> {
    type Output = bool;

    /// Resumes any pending hook and advances through all remaining phases synchronously when ready.
    ///
    /// # Arguments
    ///
    /// - `Pin<&mut Self>` - The pinned pipeline future.
    /// - `&mut task::Context<'_>` - The task waker context.
    ///
    /// # Returns
    ///
    /// - `Poll<Self::Output>` - Whether the connection remains eligible for keep-alive once complete.
    #[inline(always)]
    fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
        // SAFETY: `storage` is never moved once initialized; field projections preserve pinning.
        let Self {
            pipeline,
            stream,
            ctx,
            phase,
            index,
            keep_alive,
            check_keep_alive,
            state,
            storage,
            ..
        } = unsafe { self.get_unchecked_mut() };
        match state {
            InlinePollState::Inline { poll_fn, drop_fn } => {
                let poll_entry: InlinePollFn = *poll_fn;
                let drop_entry: unsafe fn(*mut u8) = *drop_fn;
                let ptr: *mut u8 = storage.as_mut_ptr().cast::<u8>();
                // SAFETY: `storage` holds the pinned active hook future.
                match unsafe { poll_entry(ptr, cx) } {
                    Poll::Ready(status) => {
                        *state = InlinePollState::Uninit;
                        // SAFETY: Completed future is dropped once before advancing.
                        unsafe {
                            drop_entry(ptr);
                        }
                        if status.is_reject() {
                            *phase = InlinePipelinePhase::Done;
                            let allowed: bool = *check_keep_alive
                                && stream.is_keep_alive(
                                    CompiledPipeline::response_allows_keep_alive(ctx, *keep_alive),
                                );
                            return Poll::Ready(allowed);
                        }
                    }
                    Poll::Pending => return Poll::Pending,
                }
            }
            InlinePollState::Boxed(future) => match future.as_mut().poll(cx) {
                Poll::Ready(status) => {
                    *state = InlinePollState::Uninit;
                    if status.is_reject() {
                        *phase = InlinePipelinePhase::Done;
                        let allowed: bool = *check_keep_alive
                            && stream.is_keep_alive(CompiledPipeline::response_allows_keep_alive(
                                ctx,
                                *keep_alive,
                            ));
                        return Poll::Ready(allowed);
                    }
                }
                Poll::Pending => return Poll::Pending,
            },
            InlinePollState::Uninit => {}
            InlinePollState::Done => return Poll::Ready(false),
        }
        let stream_addr: usize = (&mut **stream).into();
        let ctx_addr: usize = (&mut **ctx).into();
        let slot: *mut u8 = storage.as_mut_ptr().cast::<u8>();
        let slot_len: usize = mem::size_of::<[usize; INLINE_FUTURE_WORDS]>();
        loop {
            match *phase {
                InlinePipelinePhase::RequestMiddleware => {
                    let hooks: &[CompiledHook] = pipeline.request_middleware.as_slice();
                    let total: usize = hooks.len();
                    while *index < total {
                        let hook: &CompiledHook = &hooks[*index];
                        *index += 1;
                        match hook {
                            CompiledHook::Inline(start) => {
                                match (*start)(stream_addr, ctx_addr, slot, slot_len, cx) {
                                    InlineStartOutcome::Ready(status) => {
                                        if status.is_reject() {
                                            *phase = InlinePipelinePhase::Done;
                                            let allowed: bool = *check_keep_alive
                                                && stream.is_keep_alive(
                                                    CompiledPipeline::response_allows_keep_alive(
                                                        ctx,
                                                        *keep_alive,
                                                    ),
                                                );
                                            return Poll::Ready(allowed);
                                        }
                                    }
                                    InlineStartOutcome::PendingInline { poll_fn, drop_fn } => {
                                        *state = InlinePollState::Inline { poll_fn, drop_fn };
                                        return Poll::Pending;
                                    }
                                    InlineStartOutcome::PendingBoxed(future) => {
                                        *state = InlinePollState::Boxed(future);
                                        return Poll::Pending;
                                    }
                                }
                            }
                            CompiledHook::Dynamic(handler) => {
                                let mut future: FutureBox<Status> = handler(stream, ctx);
                                match future.as_mut().poll(cx) {
                                    Poll::Ready(status) => {
                                        if status.is_reject() {
                                            *phase = InlinePipelinePhase::Done;
                                            let allowed: bool = *check_keep_alive
                                                && stream.is_keep_alive(
                                                    CompiledPipeline::response_allows_keep_alive(
                                                        ctx,
                                                        *keep_alive,
                                                    ),
                                                );
                                            return Poll::Ready(allowed);
                                        }
                                    }
                                    Poll::Pending => {
                                        *state = InlinePollState::Boxed(future);
                                        return Poll::Pending;
                                    }
                                }
                            }
                        }
                    }
                    *phase = InlinePipelinePhase::Route;
                    *index = 0;
                }
                InlinePipelinePhase::Route => {
                    *phase = InlinePipelinePhase::ResponseMiddleware;
                    *index = 0;
                    let matched_hook: Option<&CompiledHook> = {
                        let path: &str = ctx.request.get_path().as_str();
                        pipeline.resolve_route(&mut ctx.route_params, path)
                    };
                    if let Some(hook) = matched_hook {
                        match hook {
                            CompiledHook::Inline(start) => {
                                match (*start)(stream_addr, ctx_addr, slot, slot_len, cx) {
                                    InlineStartOutcome::Ready(status) => {
                                        if status.is_reject() {
                                            *phase = InlinePipelinePhase::Done;
                                            let allowed: bool = *check_keep_alive
                                                && stream.is_keep_alive(
                                                    CompiledPipeline::response_allows_keep_alive(
                                                        ctx,
                                                        *keep_alive,
                                                    ),
                                                );
                                            return Poll::Ready(allowed);
                                        }
                                    }
                                    InlineStartOutcome::PendingInline { poll_fn, drop_fn } => {
                                        *state = InlinePollState::Inline { poll_fn, drop_fn };
                                        return Poll::Pending;
                                    }
                                    InlineStartOutcome::PendingBoxed(future) => {
                                        *state = InlinePollState::Boxed(future);
                                        return Poll::Pending;
                                    }
                                }
                            }
                            CompiledHook::Dynamic(handler) => {
                                let mut future: FutureBox<Status> = handler(stream, ctx);
                                match future.as_mut().poll(cx) {
                                    Poll::Ready(status) => {
                                        if status.is_reject() {
                                            *phase = InlinePipelinePhase::Done;
                                            let allowed: bool = *check_keep_alive
                                                && stream.is_keep_alive(
                                                    CompiledPipeline::response_allows_keep_alive(
                                                        ctx,
                                                        *keep_alive,
                                                    ),
                                                );
                                            return Poll::Ready(allowed);
                                        }
                                    }
                                    Poll::Pending => {
                                        *state = InlinePollState::Boxed(future);
                                        return Poll::Pending;
                                    }
                                }
                            }
                        }
                    }
                }
                InlinePipelinePhase::ResponseMiddleware => {
                    let hooks: &[CompiledHook] = pipeline.response_middleware.as_slice();
                    let total: usize = hooks.len();
                    while *index < total {
                        let hook: &CompiledHook = &hooks[*index];
                        *index += 1;
                        match hook {
                            CompiledHook::Inline(start) => {
                                match (*start)(stream_addr, ctx_addr, slot, slot_len, cx) {
                                    InlineStartOutcome::Ready(status) => {
                                        if status.is_reject() {
                                            *phase = InlinePipelinePhase::Done;
                                            let allowed: bool = *check_keep_alive
                                                && stream.is_keep_alive(
                                                    CompiledPipeline::response_allows_keep_alive(
                                                        ctx,
                                                        *keep_alive,
                                                    ),
                                                );
                                            return Poll::Ready(allowed);
                                        }
                                    }
                                    InlineStartOutcome::PendingInline { poll_fn, drop_fn } => {
                                        *state = InlinePollState::Inline { poll_fn, drop_fn };
                                        return Poll::Pending;
                                    }
                                    InlineStartOutcome::PendingBoxed(future) => {
                                        *state = InlinePollState::Boxed(future);
                                        return Poll::Pending;
                                    }
                                }
                            }
                            CompiledHook::Dynamic(handler) => {
                                let mut future: FutureBox<Status> = handler(stream, ctx);
                                match future.as_mut().poll(cx) {
                                    Poll::Ready(status) => {
                                        if status.is_reject() {
                                            *phase = InlinePipelinePhase::Done;
                                            let allowed: bool = *check_keep_alive
                                                && stream.is_keep_alive(
                                                    CompiledPipeline::response_allows_keep_alive(
                                                        ctx,
                                                        *keep_alive,
                                                    ),
                                                );
                                            return Poll::Ready(allowed);
                                        }
                                    }
                                    Poll::Pending => {
                                        *state = InlinePollState::Boxed(future);
                                        return Poll::Pending;
                                    }
                                }
                            }
                        }
                    }
                    *phase = InlinePipelinePhase::Done;
                    let allowed: bool = *check_keep_alive
                        && stream.is_keep_alive(CompiledPipeline::response_allows_keep_alive(
                            ctx,
                            *keep_alive,
                        ));
                    return Poll::Ready(allowed);
                }
                InlinePipelinePhase::Done => return Poll::Ready(false),
            }
        }
    }
}

/// Inherent implementation of [`CompiledPipeline`].
impl CompiledPipeline {
    /// Compiles a server's routes and middleware once before accepting connections.
    ///
    /// # Arguments
    ///
    /// - `&Server` - The configured server instance.
    ///
    /// # Returns
    ///
    /// - `Self` - The compiled zero-lock dispatch table.
    pub(crate) fn from_server(server: &Server) -> Self {
        let matcher: &RouteMatcher = server.get_route_matcher();
        let static_count: usize = matcher.get_static_route().len();
        let mut small_static_routes: SmallStaticRoutes = if static_count <= SMALL_STATIC_ROUTE_LIMIT
        {
            Vec::with_capacity(static_count)
        } else {
            Vec::new()
        };
        let mut static_routes: HashMapXxHash3_64<String, CompiledHook> = hash_map_xx_hash3_64();
        let mut min_static_len: usize = usize::MAX;
        let mut max_static_len: usize = 0;
        for (path, handler) in matcher.get_static_route().iter() {
            let len: usize = path.len();
            if len < min_static_len {
                min_static_len = len;
            }
            if len > max_static_len {
                max_static_len = len;
            }
            let compiled: CompiledHook = lookup_inline_hook(handler);
            if static_count <= SMALL_STATIC_ROUTE_LIMIT {
                small_static_routes.push((path.clone(), compiled));
            } else {
                static_routes.insert(path.clone(), compiled);
            }
        }
        let max_dyn_seg: usize = matcher
            .get_dynamic_route()
            .keys()
            .copied()
            .max()
            .unwrap_or(0);
        let has_dynamic: bool = !matcher.get_dynamic_route().is_empty();
        let mut dynamic_tries: CompiledRouteTries = if has_dynamic {
            vec![RouteTrie::default(); max_dyn_seg + 1]
        } else {
            Vec::new()
        };
        for (&count, list) in matcher.get_dynamic_route().iter() {
            let trie: &mut RouteTrie = &mut dynamic_tries[count];
            for (pattern, handler) in list.iter() {
                trie.insert(pattern, lookup_inline_hook(handler));
            }
            trie.finalize();
        }
        let max_regex_seg: usize = matcher.get_regex_route().keys().copied().max().unwrap_or(0);
        let has_regex: bool = !matcher.get_regex_route().is_empty();
        let mut regex_tries: CompiledRouteTries = if has_regex {
            vec![RouteTrie::default(); max_regex_seg + 1]
        } else {
            Vec::new()
        };
        let mut regex_tail_routes: CompiledTailRegexRoutes = Vec::new();
        for (&count, list) in matcher.get_regex_route().iter() {
            let trie: &mut RouteTrie = &mut regex_tries[count];
            for (pattern, handler) in list.iter() {
                let hook: CompiledHook = lookup_inline_hook(handler);
                if pattern.has_tail_regex() {
                    regex_tail_routes.push((count, pattern.clone(), hook.clone()));
                }
                trie.insert(pattern, hook);
            }
            trie.finalize();
        }
        let request_middleware: Vec<CompiledHook> = server
            .get_request_middleware()
            .iter()
            .map(lookup_inline_hook)
            .collect();
        let response_middleware: Vec<CompiledHook> = server
            .get_response_middleware()
            .iter()
            .map(lookup_inline_hook)
            .collect();
        Self {
            small_static_routes,
            static_routes,
            min_static_len,
            max_static_len,
            dynamic_tries,
            has_dynamic,
            regex_tries,
            regex_tail_routes,
            has_regex,
            request_middleware,
            response_middleware,
        }
    }

    /// Resolves a route path into a compiled hook, filling `params` in place for dynamic/regex routes.
    ///
    /// # Arguments
    ///
    /// - `&mut HashMapXxHash3_64<String, String>` - The context route parameter map to fill.
    /// - `&str` - The request path to match.
    ///
    /// # Returns
    ///
    /// - `Option<&CompiledHook>` - The matched compiled hook, if any.
    #[inline(always)]
    pub(crate) fn resolve_route(
        &self,
        params: &mut HashMapXxHash3_64<String, String>,
        path: &str,
    ) -> Option<&CompiledHook> {
        let Self {
            small_static_routes,
            static_routes,
            min_static_len,
            max_static_len,
            dynamic_tries,
            has_dynamic,
            regex_tries,
            regex_tail_routes,
            has_regex,
            ..
        } = self;
        let path_len: usize = path.len();
        if path_len >= *min_static_len && path_len <= *max_static_len {
            if !small_static_routes.is_empty() {
                let path_bytes: &[u8] = path.as_bytes();
                for (route_path, hook) in small_static_routes.iter() {
                    if route_path.as_bytes() == path_bytes {
                        return Some(hook);
                    }
                }
            } else if let Some(hook) = static_routes.get(path) {
                return Some(hook);
            }
        }
        if !*has_dynamic && !*has_regex {
            return None;
        }
        let trimmed: &str = path.strip_prefix(DEFAULT_HTTP_PATH).unwrap_or(path);
        let mut stack_segs: [&str; MAX_STACK_ROUTE_SEGS] = [EMPTY_STR; MAX_STACK_ROUTE_SEGS];
        let mut overflow_segs: Option<Vec<&str>> = None;
        let mut segment_count: usize = 0;
        let mut has_empty_segment: bool = false;
        if !trimmed.is_empty() {
            let sep: u8 = DEFAULT_HTTP_PATH_BYTES[0];
            let trimmed_bytes: &[u8] = trimmed.as_bytes();
            let mut seg_start: usize = 0;
            for (idx, &byte) in trimmed_bytes.iter().enumerate() {
                if byte == sep {
                    let part: &str = &trimmed[seg_start..idx];
                    if part.is_empty() {
                        has_empty_segment = true;
                    }
                    if segment_count < MAX_STACK_ROUTE_SEGS {
                        stack_segs[segment_count] = part;
                    } else {
                        let vec: &mut Vec<&str> =
                            overflow_segs.get_or_insert_with(|| stack_segs.to_vec());
                        vec.push(part);
                    }
                    segment_count += 1;
                    seg_start = idx + 1;
                }
            }
            let last_part: &str = &trimmed[seg_start..];
            if last_part.is_empty() {
                has_empty_segment = true;
            }
            if segment_count < MAX_STACK_ROUTE_SEGS {
                stack_segs[segment_count] = last_part;
            } else {
                let vec: &mut Vec<&str> = overflow_segs.get_or_insert_with(|| stack_segs.to_vec());
                vec.push(last_part);
            }
            segment_count += 1;
        }
        let seg_slice: &[&str] = match overflow_segs.as_deref() {
            Some(vec) => vec,
            None => &stack_segs[..segment_count],
        };
        if !has_empty_segment {
            if *has_dynamic
                && let Some(trie) = dynamic_tries.get(segment_count)
                && let Some(hook) = trie.try_match_segments(seg_slice, params)
            {
                return Some(hook);
            }
            if *has_regex
                && let Some(trie) = regex_tries.get(segment_count)
                && let Some(hook) = trie.try_match_segments(seg_slice, params)
            {
                return Some(hook);
            }
        }
        if *has_regex {
            for (pattern_seg_count, pattern, hook) in regex_tail_routes.iter() {
                let eligible: bool = if has_empty_segment {
                    *pattern_seg_count <= segment_count + 1
                } else {
                    *pattern_seg_count != segment_count && *pattern_seg_count <= segment_count + 1
                };
                if eligible && pattern.try_match_path_into(path, params) {
                    return Some(hook);
                }
            }
        }
        None
    }

    /// Checks whether both the request and response allow keeping the connection open.
    ///
    /// # Arguments
    ///
    /// - `&Context` - The request context after running hooks.
    /// - `bool` - Whether the request itself allowed keep-alive.
    ///
    /// # Returns
    ///
    /// - `bool` - `false` when the request or response demands closing the connection.
    #[inline(always)]
    fn response_allows_keep_alive(ctx: &Context, req_keep_alive: bool) -> bool {
        if !req_keep_alive {
            return false;
        }
        let headers: &ResponseHeaders = ctx.get_response().get_headers();
        if headers.is_empty() {
            return true;
        }
        if let Some(values) = headers.get(CONNECTION) {
            for header_value in values {
                if header_value == KEEP_ALIVE {
                    continue;
                }
                for token in header_value.split(COMMA_U8 as char) {
                    if token.trim().eq_ignore_ascii_case(CLOSE) {
                        return false;
                    }
                }
            }
            return true;
        }
        for (name, values) in headers {
            if name.len() == CONNECTION.len() && name.eq_ignore_ascii_case(CONNECTION) {
                for header_value in values {
                    for token in header_value.split(COMMA_U8 as char) {
                        if token.trim().eq_ignore_ascii_case(CLOSE) {
                            return false;
                        }
                    }
                }
            }
        }
        true
    }

    /// Executes the full request pipeline inline in a single pinned storage slot.
    ///
    /// # Arguments
    ///
    /// - `&'a self` - The compiled request pipeline.
    /// - `&'a mut Stream` - The active stream.
    /// - `&'a mut Context` - The active request context.
    /// - `Option<String>` - The original request target supplied by multiplexed protocols.
    ///
    /// # Returns
    ///
    /// - `InlineRequestFuture<'a>` - Future resolving to whether keep-alive remains enabled.
    #[inline(always)]
    pub(crate) fn run_request<'a>(
        &'a self,
        stream: &'a mut Stream,
        ctx: &'a mut Context,
        target: Option<String>,
    ) -> InlineRequestFuture<'a> {
        let check_keep_alive: bool = target.is_none();
        let keep_alive: bool = if check_keep_alive {
            ctx.get_request().is_enable_keep_alive()
        } else {
            false
        };
        ctx.set_original_head(Some(ctx.get_request().get_method().is_head()));
        if ctx.get_request().get_version().is_http1_1() {
            ctx.get_mut_response().reset();
        } else {
            let version: HttpVersion = ctx.get_request().get_version().clone();
            ctx.get_mut_response().reset().set_version(version);
        }
        ctx.clear_route_params();
        ctx.reset_request_attributes();
        match target {
            Some(target) => {
                ctx.set_request_target(target);
            }
            None => {
                let parsed_target: Option<&str> = stream.get_request_target_slice().or_else(|| {
                    let line: &str = stream.get_line_buffer();
                    line.split_ascii_whitespace().nth(1)
                });
                if let Some(target) = parsed_target {
                    ctx.set_request_target(target);
                } else {
                    let _: Option<String> = ctx.take_original_target();
                }
            }
        }
        stream.set_closed(false);
        let Self {
            request_middleware, ..
        } = self;
        let initial_phase: InlinePipelinePhase = if request_middleware.is_empty() {
            InlinePipelinePhase::Route
        } else {
            InlinePipelinePhase::RequestMiddleware
        };
        InlineRequestFuture {
            pipeline: self,
            stream,
            ctx,
            phase: initial_phase,
            index: 0,
            keep_alive,
            check_keep_alive,
            state: InlinePollState::Uninit,
            storage: MaybeUninit::uninit(),
            _pinned: PhantomPinned,
        }
    }
}