Function normalize

Source
pub fn normalize<P: AsRef<Path>>(path: P) -> PathBuf
Expand description

Normalizes a given filesystem path by syntactically removing occurrences of . and properly handling .. components.

This function iterates over the components of the input path and applies the following rules:

  • For .. (ParentDir) components, it removes the last normal (non-special) segment from the normalized path. If the last segment is another .. or if there are no preceding normal segments and the path does not start with the root directory (/), it preserves the .. to represent moving up in the directory hierarchy.
  • For paths starting with the root directory followed by .., it retains these .. components to accurately reflect paths that navigate upwards from the root.
  • Skips . (CurDir) components as they represent the current directory and don’t affect the path’s normalization.
  • Retains all other components unchanged, including normal segments and the root directory.

The normalization process is purely syntactical and does not interact with the file system. It does not resolve symbolic links, check the existence of path components, or consider the current working directory. The function ensures that paths are represented using / as the separator for consistency across different operating systems, including Windows, where the native path separator is \.

§Examples

use std::path::{ Path, PathBuf };
use proper_path_tools::path as path;

let path = Path::new( "/a/b/./c/../d" );
let normalized_path = path::normalize( path );

assert_eq!( normalized_path, PathBuf::from( "/a/b/d" ) );

§Arguments

  • path - A reference to a path that implements AsRef<Path>, which will be normalized.

§Returns

A PathBuf containing the normalized path.