Crate path_slash

source ·
Expand description

A library for converting file paths from/to slash paths

A slash path is a path whose components are separated by separator ‘/’ always.

In Unix-like OS, path separator is slash ‘/’ by default. So any conversion is not necessary. But on Windows, file path separator ’' needs to be replaced with slash ‘/’ (and of course ’' for escaping character 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’

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

  • https://golang.org/pkg/path/filepath/#FromSlash
  • https://golang.org/pkg/path/filepath/#ToSlash
use std::path::{Path, PathBuf};

// Trait for extending std::path::Path
use path_slash::PathExt;
// Trait for extending std::path::PathBuf
use path_slash::PathBufExt;

#[cfg(target_os = "windows")]
{
    assert_eq!(Path::new(r"foo\bar\piyo.txt").to_slash(), Some("foo/bar/piyo.txt".to_string()));
    assert_eq!(Path::new(r"C:\\foo\bar\piyo.txt").to_slash(), Some("C://foo/bar/piyo.txt".to_string()));

    let p = PathBuf::from_slash("foo/bar/piyo.txt");
    assert_eq!(p, PathBuf::from(r"foo\bar\piyo.txt"));
    assert_eq!(p.to_slash(), Some("foo/bar/piyo.txt".to_string()));
}

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

    let p = PathBuf::from_slash("foo/bar/piyo.txt");
    assert_eq!(p, PathBuf::from(r"foo/bar/piyo.txt"));
    assert_eq!(p.to_slash(), Some("foo/bar/piyo.txt".to_string()));
}

Traits

Trait to extend std::path::PathBuf.
Trait to extend std::path::Path.