std::vec: remove .as_imm_buf, replaced by .as_ptr & .len.

There's no need for the restrictions of a closure with the above methods.
This commit is contained in:
Huon Wilson 2013-12-18 01:49:31 +11:00
parent ac137f6dbe
commit 4c79b22ef2
16 changed files with 119 additions and 167 deletions

View File

@ -44,21 +44,18 @@ static TINFL_FLAG_PARSE_ZLIB_HEADER : c_int = 0x1; // parse zlib header and adle
static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler32 checksum static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler32 checksum
fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> ~[u8] { fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> ~[u8] {
bytes.as_imm_buf(|b, len| { unsafe {
unsafe { let mut outsz : size_t = 0;
let mut outsz : size_t = 0; let res = rustrt::tdefl_compress_mem_to_heap(bytes.as_ptr() as *c_void,
let res = bytes.len() as size_t,
rustrt::tdefl_compress_mem_to_heap(b as *c_void, &mut outsz,
len as size_t, flags);
&mut outsz, assert!(res as int != 0);
flags);
assert!(res as int != 0);
let out = vec::raw::from_buf_raw(res as *u8, let out = vec::raw::from_buf_raw(res as *u8,
outsz as uint); outsz as uint);
libc::free(res); libc::free(res);
out out
} }
})
} }
pub fn deflate_bytes(bytes: &[u8]) -> ~[u8] { pub fn deflate_bytes(bytes: &[u8]) -> ~[u8] {
@ -70,21 +67,18 @@ pub fn deflate_bytes_zlib(bytes: &[u8]) -> ~[u8] {
} }
fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> ~[u8] { fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> ~[u8] {
bytes.as_imm_buf(|b, len| { unsafe {
unsafe { let mut outsz : size_t = 0;
let mut outsz : size_t = 0; let res = rustrt::tinfl_decompress_mem_to_heap(bytes.as_ptr() as *c_void,
let res = bytes.len() as size_t,
rustrt::tinfl_decompress_mem_to_heap(b as *c_void, &mut outsz,
len as size_t, flags);
&mut outsz, assert!(res as int != 0);
flags); let out = vec::raw::from_buf_raw(res as *u8,
assert!(res as int != 0); outsz as uint);
let out = vec::raw::from_buf_raw(res as *u8, libc::free(res);
outsz as uint); out
libc::free(res); }
out
}
})
} }
pub fn inflate_bytes(bytes: &[u8]) -> ~[u8] { pub fn inflate_bytes(bytes: &[u8]) -> ~[u8] {

View File

@ -354,9 +354,7 @@ pub mod write {
add(*arg); add(*arg);
} }
llvm_args.as_imm_buf(|p, len| { llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int, llvm_args.as_ptr());
llvm::LLVMRustSetLLVMOptions(len as c_int, p);
})
} }
unsafe fn populate_llvm_passes(fpm: lib::llvm::PassManagerRef, unsafe fn populate_llvm_passes(fpm: lib::llvm::PassManagerRef,

View File

@ -55,7 +55,7 @@ mod windows {
let mut t = s.to_utf16(); let mut t = s.to_utf16();
// Null terminate before passing on. // Null terminate before passing on.
t.push(0u16); t.push(0u16);
t.as_imm_buf(|buf, _len| f(buf)) f(t.as_ptr())
} }
#[link_name = "kernel32"] #[link_name = "kernel32"]
@ -86,14 +86,12 @@ mod windows {
return Err(format!("failure in BeginUpdateResourceW: {}", os::last_os_error())); return Err(format!("failure in BeginUpdateResourceW: {}", os::last_os_error()));
} }
let ok = manifest.as_imm_buf(|p, len| { let ok = UpdateResourceW(hUpdate,
UpdateResourceW(hUpdate, MAKEINTRESOURCEW(24), // RT_MANIFEST
MAKEINTRESOURCEW(24), // RT_MANIFEST MAKEINTRESOURCEW(1), // CREATEPROCESS_MANIFEST_RESOURCE_ID
MAKEINTRESOURCEW(1), // CREATEPROCESS_MANIFEST_RESOURCE_ID 0, // LANG_NEUTRAL, SUBLANG_NEUTRAL
0, // LANG_NEUTRAL, SUBLANG_NEUTRAL manifest.as_ptr() as LPCVOID,
p as LPCVOID, manifest.len() as u32);
len as u32)
});
if ok == FALSE { if ok == FALSE {
return Err(format!("failure in UpdateResourceW: {}", os::last_os_error())); return Err(format!("failure in UpdateResourceW: {}", os::last_os_error()));
} }

View File

