Skip to content

Commit

Permalink
Add an &str.to_managed method to allow creating non-constant @str val…
Browse files Browse the repository at this point in the history
…ues (for issue rust-lang#3433).
  • Loading branch information
Dretch committed Oct 4, 2012
1 parent 5585514 commit 851617d
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/libcore/str.rs
Expand Up @@ -1869,6 +1869,11 @@ pub pure fn escape_unicode(s: &str) -> ~str {
move out
}

extern mod rustrt {
#[rust_stack]
pure fn upcall_str_new_shared(cstr: *libc::c_char, len: size_t) -> @str;
}

/// Unsafe operations
pub mod raw {

Expand Down Expand Up @@ -2087,6 +2092,7 @@ pub trait StrSlice {
fn escape_default() -> ~str;
fn escape_unicode() -> ~str;
pure fn to_unique() -> ~str;
pure fn to_managed() -> @str;
pure fn char_at(i: uint) -> char;
}

Expand Down Expand Up @@ -2198,6 +2204,14 @@ impl &str: StrSlice {
#[inline]
pure fn to_unique() -> ~str { self.slice(0, self.len()) }

#[inline]
pure fn to_managed() -> @str {
do str::as_buf(self) |p, _len| {
rustrt::upcall_str_new_shared(p as *libc::c_char,
self.len() as size_t)
}
}

#[inline]
pure fn char_at(i: uint) -> char { char_at(self, i) }
}
Expand Down Expand Up @@ -3175,4 +3189,10 @@ mod tests {
assert escape_default(~"\U0001d4ea\r") == ~"\\U0001d4ea\\r";
}
#[test]
fn test_to_managed() {
assert (~"abc").to_managed() == @"abc";
assert view("abcdef", 1, 5).to_managed() == @"bcde";
}

}

0 comments on commit 851617d

Please sign in to comment.