salvo_core 0.91.1

Salvo is a powerful web framework that can make your work easier.
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
//! Routing and filters.
//!
//! # What is router
//!
//! Router can route HTTP requests to different handlers. This is a basic and key feature in salvo.
//!
//! The interior of [`Router`] is actually composed of a series of filters. When a request comes,
//! the route will test itself and its descendants in order to see if they can match the request in
//! the order they were added, and then execute the middleware on the entire chain formed by the
//! route and its descendants in sequence. If the status of [`Response`](crate::http::Response) is
//! set to error (4XX, 5XX) or jump (3XX) during processing, the subsequent middleware and
//! [`Handler`] will be skipped. You can also manually adjust `ctrl.skip_rest()` to skip subsequent
//! middleware and [`Handler`].
//!
//! # Write in flat way
//!
//! We can write routers in flat way, like this:
//!
//! ```rust
//! # use salvo_core::prelude::*;
//!
//! # #[handler]
//! # async fn create_writer(res: &mut Response) {
//! # }
//! # #[handler]
//! # async fn show_writer(res: &mut Response) {
//! # }
//! # #[handler]
//! # async fn list_writers(res: &mut Response) {
//! # }
//! # #[handler]
//! # async fn edit_writer(res: &mut Response) {
//! # }
//! # #[handler]
//! # async fn delete_writer(res: &mut Response) {
//! # }
//! # #[handler]
//! # async fn list_writer_articles(res: &mut Response) {
//! # }
//! Router::with_path("writers")
//!     .get(list_writers)
//!     .post(create_writer);
//! Router::with_path("writers/{id}")
//!     .get(show_writer)
//!     .patch(edit_writer)
//!     .delete(delete_writer);
//! Router::with_path("writers/{id}/articles").get(list_writer_articles);
//! ```
//!
//! # Write in tree way
//!
//! We can write router like a tree, this is also the recommended way:
//!
//! ```rust
//! # use salvo_core::prelude::*;
//!
//! # #[handler]
//! # async fn create_writer(res: &mut Response) {
//! # }
//! # #[handler]
//! # async fn show_writer(res: &mut Response) {
//! # }
//! # #[handler]
//! # async fn list_writers(res: &mut Response) {
//! # }
//! # #[handler]
//! # async fn edit_writer(res: &mut Response) {
//! # }
//! # #[handler]
//! # async fn delete_writer(res: &mut Response) {
//! # }
//! # #[handler]
//! # async fn list_writer_articles(res: &mut Response) {
//! # }
//! Router::with_path("writers")
//!     .get(list_writers)
//!     .post(create_writer)
//!     .push(
//!         Router::with_path("{id}")
//!             .get(show_writer)
//!             .patch(edit_writer)
//!             .delete(delete_writer)
//!             .push(Router::with_path("articles").get(list_writer_articles)),
//!     );
//! ```
//!
//! This form of definition can make the definition of router clear and simple for complex projects.
//!
//! There are many methods in `Router` that will return to `Self` after being called, so as to write
//! code in a chain. Sometimes, you need to decide how to route according to certain conditions, and
//! the `Router` also provides `then` function, which is also easy to use:
//!
//! ```rust
//! # use salvo_core::prelude::*;
//!
//! # #[handler]
//! # async fn list_articles(res: &mut Response) {
//! # }
//! # #[handler]
//! # async fn show_article(res: &mut Response) {
//! # }
//! # #[handler]
//! # async fn create_article(res: &mut Response) {
//! # }
//! # #[handler]
//! # async fn update_article(res: &mut Response) {
//! # }
//! # #[handler]
//! # async fn delete_writer(res: &mut Response) {
//! # }
//! fn admin_mode() -> bool {
//!     true
//! };
//! Router::new().push(
//!     Router::with_path("articles")
//!         .get(list_articles)
//!         .push(Router::with_path("{id}").get(show_article))
//!         .then(|router| {
//!             if admin_mode() {
//!                 router.post(create_article).push(
//!                     Router::with_path("{id}")
//!                         .patch(update_article)
//!                         .delete(delete_writer),
//!                 )
//!             } else {
//!                 router
//!             }
//!         }),
//! );
//! ```
//!
//! This example represents that only when the server is in `admin_mode`, routers such as creating
//! articles, editing and deleting articles will be added.
//!
//! # Get param in routers
//!
//! In the previous source code, `{id}` is a param definition. We can access its value via Request
//! instance:
//!
//! ```rust
//! use salvo_core::prelude::*;
//!
//! #[handler]
//! async fn show_writer(req: &mut Request) {
//!     let id = req.param::<i64>("id").unwrap();
//! }
//! ```
//!
//! `{id}` matches a fragment in the path, under normal circumstances, the article `id` is just a
//! number, which we can use regular expressions to restrict `id` matching rules, `r"{id|\d+}"`.
//!
//! For numeric characters there is an easier way to use `{id:num}`, the specific writing is:
//!
//! - `{id:num}`, matches any number of numeric characters;
//! - `{id:num[10]}`, only matches a certain number of numeric characters, where 10 means that the
//!   match only matches 10 numeric characters;
//! - `{id:num(..10)}` means matching 1 to 9 numeric characters;
//! - `{id:num(3..10)}` means matching 3 to 9 numeric characters;
//! - `{id:num(..=10)}` means matching 1 to 10 numeric characters;
//! - `{id:num(3..=10)}` means match 3 to 10 numeric characters;
//! - `{id:num(10..)}` means to match at least 10 numeric characters.
//!
//! You can also use `{**}`, `{*+*}` or `{*?}` to match all remaining path fragments.
//! In order to make the code more readable, you can also add appropriate name to make the path
//! semantics more clear, for example: `{**file_path}`.
//!
//! It is allowed to combine multiple expressions to match the same path segment,
//! such as `/articles/article_{id:num}/`, `/images/{name}.{ext}`.
//!
//! # Add middlewares
//!
//! Middleware can be added via `hoop` method.
//!
//! ```rust
//! # use salvo_core::prelude::*;
//!
//! # #[handler] fn create_writer() {}
//! # #[handler] fn show_writer() {}
//! # #[handler] fn list_writers() {}
//! # #[handler] fn edit_writer() {}
//! # #[handler] fn delete_writer() {}
//! # #[handler] fn list_writer_articles() {}
//! # #[handler] fn check_authed() {}
//! Router::new()
//!     .hoop(check_authed)
//!     .path("writers")
//!     .get(list_writers)
//!     .post(create_writer)
//!     .push(
//!         Router::with_path("{id}")
//!             .get(show_writer)
//!             .patch(edit_writer)
//!             .delete(delete_writer)
//!             .push(Router::with_path("articles").get(list_writer_articles)),
//!     );
//! ```
//!
//! In this example, the root router has a middleware to check current user is authenticated. This
//! middleware will affect the root router and its descendants.
//!
//! If we don't want to check user is authed when current user view writer information and articles.
//! We can write router like this:
//!
//! ```rust
//! # use salvo_core::prelude::*;
//!
//! # #[handler] fn create_writer() {}
//! # #[handler] fn show_writer() {}
//! # #[handler] fn list_writers() {}
//! # #[handler] fn edit_writer() {}
//! # #[handler] fn delete_writer() {}
//! # #[handler] fn list_writer_articles() {}
//! # #[handler] fn check_authed() {}
//! Router::new()
//!     .push(
//!         Router::new()
//!             .hoop(check_authed)
//!             .path("writers")
//!             .post(create_writer)
//!             .push(
//!                 Router::with_path("{id}")
//!                     .patch(edit_writer)
//!                     .delete(delete_writer),
//!             ),
//!     )
//!     .push(
//!         Router::new().path("writers").get(list_writers).push(
//!             Router::with_path("{id}")
//!                 .get(show_writer)
//!                 .push(Router::with_path("articles").get(list_writer_articles)),
//!         ),
//!     );
//! ```
//!
//! Although there are two routers have the same `path("writers")`, they can still be added to the
//! same parent route at the same time.
//!
//! # Filters
//!
//! Many methods in `Router` return to themselves in order to easily implement chain writing.
//! Sometimes, in some cases, you need to judge based on conditions before you can add routing.
//! Routing also provides some convenience Method, simplify code writing.
//!
//! `Router` uses the filter to determine whether the route matches. The filter supports logical
//! operations and or. Multiple filters can be added to a route. When all the added filters match,
//! the route is matched successfully.
//!
//! It should be noted that the URL collection of the website is a tree structure, and this
//! structure is not equivalent to the tree structure of `Router`. A node of the URL may correspond
//! to multiple `Router`. For example, some paths under the `articles/` path require login, and some
//! paths do not require login. Therefore, we can put the same login requirements under a `Router`,
//! and on top of them Add authentication middleware on `Router`.
//!
//! In addition, you can access it without logging in and put it under another route without
//! authentication middleware:
//!
//! ```rust
//! # use salvo_core::prelude::*;
//!
//! # #[handler] fn list_articles() {}
//! # #[handler] fn show_article() {}
//! # #[handler] fn edit_article() {}
//! # #[handler] fn delete_article() {}
//! # #[handler] fn auth_check() {}
//! Router::new()
//!     .push(
//!         Router::new()
//!             .path("articles")
//!             .get(list_articles)
//!             .push(Router::new().path("{id}").get(show_article)),
//!     )
//!     .push(
//!         Router::new()
//!             .path("articles")
//!             .hoop(auth_check)
//!             .post(list_articles)
//!             .push(
//!                 Router::new()
//!                     .path("{id}")
//!                     .patch(edit_article)
//!                     .delete(delete_article),
//!             ),
//!     );
//! ```
//!
//! Router is used to filter requests, and then send the requests to different Handlers for
//! processing.
//!
//! The most commonly used filtering is `path` and `method`. `path` matches path information;
//! `method` matches the requested Method.
//!
//! We can use `and`, `or` to connect between filter conditions, for example:
//!
//! ```rust
//! use salvo_core::prelude::*;
//! use salvo_core::routing::*;
//!
//! Router::new().filter(filters::path("hello").and(filters::get()));
//! ```
//!
//! ## Path filter
//!
//! The filter is based on the request path is the most frequently used. Parameters can be defined
//! in the path filter, such as:
//!
//! ```rust
//! use salvo_core::prelude::*;
//!
//! # #[handler] fn show_article() {}
//! # #[handler] fn serve_file() {}
//! Router::with_path("articles/{id}").get(show_article);
//! Router::with_path("files/{**rest_path}").get(serve_file);
//! ```
//!
//! In `Handler`, it can be obtained through the `get_param` function of the `Request` object:
//!
//! ```rust
//! use salvo_core::prelude::*;
//!
//! #[handler]
//! fn show_article(req: &mut Request) {
//!     let article_id = req.param::<i64>("id");
//! }
//!
//! #[handler]
//! fn serve_file(req: &mut Request) {
//!     let rest_path = req.param::<i64>("rest_path");
//! }
//! ```
//!
//! ## Method filter
//!
//! Filter requests based on the `HTTP` request's `Method`, for example:
//!
//! ```rust
//! use salvo_core::prelude::*;
//!
//! # #[handler] fn show_article() {}
//! # #[handler] fn update_article() {}
//! # #[handler] fn delete_article() {}
//! Router::new()
//!     .get(show_article)
//!     .patch(update_article)
//!     .delete(delete_article);
//! ```
//!
//! Here `get`, `patch`, `delete` are all Method filters. It is actually equivalent to:
//!
//! ```rust
//! use salvo_core::prelude::*;
//! use salvo_core::routing::*;
//! # #[handler] fn show_article() {}
//! # #[handler] fn update_article() {}
//! # #[handler] fn delete_article() {}
//!
//! let show_router = Router::with_filter(filters::get()).goal(show_article);
//! let update_router = Router::with_filter(filters::patch()).goal(update_article);
//! let delete_router = Router::with_filter(filters::get()).goal(delete_article);
//! Router::new()
//!     .push(show_router)
//!     .push(update_router)
//!     .push(delete_router);
//! ```
//!
//! ## Custom Wisp
//!
//! For some frequently-occurring matching expressions, we can name a short name by
//! `PathFilter::register_wisp_regex` or `PathFilter::register_wisp_builder`. For example, GUID
//! format is often used in paths appears, normally written like this every time a match is
//! required:
//!
//! ```rust
//! use salvo_core::prelude::*;
//!
//! Router::with_path("/articles/{id|[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}}");
//! Router::with_path("/users/{id|[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}}");
//! ```
//!
//! However, writing this complex regular expression every time is prone to errors and hard-coding
//! the regex is not ideal. We could separate the regex into its own Regex variable like so:
//!
//! ```rust
//! use salvo_core::prelude::*;
//! use salvo_core::routing::filters::PathFilter;
//!
//! # #[handler] fn show_article() {}
//! # #[handler] fn show_user() {}
//!
//! #[tokio::main]
//! async fn main() {
//!     let guid = regex::Regex::new("[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}").unwrap();
//!     PathFilter::register_wisp_regex("guid", guid);
//!     Router::new()
//!         .push(Router::with_path("/articles/{id:guid}").get(show_article))
//!         .push(Router::with_path("/users/{id:guid}").get(show_user));
//! }
//! ```
//!
//! You only need to register once, and then you can directly match the GUID through the simple
//! writing method as `{id:guid}`, which simplifies the writing of the code.