@ -2414,9 +2414,9 @@ pub fn create_entry_wrapper(ccx: @mut CrateContext,
(rust_main, args) (rust_main, args)
}; };
let result = args.as_imm_buf(|buf, len| { let result = llvm::LLVMBuildCall(bld, start_fn,
llvm::LLVMBuildCall(bld, start_fn, buf, len as c_uint, noname()) args.as_ptr(), args.len() as c_uint,
}); noname());
llvm::LLVMBuildRet(bld, result); llvm::LLVMBuildRet(bld, result);
} }

View File

@ -464,11 +464,11 @@ impl Builder {
let min = llvm::LLVMConstInt(t, lo, signed); let min = llvm::LLVMConstInt(t, lo, signed);
let max = llvm::LLVMConstInt(t, hi, signed); let max = llvm::LLVMConstInt(t, hi, signed);
[min, max].as_imm_buf(|ptr, len| { let v = [min, max];
llvm::LLVMSetMetadata(value, lib::llvm::MD_range as c_uint,
llvm::LLVMMDNodeInContext(self.ccx.llcx, llvm::LLVMSetMetadata(value, lib::llvm::MD_range as c_uint,
ptr, len as c_uint)); llvm::LLVMMDNodeInContext(self.ccx.llcx,
}) v.as_ptr(), v.len() as c_uint));
} }
value value

View File

