Skip to content

Commit 0dacefb

Browse files
committed
Merge pull request #1814 from uasi/from-cstr-len
Implement core::str::from_cstr_len with a test, close issue #1666
2 parents 005a3ef + 70b04a1 commit 0dacefb

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/libcore/str.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ export
1717
from_char,
1818
from_chars,
1919
from_cstr,
20+
from_cstr_len,
2021
concat,
2122
connect,
2223

@@ -210,6 +211,24 @@ unsafe fn from_cstr(cstr: sbuf) -> str {
210211
ret from_bytes(res);
211212
}
212213

214+
/*
215+
Function: from_cstr_len
216+
217+
Create a Rust string from a C string of the given length
218+
*/
219+
unsafe fn from_cstr_len(cstr: sbuf, len: uint) -> str {
220+
let res = [];
221+
let start = cstr;
222+
let curr = start;
223+
let i = 0u;
224+
while i < len {
225+
vec::push(res, *curr);
226+
i += 1u;
227+
curr = ptr::offset(start, i);
228+
}
229+
ret from_bytes(res);
230+
}
231+
213232
/*
214233
Function: concat
215234
@@ -1960,6 +1979,14 @@ mod tests {
19601979
assert (c == "AAAAAAA");
19611980
}
19621981

1982+
#[test]
1983+
fn test_from_cstr_len() unsafe {
1984+
let a = [65u8, 65u8, 65u8, 65u8, 65u8, 65u8, 65u8, 0u8];
1985+
let b = vec::to_ptr(a);
1986+
let c = from_cstr_len(b, 3u);
1987+
assert (c == "AAA");
1988+
}
1989+
19631990
#[test]
19641991
fn test_as_buf() unsafe {
19651992
let a = "Abcdefg";

0 commit comments

Comments
 (0)