pub mod filters;
pub use filters::*;
mod router;
pub use router::Router;

mod path_params;
pub use path_params::PathParams;
mod path_state;
pub use path_state::PathState;
mod flow_ctrl;
use std::fmt::{self, Debug, Formatter};
use std::sync::Arc;

pub use flow_ctrl::FlowCtrl;
use percent_encoding::{AsciiSet, CONTROLS, utf8_percent_encode};

use crate::http::uri::{Parts as UriParts, Uri};
use crate::{Handler, Response};

const HTML_ENCODE_SET: &AsciiSet = &CONTROLS
    .add(b'\'')
    .add(b'"')
    .add(b'`')
    .add(b'<')
    .add(b'>')
    .add(b'&');

#[doc(hidden)]
pub struct DetectMatched {
    pub hoops: Vec<Arc<dyn Handler>>,
    pub goal: Arc<dyn Handler>,
}

impl Debug for DetectMatched {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("DetectMatched")
            .field("hoops.len", &self.hoops.len())
            .finish()
    }
}

pub(crate) fn split_wild_name(name: &str) -> (&str, &str) {
    if name.starts_with("*+") || name.starts_with("*?") || name.starts_with("**") {
        (&name[0..2], &name[2..])
    } else if let Some(stripped) = name.strip_prefix('*') {
        ("*", stripped)
    } else {
        ("", name)
    }
}

