Add std::istr::str_from_cstr. Issue #855

This commit is contained in:
Brian Anderson 2011-08-24 23:18:23 -07:00
parent b2408d57f0
commit ccc68fc18b
2 changed files with 23 additions and 1 deletions

View File

@ -3,7 +3,7 @@ index, rindex, find, starts_with, ends_with, substr, slice, split,
concat, connect, to_upper, replace, char_slice, trim_left, trim_right, trim,
unshift_char, shift_char, pop_char, push_char, is_utf8, from_chars, to_chars,
char_len, char_at, bytes, is_ascii, shift_byte, pop_byte, unsafe_from_byte,
unsafe_from_bytes, from_char, char_range_at;
unsafe_from_bytes, from_char, char_range_at, str_from_cstr;
export from_estr, to_estr, from_estrs, to_estrs;
@ -461,4 +461,17 @@ fn trim_right(s: &istr) -> istr {
fn trim(s: &istr) -> istr {
trim_left(trim_right(s))
}
fn str_from_cstr(cstr: *u8) -> istr {
let res = ~"";
let start = cstr;
let curr = start;
let i = 0u;
while *curr != 0u8 {
push_byte(res, *curr);
i += 1u;
curr = ptr::offset(start, i);
}
ret res;
}

View File

@ -1,4 +1,5 @@
import std::istr;
import std::vec;
#[test]
fn test_eq() {
@ -255,4 +256,12 @@ fn unsafe_from_bytes() {
let a = [65u8, 65u8, 65u8, 65u8, 65u8, 65u8, 65u8];
let b = istr::unsafe_from_bytes(a);
assert b == ~"AAAAAAA";
}
#[test]
fn str_from_cstr() {
let a = [65u8, 65u8, 65u8, 65u8, 65u8, 65u8, 65u8, 0u8];
let b = vec::to_ptr(a);
let c = istr::str_from_cstr(b);
assert c == ~"AAAAAAA";
}