@ -952,17 +952,16 @@ pub fn C_zero_byte_arr(size: uint) -> ValueRef {
pub fn C_struct(elts: &[ValueRef], packed: bool) -> ValueRef { pub fn C_struct(elts: &[ValueRef], packed: bool) -> ValueRef {
unsafe { unsafe {
elts.as_imm_buf(|ptr, len| {
llvm::LLVMConstStructInContext(base::task_llcx(), ptr, len as c_uint, packed as Bool) llvm::LLVMConstStructInContext(base::task_llcx(),
}) elts.as_ptr(), elts.len() as c_uint,
packed as Bool)
} }
} }
pub fn C_named_struct(T: Type, elts: &[ValueRef]) -> ValueRef { pub fn C_named_struct(T: Type, elts: &[ValueRef]) -> ValueRef {
unsafe { unsafe {
elts.as_imm_buf(|ptr, len| { llvm::LLVMConstNamedStruct(T.to_ref(), elts.as_ptr(), elts.len() as c_uint)
llvm::LLVMConstNamedStruct(T.to_ref(), ptr, len as c_uint)
})
} }
} }
@ -988,9 +987,7 @@ pub fn get_param(fndecl: ValueRef, param: uint) -> ValueRef {
pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint]) pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint])
-> ValueRef { -> ValueRef {
unsafe { unsafe {
let r = us.as_imm_buf(|p, len| { let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
llvm::LLVMConstExtractValue(v, p, len as c_uint)
});
debug!("const_get_elt(v={}, us={:?}, r={})", debug!("const_get_elt(v={}, us={:?}, r={})",
cx.tn.val_to_str(v), us, cx.tn.val_to_str(r)); cx.tn.val_to_str(v), us, cx.tn.val_to_str(r));

View File

@ -646,11 +646,9 @@ pub fn trans_rust_fn_with_foreign_abi(ccx: @mut CrateContext,
} }
// Perform the call itself // Perform the call itself
let llrust_ret_val = llrust_args.as_imm_buf(|ptr, len| { debug!("calling llrustfn = {}", ccx.tn.val_to_str(llrustfn));
debug!("calling llrustfn = {}", ccx.tn.val_to_str(llrustfn)); let llrust_ret_val = llvm::LLVMBuildCall(builder, llrustfn, llrust_args.as_ptr(),
llvm::LLVMBuildCall(builder, llrustfn, ptr, llrust_args.len() as c_uint, noname());
len as c_uint, noname())
});
// Get the return value where the foreign fn expects it. // Get the return value where the foreign fn expects it.
let llforeign_ret_ty = match tys.fn_ty.ret_ty.cast { let llforeign_ret_ty = match tys.fn_ty.ret_ty.cast {

View File

@ -70,7 +70,7 @@ impl Process {
}, },
flags: 0, flags: 0,
stdio_count: stdio.len() as libc::c_int, stdio_count: stdio.len() as libc::c_int,
stdio: stdio.as_imm_buf(|p, _| p), stdio: stdio.as_ptr(),
uid: 0, uid: 0,
gid: 0, gid: 0,
}; };
@ -163,7 +163,7 @@ fn with_argv<T>(prog: &str, args: &[~str], f: |**libc::c_char| -> T) -> T {
c_args.push(s.with_ref(|p| p)); c_args.push(s.with_ref(|p| p));
} }
c_args.push(ptr::null()); c_args.push(ptr::null());
c_args.as_imm_buf(|buf, _| f(buf)) f(c_args.as_ptr())
} }
/// Converts the environment to the env array expected by libuv /// Converts the environment to the env array expected by libuv
@ -182,7 +182,7 @@ fn with_env<T>(env: Option<&[(~str, ~str)]>, f: |**libc::c_char| -> T) -> T {
c_envp.push(s.with_ref(|p| p)); c_envp.push(s.with_ref(|p| p));
} }
c_envp.push(ptr::null()); c_envp.push(ptr::null());
c_envp.as_imm_buf(|buf, _| f(buf)) f(c_envp.as_ptr())
} }
impl HomingIO for Process { impl HomingIO for Process {

View File

@ -267,17 +267,16 @@ impl<'a> ToCStr for &'a [u8] {
} }
unsafe fn to_c_str_unchecked(&self) -> CString { unsafe fn to_c_str_unchecked(&self) -> CString {
self.as_imm_buf(|self_buf, self_len| { let self_len = self.len();
let buf = libc::malloc(self_len as libc::size_t + 1) as *mut u8; let buf = libc::malloc(self_len as libc::size_t + 1) as *mut u8;
if buf.is_null() { if buf.is_null() {
fail!("failed to allocate memory!"); fail!("failed to allocate memory!");
} }
ptr::copy_memory(buf, self_buf, self_len); ptr::copy_memory(buf, self.as_ptr(), self_len);
*ptr::mut_offset(buf, self_len as int) = 0; *ptr::mut_offset(buf, self_len as int) = 0;
CString::new(buf as *libc::c_char, true) CString::new(buf as *libc::c_char, true)
})
} }
fn with_c_str<T>(&self, f: |*libc::c_char| -> T) -> T { fn with_c_str<T>(&self, f: |*libc::c_char| -> T) -> T {

View File

@ -37,8 +37,8 @@ fn keep_going(data: &[u8], f: |*u8, uint| -> i64) -> i64 {
#[cfg(windows)] static eintr: int = 0; // doesn't matter #[cfg(windows)] static eintr: int = 0; // doesn't matter
#[cfg(not(windows))] static eintr: int = libc::EINTR as int; #[cfg(not(windows))] static eintr: int = libc::EINTR as int;
let (data, origamt) = data.as_imm_buf(|data, amt| (data, amt)); let origamt = data.len();
let mut data = data; let mut data = data.as_ptr();
let mut amt = origamt; let mut amt = origamt;
while amt > 0 { while amt > 0 {
let mut ret; let mut ret;

View File

@ -8,7 +8,6 @@
// option. This file may not be copied, modified, or distributed // option. This file may not be copied, modified, or distributed
// except according to those terms. // except according to those terms.
use cast;
use io; use io;
use libc::{pid_t, c_void, c_int}; use libc::{pid_t, c_void, c_int};
use libc; use libc;
@ -17,6 +16,8 @@ use prelude::*;
use ptr; use ptr;
use rt::rtio; use rt::rtio;
use super::file; use super::file;
#[cfg(windows)]
use cast;
use p = io::process; use p = io::process;
@ -453,7 +454,7 @@ fn with_argv<T>(prog: &str, args: &[~str], cb: |**libc::c_char| -> T) -> T {
// Finally, make sure we add a null pointer. // Finally, make sure we add a null pointer.
ptrs.push(ptr::null()); ptrs.push(ptr::null());
ptrs.as_imm_buf(|buf, _| cb(buf)) cb(ptrs.as_ptr())
} }
#[cfg(unix)] #[cfg(unix)]
@ -476,7 +477,7 @@ fn with_envp<T>(env: Option<~[(~str, ~str)]>, cb: |*c_void| -> T) -> T {
let mut ptrs = tmps.map(|tmp| tmp.with_ref(|buf| buf)); let mut ptrs = tmps.map(|tmp| tmp.with_ref(|buf| buf));
ptrs.push(ptr::null()); ptrs.push(ptr::null());
ptrs.as_imm_buf(|buf, _| unsafe { cb(cast::transmute(buf)) }) cb(ptrs.as_ptr() as *c_void)
} }
_ => cb(ptr::null()) _ => cb(ptr::null())
} }
@ -499,7 +500,7 @@ fn with_envp<T>(env: Option<~[(~str, ~str)]>, cb: |*mut c_void| -> T) -> T {
blk.push(0); blk.push(0);
blk.as_imm_buf(|p, _len| unsafe { cb(cast::transmute(p)) }) cb(blk.as_mut_ptr() as *mut c_void)
} }
_ => cb(ptr::mut_null()) _ => cb(ptr::mut_null())
} }