#[inline]
#[doc(hidden)]
#[must_use]
pub fn decode_url_path(path: &str) -> String {
    percent_encoding::percent_decode_str(path)
        .decode_utf8_lossy()
        .to_string()
}

#[inline]
#[doc(hidden)]
#[must_use]
pub fn encode_url_path(path: &str) -> String {
    let mut result = String::with_capacity(path.len());
    for (i, s) in path.split('/').enumerate() {
        if i > 0 {
            result.push('/');
        }
        result.extend(utf8_percent_encode(s, HTML_ENCODE_SET));
    }
    result
}

#[doc(hidden)]
#[must_use]
pub fn normalize_url_path(path: &str) -> String {
    let final_slash = if path.ends_with('/') { "/" } else { "" };
    let mut used_parts = Vec::with_capacity(8);
    for part in path.split(['/', '\\']) {
        // Skip empty parts, current directory references, and parts with drive letters
        if part.is_empty() || part == "." || (cfg!(windows) && part.contains(':')) {
            continue;
        }
        // Skip parts containing null bytes (security risk)
        if part.contains('\0') {
            continue;
        }
        // Handle parent directory references
        if part == ".." {
            used_parts.pop();
        } else if cfg!(windows) && is_windows_reserved_name(part) {
            // Skip Windows reserved device names
        } else {
            used_parts.push(part);
        }
    }
    used_parts.join("/") + final_slash
}

