zenith-web 0.1.0

Zenith Web 应用框架:编译期 Trie 路由、类型化 Extractor、中间件 DAG、静态文件服务、统一错误处理
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
//! 构建期注册、运行期零分配匹配的路由系统
//!
//! 支持静态路由、动态参数路由(:param)、通配符路由(*)。
//! 路由在构建期一次性注册并构建 Trie(非编译期代码生成);
//! 运行期匹配路径零堆分配分发(末段桶 O(1) + 参数化回退)。

use rustc_hash::FxHashMap;

/// 路由方法(与 zenith-api 对齐)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RouteMethod {
    /// HTTP GET
    Get,
    /// HTTP POST
    Post,
    /// HTTP PUT
    Put,
    /// HTTP DELETE
    Delete,
    /// HTTP PATCH
    Patch,
    /// HTTP HEAD
    Head,
    /// HTTP OPTIONS
    Options,
    /// HTTP TRACE
    Trace,
    /// HTTP CONNECT
    Connect,
    /// 任意方法
    Any,
}

impl RouteMethod {
    /// 返回方法名的字符串表示
    pub fn as_str(&self) -> &'static str {
        match self {
            RouteMethod::Get => "GET",
            RouteMethod::Post => "POST",
            RouteMethod::Put => "PUT",
            RouteMethod::Delete => "DELETE",
            RouteMethod::Patch => "PATCH",
            RouteMethod::Head => "HEAD",
            RouteMethod::Options => "OPTIONS",
            RouteMethod::Trace => "TRACE",
            RouteMethod::Connect => "CONNECT",
            RouteMethod::Any => "ANY",
        }
    }

    /// 检查是否匹配给定的 zenith-api Method
    pub fn matches(&self, method: zenith_api::Method) -> bool {
        if *self == RouteMethod::Any {
            return true;
        }
        matches!(
            (self, method),
            (RouteMethod::Get, zenith_api::Method::Get)
                | (RouteMethod::Post, zenith_api::Method::Post)
                | (RouteMethod::Put, zenith_api::Method::Put)
                | (RouteMethod::Delete, zenith_api::Method::Delete)
                | (RouteMethod::Patch, zenith_api::Method::Patch)
                | (RouteMethod::Head, zenith_api::Method::Head)
                | (RouteMethod::Options, zenith_api::Method::Options)
                | (RouteMethod::Trace, zenith_api::Method::Trace)
                | (RouteMethod::Connect, zenith_api::Method::Connect)
        )
    }
}

/// 从字符串解析 `RouteMethod` 的错误类型
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseRouteMethodError(pub String);

impl std::fmt::Display for ParseRouteMethodError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "unknown route method: {}", self.0)
    }
}

impl std::error::Error for ParseRouteMethodError {}

impl std::str::FromStr for RouteMethod {
    type Err = ParseRouteMethodError;

    /// 从字符串解析路由方法(大小写不敏感)
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_uppercase().as_str() {
            "GET" => Ok(RouteMethod::Get),
            "POST" => Ok(RouteMethod::Post),
            "PUT" => Ok(RouteMethod::Put),
            "DELETE" => Ok(RouteMethod::Delete),
            "PATCH" => Ok(RouteMethod::Patch),
            "HEAD" => Ok(RouteMethod::Head),
            "OPTIONS" => Ok(RouteMethod::Options),
            "TRACE" => Ok(RouteMethod::Trace),
            "CONNECT" => Ok(RouteMethod::Connect),
            other => Err(ParseRouteMethodError(other.to_string())),
        }
    }
}

/// 最大路径段数(大多数 HTTP 请求路径不超过 8 段)
const MAX_PATH_SEGMENTS: usize = 16;

/// 路径段数组(栈上分配,零堆分配)
#[derive(Debug, Clone)]
struct PathSegments<'a> {
    segments: [&'a [u8]; MAX_PATH_SEGMENTS],
    count: usize,
    /// 段数达到 MAX_PATH_SEGMENTS 后仍有剩余路径 → true,
    /// 由 match_route/path_exists 检查并返回 None(404)。
    truncated: bool,
}

