提交 3629f702 编写于 作者: E Erick Tryzelaar

std: merge str::raw::from_buf and str::raw::from_c_str

上级 bd908d4c
......@@ -93,7 +93,7 @@ pub fn fill_charp_buf(f: &fn(*mut c_char, size_t) -> bool) -> Option<~str> {
do buf.as_mut_buf |b, sz| {
if f(b, sz as size_t) {
unsafe {
Some(str::raw::from_buf(b as *u8))
Some(str::raw::from_c_str(b as *c_char))
}
} else {
None
......
......@@ -763,17 +763,6 @@ pub mod raw {
use vec::MutableVector;
use unstable::raw::{Slice, String};
/// Create a Rust string from a null-terminated *u8 buffer
pub unsafe fn from_buf(buf: *u8) -> ~str {
let mut curr = buf;
let mut i = 0u;
while *curr != 0u8 {
i += 1u;
curr = ptr::offset(buf, i as int);
}
return from_buf_len(buf, i);
}
/// Create a Rust string from a *u8 buffer of the given length
pub unsafe fn from_buf_len(buf: *u8, len: uint) -> ~str {
let mut v: ~[u8] = vec::with_capacity(len + 1);
......@@ -784,17 +773,18 @@ pub unsafe fn from_buf_len(buf: *u8, len: uint) -> ~str {
v.push(0u8);
assert!(is_utf8(v));
return cast::transmute(v);
cast::transmute(v)
}
/// Create a Rust string from a null-terminated C string
pub unsafe fn from_c_str(c_str: *libc::c_char) -> ~str {
from_buf(c_str as *u8)
}
/// Create a Rust string from a `*c_char` buffer of the given length
pub unsafe fn from_c_str_len(c_str: *libc::c_char, len: uint) -> ~str {
from_buf_len(c_str as *u8, len)
pub unsafe fn from_c_str(buf: *libc::c_char) -> ~str {
let mut curr = buf;
let mut i = 0;
while *curr != 0 {
i += 1;
curr = ptr::offset(buf, i);
}
from_buf_len(buf as *u8, i as uint)
}
/// Converts a vector of bytes to a new owned string.
......@@ -2805,11 +2795,11 @@ fn test_from_bytes_fail() {
}
#[test]
fn test_from_buf() {
fn test_raw_from_c_str() {
unsafe {
let a = ~[65u8, 65u8, 65u8, 65u8, 65u8, 65u8, 65u8, 0u8];
let a = ~[65, 65, 65, 65, 65, 65, 65, 0];
let b = vec::raw::to_ptr(a);
let c = raw::from_buf(b);
let c = raw::from_c_str(b);
assert_eq!(c, ~"AAAAAAA");
}
}
......
......@@ -10,15 +10,20 @@
use std::str;
static a: [u8, ..3] = ['h' as u8, 'i' as u8, 0 as u8];
static c: &'static [u8, ..3] = &a;
static b: *u8 = c as *u8;
static A: [u8, ..2] = ['h' as u8, 'i' as u8];
static B: &'static [u8, ..2] = &A;
static C: *u8 = B as *u8;
pub fn main() {
let foo = &a as *u8;
assert_eq!(unsafe { str::raw::from_bytes(a) }, ~"hi\x00");
assert_eq!(unsafe { str::raw::from_buf(foo) }, ~"hi");
assert_eq!(unsafe { str::raw::from_buf(b) }, ~"hi");
assert!(unsafe { *b == a[0] });
assert!(unsafe { *(&c[0] as *u8) == a[0] });
unsafe {
let foo = &A as *u8;
assert_eq!(str::raw::from_bytes(A), ~"hi");
assert_eq!(str::raw::from_buf_len(foo, A.len()), ~"hi");
assert_eq!(str::raw::from_buf_len(C, B.len()), ~"hi");
assert!(*C == A[0]);
assert!(*(&B[0] as *u8) == A[0]);
let bar = str::raw::from_bytes(A).to_c_str();
assert_eq!(bar.with_ref(|buf| str::raw::from_c_str(buf)), ~"hi");
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册