#[doc(hidden)]
pub fn redirect_to_dir_url(req_uri: &Uri, res: &mut Response) {
    let UriParts {
        scheme,
        authority,
        path_and_query,
        ..
    } = req_uri.clone().into_parts();
    let mut builder = Uri::builder();
    if let Some(scheme) = scheme {
        builder = builder.scheme(scheme);
    }
    if let Some(authority) = authority {
        builder = builder.authority(authority);
    }
    if let Some(path_and_query) = path_and_query {
        if let Some(query) = path_and_query.query() {
            builder = builder.path_and_query(format!("{}/?{}", path_and_query.path(), query));
        } else {
            builder = builder.path_and_query(format!("{}/", path_and_query.path()));
        }
    }
    match builder.build() {
        Ok(redirect_uri) => {
            res.render(crate::writing::Redirect::found(redirect_uri.to_string()));
        }
        Err(e) => {
            tracing::error!(error = ?e, "failed to build redirect URI");
            res.status_code(crate::http::StatusCode::INTERNAL_SERVER_ERROR);
        }
    }
}

/// Check if a path component is a Windows reserved device name.
/// These names are reserved regardless of extension (e.g., "CON.txt" is also reserved).
fn is_windows_reserved_name(name: &str) -> bool {
    // Get the base name without extension
    let base = name.split('.').next().unwrap_or(name);

    base.eq_ignore_ascii_case("CON")
        || base.eq_ignore_ascii_case("PRN")
        || base.eq_ignore_ascii_case("AUX")
        || base.eq_ignore_ascii_case("NUL")
        || (base.len() == 4
            && (base[..3].eq_ignore_ascii_case("COM") || base[..3].eq_ignore_ascii_case("LPT"))
            && base.as_bytes()[3].is_ascii_digit()
            && base.as_bytes()[3] != b'0')
}