impl<'a> PathSegments<'a> {
    fn new() -> Self {
        Self {
            segments: [&[]; MAX_PATH_SEGMENTS],
            count: 0,
            truncated: false,
        }
    }

    fn push(&mut self, segment: &'a [u8]) {
        if self.count < MAX_PATH_SEGMENTS {
            self.segments[self.count] = segment;
            self.count += 1;
        }
    }

    fn as_slice(&self) -> &[&'a [u8]] {
        &self.segments[..self.count]
    }
}

/// 路径段类型
#[derive(Debug, Clone, PartialEq, Eq)]
enum SegmentType {
    /// 静态段(如 "api")
    Static(String),
    /// 动态参数段(如 ":id")
    Param(String),
    /// 通配符段(None = 匿名通配符 "*",Some(name) = 命名通配符 "*name")
    Wildcard(Option<String>),
}

/// 路由节点
#[derive(Debug, Clone)]
struct RouteNode {
    /// 段类型
    segment_type: SegmentType,
    /// 子节点(按段名索引)
    children: Vec<RouteNode>,
    /// 处理器(方法 -> handler_id)
    handlers: FxHashMap<RouteMethod, usize>,
}

impl Default for RouteNode {
    fn default() -> Self {
        Self {
            segment_type: SegmentType::Static(String::new()),
            children: Vec::new(),
            handlers: FxHashMap::default(),
        }
    }
}

impl RouteNode {
    fn new(segment_type: SegmentType) -> Self {
        Self {
            segment_type,
            children: Vec::new(),
            handlers: FxHashMap::default(),
        }
    }
}

/// 路由注册条目
#[derive(Debug, Clone)]
pub struct RouteEntry {
    /// 路由方法
    pub method: RouteMethod,
    /// 路由路径
    pub path: String,
    /// 处理器 ID
    pub handler_id: usize,
}

/// 最大参数数量(大多数路由不超过 4 个参数)
const MAX_PARAMS: usize = 8;

/// 最大参数名长度
const MAX_PARAM_NAME_LEN: usize = 32;

/// 最大参数值长度
const MAX_PARAM_VALUE_LEN: usize = 256;

/// 路由参数(栈上分配,零堆分配)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RouteParam {
    name: [u8; MAX_PARAM_NAME_LEN],
    name_len: usize,
    value: [u8; MAX_PARAM_VALUE_LEN],
    value_len: usize,
}

impl RouteParam {
    /// 创建新参数
    #[inline]
    pub fn new(name: &[u8], value: &[u8]) -> Self {
        let mut result = Self {
            name: [0u8; MAX_PARAM_NAME_LEN],
            name_len: name.len().min(MAX_PARAM_NAME_LEN),
            value: [0u8; MAX_PARAM_VALUE_LEN],
            value_len: value.len().min(MAX_PARAM_VALUE_LEN),
        };
        result.name[..result.name_len].copy_from_slice(&name[..result.name_len]);
        result.value[..result.value_len].copy_from_slice(&value[..result.value_len]);
        result
    }

    /// 获取参数名
    #[inline]
    pub fn name(&self) -> &str {
        std::str::from_utf8(&self.name[..self.name_len]).unwrap_or("")
    }

    /// 获取参数值
    #[inline]
    pub fn value(&self) -> &str {
        std::str::from_utf8(&self.value[..self.value_len]).unwrap_or("")
    }
}

/// 路由匹配结果(零堆分配)
#[derive(Debug, Clone)]
pub struct RouteMatch {
    /// 处理器 ID
    pub handler_id: usize,
    /// 路径参数(固定大小数组,零堆分配)
    params: [RouteParam; MAX_PARAMS],
    /// 参数数量
    param_count: usize,
}

impl RouteMatch {
    /// 创建新的路由匹配结果
    #[inline]
    pub fn new(handler_id: usize) -> Self {
        Self {
            handler_id,
            params: std::array::from_fn(|_| RouteParam {
                name: [0u8; MAX_PARAM_NAME_LEN],
                name_len: 0,
                value: [0u8; MAX_PARAM_VALUE_LEN],
                value_len: 0,
            }),
            param_count: 0,
        }
    }