View File

@ -130,7 +130,7 @@ pub mod win32 {
let mut t = s.to_utf16(); let mut t = s.to_utf16();
// Null terminate before passing on. // Null terminate before passing on.
t.push(0u16); t.push(0u16);
t.as_imm_buf(|buf, _len| f(buf)) f(t.as_ptr())
} }
} }

View File

@ -511,10 +511,9 @@ pub mod ptr_tests {
"there".with_c_str(|p1| { "there".with_c_str(|p1| {
"thing".with_c_str(|p2| { "thing".with_c_str(|p2| {
let v = ~[p0, p1, p2, null()]; let v = ~[p0, p1, p2, null()];
v.as_imm_buf(|vp, len| { unsafe {
assert_eq!(unsafe { buf_len(vp) }, 3u); assert_eq!(buf_len(v.as_ptr()), 3u);
assert_eq!(len, 4u); }
})
}) })
}) })
}) })
@ -623,23 +622,21 @@ pub mod ptr_tests {
one, two, three one, two, three
]; ];
arr.as_imm_buf(|arr_ptr, arr_len| { let mut ctr = 0;
let mut ctr = 0; let mut iteration_count = 0;
let mut iteration_count = 0; array_each_with_len(arr.as_ptr(), arr.len(), |e| {
array_each_with_len(arr_ptr, arr_len, |e| { let actual = str::raw::from_c_str(e);
let actual = str::raw::from_c_str(e); let expected = expected_arr[ctr].with_ref(|buf| {
let expected = expected_arr[ctr].with_ref(|buf| { str::raw::from_c_str(buf)
str::raw::from_c_str(buf) });
}); debug!(
debug!( "test_ptr_array_each_with_len e: {}, a: {}",
"test_ptr_array_each_with_len e: {}, a: {}", expected, actual);
expected, actual); assert_eq!(actual, expected);
assert_eq!(actual, expected); ctr += 1;
ctr += 1; iteration_count += 1;
iteration_count += 1;
}); });
assert_eq!(iteration_count, 3u); assert_eq!(iteration_count, 3u);
})
} }
} }
@ -660,23 +657,22 @@ pub mod ptr_tests {
one, two, three one, two, three
]; ];
arr.as_imm_buf(|arr_ptr, _| { let arr_ptr = arr.as_ptr();
let mut ctr = 0; let mut ctr = 0;
let mut iteration_count = 0; let mut iteration_count = 0;
array_each(arr_ptr, |e| { array_each(arr_ptr, |e| {
let actual = str::raw::from_c_str(e); let actual = str::raw::from_c_str(e);
let expected = expected_arr[ctr].with_ref(|buf| { let expected = expected_arr[ctr].with_ref(|buf| {
str::raw::from_c_str(buf) str::raw::from_c_str(buf)
}); });
debug!( debug!(
"test_ptr_array_each e: {}, a: {}", "test_ptr_array_each e: {}, a: {}",
expected, actual); expected, actual);
assert_eq!(actual, expected); assert_eq!(actual, expected);
ctr += 1; ctr += 1;
iteration_count += 1; iteration_count += 1;
}); });
assert_eq!(iteration_count, 3); assert_eq!(iteration_count, 3);
})
} }
} }

View File

@ -2502,7 +2502,7 @@ impl<'a> StrSlice<'a> for &'a str {
#[inline] #[inline]
fn as_imm_buf<T>(&self, f: |*u8, uint| -> T) -> T { fn as_imm_buf<T>(&self, f: |*u8, uint| -> T) -> T {
let v: &[u8] = unsafe { cast::transmute(*self) }; let v: &[u8] = unsafe { cast::transmute(*self) };
v.as_imm_buf(f) f(v.as_ptr(), v.len())
} }
} }

View File

