From 1ad68eafd2505e39d76c0082470e37ab8869ed48 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Mon, 1 Aug 2011 18:28:17 -0700 Subject: [PATCH] Add std::str::trim/trim_left/trim_right --- src/lib/str.rs | 39 +++++++++++++++++++++++++++++++++++++++ src/test/stdtest/str.rs | 30 ++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) diff --git a/src/lib/str.rs b/src/lib/str.rs index b3a94cd6e12..f32daa67057 100644 --- a/src/lib/str.rs +++ b/src/lib/str.rs @@ -54,6 +54,9 @@ export is_empty; export is_not_empty; export replace; export char_slice; +export trim_left; +export trim_right; +export trim; native "rust" mod rustrt { type sbuf; @@ -524,6 +527,42 @@ fn char_slice(s: &str, begin: uint, end: uint) -> str { from_chars(vec::slice(to_chars(s), begin, end)) } +fn trim_left(s: &str) -> str { + fn count_whities(s: &vec[char]) -> uint { + let i = 0u; + while i < vec::len(s) { + if !char::is_whitespace(s.(i)) { + break; + } + i += 1u; + } + ret i; + } + let chars = to_chars(s); + let whities = count_whities(chars); + ret from_chars(vec::slice(chars, whities, vec::len(chars))); +} + +fn trim_right(s: &str) -> str { + fn count_whities(s: &vec[char]) -> uint { + let i = vec::len(s); + while 0u < i { + if !char::is_whitespace(s.(i - 1u)) { + break; + } + i -= 1u; + } + ret i; + } + let chars = to_chars(s); + let whities = count_whities(chars); + ret from_chars(vec::slice(chars, 0u, whities)); +} + +fn trim(s: &str) -> str { + trim_left(trim_right(s)) +} + // Local Variables: // mode: rust; // fill-column: 78; diff --git a/src/test/stdtest/str.rs b/src/test/stdtest/str.rs index 00652996e77..08e78a56137 100644 --- a/src/test/stdtest/str.rs +++ b/src/test/stdtest/str.rs @@ -162,6 +162,36 @@ fn test_char_slice() { assert (str::eq("\u65e5", str::char_slice("\u65e5\u672c", 0u, 1u))); } +#[test] +fn trim_left() { + assert str::trim_left("") == ""; + assert str::trim_left("a") == "a"; + assert str::trim_left(" ") == ""; + assert str::trim_left(" blah") == "blah"; + assert str::trim_left(" \u3000 wut") == "wut"; + assert str::trim_left("hey ") == "hey "; +} + +#[test] +fn trim_right() { + assert str::trim_right("") == ""; + assert str::trim_right("a") == "a"; + assert str::trim_right(" ") == ""; + assert str::trim_right("blah ") == "blah"; + assert str::trim_right("wut \u3000 ") == "wut"; + assert str::trim_right(" hey") == " hey"; +} + +#[test] +fn trim() { + assert str::trim("") == ""; + assert str::trim("a") == "a"; + assert str::trim(" ") == ""; + assert str::trim(" blah ") == "blah"; + assert str::trim("\nwut \u3000 ") == "wut"; + assert str::trim(" hey dude ") == "hey dude"; +} + // Local Variables: // mode: rust; // fill-column: 78;