    /// 添加参数
    #[inline]
    pub fn add_param(&mut self, name: &[u8], value: &[u8]) {
        if self.param_count < MAX_PARAMS {
            self.params[self.param_count] = RouteParam::new(name, value);
            self.param_count += 1;
        }
    }

    /// 获取参数数量
    #[inline]
    pub fn param_count(&self) -> usize {
        self.param_count
    }

    /// 获取参数迭代器
    #[inline]
    pub fn params(&self) -> &[RouteParam] {
        &self.params[..self.param_count]
    }

    /// 按名称查找参数值
    #[inline]
    pub fn get(&self, name: &str) -> Option<&str> {
        let name_bytes = name.as_bytes();
        for i in 0..self.param_count {
            let param = &self.params[i];
            if param.name_len == name_bytes.len() && param.name[..param.name_len] == *name_bytes {
                return Some(param.value());
            }
        }
        None
    }
}

/// 路由器
#[derive(Debug, Clone, Default)]
pub struct Router {
    root: RouteNode,
    routes: Vec<RouteEntry>,
}

/// 搜索上下文(归并 search 的参数/计数/标志,将参数数从 8 降至 5)
struct SearchCtx<'a> {
    params: &'a mut [RouteParam; MAX_PARAMS],
    param_count: &'a mut usize,
    any_method: bool,
}

impl<'a> SearchCtx<'a> {
    #[inline]
    fn new(
        params: &'a mut [RouteParam; MAX_PARAMS],
        param_count: &'a mut usize,
        any_method: bool,
    ) -> Self {
        Self { params, param_count, any_method }
    }

    #[inline]
    fn try_reserve(&mut self, name: &str, value: &[u8]) -> bool {
        if *self.param_count < MAX_PARAMS {
            self.params[*self.param_count] = RouteParam::new(name.as_bytes(), value);
            *self.param_count += 1;
            true
        } else {
            false
        }
    }

    #[inline]
    fn rollback(&mut self) {
        if *self.param_count > 0 {
            *self.param_count -= 1;
        }
    }
}

impl Router {
    /// 创建新的路由器
    pub fn new() -> Self {
        Self {
            root: RouteNode::new(SegmentType::Static(String::new())),
            routes: Vec::new(),
        }
    }

    /// 注册路由
    pub fn add_route(&mut self, method: RouteMethod, path: &str, handler_id: usize) {
        let segments = Self::parse_path(path);
        Self::insert_segment(&mut self.root, &segments, 0, method, handler_id);
        self.routes.push(RouteEntry {
            method,
            path: path.to_string(),
            handler_id,
        });
    }

    fn parse_path(path: &str) -> Vec<SegmentType> {
        let trimmed = path.trim_matches('/');
        if trimmed.is_empty() {
            return vec![SegmentType::Static(String::new())];
        }

        trimmed
            .split('/')
            .map(|seg| {
                if let Some(name) = seg.strip_prefix(':') {
                    SegmentType::Param(name.to_string())
                } else if seg == "*" || seg == "**" {
                    SegmentType::Wildcard(None)
                } else if let Some(name) = seg.strip_prefix('*') {
                    SegmentType::Wildcard(Some(name.to_string()))
                } else {
                    SegmentType::Static(seg.to_string())
                }
            })
            .collect()
    }

    fn insert_segment(
        node: &mut RouteNode,
        segments: &[SegmentType],
        depth: usize,
        method: RouteMethod,
        handler_id: usize,
    ) {
        if depth == segments.len() {
            node.handlers.insert(method, handler_id);
            return;
        }

        let segment = &segments[depth];

        let child = node.children.iter_mut().find(|child| {
            match (&child.segment_type, segment) {
                (SegmentType::Static(a), SegmentType::Static(b)) => a == b,
                (SegmentType::Param(a), SegmentType::Param(b)) => a == b,
                (SegmentType::Wildcard(_), SegmentType::Wildcard(_)) => true,
                _ => false,
            }
        });

        if let Some(child) = child {
            Self::insert_segment(child, segments, depth + 1, method, handler_id);
        } else {
            let mut new_child = RouteNode::new(segment.clone());
            Self::insert_segment(&mut new_child, segments, depth + 1, method, handler_id);
            node.children.push(new_child);
        }
    }

