Expand description

A library for converting file paths to and from “slash paths”.

A “slash path” is a path whose components are always separated by / and never \.

On Unix-like OS, the path separator is /. So any conversion is not necessary. But on Windows, the file path separator is \, and needs to be replaced with / for converting the paths to “slash paths”. Of course, \s used for escaping characters should not be replaced.

For example, a file path foo\bar\piyo.txt can be converted to/from a slash path foo/bar/piyo.txt.

Supported Rust version is 1.38.0 or later.

This package was inspired by Go’s path/filepath.FromSlash and path/filepath.ToSlash.

use std::path::{Path, PathBuf};
use std::borrow::Cow;

// Trait for extending std::path::Path
use path_slash::PathExt as _;
// Trait for extending std::path::PathBuf
use path_slash::PathBufExt as _;
// Trait for extending std::borrow::Cow
use path_slash::CowExt as _;

#[cfg(target_os = "windows")]
{
    // Convert from `Path`
    assert_eq!(
        Path::new(r"foo\bar\piyo.txt").to_slash().unwrap(),
        "foo/bar/piyo.txt",
    );

    // Convert to/from PathBuf
    let p = PathBuf::from_slash("foo/bar/piyo.txt");
    assert_eq!(p, PathBuf::from(r"foo\bar\piyo.txt"));
    assert_eq!(p.to_slash().unwrap(), "foo/bar/piyo.txt");

    // Convert to/from Cow<'_, Path>
    let p = Cow::from_slash("foo/bar/piyo.txt");
    assert_eq!(p, Cow::<Path>::Owned(PathBuf::from(r"foo\bar\piyo.txt")));
    assert_eq!(p.to_slash().unwrap(), "foo/bar/piyo.txt");
}

#[cfg(not(target_os = "windows"))]
{
    // Convert from `Path`
    assert_eq!(
        Path::new("foo/bar/piyo.txt").to_slash().unwrap(),
        "foo/bar/piyo.txt",
    );

    // Convert to/from PathBuf
    let p = PathBuf::from_slash("foo/bar/piyo.txt");
    assert_eq!(p, PathBuf::from("foo/bar/piyo.txt"));
    assert_eq!(p.to_slash().unwrap(), "foo/bar/piyo.txt");

    // Convert to/from Cow<'_, Path>
    let p = Cow::from_slash("foo/bar/piyo.txt");
    assert_eq!(p, Cow::Borrowed(Path::new("foo/bar/piyo.txt")));
    assert_eq!(p.to_slash().unwrap(), "foo/bar/piyo.txt");
}

Traits

Trait to extend Cow.

Trait to extend PathBuf.

Trait to extend Path.