std_macro_extensions/path/macro.rs
1/// Combines multiple paths into a single valid path, handling overlapping slashes.
2///
3/// - Removes trailing slashes from the base path.
4/// - Removes leading slashes from subsequent paths to avoid duplication.
5/// - Supports multiple path segments for flexible usage.
6///
7/// # Parameters
8/// - `base` - The base path as a string slice. It serves as the starting point for the combined path.
9/// - `sub_path` - One or more subsequent paths as string slices. These are appended to the base path in order.
10///
11/// # Returns
12/// - `String` - The resulting combined path as a `String`, with platform-specific separators and cleaned of redundant slashes.
13#[macro_export]
14macro_rules! join_paths {
15 ($base:expr, $($sub_path:expr),+) => {{
16 let mut path: std::path::PathBuf =
17 std::path::PathBuf::from($base.trim_end_matches(['/', '\\'].as_ref()));
18 if cfg!(target_os = "windows") {
19 if path.is_dir() && path.to_string_lossy().ends_with(":") {
20 path.push("/");
21 }
22 }
23 $(
24 let clean_sub_path: &str = $sub_path.trim_start_matches(['/', '\\'].as_ref());
25 path.push(clean_sub_path);
26 )+
27 path.to_string_lossy().replace("\\", "/")
28 }};
29}