Sha256: 16267f2f789780c27957eb9aafcef964c3371a17851edd9f8368e2c29360a8da

Contents?: true

Size: 1.29 KB

Versions: 3

Compression:

Stored size: 1.29 KB

Contents

use std::str;
use path_parsing::{find_last_sep_pos, find_last_non_sep_pos};

pub fn dirname(path: &str) -> &str {
  let bytes = path.as_bytes();
  let mut last_slash_pos = match find_last_sep_pos(bytes) {
    Some(pos) => pos,
    _ => return ".",
  };
  // Skip trailing slashes.
  if last_slash_pos == bytes.len() - 1 {
    let last_non_slash_pos = match find_last_non_sep_pos(&bytes[..last_slash_pos]) {
      Some(pos) => pos,
      _ => return "/"
    };
    last_slash_pos = match find_last_sep_pos(&bytes[..last_non_slash_pos]) {
      Some(pos) => pos,
      _ => return "."
    };
  };
  if let Some(end) = find_last_non_sep_pos(&bytes[..last_slash_pos]) {
    &path[..end + 1]
  } else {
    "/"
  }
}

#[test]
fn absolute() {
  assert_eq!(dirname("/a/b///c"), "/a/b");
}

#[test]
fn trailing_slashes_absolute() {
  assert_eq!(dirname("/a/b///c//////"), "/a/b");
}

#[test]
fn relative() {
  assert_eq!(dirname("b///c"), "b");
}

#[test]
fn trailing_slashes_relative() {
  assert_eq!(dirname("b/c//"), "b");
}

#[test]
fn root() {
  assert_eq!(dirname("//c"), "/");
}

#[test]
fn trailing_slashes_root() {
  assert_eq!(dirname("//c//"), "/");
}

#[test]
fn trailing_slashes_relative_root() {
  assert_eq!(dirname("c//"), ".");
}

#[test]
fn returns_dot_for_empty_string() {
  assert_eq!(dirname(""), ".");
}

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
faster_path-0.3.10 src/dirname.rs
faster_path-0.3.9 src/dirname.rs
faster_path-0.3.8 src/dirname.rs