#[cfg(test)]
mod tests {
    use crate::prelude::*;
    use crate::routing::{is_windows_reserved_name, normalize_url_path};
    use crate::test::{ResponseExt, TestClient};

    #[tokio::test]
    async fn test_custom_filter() {
        #[handler]
        async fn hello() -> &'static str {
            "Hello World"
        }

        let router = Router::new()
            .filter_fn(|req, _| {
                let host = req.uri().host().unwrap_or_default();
                host == "localhost"
            })
            .get(hello);
        let service = Service::new(router);

        async fn access(service: &Service, host: &str) -> String {
            TestClient::get(format!("http://{host}/"))
                .send(service)
                .await
                .take_string()
                .await
                .unwrap()
        }

        assert!(
            access(&service, "127.0.0.1")
                .await
                .contains("404: Not Found")
        );
        assert_eq!(access(&service, "localhost").await, "Hello World");
    }

    #[tokio::test]
    async fn test_matched_path() {
        #[handler]
        async fn alice1(req: &mut Request) {
            assert_eq!(req.matched_path(), "open/alice1");
        }
        #[handler]
        async fn bob1(req: &mut Request) {
            assert_eq!(req.matched_path(), "open/alice1/bob1");
        }

        #[handler]
        async fn alice2(req: &mut Request) {
            assert_eq!(req.matched_path(), "open/alice2");
        }
        #[handler]
        async fn bob2(req: &mut Request) {
            assert_eq!(req.matched_path(), "open/alice2/bob2");
        }

        #[handler]
        async fn alice3(req: &mut Request) {
            assert_eq!(req.matched_path(), "alice3");
        }
        #[handler]
        async fn bob3(req: &mut Request) {
            assert_eq!(req.matched_path(), "alice3/bob3");
        }

        let router = Router::new()
            .push(
                Router::with_path("open").push(
                    Router::with_path("alice1")
                        .get(alice1)
                        .push(Router::with_path("bob1").get(bob1)),
                ),
            )
            .push(
                Router::with_path("open").push(
                    Router::with_path("alice2")
                        .get(alice2)
                        .push(Router::with_path("bob2").get(bob2)),
                ),
            )
            .push(
                Router::with_path("alice3")
                    .get(alice3)
                    .push(Router::with_path("bob3").get(bob3)),
            );
        let service = Service::new(router);

        async fn access(service: &Service, path: &str) {
            TestClient::get(format!("http://127.0.0.1/{path}"))
                .send(service)
                .await;
        }
        access(&service, "/open/alice1").await;
        access(&service, "/open/alice1/bob1").await;
        access(&service, "/open/alice2").await;
        access(&service, "/open/alice2/bob2").await;
        access(&service, "/alice3").await;
        access(&service, "/alice1/bob3").await;
    }

    #[test]
    fn test_normalize_url_path() {
        // Basic path normalization
        assert_eq!(normalize_url_path("a/b/c"), "a/b/c");
        assert_eq!(normalize_url_path("/a/b/c"), "a/b/c");
        assert_eq!(normalize_url_path("a/b/c/"), "a/b/c/");

        // Parent directory handling
        assert_eq!(normalize_url_path("a/../b"), "b");
        assert_eq!(normalize_url_path("a/b/../c"), "a/c");
        assert_eq!(normalize_url_path("../a/b"), "a/b");
        assert_eq!(normalize_url_path("a/../../b"), "b");

        // Current directory handling
        assert_eq!(normalize_url_path("./a/b"), "a/b");
        assert_eq!(normalize_url_path("a/./b"), "a/b");

        // Backslash handling
        assert_eq!(normalize_url_path("a\\b\\c"), "a/b/c");
        assert_eq!(normalize_url_path("a\\..\\b"), "b");

        // Empty parts
        assert_eq!(normalize_url_path("a//b"), "a/b");
        assert_eq!(normalize_url_path(""), "");
    }

    #[test]
    #[cfg(windows)]
    fn test_normalize_url_path_windows() {
        // Windows drive letters
        assert_eq!(normalize_url_path("C:/Windows"), "Windows");
        assert_eq!(normalize_url_path("a/C:/b"), "a/b");

        // Windows reserved device names
        assert_eq!(normalize_url_path("CON"), "");
        assert_eq!(normalize_url_path("a/CON/b"), "a/b");
        assert_eq!(normalize_url_path("a/con.txt/b"), "a/b");
        assert_eq!(normalize_url_path("PRN"), "");
        assert_eq!(normalize_url_path("AUX"), "");
        assert_eq!(normalize_url_path("NUL"), "");
        assert_eq!(normalize_url_path("COM1"), "");
        assert_eq!(normalize_url_path("LPT1"), "");
    }

    #[test]
    fn test_is_windows_reserved_name() {
        // Test reserved names
        assert!(is_windows_reserved_name("CON"));
        assert!(is_windows_reserved_name("con"));
        assert!(is_windows_reserved_name("Con"));
        assert!(is_windows_reserved_name("CON.txt"));
        assert!(is_windows_reserved_name("PRN"));
        assert!(is_windows_reserved_name("AUX"));
        assert!(is_windows_reserved_name("NUL"));
        assert!(is_windows_reserved_name("COM1"));
        assert!(is_windows_reserved_name("COM9"));
        assert!(is_windows_reserved_name("LPT1"));
        assert!(is_windows_reserved_name("LPT9"));

        // Test non-reserved names
        assert!(!is_windows_reserved_name("file.txt"));
        assert!(!is_windows_reserved_name("CONSOLE"));
        assert!(!is_windows_reserved_name("COM10"));
        assert!(!is_windows_reserved_name("LPT10"));
        assert!(!is_windows_reserved_name(""));
    }
}