rust
45 lines · 8 steps
Normalizing filesystem paths in Rust
A stack-based walk collapses '.' and '..' segments into a clean canonical path, then reuses that logic to join two paths.
Explained by
highlit
1pub fn normalize_path(input: &str) -> String {
2 let is_absolute = input.starts_with('/');
3 let has_trailing_slash = input.len() > 1 && input.ends_with('/');
4 let mut stack: Vec<&str> = Vec::new();
5
6 for segment in input.split('/') {
7 match segment {
8 "" | "." => continue,
9 ".." => {
10 if let Some(&last) = stack.last() {
11 if last != ".." {
12 stack.pop();
13 continue;
14 }
15 }
16 if !is_absolute {
17 stack.push("..");
18 }
19 }
20 other => stack.push(other),
21 }
22 }
23
24 let mut result = String::new();
25 if is_absolute {
26 result.push('/');
27 }
28 result.push_str(&stack.join("/"));
29
30 if result.is_empty() {
31 return ".".to_string();
32 }
33 if has_trailing_slash && !result.ends_with('/') {
34 result.push('/');
35 }
36 result
37}
38
39pub fn join_paths(base: &str, relative: &str) -> String {
40 if relative.starts_with('/') {
41 return normalize_path(relative);
42 }
43 let trimmed = base.trim_end_matches('/');
44 normalize_path(&format!("{trimmed}/{relative}"))
45}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A stack is the natural structure for resolving '..' because each parent reference simply pops the most recent segment.
- 2Capturing structural flags (absoluteness, trailing slash) up front lets you rebuild them faithfully after the segments are collapsed.
- 3Building higher-level operations like join on top of one normalizer keeps edge-case handling in a single place.
Related explainers
rust
use rand::distributions::{Alphanumeric, DistString}; use rand::rngs::OsRng; #[derive(Debug, Clone, PartialEq, Eq)]
A newtype wrapper for API tokens in Rust
newtype-pattern
randomness
encapsulation
Intermediate
6 steps
typescript
interface UserAgentInfo { browser: { name: string; version: string }; os: { name: string; version: string }; device: 'mobile' | 'tablet' | 'desktop';
Parsing a user-agent string with ordered rules
regex
parsing
pattern-matching
Intermediate
9 steps
rust
use axum::{ extract::Query, response::IntoResponse, Json,
Parsing query strings in Axum handlers
deserialization
query-parameters
defaults
Intermediate
7 steps
rust
use axum::{ body::{Body, Bytes}, extract::Request, http::StatusCode,
Logging request and response sizes in Axum
middleware
http
streaming-bodies
Advanced
8 steps
rust
use std::borrow::Cow; pub fn escape_html(input: &str) -> Cow<'_, str> { let needs_escape = input
Zero-copy HTML escaping with Cow in Rust
clone-on-write
zero-copy
string-escaping
Intermediate
6 steps
rust
use once_cell::sync::Lazy; use regex::Regex; static CREDIT_CARD: Lazy<Regex> = Lazy::new(|| {
Redacting sensitive data from logs in Rust
regex
lazy-initialization
checksum-validation
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/normalizing-filesystem-paths-in-rust-explained-rust-f75a/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.