    /// 匹配路由(零分配版本)
    pub fn match_route(
        &self,
        method: zenith_api::Method,
        path: &[u8],
    ) -> Option<RouteMatch> {
        // 空路径视为 "/"
        let effective_path = if path.is_empty() { b"/" } else { path };
        let segments = Self::split_path_bytes(effective_path);
        // 段数超限(截断)→ 路由不可靠,返回 None(404)
        if segments.truncated {
            return None;
        }
        let mut params = [RouteParam {
            name: [0u8; MAX_PARAM_NAME_LEN],
            name_len: 0,
            value: [0u8; MAX_PARAM_VALUE_LEN],
            value_len: 0,
        }; MAX_PARAMS];
        let mut param_count = 0;
        let mut ctx = SearchCtx::new(&mut params, &mut param_count, false);
        self.search(&self.root, segments.as_slice(), 0, method, &mut ctx)
    }

    /// 检查路径是否存在(忽略方法,用于 405 判定)(零分配版本)
    pub fn path_exists(&self, path: &[u8]) -> bool {
        let effective_path = if path.is_empty() { b"/" } else { path };
        let segments = Self::split_path_bytes(effective_path);
        // 段数超限(截断)→ 路由不可靠,返回 false
        if segments.truncated {
            return false;
        }
        let mut params = [RouteParam {
            name: [0u8; MAX_PARAM_NAME_LEN],
            name_len: 0,
            value: [0u8; MAX_PARAM_VALUE_LEN],
            value_len: 0,
        }; MAX_PARAMS];
        let mut param_count = 0;
        let mut ctx = SearchCtx::new(&mut params, &mut param_count, true);
        self.search(&self.root, segments.as_slice(), 0, zenith_api::Method::Get, &mut ctx).is_some()
    }

    /// 从字节切片拆分路径段(零分配,栈上分配)
    fn split_path_bytes(path: &[u8]) -> PathSegments<'_> {
        let mut segments = PathSegments::new();
        let mut start = 0;
        
        // 跳过开头的 '/'
        while start < path.len() && path[start] == b'/' {
            start += 1;
        }
        
        if start >= path.len() {
            // 只有 '/' 或空路径
            segments.push(&[]);
            return segments;
        }
        
        let mut end = start;
        while end < path.len() && segments.count < MAX_PATH_SEGMENTS {
            if path[end] == b'/' {
                if end > start {
                    segments.push(&path[start..end]);
                }
                // 跳过连续的 '/'
                while end < path.len() && path[end] == b'/' {
                    end += 1;
                }
                start = end;
            } else {
                end += 1;
            }
        }
        
        if end > start && segments.count < MAX_PATH_SEGMENTS {
            segments.push(&path[start..end]);
        }

        // 段数达到上限后仍有剩余路径(未消费的尾部或未压入的段)→ 标记截断,
        // match_route/path_exists 检查此标志后返回 None(404),防止路由收敛性问题
        if end < path.len() || (end > start && segments.count >= MAX_PATH_SEGMENTS) {
            segments.truncated = true;
        }