@ -775,7 +775,7 @@ impl<'a, T> Container for &'a [T] {
/// Returns the length of a vector /// Returns the length of a vector
#[inline] #[inline]
fn len(&self) -> uint { fn len(&self) -> uint {
self.as_imm_buf(|_p, len| len) self.repr().len
} }
} }
@ -783,7 +783,7 @@ impl<T> Container for ~[T] {
/// Returns the length of a vector /// Returns the length of a vector
#[inline] #[inline]
fn len(&self) -> uint { fn len(&self) -> uint {
self.as_imm_buf(|_p, len| len) self.repr().len
} }
} }
@ -984,14 +984,6 @@ pub trait ImmutableVector<'a, T> {
/// of a vector and return the results. /// of a vector and return the results.
fn map<U>(&self, |t: &T| -> U) -> ~[U]; fn map<U>(&self, |t: &T| -> U) -> ~[U];
/**
* Work with the buffer of a vector.
*
* Allows for unsafe manipulation of vector contents, which is useful for
* foreign interop.
*/
fn as_imm_buf<U>(&self, f: |*T, uint| -> U) -> U;
/** /**
* Returns a mutable reference to the first element in this slice * Returns a mutable reference to the first element in this slice
* and adjusts the slice in place so that it no longer contains * and adjusts the slice in place so that it no longer contains
@ -1032,14 +1024,12 @@ impl<'a,T> ImmutableVector<'a, T> for &'a [T] {
fn slice(&self, start: uint, end: uint) -> &'a [T] { fn slice(&self, start: uint, end: uint) -> &'a [T] {
assert!(start <= end); assert!(start <= end);
assert!(end <= self.len()); assert!(end <= self.len());
self.as_imm_buf(|p, _len| { unsafe {
unsafe { cast::transmute(Slice {
cast::transmute(Slice { data: self.as_ptr().offset(start as int),
data: ptr::offset(p, start as int),
len: (end - start) len: (end - start)
}) })
} }
})
} }
#[inline] #[inline]
@ -1197,12 +1187,6 @@ impl<'a,T> ImmutableVector<'a, T> for &'a [T] {
self.iter().map(f).collect() self.iter().map(f).collect()
} }
#[inline]
fn as_imm_buf<U>(&self, f: |*T, uint| -> U) -> U {
let s = self.repr();
f(s.data, s.len)
}
fn shift_ref(&mut self) -> &'a T { fn shift_ref(&mut self) -> &'a T {
unsafe { unsafe {
let s: &mut Slice<T> = cast::transmute(self); let s: &mut Slice<T> = cast::transmute(self);
@ -2206,10 +2190,9 @@ impl<'a,T> MutableVector<'a, T> for &'a mut [T] {
#[inline] #[inline]
unsafe fn copy_memory(self, src: &[T]) { unsafe fn copy_memory(self, src: &[T]) {
self.as_mut_buf(|p_dst, len_dst| { self.as_mut_buf(|p_dst, len_dst| {
src.as_imm_buf(|p_src, len_src| { let len_src = src.len();
assert!(len_dst >= len_src) assert!(len_dst >= len_src);
ptr::copy_nonoverlapping_memory(p_dst, p_src, len_src) ptr::copy_nonoverlapping_memory(p_dst, src.as_ptr(), len_src)
})
}) })
} }
@ -2369,9 +2352,7 @@ pub mod bytes {
dst.reserve_additional(src.len()); dst.reserve_additional(src.len());
unsafe { unsafe {
dst.as_mut_buf(|p_dst, len_dst| { dst.as_mut_buf(|p_dst, len_dst| {
src.as_imm_buf(|p_src, len_src| { ptr::copy_memory(p_dst.offset(len_dst as int), src.as_ptr(), src.len())
ptr::copy_memory(p_dst.offset(len_dst as int), p_src, len_src)
})
}); });
dst.set_len(old_len + src.len()); dst.set_len(old_len + src.len());
} }
@ -3553,15 +3534,6 @@ mod tests {
} }
} }
#[test]
#[should_fail]
fn test_as_imm_buf_fail() {
let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
v.as_imm_buf(|_buf, _i| {
fail!()
})
}
#[test] #[test]
#[should_fail] #[should_fail]
fn test_as_mut_buf_fail() { fn test_as_mut_buf_fail() {

View File

@ -21,16 +21,15 @@ fn main() {
// huge). // huge).
let x = ~[1u,2u,3u]; let x = ~[1u,2u,3u];
x.as_imm_buf(|p, _len| {
let base = p as uint;
let idx = base / mem::size_of::<uint>();
error!("ov1 base = 0x{:x}", base);
error!("ov1 idx = 0x{:x}", idx);
error!("ov1 sizeof::<uint>() = 0x{:x}", mem::size_of::<uint>());
error!("ov1 idx * sizeof::<uint>() = 0x{:x}",
idx * mem::size_of::<uint>());
// This should fail. let base = x.as_ptr() as uint;
error!("ov1 0x{:x}", x[idx]); let idx = base / mem::size_of::<uint>();
}) error!("ov1 base = 0x{:x}", base);
error!("ov1 idx = 0x{:x}", idx);
error!("ov1 sizeof::<uint>() = 0x{:x}", mem::size_of::<uint>());
error!("ov1 idx * sizeof::<uint>() = 0x{:x}",
idx * mem::size_of::<uint>());
// This should fail.
error!("ov1 0x{:x}", x[idx]);
} }