path

Macro path 

Source
macro_rules! path {
    (@build_seg [$($result:expr),*] [$($current:tt)*] $lit:literal $($rest:tt)*) => { ... };
    (@build_seg [$($result:expr),*] [$($current:tt)*] { $($expr:tt)+ } $($rest:tt)*) => { ... };
    (@build_seg [$($result:expr),*] [$($current:tt)+] / $($rest:tt)*) => { ... };
    (@build_seg [$($result:expr),*] [] / $($rest:tt)*) => { ... };
    (@build_seg [$($result:expr),*] [$($current:tt)+] , $($rest:tt)*) => { ... };
    (@build_seg [$($result:expr),*] [] , $($rest:tt)*) => { ... };
    (@build_seg [$($result:expr),*] [$($current:tt)*] $next:tt $($rest:tt)*) => { ... };
    (@build_seg [$($result:expr),*] [$($current:tt)+]) => { ... };
    (@build_seg [$($result:expr),*] []) => { ... };
    (@finish_seg []) => { ... };
    (@finish_seg [$($tokens:tt)+]) => { ... };
    ($($tokens:tt)*) => { ... };
}
Expand description

Cross-platform path construction macro.

Returns a [PathBuf].

§Supported Syntax

Supports two styles of separators:

  • path!(a / b / c) — uses slashes (/)
  • path!(a, b, c) — uses commas (,).

§Supported Segment Types

  • Identifiers: vendor, dll (converted with stringify!)
  • Dotted identifiers: file.txt, windivert.c (treated as single segments)
  • String literals: "my folder", "file name.txt"
  • Variable expressions: wrapped in curly braces {base_path}, {my_var}

§Examples

use path_macro2::path;

// Basic usage
let path1 = path!(vendor / dll / windivert.c);
let path2 = path!(vendor, dll, windivert.c);

// Quoted segments (for names containing spaces)
let path3 = path!("my folder" / "sub folder" / file.txt);

// Using variables (wrapped in `{}`)
let base = "vendor";
let path4 = path!({base} / dll / file.txt);

// ---
// Platform-specific examples

// Unix absolute path
#[cfg(not(target_os = "windows"))]
{
    let abs = path!("/", "test", "data", "windivert.c");
    assert_eq!(abs, std::path::PathBuf::from("/test/data/windivert.c"));
}

// Windows absolute path (with drive letter)
#[cfg(target_os = "windows")]
{
    let a = path!("C:\\", "Program Files", "Windivert", "driver.sys");
    assert_eq!(
        a.to_string_lossy(),
        "C:\\Program Files\\Windivert\\driver.sys"
    );
    // UNC-style path
    let unc = path!("\\\\server", "share dir", "file.txt");
    assert_eq!(unc.to_string_lossy(), "\\\\server\\share dir\\file.txt");
}

Works consistently across all platforms.