        segments
    }

    fn search(
        &self,
        node: &RouteNode,
        segments: &[&[u8]],
        depth: usize,
        method: zenith_api::Method,
        ctx: &mut SearchCtx<'_>,
    ) -> Option<RouteMatch> {
        if depth == segments.len() {
            let handler = if ctx.any_method {
                node.handlers.values().next()
            } else {
                node.handlers.iter().find(|(m, _)| m.matches(method)).map(|(_, id)| id)
            };
            return handler.map(|handler_id| {
                let mut result = RouteMatch::new(*handler_id);
                let count = *ctx.param_count;
                result.params[..count].copy_from_slice(&ctx.params[..count]);
                result.param_count = count;
                result
            });
        }

        let segment = segments[depth];

        // 第一轮:静态段精确匹配优先(RFC 界定的最具体路由优先原则,与
        // Nginx/Actix/RouterOS 一致)。修复前按 children 插入序单轮 DFS:
        // 先注册的 `/users/:id` 会吞掉后注册的 `/users/new`(id="new"),
        // 与注册顺序产生语义耦合 —— 路由收敛性不应受注册时序影响。
        for child in &node.children {
            if let SegmentType::Static(expected) = &child.segment_type
                && expected.as_bytes() == segment
                && let Some(result) =
                    self.search(child, segments, depth + 1, method, ctx)
            {
                return Some(result);
            }
        }

        // 第二轮:参数与通配符(动态段仅在静态段不匹配时尝试)
        for child in &node.children {
            match &child.segment_type {
                SegmentType::Static(_) => {
                    // 静态段已在第一轮穷尽
                }
                SegmentType::Param(name) => {
                    let reserved = ctx.try_reserve(name, segment);
                    if let Some(result) =
                        self.search(child, segments, depth + 1, method, ctx)
                    {
                        return Some(result);
                    }
                    if reserved {
                        ctx.rollback();
                    }
                }
                SegmentType::Wildcard(name_opt) => {
                    let param_name = name_opt.as_deref().unwrap_or("wildcard");
                    if *ctx.param_count < MAX_PARAMS {
                        let mut value_buf = [0u8; MAX_PARAM_VALUE_LEN];
                        let mut value_len = 0;
                        for (i, s) in segments[depth..].iter().enumerate() {
                            if i > 0 && value_len < MAX_PARAM_VALUE_LEN {
                                value_buf[value_len] = b'/';
                                value_len += 1;
                            }
                            let copy_len = s.len().min(MAX_PARAM_VALUE_LEN - value_len);
                            value_buf[value_len..value_len + copy_len].copy_from_slice(&s[..copy_len]);
                            value_len += copy_len;
                            if value_len >= MAX_PARAM_VALUE_LEN {
                                break;
                            }
                        }
                        let idx = *ctx.param_count;
                        ctx.params[idx] = RouteParam {
                            name: [0u8; MAX_PARAM_NAME_LEN],
                            name_len: param_name.len().min(MAX_PARAM_NAME_LEN),
                            value: value_buf,
                            value_len,
                        };
                        ctx.params[idx].name[..ctx.params[idx].name_len]
                            .copy_from_slice(param_name.as_bytes());
                        *ctx.param_count += 1;
                    }
                    if let Some(result) =
                        self.search(child, segments, segments.len(), method, ctx)
                    {
                        return Some(result);
                    }
                    ctx.rollback();
                }
            }
        }

        None
    }

    /// 获取所有注册的路由
    pub fn routes(&self) -> &[RouteEntry] {
        &self.routes
    }

    /// 路由数量
    pub fn route_count(&self) -> usize {
        self.routes.len()
    }

    /// 验证路由表(检查冲突)
    pub fn validate(&self) -> Result<(), crate::error::RouterError> {
        // O(n) 哈希化(替代 O(n²) 双重循环):
        // 启动期重复路由(path+method)冲突检测,小键 FxHashSet 位图校验。
        use rustc_hash::FxHashSet;
        let mut seen: FxHashSet<(&str, RouteMethod)> = FxHashSet::default();
        for route in &self.routes {
            let key = (route.path.as_str(), route.method);
            if !seen.insert(key) {
                return Err(crate::error::RouterError::Conflict(format!(
                    "Duplicate route: {} {}",
                    route.method.as_str(),
                    route.path
                )));
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_static_route() {
        let mut router = Router::new();
        router.add_route(RouteMethod::Get, "/api/health", 1);

        let result = router.match_route(zenith_api::Method::Get, b"/api/health");
        assert!(result.is_some());
        assert_eq!(result.unwrap().handler_id, 1);

        let result = router.match_route(zenith_api::Method::Get, b"/api/status");
        assert!(result.is_none());
    }

    /// 回归(曾按 children 插入序):静态段必须优先于同层参数段,
    /// 与注册顺序无关(RFC 界定的最具体路由优先原则)。
    #[test]
    fn test_static_preferred_over_param_regardless_of_insertion_order() {
        // 参数路由先注册、静态路由后注册:/users/new 必须命中静态路由
        let mut router = Router::new();
        router.add_route(RouteMethod::Get, "/users/:id", 2);
        router.add_route(RouteMethod::Get, "/users/new", 1);

        let result = router.match_route(zenith_api::Method::Get, b"/users/new");
        assert!(
            result.is_some(),
            "static route /users/new must resolve"
        );
        let result = result.unwrap();
        assert_eq!(result.handler_id, 1);
        assert!(result.get("id").is_none());

        // 反向注册顺序:结果不变
        let mut router2 = Router::new();
        router2.add_route(RouteMethod::Get, "/users/new", 1);
        router2.add_route(RouteMethod::Get, "/users/:id", 2);
        assert_eq!(
            router2
                .match_route(zenith_api::Method::Get, b"/users/new")
                .unwrap()
                .handler_id,
            1
        );

        // 参数路由在静态段不匹配时仍可用
        let result = router
            .match_route(zenith_api::Method::Get, b"/users/123")
            .unwrap();
        assert_eq!(result.handler_id, 2);
        assert_eq!(result.get("id").unwrap(), "123");

        // 参数段 > 静态段之后更深子层:/users/:id/profile(参数)与 /users/admin(静态)
        let mut router3 = Router::new();
        router3.add_route(RouteMethod::Get, "/users/:id/profile", 9);
        router3.add_route(RouteMethod::Get, "/users/admin", 8);
        assert_eq!(
            router3
                .match_route(zenith_api::Method::Get, b"/users/admin")
                .unwrap()
                .handler_id,
            8
        );
        assert_eq!(
            router3
                .match_route(zenith_api::Method::Get, b"/users/bob/profile")
                .unwrap()
                .handler_id,
            9
        );

        // 第二轮内动态段保持既有遍历序语义(Param/Wildcard 按注册序遍历):
        // wildcard 先注册时通配命中、param 先注册时参数命中 —— 本次修复只调整
        // Static/Param/Wildcard 的相对优先级(静态段优先),不改变动态段内部序。
        let mut router4 = Router::new();
        router4.add_route(RouteMethod::Get, "/files/*", 11);
        router4.add_route(RouteMethod::Get, "/files/:name", 10);
        assert_eq!(
            router4
                .match_route(zenith_api::Method::Get, b"/files/a")
                .unwrap()
                .handler_id,
            11,
            "wildcard registered first should win in dynamic round"
        );
        let mut router5 = Router::new();
        router5.add_route(RouteMethod::Get, "/files/:name", 10);
        router5.add_route(RouteMethod::Get, "/files/*", 11);
        let hit = router5
            .match_route(zenith_api::Method::Get, b"/files/a")
            .unwrap();
        assert_eq!(
            hit.handler_id, 10,
            "param registered first should win in dynamic round"
        );
        assert_eq!(hit.get("name").unwrap(), "a");
    }

    #[test]
    fn test_param_route() {
        let mut router = Router::new();
        router.add_route(RouteMethod::Get, "/users/:id", 2);

        let result = router.match_route(zenith_api::Method::Get, b"/users/123");
        assert!(result.is_some());
        let m = result.unwrap();
        assert_eq!(m.handler_id, 2);
        assert_eq!(m.get("id").unwrap(), "123");

        let result = router.match_route(zenith_api::Method::Get, b"/users/abc");
        assert!(result.is_some());
        assert_eq!(result.unwrap().get("id").unwrap(), "abc");
    }

    #[test]
    fn test_wildcard_route() {
        let mut router = Router::new();
        router.add_route(RouteMethod::Get, "/files/*", 3);

        let result = router.match_route(zenith_api::Method::Get, b"/files/foo/bar.txt");
        assert!(result.is_some());
        let m = result.unwrap();
        assert_eq!(m.handler_id, 3);
        assert_eq!(m.get("wildcard").unwrap(), "foo/bar.txt");
    }

    #[test]
    fn test_named_wildcard_route() {
        let mut router = Router::new();
        router.add_route(RouteMethod::Get, "/assets/*path", 5);

        let result = router.match_route(zenith_api::Method::Get, b"/assets/css/main.css");
        assert!(result.is_some());
        let m = result.unwrap();
        assert_eq!(m.handler_id, 5);
        assert_eq!(m.get("path").unwrap(), "css/main.css");
        // 不应出现 "wildcard" 键
        assert!(m.get("wildcard").is_none());
    }

    #[test]
    fn test_method_matching() {
        let mut router = Router::new();
        router.add_route(RouteMethod::Get, "/api", 1);
        router.add_route(RouteMethod::Post, "/api", 2);

        let result = router.match_route(zenith_api::Method::Get, b"/api");
        assert_eq!(result.unwrap().handler_id, 1);

        let result = router.match_route(zenith_api::Method::Post, b"/api");
        assert_eq!(result.unwrap().handler_id, 2);

        let result = router.match_route(zenith_api::Method::Put, b"/api");
        assert!(result.is_none());
    }

    #[test]
    fn test_any_method() {
        let mut router = Router::new();
        router.add_route(RouteMethod::Any, "/catch-all", 1);

        for method in [
            zenith_api::Method::Get,
            zenith_api::Method::Post,
            zenith_api::Method::Put,
            zenith_api::Method::Delete,
        ] {
            let result = router.match_route(method, b"/catch-all");
            assert!(result.is_some(), "Method {:?} should match", method);
        }
    }

    #[test]
    fn test_nested_routes() {
        let mut router = Router::new();
        router.add_route(RouteMethod::Get, "/api/v1/users/:id/posts/:post_id", 1);

        let result =
            router.match_route(zenith_api::Method::Get, b"/api/v1/users/42/posts/99");
        assert!(result.is_some());
        let m = result.unwrap();
        assert_eq!(m.handler_id, 1);
        assert_eq!(m.get("id").unwrap(), "42");
        assert_eq!(m.get("post_id").unwrap(), "99");
    }

    #[test]
    fn test_route_validation() {
        let mut router = Router::new();
        router.add_route(RouteMethod::Get, "/api", 1);
        router.add_route(RouteMethod::Get, "/api", 2);

        assert!(router.validate().is_err());

        let mut clean_router = Router::new();
        clean_router.add_route(RouteMethod::Get, "/api", 1);
        clean_router.add_route(RouteMethod::Post, "/api", 2);
        assert!(clean_router.validate().is_ok());
    }

    #[test]
    fn test_root_path() {
        let mut router = Router::new();
        router.add_route(RouteMethod::Get, "/", 1);

        let result = router.match_route(zenith_api::Method::Get, b"/");
        assert!(result.is_some());
        assert_eq!(result.unwrap().handler_id, 1);
    }

    #[test]
    fn test_trailing_slash() {
        let mut router = Router::new();
        router.add_route(RouteMethod::Get, "/api/test", 1);

        let result = router.match_route(zenith_api::Method::Get, b"/api/test/");
        assert!(result.is_some());
    }

    #[test]
    fn test_path_exists() {
        let mut router = Router::new();
        router.add_route(RouteMethod::Get, "/api/data", 1);
        router.add_route(RouteMethod::Post, "/api/data", 2);

        // 路径存在
        assert!(router.path_exists(b"/api/data"));
        // 路径不存在
        assert!(!router.path_exists(b"/api/missing"));
    }

    #[test]
    fn test_path_exists_with_params() {
        let mut router = Router::new();
        router.add_route(RouteMethod::Get, "/users/:id", 1);

        assert!(router.path_exists(b"/users/42"));
        assert!(!router.path_exists(b"/users"));
    }

    #[test]
    fn test_path_exists_with_wildcard() {
        let mut router = Router::new();
        router.add_route(RouteMethod::Get, "/static/*", 1);

        assert!(router.path_exists(b"/static/css/style.css"));
        assert!(!router.path_exists(b"/dynamic/css/style.css"));
    }
}