From 7e55061def5c09567ab51da9d9dcaa5016183806 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Mon, 18 Jul 2011 16:07:34 -0700 Subject: [PATCH] Add str::replace --- src/lib/str.rs | 17 +++++++++++++++++ src/test/run-pass/lib-str.rs | 26 +++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/src/lib/str.rs b/src/lib/str.rs index fb0d0e7e773..15ca04df190 100644 --- a/src/lib/str.rs +++ b/src/lib/str.rs @@ -52,6 +52,7 @@ export bytes_ivec; export unsafe_from_bytes_ivec; export is_empty; export is_not_empty; +export replace; native "rust" mod rustrt { type sbuf; @@ -511,6 +512,22 @@ fn to_upper(str s) -> str { } ret outstr; } + +// FIXME: This is super-inefficient +fn replace(str s, str from, str to) : is_not_empty(from) -> str { + // FIXME (694): Shouldn't have to check this + check is_not_empty(from); + if (byte_len(s) == 0u) { + ret ""; + } else if (starts_with(s, from)) { + ret to + replace(slice(s, byte_len(from), byte_len(s)), + from, to); + } else { + ret unsafe_from_byte(s.(0)) + + replace(slice(s, 1u, byte_len(s)), from, to); + } +} + // Local Variables: // mode: rust; // fill-column: 78; diff --git a/src/test/run-pass/lib-str.rs b/src/test/run-pass/lib-str.rs index cfef1cff1c0..52ec5b78add 100644 --- a/src/test/run-pass/lib-str.rs +++ b/src/test/run-pass/lib-str.rs @@ -132,6 +132,19 @@ fn test_is_not_empty() { assert !str::is_not_empty(""); } +fn test_replace() { + auto a = "a"; + check str::is_not_empty(a); + assert str::replace("", a, "b") == ""; + assert str::replace("a", a, "b") == "b"; + assert str::replace("ab", a, "b") == "bb"; + auto test = "test"; + check str::is_not_empty(test); + assert str::replace(" test test ", test, "toast") + == " toast toast "; + assert str::replace(" test test ", test, "") == " "; +} + fn main() { test_bytes_len(); test_index_and_rindex(); @@ -145,4 +158,15 @@ fn main() { test_ends_with(); test_is_empty(); test_is_not_empty(); -} \ No newline at end of file + test_replace(); +} + + +// Local Variables: +// mode: rust; +// fill-column: 78; +// indent-tabs-mode: nil +// c-basic-offset: 4 +// buffer-file-coding-system: utf-8-unix +// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'"; +// End: