libstd: Remove all non-proc uses of do from libstd

This commit is contained in:
Patrick Walton 2013-11-20 14:17:12 -08:00
parent 6801bc8f55
commit 1eca34de7d
56 changed files with 722 additions and 895 deletions

View file

@ -290,7 +290,7 @@ impl<'self> AsciiStr for &'self [Ascii] {
#[inline] #[inline]
fn eq_ignore_case(self, other: &[Ascii]) -> bool { fn eq_ignore_case(self, other: &[Ascii]) -> bool {
do self.iter().zip(other.iter()).all |(&a, &b)| { a.eq_ignore_case(b) } self.iter().zip(other.iter()).all(|(&a, &b)| a.eq_ignore_case(b))
} }
} }

View file

@ -56,24 +56,24 @@ pub fn build<A>(size: Option<uint>, builder: |push: |v: A||) -> @[A] {
/// `lhs`. Afterwards, the `lhs` is then returned for use again. /// `lhs`. Afterwards, the `lhs` is then returned for use again.
#[inline] #[inline]
pub fn append<T:Clone>(lhs: @[T], rhs: &[T]) -> @[T] { pub fn append<T:Clone>(lhs: @[T], rhs: &[T]) -> @[T] {
do build(Some(lhs.len() + rhs.len())) |push| { build(Some(lhs.len() + rhs.len()), |push| {
for x in lhs.iter() { for x in lhs.iter() {
push((*x).clone()); push((*x).clone());
} }
for elt in rhs.iter() { for elt in rhs.iter() {
push(elt.clone()); push(elt.clone());
} }
} })
} }
/// Apply a function to each element of a vector and return the results /// Apply a function to each element of a vector and return the results
pub fn map<T, U>(v: &[T], f: |x: &T| -> U) -> @[U] { pub fn map<T, U>(v: &[T], f: |x: &T| -> U) -> @[U] {
do build(Some(v.len())) |push| { build(Some(v.len()), |push| {
for elem in v.iter() { for elem in v.iter() {
push(f(elem)); push(f(elem));
} }
} })
} }
/** /**
@ -83,10 +83,10 @@ pub fn map<T, U>(v: &[T], f: |x: &T| -> U) -> @[U] {
* to the value returned by the function `op`. * to the value returned by the function `op`.
*/ */
pub fn from_fn<T>(n_elts: uint, op: |uint| -> T) -> @[T] { pub fn from_fn<T>(n_elts: uint, op: |uint| -> T) -> @[T] {
do build(Some(n_elts)) |push| { build(Some(n_elts), |push| {
let mut i: uint = 0u; let mut i: uint = 0u;
while i < n_elts { push(op(i)); i += 1u; } while i < n_elts { push(op(i)); i += 1u; }
} })
} }
/** /**
@ -96,13 +96,13 @@ pub fn from_fn<T>(n_elts: uint, op: |uint| -> T) -> @[T] {
* to the value `t`. * to the value `t`.
*/ */
pub fn from_elem<T:Clone>(n_elts: uint, t: T) -> @[T] { pub fn from_elem<T:Clone>(n_elts: uint, t: T) -> @[T] {
do build(Some(n_elts)) |push| { build(Some(n_elts), |push| {
let mut i: uint = 0u; let mut i: uint = 0u;
while i < n_elts { while i < n_elts {
push(t.clone()); push(t.clone());
i += 1u; i += 1u;
} }
} })
} }
/** /**
@ -137,11 +137,11 @@ impl<T> Clone for @[T] {
impl<A> FromIterator<A> for @[A] { impl<A> FromIterator<A> for @[A] {
fn from_iterator<T: Iterator<A>>(iterator: &mut T) -> @[A] { fn from_iterator<T: Iterator<A>>(iterator: &mut T) -> @[A] {
let (lower, _) = iterator.size_hint(); let (lower, _) = iterator.size_hint();
do build(Some(lower)) |push| { build(Some(lower), |push| {
for x in *iterator { for x in *iterator {
push(x); push(x);
} }
} })
} }
} }
@ -259,9 +259,9 @@ pub mod raw {
use rt::local::Local; use rt::local::Local;
use rt::task::Task; use rt::task::Task;
do Local::borrow |task: &mut Task| { Local::borrow(|task: &mut Task| {
task.heap.realloc(ptr as *mut Box<()>, size) as *() task.heap.realloc(ptr as *mut Box<()>, size) as *()
} })
} }
} }
@ -295,11 +295,11 @@ mod test {
fn test() { fn test() {
// Some code that could use that, then: // Some code that could use that, then:
fn seq_range(lo: uint, hi: uint) -> @[uint] { fn seq_range(lo: uint, hi: uint) -> @[uint] {
do build(None) |push| { build(None, |push| {
for i in range(lo, hi) { for i in range(lo, hi) {
push(i); push(i);
} }
} })
} }
assert_eq!(seq_range(10, 15), @[10, 11, 12, 13, 14]); assert_eq!(seq_range(10, 15), @[10, 11, 12, 13, 14]);
@ -333,9 +333,7 @@ mod test {
#[bench] #[bench]
fn bench_capacity(b: &mut bh) { fn bench_capacity(b: &mut bh) {
let x = @[1, 2, 3]; let x = @[1, 2, 3];
do b.iter { b.iter(|| capacity(x));
capacity(x);
}
} }
#[bench] #[bench]
@ -359,54 +357,42 @@ mod test {
fn bench_append(b: &mut bh) { fn bench_append(b: &mut bh) {
let lhs = @[7, ..128]; let lhs = @[7, ..128];
let rhs = range(0, 256).to_owned_vec(); let rhs = range(0, 256).to_owned_vec();
do b.iter { b.iter(|| append(lhs, rhs))
append(lhs, rhs);
}
} }
#[bench] #[bench]
fn bench_map(b: &mut bh) { fn bench_map(b: &mut bh) {
let elts = range(0, 256).to_owned_vec(); let elts = range(0, 256).to_owned_vec();
do b.iter { b.iter(|| map(elts, |x| x*2))
map(elts, |x| x*2);
}
} }
#[bench] #[bench]
fn bench_from_fn(b: &mut bh) { fn bench_from_fn(b: &mut bh) {
do b.iter { b.iter(|| from_fn(1024, |x| x));
from_fn(1024, |x| x);
}
} }
#[bench] #[bench]
fn bench_from_elem(b: &mut bh) { fn bench_from_elem(b: &mut bh) {
do b.iter { b.iter(|| from_elem(1024, 0u64));
from_elem(1024, 0u64);
}
} }
#[bench] #[bench]
fn bench_to_managed_move(b: &mut bh) { fn bench_to_managed_move(b: &mut bh) {
do b.iter { b.iter(|| {
let elts = range(0, 1024).to_owned_vec(); // yikes! can't move out of capture, though let elts = range(0, 1024).to_owned_vec(); // yikes! can't move out of capture, though
to_managed_move(elts); to_managed_move(elts);
} })
} }
#[bench] #[bench]
fn bench_to_managed(b: &mut bh) { fn bench_to_managed(b: &mut bh) {
let elts = range(0, 1024).to_owned_vec(); let elts = range(0, 1024).to_owned_vec();
do b.iter { b.iter(|| to_managed(elts));
to_managed(elts);
}
} }
#[bench] #[bench]
fn bench_clone(b: &mut bh) { fn bench_clone(b: &mut bh) {
let elts = to_managed(range(0, 1024).to_owned_vec()); let elts = to_managed(range(0, 1024).to_owned_vec());
do b.iter { b.iter(|| elts.clone());
elts.clone();
}
} }
} }

View file

@ -49,15 +49,15 @@ let my_string = "Hello, world!";
// Allocate the C string with an explicit local that owns the string. The // Allocate the C string with an explicit local that owns the string. The
// `c_buffer` pointer will be deallocated when `my_c_string` goes out of scope. // `c_buffer` pointer will be deallocated when `my_c_string` goes out of scope.
let my_c_string = my_string.to_c_str(); let my_c_string = my_string.to_c_str();
do my_c_string.with_ref |c_buffer| { my_c_string.with_ref(|c_buffer| {
unsafe { puts(c_buffer); } unsafe { puts(c_buffer); }
} })
// Don't save off the allocation of the C string, the `c_buffer` will be // Don't save off the allocation of the C string, the `c_buffer` will be
// deallocated when this block returns! // deallocated when this block returns!
do my_string.with_c_str |c_buffer| { my_string.with_c_str(|c_buffer| {
unsafe { puts(c_buffer); } unsafe { puts(c_buffer); }
} })
``` ```
*/ */
@ -262,14 +262,12 @@ static BUF_LEN: uint = 128;
impl<'self> ToCStr for &'self [u8] { impl<'self> ToCStr for &'self [u8] {
fn to_c_str(&self) -> CString { fn to_c_str(&self) -> CString {
let mut cs = unsafe { self.to_c_str_unchecked() }; let mut cs = unsafe { self.to_c_str_unchecked() };
do cs.with_mut_ref |buf| { cs.with_mut_ref(|buf| check_for_null(*self, buf));
check_for_null(*self, buf);
}
cs cs
} }
unsafe fn to_c_str_unchecked(&self) -> CString { unsafe fn to_c_str_unchecked(&self) -> CString {
do self.as_imm_buf |self_buf, self_len| { self.as_imm_buf(|self_buf, 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!");
@ -279,7 +277,7 @@ impl<'self> ToCStr for &'self [u8] {
*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 {
@ -298,13 +296,13 @@ unsafe fn with_c_str<T>(v: &[u8], checked: bool, f: |*libc::c_char| -> T) -> T {
vec::bytes::copy_memory(buf, v, v.len()); vec::bytes::copy_memory(buf, v, v.len());
buf[v.len()] = 0; buf[v.len()] = 0;
do buf.as_mut_buf |buf, _| { buf.as_mut_buf(|buf, _| {
if checked { if checked {
check_for_null(v, buf as *mut libc::c_char); check_for_null(v, buf as *mut libc::c_char);
} }
f(buf as *libc::c_char) f(buf as *libc::c_char)
} })
} else if checked { } else if checked {
v.to_c_str().with_ref(f) v.to_c_str().with_ref(f)
} else { } else {
@ -390,10 +388,10 @@ mod tests {
let ptr = vec::raw::to_ptr(input); let ptr = vec::raw::to_ptr(input);
let expected = ["zero", "one"]; let expected = ["zero", "one"];
let mut it = expected.iter(); let mut it = expected.iter();
let result = do from_c_multistring(ptr as *libc::c_char, None) |c| { let result = from_c_multistring(ptr as *libc::c_char, None, |c| {
let cbytes = c.as_bytes().slice_to(c.len()); let cbytes = c.as_bytes().slice_to(c.len());
assert_eq!(cbytes, it.next().unwrap().as_bytes()); assert_eq!(cbytes, it.next().unwrap().as_bytes());
}; });
assert_eq!(result, 2); assert_eq!(result, 2);
assert!(it.next().is_none()); assert!(it.next().is_none());
} }
@ -401,13 +399,13 @@ mod tests {
#[test] #[test]
fn test_str_to_c_str() { fn test_str_to_c_str() {
do "".to_c_str().with_ref |buf| { "".to_c_str().with_ref(|buf| {
unsafe { unsafe {
assert_eq!(*ptr::offset(buf, 0), 0); assert_eq!(*ptr::offset(buf, 0), 0);
} }
} });
do "hello".to_c_str().with_ref |buf| { "hello".to_c_str().with_ref(|buf| {
unsafe { unsafe {
assert_eq!(*ptr::offset(buf, 0), 'h' as libc::c_char); assert_eq!(*ptr::offset(buf, 0), 'h' as libc::c_char);
assert_eq!(*ptr::offset(buf, 1), 'e' as libc::c_char); assert_eq!(*ptr::offset(buf, 1), 'e' as libc::c_char);
@ -416,19 +414,19 @@ mod tests {
assert_eq!(*ptr::offset(buf, 4), 'o' as libc::c_char); assert_eq!(*ptr::offset(buf, 4), 'o' as libc::c_char);
assert_eq!(*ptr::offset(buf, 5), 0); assert_eq!(*ptr::offset(buf, 5), 0);
} }
} })
} }
#[test] #[test]
fn test_vec_to_c_str() { fn test_vec_to_c_str() {
let b: &[u8] = []; let b: &[u8] = [];
do b.to_c_str().with_ref |buf| { b.to_c_str().with_ref(|buf| {
unsafe { unsafe {
assert_eq!(*ptr::offset(buf, 0), 0); assert_eq!(*ptr::offset(buf, 0), 0);
} }
} });
do bytes!("hello").to_c_str().with_ref |buf| { let _ = bytes!("hello").to_c_str().with_ref(|buf| {
unsafe { unsafe {
assert_eq!(*ptr::offset(buf, 0), 'h' as libc::c_char); assert_eq!(*ptr::offset(buf, 0), 'h' as libc::c_char);
assert_eq!(*ptr::offset(buf, 1), 'e' as libc::c_char); assert_eq!(*ptr::offset(buf, 1), 'e' as libc::c_char);
@ -437,9 +435,9 @@ mod tests {
assert_eq!(*ptr::offset(buf, 4), 'o' as libc::c_char); assert_eq!(*ptr::offset(buf, 4), 'o' as libc::c_char);
assert_eq!(*ptr::offset(buf, 5), 0); assert_eq!(*ptr::offset(buf, 5), 0);
} }
} });
do bytes!("foo", 0xff).to_c_str().with_ref |buf| { let _ = bytes!("foo", 0xff).to_c_str().with_ref(|buf| {
unsafe { unsafe {
assert_eq!(*ptr::offset(buf, 0), 'f' as libc::c_char); assert_eq!(*ptr::offset(buf, 0), 'f' as libc::c_char);
assert_eq!(*ptr::offset(buf, 1), 'o' as libc::c_char); assert_eq!(*ptr::offset(buf, 1), 'o' as libc::c_char);
@ -447,7 +445,7 @@ mod tests {
assert_eq!(*ptr::offset(buf, 3), 0xff); assert_eq!(*ptr::offset(buf, 3), 0xff);
assert_eq!(*ptr::offset(buf, 4), 0); assert_eq!(*ptr::offset(buf, 4), 0);
} }
} });
} }
#[test] #[test]
@ -500,18 +498,16 @@ mod tests {
use c_str::null_byte::cond; use c_str::null_byte::cond;
let mut error_happened = false; let mut error_happened = false;
do cond.trap(|err| { cond.trap(|err| {
assert_eq!(err, bytes!("he", 0, "llo").to_owned()) assert_eq!(err, bytes!("he", 0, "llo").to_owned())
error_happened = true; error_happened = true;
Truncate Truncate
}).inside { }).inside(|| "he\x00llo".to_c_str());
"he\x00llo".to_c_str()
};
assert!(error_happened); assert!(error_happened);
do cond.trap(|_| { cond.trap(|_| {
ReplaceWith('?' as libc::c_char) ReplaceWith('?' as libc::c_char)
}).inside(|| "he\x00llo".to_c_str()).with_ref |buf| { }).inside(|| "he\x00llo".to_c_str()).with_ref(|buf| {
unsafe { unsafe {
assert_eq!(*buf.offset(0), 'h' as libc::c_char); assert_eq!(*buf.offset(0), 'h' as libc::c_char);
assert_eq!(*buf.offset(1), 'e' as libc::c_char); assert_eq!(*buf.offset(1), 'e' as libc::c_char);
@ -521,13 +517,13 @@ mod tests {
assert_eq!(*buf.offset(5), 'o' as libc::c_char); assert_eq!(*buf.offset(5), 'o' as libc::c_char);
assert_eq!(*buf.offset(6), 0); assert_eq!(*buf.offset(6), 0);
} }
} })
} }
#[test] #[test]
fn test_to_c_str_unchecked() { fn test_to_c_str_unchecked() {
unsafe { unsafe {
do "he\x00llo".to_c_str_unchecked().with_ref |buf| { "he\x00llo".to_c_str_unchecked().with_ref(|buf| {
assert_eq!(*buf.offset(0), 'h' as libc::c_char); assert_eq!(*buf.offset(0), 'h' as libc::c_char);
assert_eq!(*buf.offset(1), 'e' as libc::c_char); assert_eq!(*buf.offset(1), 'e' as libc::c_char);
assert_eq!(*buf.offset(2), 0); assert_eq!(*buf.offset(2), 0);
@ -535,7 +531,7 @@ mod tests {
assert_eq!(*buf.offset(4), 'l' as libc::c_char); assert_eq!(*buf.offset(4), 'l' as libc::c_char);
assert_eq!(*buf.offset(5), 'o' as libc::c_char); assert_eq!(*buf.offset(5), 'o' as libc::c_char);
assert_eq!(*buf.offset(6), 0); assert_eq!(*buf.offset(6), 0);
} })
} }
} }
@ -579,7 +575,7 @@ mod bench {
#[inline] #[inline]
fn check(s: &str, c_str: *libc::c_char) { fn check(s: &str, c_str: *libc::c_char) {
do s.as_imm_buf |s_buf, s_len| { s.as_imm_buf(|s_buf, s_len| {
for i in range(0, s_len) { for i in range(0, s_len) {
unsafe { unsafe {
assert_eq!( assert_eq!(
@ -587,7 +583,7 @@ mod bench {
*ptr::offset(c_str, i as int)); *ptr::offset(c_str, i as int));
} }
} }
} })
} }
static s_short: &'static str = "Mary"; static s_short: &'static str = "Mary";
@ -601,12 +597,10 @@ mod bench {
Mary had a little lamb, Little lamb"; Mary had a little lamb, Little lamb";
fn bench_to_str(bh: &mut BenchHarness, s: &str) { fn bench_to_str(bh: &mut BenchHarness, s: &str) {
do bh.iter { bh.iter(|| {
let c_str = s.to_c_str(); let c_str = s.to_c_str();
do c_str.with_ref |c_str_buf| { c_str.with_ref(|c_str_buf| check(s, c_str_buf))
check(s, c_str_buf) })
}
}
} }
#[bench] #[bench]
@ -625,12 +619,10 @@ mod bench {
} }
fn bench_to_c_str_unchecked(bh: &mut BenchHarness, s: &str) { fn bench_to_c_str_unchecked(bh: &mut BenchHarness, s: &str) {
do bh.iter { bh.iter(|| {
let c_str = unsafe { s.to_c_str_unchecked() }; let c_str = unsafe { s.to_c_str_unchecked() };
do c_str.with_ref |c_str_buf| { c_str.with_ref(|c_str_buf| check(s, c_str_buf))
check(s, c_str_buf) })
}
}
} }
#[bench] #[bench]
@ -649,11 +641,9 @@ mod bench {
} }
fn bench_with_c_str(bh: &mut BenchHarness, s: &str) { fn bench_with_c_str(bh: &mut BenchHarness, s: &str) {
do bh.iter { bh.iter(|| {
do s.with_c_str |c_str_buf| { s.with_c_str(|c_str_buf| check(s, c_str_buf))
check(s, c_str_buf) })
}
}
} }
#[bench] #[bench]
@ -672,13 +662,11 @@ mod bench {
} }
fn bench_with_c_str_unchecked(bh: &mut BenchHarness, s: &str) { fn bench_with_c_str_unchecked(bh: &mut BenchHarness, s: &str) {
do bh.iter { bh.iter(|| {
unsafe { unsafe {
do s.with_c_str_unchecked |c_str_buf| { s.with_c_str_unchecked(|c_str_buf| check(s, c_str_buf))
check(s, c_str_buf)
}
} }
} })
} }
#[bench] #[bench]

View file

@ -82,6 +82,7 @@ pub struct RefCell<T> {
priv nc: NonCopyable priv nc: NonCopyable
} }
<<<<<<< HEAD
// Values [1, MAX-1] represent the number of `Ref` active // Values [1, MAX-1] represent the number of `Ref` active
// (will not outgrow its range since `uint` is the size of the address space) // (will not outgrow its range since `uint` is the size of the address space)
type BorrowFlag = uint; type BorrowFlag = uint;

View file

@ -82,7 +82,7 @@ pub unsafe fn annihilate() {
// //
// In this pass, nothing gets freed, so it does not matter whether // In this pass, nothing gets freed, so it does not matter whether
// we read the next field before or after the callback. // we read the next field before or after the callback.
do each_live_alloc(true) |box, uniq| { each_live_alloc(true, |box, uniq| {
stats.n_total_boxes += 1; stats.n_total_boxes += 1;
if uniq { if uniq {
stats.n_unique_boxes += 1; stats.n_unique_boxes += 1;
@ -90,21 +90,21 @@ pub unsafe fn annihilate() {
(*box).ref_count = managed::RC_IMMORTAL; (*box).ref_count = managed::RC_IMMORTAL;
} }
true true
}; });
// Pass 2: Drop all boxes. // Pass 2: Drop all boxes.
// //
// In this pass, unique-managed boxes may get freed, but not // In this pass, unique-managed boxes may get freed, but not
// managed boxes, so we must read the `next` field *after* the // managed boxes, so we must read the `next` field *after* the
// callback, as the original value may have been freed. // callback, as the original value may have been freed.
do each_live_alloc(false) |box, uniq| { each_live_alloc(false, |box, uniq| {
if !uniq { if !uniq {
let tydesc = (*box).type_desc; let tydesc = (*box).type_desc;
let data = &(*box).data as *(); let data = &(*box).data as *();
((*tydesc).drop_glue)(data as *i8); ((*tydesc).drop_glue)(data as *i8);
} }
true true
}; });
// Pass 3: Free all boxes. // Pass 3: Free all boxes.
// //
@ -112,7 +112,7 @@ pub unsafe fn annihilate() {
// unique-managed boxes, though I think that none of those are // unique-managed boxes, though I think that none of those are
// left), so we must read the `next` field before, since it will // left), so we must read the `next` field before, since it will
// not be valid after. // not be valid after.
do each_live_alloc(true) |box, uniq| { each_live_alloc(true, |box, uniq| {
if !uniq { if !uniq {
stats.n_bytes_freed += stats.n_bytes_freed +=
(*((*box).type_desc)).size (*((*box).type_desc)).size
@ -120,7 +120,7 @@ pub unsafe fn annihilate() {
local_free(box as *i8); local_free(box as *i8);
} }
true true
}; });
if debug_mem() { if debug_mem() {
// We do logging here w/o allocation. // We do logging here w/o allocation.

View file

@ -209,23 +209,23 @@ pub type Rights<L, R, Iter> = FilterMap<'static, Either<L, R>, R, Iter>;
/// Extracts all the left values /// Extracts all the left values
pub fn lefts<L, R, Iter: Iterator<Either<L, R>>>(eithers: Iter) pub fn lefts<L, R, Iter: Iterator<Either<L, R>>>(eithers: Iter)
-> Lefts<L, R, Iter> { -> Lefts<L, R, Iter> {
do eithers.filter_map |elt| { eithers.filter_map(|elt| {
match elt { match elt {
Left(x) => Some(x), Left(x) => Some(x),
_ => None, _ => None,
} }
} })
} }
/// Extracts all the right values /// Extracts all the right values
pub fn rights<L, R, Iter: Iterator<Either<L, R>>>(eithers: Iter) pub fn rights<L, R, Iter: Iterator<Either<L, R>>>(eithers: Iter)
-> Rights<L, R, Iter> { -> Rights<L, R, Iter> {
do eithers.filter_map |elt| { eithers.filter_map(|elt| {
match elt { match elt {
Right(x) => Some(x), Right(x) => Some(x),
_ => None, _ => None,
} }
} })
} }

View file

@ -801,12 +801,12 @@ impl<'self> Formatter<'self> {
} }
fn runplural(&mut self, value: uint, pieces: &[rt::Piece]) { fn runplural(&mut self, value: uint, pieces: &[rt::Piece]) {
do ::uint::to_str_bytes(value, 10) |buf| { ::uint::to_str_bytes(value, 10, |buf| {
let valuestr = str::from_utf8_slice(buf); let valuestr = str::from_utf8_slice(buf);
for piece in pieces.iter() { for piece in pieces.iter() {
self.run(piece, Some(valuestr)); self.run(piece, Some(valuestr));
} }
} })
} }
// Helper methods used for padding and processing formatting arguments that // Helper methods used for padding and processing formatting arguments that
@ -868,9 +868,9 @@ impl<'self> Formatter<'self> {
self.fill = '0'; self.fill = '0';
sign(self); sign(self);
} }
do self.with_padding(min - actual_len, parse::AlignRight) |me| { self.with_padding(min - actual_len, parse::AlignRight, |me| {
emit(me); emit(me);
} })
} }
} }
} }
@ -924,9 +924,9 @@ impl<'self> Formatter<'self> {
// If we're under both the maximum and the minimum width, then fill // If we're under both the maximum and the minimum width, then fill
// up the minimum width with the specified string + some alignment. // up the minimum width with the specified string + some alignment.
Some(width) => { Some(width) => {
do self.with_padding(width - s.len(), parse::AlignLeft) |me| { self.with_padding(width - s.len(), parse::AlignLeft, |me| {
me.buf.write(s.as_bytes()); me.buf.write(s.as_bytes());
} })
} }
} }
} }
@ -1007,18 +1007,18 @@ macro_rules! int_base(($ty:ident, $into:ident, $base:expr,
$name:ident, $prefix:expr) => { $name:ident, $prefix:expr) => {
impl $name for $ty { impl $name for $ty {
fn fmt(c: &$ty, f: &mut Formatter) { fn fmt(c: &$ty, f: &mut Formatter) {
do ::$into::to_str_bytes(*c as $into, $base) |buf| { ::$into::to_str_bytes(*c as $into, $base, |buf| {
f.pad_integral(buf, $prefix, true); f.pad_integral(buf, $prefix, true);
} })
} }
} }
}) })
macro_rules! upper_hex(($ty:ident, $into:ident) => { macro_rules! upper_hex(($ty:ident, $into:ident) => {
impl UpperHex for $ty { impl UpperHex for $ty {
fn fmt(c: &$ty, f: &mut Formatter) { fn fmt(c: &$ty, f: &mut Formatter) {
do ::$into::to_str_bytes(*c as $into, 16) |buf| { ::$into::to_str_bytes(*c as $into, 16, |buf| {
upperhex(buf, f); upperhex(buf, f);
} })
} }
} }
}) })
@ -1045,9 +1045,9 @@ macro_rules! integer(($signed:ident, $unsigned:ident) => {
// nothing else should do that, however. // nothing else should do that, however.
impl Signed for $signed { impl Signed for $signed {
fn fmt(c: &$signed, f: &mut Formatter) { fn fmt(c: &$signed, f: &mut Formatter) {
do ::$unsigned::to_str_bytes(c.abs() as $unsigned, 10) |buf| { ::$unsigned::to_str_bytes(c.abs() as $unsigned, 10, |buf| {
f.pad_integral(buf, "", *c >= 0); f.pad_integral(buf, "", *c >= 0);
} })
} }
} }
int_base!($signed, $unsigned, 2, Binary, "0b") int_base!($signed, $unsigned, 2, Binary, "0b")
@ -1104,9 +1104,9 @@ impl<T> Poly for T {
impl<T> Pointer for *T { impl<T> Pointer for *T {
fn fmt(t: &*T, f: &mut Formatter) { fn fmt(t: &*T, f: &mut Formatter) {
f.flags |= 1 << (parse::FlagAlternate as uint); f.flags |= 1 << (parse::FlagAlternate as uint);
do ::uint::to_str_bytes(*t as uint, 16) |buf| { ::uint::to_str_bytes(*t as uint, 16, |buf| {
f.pad_integral(buf, "0x", true); f.pad_integral(buf, "0x", true);
} })
} }
} }
impl<T> Pointer for *mut T { impl<T> Pointer for *mut T {

View file

@ -83,10 +83,10 @@ impl<A:IterBytes> Hash for A {
#[inline] #[inline]
fn hash_keyed(&self, k0: u64, k1: u64) -> u64 { fn hash_keyed(&self, k0: u64, k1: u64) -> u64 {
let mut s = State::new(k0, k1); let mut s = State::new(k0, k1);
do self.iter_bytes(true) |bytes| { self.iter_bytes(true, |bytes| {
s.input(bytes); s.input(bytes);
true true
}; });
s.result_u64() s.result_u64()
} }
} }
@ -94,14 +94,14 @@ impl<A:IterBytes> Hash for A {
fn hash_keyed_2<A: IterBytes, fn hash_keyed_2<A: IterBytes,
B: IterBytes>(a: &A, b: &B, k0: u64, k1: u64) -> u64 { B: IterBytes>(a: &A, b: &B, k0: u64, k1: u64) -> u64 {
let mut s = State::new(k0, k1); let mut s = State::new(k0, k1);
do a.iter_bytes(true) |bytes| { a.iter_bytes(true, |bytes| {
s.input(bytes); s.input(bytes);
true true
}; });
do b.iter_bytes(true) |bytes| { b.iter_bytes(true, |bytes| {
s.input(bytes); s.input(bytes);
true true
}; });
s.result_u64() s.result_u64()
} }
@ -109,18 +109,18 @@ fn hash_keyed_3<A: IterBytes,
B: IterBytes, B: IterBytes,
C: IterBytes>(a: &A, b: &B, c: &C, k0: u64, k1: u64) -> u64 { C: IterBytes>(a: &A, b: &B, c: &C, k0: u64, k1: u64) -> u64 {
let mut s = State::new(k0, k1); let mut s = State::new(k0, k1);
do a.iter_bytes(true) |bytes| { a.iter_bytes(true, |bytes| {
s.input(bytes); s.input(bytes);
true true
}; });
do b.iter_bytes(true) |bytes| { b.iter_bytes(true, |bytes| {
s.input(bytes); s.input(bytes);
true true
}; });
do c.iter_bytes(true) |bytes| { c.iter_bytes(true, |bytes| {
s.input(bytes); s.input(bytes);
true true
}; });
s.result_u64() s.result_u64()
} }
@ -136,22 +136,22 @@ fn hash_keyed_4<A: IterBytes,
k1: u64) k1: u64)
-> u64 { -> u64 {
let mut s = State::new(k0, k1); let mut s = State::new(k0, k1);
do a.iter_bytes(true) |bytes| { a.iter_bytes(true, |bytes| {
s.input(bytes); s.input(bytes);
true true
}; });
do b.iter_bytes(true) |bytes| { b.iter_bytes(true, |bytes| {
s.input(bytes); s.input(bytes);
true true
}; });
do c.iter_bytes(true) |bytes| { c.iter_bytes(true, |bytes| {
s.input(bytes); s.input(bytes);
true true
}; });
do d.iter_bytes(true) |bytes| { d.iter_bytes(true, |bytes| {
s.input(bytes); s.input(bytes);
true true
}; });
s.result_u64() s.result_u64()
} }
@ -169,26 +169,26 @@ fn hash_keyed_5<A: IterBytes,
k1: u64) k1: u64)
-> u64 { -> u64 {
let mut s = State::new(k0, k1); let mut s = State::new(k0, k1);
do a.iter_bytes(true) |bytes| { a.iter_bytes(true, |bytes| {
s.input(bytes); s.input(bytes);
true true
}; });
do b.iter_bytes(true) |bytes| { b.iter_bytes(true, |bytes| {
s.input(bytes); s.input(bytes);
true true
}; });
do c.iter_bytes(true) |bytes| { c.iter_bytes(true, |bytes| {
s.input(bytes); s.input(bytes);
true true
}; });
do d.iter_bytes(true) |bytes| { d.iter_bytes(true, |bytes| {
s.input(bytes); s.input(bytes);
true true
}; });
do e.iter_bytes(true) |bytes| { e.iter_bytes(true, |bytes| {
s.input(bytes); s.input(bytes);
true true
}; });
s.result_u64() s.result_u64()
} }

View file

@ -110,7 +110,7 @@ impl<K:Hash + Eq,V> HashMap<K, V> {
k: &K) k: &K)
-> SearchResult { -> SearchResult {
let mut ret = TableFull; let mut ret = TableFull;
do self.bucket_sequence(hash) |i| { self.bucket_sequence(hash, |i| {
match self.buckets[i] { match self.buckets[i] {
Some(ref bkt) if bkt.hash == hash && *k == bkt.key => { Some(ref bkt) if bkt.hash == hash && *k == bkt.key => {
ret = FoundEntry(i); false ret = FoundEntry(i); false
@ -118,7 +118,7 @@ impl<K:Hash + Eq,V> HashMap<K, V> {
None => { ret = FoundHole(i); false } None => { ret = FoundHole(i); false }
_ => true, _ => true,
} }
}; });
ret ret
} }
@ -128,7 +128,7 @@ impl<K:Hash + Eq,V> HashMap<K, V> {
k: &Q) k: &Q)
-> SearchResult { -> SearchResult {
let mut ret = TableFull; let mut ret = TableFull;
do self.bucket_sequence(hash) |i| { self.bucket_sequence(hash, |i| {
match self.buckets[i] { match self.buckets[i] {
Some(ref bkt) if bkt.hash == hash && k.equiv(&bkt.key) => { Some(ref bkt) if bkt.hash == hash && k.equiv(&bkt.key) => {
ret = FoundEntry(i); false ret = FoundEntry(i); false
@ -136,7 +136,7 @@ impl<K:Hash + Eq,V> HashMap<K, V> {
None => { ret = FoundHole(i); false } None => { ret = FoundHole(i); false }
_ => true, _ => true,
} }
}; });
ret ret
} }
@ -236,9 +236,7 @@ impl<K:Hash + Eq,V> HashMap<K, V> {
let len_buckets = self.buckets.len(); let len_buckets = self.buckets.len();
let bucket = self.buckets[idx].take(); let bucket = self.buckets[idx].take();
let value = do bucket.map |bucket| { let value = bucket.map(|bucket| bucket.value);
bucket.value
};
/* re-inserting buckets may cause changes in size, so remember /* re-inserting buckets may cause changes in size, so remember
what our new size is ahead of time before we start insertions */ what our new size is ahead of time before we start insertions */
@ -500,12 +498,12 @@ impl<K:Hash + Eq,V:Eq> Eq for HashMap<K, V> {
fn eq(&self, other: &HashMap<K, V>) -> bool { fn eq(&self, other: &HashMap<K, V>) -> bool {
if self.len() != other.len() { return false; } if self.len() != other.len() { return false; }
do self.iter().all |(key, value)| { self.iter().all(|(key, value)| {
match other.find(key) { match other.find(key) {
None => false, None => false,
Some(v) => value == v Some(v) => value == v
} }
} })
} }
fn ne(&self, other: &HashMap<K, V>) -> bool { !self.eq(other) } fn ne(&self, other: &HashMap<K, V>) -> bool { !self.eq(other) }

View file

@ -76,7 +76,7 @@ pub struct File {
} }
fn io_raise<T>(f: |io: &mut IoFactory| -> Result<T, IoError>) -> Option<T> { fn io_raise<T>(f: |io: &mut IoFactory| -> Result<T, IoError>) -> Option<T> {
do with_local_io |io| { with_local_io(|io| {
match f(io) { match f(io) {
Ok(t) => Some(t), Ok(t) => Some(t),
Err(ioerr) => { Err(ioerr) => {
@ -84,7 +84,7 @@ fn io_raise<T>(f: |io: &mut IoFactory| -> Result<T, IoError>) -> Option<T> {
None None
} }
} }
} })
} }
impl File { impl File {
@ -97,9 +97,9 @@ impl File {
/// ///
/// let p = Path::new("/some/file/path.txt"); /// let p = Path::new("/some/file/path.txt");
/// ///
/// do io_error::cond.trap(|_| { /// io_error::cond.trap(|_| {
/// // hoo-boy... /// // hoo-boy...
/// }).inside { /// }).inside(|| {
/// let file = match File::open_mode(&p, Open, ReadWrite) { /// let file = match File::open_mode(&p, Open, ReadWrite) {
/// Some(s) => s, /// Some(s) => s,
/// None => fail!("whoops! I'm sure this raised, anyways..") /// None => fail!("whoops! I'm sure this raised, anyways..")
@ -107,7 +107,7 @@ impl File {
/// // do some stuff with that file /// // do some stuff with that file
/// ///
/// // the file will be closed at the end of this block /// // the file will be closed at the end of this block
/// } /// })
/// // .. /// // ..
/// ///
/// `FileMode` and `FileAccess` provide information about the permissions /// `FileMode` and `FileAccess` provide information about the permissions
@ -132,7 +132,7 @@ impl File {
pub fn open_mode(path: &Path, pub fn open_mode(path: &Path,
mode: FileMode, mode: FileMode,
access: FileAccess) -> Option<File> { access: FileAccess) -> Option<File> {
do with_local_io |io| { with_local_io(|io| {
match io.fs_open(&path.to_c_str(), mode, access) { match io.fs_open(&path.to_c_str(), mode, access) {
Ok(fd) => Some(File { Ok(fd) => Some(File {
path: path.clone(), path: path.clone(),
@ -144,7 +144,7 @@ impl File {
None None
} }
} }
} })
} }
/// Attempts to open a file in read-only mode. This function is equivalent to /// Attempts to open a file in read-only mode. This function is equivalent to
@ -244,7 +244,7 @@ impl File {
/// directory, the user lacks permissions to remove the file, or if some /// directory, the user lacks permissions to remove the file, or if some
/// other filesystem-level error occurs. /// other filesystem-level error occurs.
pub fn unlink(path: &Path) { pub fn unlink(path: &Path) {
do io_raise |io| { io.fs_unlink(&path.to_c_str()) }; io_raise(|io| io.fs_unlink(&path.to_c_str()));
} }
/// Given a path, query the file system to get information about a file, /// Given a path, query the file system to get information about a file,
@ -272,9 +272,7 @@ pub fn unlink(path: &Path) {
/// requisite permissions to perform a `stat` call on the given path or if /// requisite permissions to perform a `stat` call on the given path or if
/// there is no entry in the filesystem at the provided path. /// there is no entry in the filesystem at the provided path.
pub fn stat(path: &Path) -> FileStat { pub fn stat(path: &Path) -> FileStat {
do io_raise |io| { io_raise(|io| io.fs_stat(&path.to_c_str())).unwrap_or_else(dummystat)
io.fs_stat(&path.to_c_str())
}.unwrap_or_else(dummystat)
} }
fn dummystat() -> FileStat { fn dummystat() -> FileStat {
@ -310,9 +308,7 @@ fn dummystat() -> FileStat {
/// ///
/// See `stat` /// See `stat`
pub fn lstat(path: &Path) -> FileStat { pub fn lstat(path: &Path) -> FileStat {
do io_raise |io| { io_raise(|io| io.fs_lstat(&path.to_c_str())).unwrap_or_else(dummystat)
io.fs_lstat(&path.to_c_str())
}.unwrap_or_else(dummystat)
} }
/// Rename a file or directory to a new name. /// Rename a file or directory to a new name.
@ -330,9 +326,7 @@ pub fn lstat(path: &Path) -> FileStat {
/// the process lacks permissions to view the contents, or if some other /// the process lacks permissions to view the contents, or if some other
/// intermittent I/O error occurs. /// intermittent I/O error occurs.
pub fn rename(from: &Path, to: &Path) { pub fn rename(from: &Path, to: &Path) {
do io_raise |io| { io_raise(|io| io.fs_rename(&from.to_c_str(), &to.to_c_str()));
io.fs_rename(&from.to_c_str(), &to.to_c_str())
};
} }
/// Copies the contents of one file to another. This function will also /// Copies the contents of one file to another. This function will also
@ -403,9 +397,7 @@ pub fn copy(from: &Path, to: &Path) {
/// condition. Some possible error situations are not having the permission to /// condition. Some possible error situations are not having the permission to
/// change the attributes of a file or the file not existing. /// change the attributes of a file or the file not existing.
pub fn chmod(path: &Path, mode: io::FilePermission) { pub fn chmod(path: &Path, mode: io::FilePermission) {
do io_raise |io| { io_raise(|io| io.fs_chmod(&path.to_c_str(), mode));
io.fs_chmod(&path.to_c_str(), mode)
};
} }
/// Change the user and group owners of a file at the specified path. /// Change the user and group owners of a file at the specified path.
@ -414,7 +406,7 @@ pub fn chmod(path: &Path, mode: io::FilePermission) {
/// ///
/// This funtion will raise on the `io_error` condition on failure. /// This funtion will raise on the `io_error` condition on failure.
pub fn chown(path: &Path, uid: int, gid: int) { pub fn chown(path: &Path, uid: int, gid: int) {
do io_raise |io| { io.fs_chown(&path.to_c_str(), uid, gid) }; io_raise(|io| io.fs_chown(&path.to_c_str(), uid, gid));
} }
/// Creates a new hard link on the filesystem. The `dst` path will be a /// Creates a new hard link on the filesystem. The `dst` path will be a
@ -425,7 +417,7 @@ pub fn chown(path: &Path, uid: int, gid: int) {
/// ///
/// This function will raise on the `io_error` condition on failure. /// This function will raise on the `io_error` condition on failure.
pub fn link(src: &Path, dst: &Path) { pub fn link(src: &Path, dst: &Path) {
do io_raise |io| { io.fs_link(&src.to_c_str(), &dst.to_c_str()) }; io_raise(|io| io.fs_link(&src.to_c_str(), &dst.to_c_str()));
} }
/// Creates a new symbolic link on the filesystem. The `dst` path will be a /// Creates a new symbolic link on the filesystem. The `dst` path will be a
@ -435,7 +427,7 @@ pub fn link(src: &Path, dst: &Path) {
/// ///
/// This function will raise on the `io_error` condition on failure. /// This function will raise on the `io_error` condition on failure.
pub fn symlink(src: &Path, dst: &Path) { pub fn symlink(src: &Path, dst: &Path) {
do io_raise |io| { io.fs_symlink(&src.to_c_str(), &dst.to_c_str()) }; io_raise(|io| io.fs_symlink(&src.to_c_str(), &dst.to_c_str()));
} }
/// Reads a symlink, returning the file that the symlink points to. /// Reads a symlink, returning the file that the symlink points to.
@ -446,7 +438,7 @@ pub fn symlink(src: &Path, dst: &Path) {
/// conditions include reading a file that does not exist or reading a file /// conditions include reading a file that does not exist or reading a file
/// which is not a symlink. /// which is not a symlink.
pub fn readlink(path: &Path) -> Option<Path> { pub fn readlink(path: &Path) -> Option<Path> {
do io_raise |io| { io.fs_readlink(&path.to_c_str()) } io_raise(|io| io.fs_readlink(&path.to_c_str()))
} }
/// Create a new, empty directory at the provided path /// Create a new, empty directory at the provided path
@ -466,9 +458,7 @@ pub fn readlink(path: &Path) -> Option<Path> {
/// to make a new directory at the provided path, or if the directory already /// to make a new directory at the provided path, or if the directory already
/// exists. /// exists.
pub fn mkdir(path: &Path, mode: FilePermission) { pub fn mkdir(path: &Path, mode: FilePermission) {
do io_raise |io| { io_raise(|io| io.fs_mkdir(&path.to_c_str(), mode));
io.fs_mkdir(&path.to_c_str(), mode)
};
} }
/// Remove an existing, empty directory /// Remove an existing, empty directory
@ -487,9 +477,7 @@ pub fn mkdir(path: &Path, mode: FilePermission) {
/// to remove the directory at the provided path, or if the directory isn't /// to remove the directory at the provided path, or if the directory isn't
/// empty. /// empty.
pub fn rmdir(path: &Path) { pub fn rmdir(path: &Path) {
do io_raise |io| { io_raise(|io| io.fs_rmdir(&path.to_c_str()));
io.fs_rmdir(&path.to_c_str())
};
} }
/// Retrieve a vector containing all entries within a provided directory /// Retrieve a vector containing all entries within a provided directory
@ -516,9 +504,7 @@ pub fn rmdir(path: &Path) {
/// the process lacks permissions to view the contents or if the `path` points /// the process lacks permissions to view the contents or if the `path` points
/// at a non-directory file /// at a non-directory file
pub fn readdir(path: &Path) -> ~[Path] { pub fn readdir(path: &Path) -> ~[Path] {
do io_raise |io| { io_raise(|io| io.fs_readdir(&path.to_c_str(), 0)).unwrap_or_else(|| ~[])
io.fs_readdir(&path.to_c_str(), 0)
}.unwrap_or_else(|| ~[])
} }
/// Returns an iterator which will recursively walk the directory structure /// Returns an iterator which will recursively walk the directory structure
@ -599,9 +585,7 @@ pub fn rmdir_recursive(path: &Path) {
/// happens. /// happens.
// FIXME(#10301) these arguments should not be u64 // FIXME(#10301) these arguments should not be u64
pub fn change_file_times(path: &Path, atime: u64, mtime: u64) { pub fn change_file_times(path: &Path, atime: u64, mtime: u64) {
do io_raise |io| { io_raise(|io| io.fs_utime(&path.to_c_str(), atime, mtime));
io.fs_utime(&path.to_c_str(), atime, mtime)
};
} }
impl Reader for File { impl Reader for File {
@ -797,12 +781,12 @@ mod test {
let tmpdir = tmpdir(); let tmpdir = tmpdir();
let filename = &tmpdir.join("file_that_does_not_exist.txt"); let filename = &tmpdir.join("file_that_does_not_exist.txt");
let mut called = false; let mut called = false;
do io_error::cond.trap(|_| { io_error::cond.trap(|_| {
called = true; called = true;
}).inside { }).inside(|| {
let result = File::open_mode(filename, Open, Read); let result = File::open_mode(filename, Open, Read);
assert!(result.is_none()); assert!(result.is_none());
} });
assert!(called); assert!(called);
}) })
@ -810,11 +794,9 @@ mod test {
let tmpdir = tmpdir(); let tmpdir = tmpdir();
let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt"); let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
let mut called = false; let mut called = false;
do io_error::cond.trap(|_| { io_error::cond.trap(|_| {
called = true; called = true;
}).inside { }).inside(|| unlink(filename));
unlink(filename);
}
assert!(called); assert!(called);
}) })

View file

@ -40,9 +40,9 @@ Some examples of obvious things you might want to do
* Iterate over the lines of a file * Iterate over the lines of a file
do File::open("message.txt").each_line |line| { File::open("message.txt").each_line(|line| {
println(line) println(line)
} })
* Pull the lines of a file into a vector of strings * Pull the lines of a file into a vector of strings
@ -395,13 +395,11 @@ condition! {
/// Helper for wrapper calls where you want to /// Helper for wrapper calls where you want to
/// ignore any io_errors that might be raised /// ignore any io_errors that might be raised
pub fn ignore_io_error<T>(cb: || -> T) -> T { pub fn ignore_io_error<T>(cb: || -> T) -> T {
do io_error::cond.trap(|_| { io_error::cond.trap(|_| {
// just swallow the error.. downstream users // just swallow the error.. downstream users
// who can make a decision based on a None result // who can make a decision based on a None result
// won't care // won't care
}).inside { }).inside(|| cb())
cb()
}
} }
/// Helper for catching an I/O error and wrapping it in a Result object. The /// Helper for catching an I/O error and wrapping it in a Result object. The
@ -501,7 +499,7 @@ pub trait Reader {
buf.reserve_additional(len); buf.reserve_additional(len);
vec::raw::set_len(buf, start_len + len); vec::raw::set_len(buf, start_len + len);
do (|| { (|| {
while total_read < len { while total_read < len {
let len = buf.len(); let len = buf.len();
let slice = buf.mut_slice(start_len + total_read, len); let slice = buf.mut_slice(start_len + total_read, len);
@ -515,9 +513,7 @@ pub trait Reader {
} }
} }
} }
}).finally { }).finally(|| vec::raw::set_len(buf, start_len + total_read))
vec::raw::set_len(buf, start_len + total_read);
}
} }
} }
@ -542,17 +538,17 @@ pub trait Reader {
fn read_to_end(&mut self) -> ~[u8] { fn read_to_end(&mut self) -> ~[u8] {
let mut buf = vec::with_capacity(DEFAULT_BUF_SIZE); let mut buf = vec::with_capacity(DEFAULT_BUF_SIZE);
let mut keep_reading = true; let mut keep_reading = true;
do io_error::cond.trap(|e| { io_error::cond.trap(|e| {
if e.kind == EndOfFile { if e.kind == EndOfFile {
keep_reading = false; keep_reading = false;
} else { } else {
io_error::cond.raise(e) io_error::cond.raise(e)
} }
}).inside { }).inside(|| {
while keep_reading { while keep_reading {
self.push_bytes(&mut buf, DEFAULT_BUF_SIZE) self.push_bytes(&mut buf, DEFAULT_BUF_SIZE)
} }
} });
return buf; return buf;
} }

View file

@ -37,7 +37,7 @@ 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) = do data.as_imm_buf |data, amt| { (data, amt) }; let (data, origamt) = data.as_imm_buf(|data, amt| (data, amt));
let mut data = data; let mut data = data;
let mut amt = origamt; let mut amt = origamt;
while amt > 0 { while amt > 0 {
@ -83,11 +83,11 @@ impl FileDesc {
fn inner_read(&mut self, buf: &mut [u8]) -> Result<uint, IoError> { fn inner_read(&mut self, buf: &mut [u8]) -> Result<uint, IoError> {
#[cfg(windows)] type rlen = libc::c_uint; #[cfg(windows)] type rlen = libc::c_uint;
#[cfg(not(windows))] type rlen = libc::size_t; #[cfg(not(windows))] type rlen = libc::size_t;
let ret = do keep_going(buf) |buf, len| { let ret = keep_going(buf, |buf, len| {
unsafe { unsafe {
libc::read(self.fd, buf as *mut libc::c_void, len as rlen) as i64 libc::read(self.fd, buf as *mut libc::c_void, len as rlen) as i64
} }
}; });
if ret == 0 { if ret == 0 {
Err(io::standard_error(io::EndOfFile)) Err(io::standard_error(io::EndOfFile))
} else if ret < 0 { } else if ret < 0 {
@ -99,11 +99,11 @@ impl FileDesc {
fn inner_write(&mut self, buf: &[u8]) -> Result<(), IoError> { fn inner_write(&mut self, buf: &[u8]) -> Result<(), IoError> {
#[cfg(windows)] type wlen = libc::c_uint; #[cfg(windows)] type wlen = libc::c_uint;
#[cfg(not(windows))] type wlen = libc::size_t; #[cfg(not(windows))] type wlen = libc::size_t;
let ret = do keep_going(buf) |buf, len| { let ret = keep_going(buf, |buf, len| {
unsafe { unsafe {
libc::write(self.fd, buf as *libc::c_void, len as wlen) as i64 libc::write(self.fd, buf as *libc::c_void, len as wlen) as i64
} }
}; });
if ret < 0 { if ret < 0 {
Err(super::last_error()) Err(super::last_error())
} else { } else {
@ -344,12 +344,12 @@ impl CFile {
impl rtio::RtioFileStream for CFile { impl rtio::RtioFileStream for CFile {
fn read(&mut self, buf: &mut [u8]) -> Result<int, IoError> { fn read(&mut self, buf: &mut [u8]) -> Result<int, IoError> {
let ret = do keep_going(buf) |buf, len| { let ret = keep_going(buf, |buf, len| {
unsafe { unsafe {
libc::fread(buf as *mut libc::c_void, 1, len as libc::size_t, libc::fread(buf as *mut libc::c_void, 1, len as libc::size_t,
self.file) as i64 self.file) as i64
} }
}; });
if ret == 0 { if ret == 0 {
Err(io::standard_error(io::EndOfFile)) Err(io::standard_error(io::EndOfFile))
} else if ret < 0 { } else if ret < 0 {
@ -360,12 +360,12 @@ impl rtio::RtioFileStream for CFile {
} }
fn write(&mut self, buf: &[u8]) -> Result<(), IoError> { fn write(&mut self, buf: &[u8]) -> Result<(), IoError> {
let ret = do keep_going(buf) |buf, len| { let ret = keep_going(buf, |buf, len| {
unsafe { unsafe {
libc::fwrite(buf as *libc::c_void, 1, len as libc::size_t, libc::fwrite(buf as *libc::c_void, 1, len as libc::size_t,
self.file) as i64 self.file) as i64
} }
}; });
if ret < 0 { if ret < 0 {
Err(super::last_error()) Err(super::last_error())
} else { } else {
@ -445,9 +445,9 @@ pub fn open(path: &CString, fm: io::FileMode, fa: io::FileAccess)
#[cfg(windows)] #[cfg(windows)]
fn os_open(path: &CString, flags: c_int, mode: c_int) -> c_int { fn os_open(path: &CString, flags: c_int, mode: c_int) -> c_int {
do as_utf16_p(path.as_str().unwrap()) |path| { as_utf16_p(path.as_str().unwrap(), |path| {
unsafe { libc::wopen(path, flags, mode) } unsafe { libc::wopen(path, flags, mode) }
} })
} }
#[cfg(unix)] #[cfg(unix)]
@ -463,9 +463,9 @@ pub fn mkdir(p: &CString, mode: io::FilePermission) -> IoResult<()> {
fn os_mkdir(p: &CString, _mode: c_int) -> IoResult<()> { fn os_mkdir(p: &CString, _mode: c_int) -> IoResult<()> {
super::mkerr_winbool(unsafe { super::mkerr_winbool(unsafe {
// FIXME: turn mode into something useful? #2623 // FIXME: turn mode into something useful? #2623
do as_utf16_p(p.as_str().unwrap()) |buf| { as_utf16_p(p.as_str().unwrap(), |buf| {
libc::CreateDirectoryW(buf, ptr::mut_null()) libc::CreateDirectoryW(buf, ptr::mut_null())
} })
}) })
} }
@ -497,9 +497,7 @@ pub fn readdir(p: &CString) -> IoResult<~[Path]> {
} }
debug!("os::list_dir -- BEFORE OPENDIR"); debug!("os::list_dir -- BEFORE OPENDIR");
let dir_ptr = do p.with_ref |buf| { let dir_ptr = p.with_ref(|buf| opendir(buf));
opendir(buf)
};
if (dir_ptr as uint != 0) { if (dir_ptr as uint != 0) {
let mut paths = ~[]; let mut paths = ~[];
@ -540,7 +538,7 @@ pub fn readdir(p: &CString) -> IoResult<~[Path]> {
let p = CString::new(p.with_ref(|p| p), false); let p = CString::new(p.with_ref(|p| p), false);
let p = Path::new(p); let p = Path::new(p);
let star = p.join("*"); let star = p.join("*");
do as_utf16_p(star.as_str().unwrap()) |path_ptr| { as_utf16_p(star.as_str().unwrap(), |path_ptr| {
let wfd_ptr = malloc_raw(rust_list_dir_wfd_size() as uint); let wfd_ptr = malloc_raw(rust_list_dir_wfd_size() as uint);
let find_handle = FindFirstFileW(path_ptr, wfd_ptr as HANDLE); let find_handle = FindFirstFileW(path_ptr, wfd_ptr as HANDLE);
if find_handle as libc::c_int != INVALID_HANDLE_VALUE { if find_handle as libc::c_int != INVALID_HANDLE_VALUE {
@ -565,7 +563,7 @@ pub fn readdir(p: &CString) -> IoResult<~[Path]> {
} else { } else {
Err(super::last_error()) Err(super::last_error())
} }
} })
} }
get_list(p).map(|paths| prune(p, paths)) get_list(p).map(|paths| prune(p, paths))
@ -578,9 +576,7 @@ pub fn unlink(p: &CString) -> IoResult<()> {
#[cfg(windows)] #[cfg(windows)]
fn os_unlink(p: &CString) -> IoResult<()> { fn os_unlink(p: &CString) -> IoResult<()> {
super::mkerr_winbool(unsafe { super::mkerr_winbool(unsafe {
do as_utf16_p(p.as_str().unwrap()) |buf| { as_utf16_p(p.as_str().unwrap(), |buf| libc::DeleteFileW(buf));
libc::DeleteFileW(buf)
}
}) })
} }
@ -596,11 +592,11 @@ pub fn rename(old: &CString, new: &CString) -> IoResult<()> {
#[cfg(windows)] #[cfg(windows)]
fn os_rename(old: &CString, new: &CString) -> IoResult<()> { fn os_rename(old: &CString, new: &CString) -> IoResult<()> {
super::mkerr_winbool(unsafe { super::mkerr_winbool(unsafe {
do as_utf16_p(old.as_str().unwrap()) |old| { as_utf16_p(old.as_str().unwrap(), |old| {
do as_utf16_p(new.as_str().unwrap()) |new| { as_utf16_p(new.as_str().unwrap(), |new| {
libc::MoveFileExW(old, new, libc::MOVEFILE_REPLACE_EXISTING) libc::MoveFileExW(old, new, libc::MOVEFILE_REPLACE_EXISTING)
} })
} })
}) })
} }
@ -618,9 +614,7 @@ pub fn chmod(p: &CString, mode: io::FilePermission) -> IoResult<()> {
#[cfg(windows)] #[cfg(windows)]
fn os_chmod(p: &CString, mode: c_int) -> c_int { fn os_chmod(p: &CString, mode: c_int) -> c_int {
unsafe { unsafe {
do as_utf16_p(p.as_str().unwrap()) |p| { as_utf16_p(p.as_str().unwrap(), |p| libc::wchmod(p, mode))
libc::wchmod(p, mode)
}
} }
} }
@ -636,7 +630,7 @@ pub fn rmdir(p: &CString) -> IoResult<()> {
#[cfg(windows)] #[cfg(windows)]
fn os_rmdir(p: &CString) -> c_int { fn os_rmdir(p: &CString) -> c_int {
unsafe { unsafe {
do as_utf16_p(p.as_str().unwrap()) |p| { libc::wrmdir(p) } as_utf16_p(p.as_str().unwrap(), |p| libc::wrmdir(p))
} }
} }
@ -669,7 +663,7 @@ pub fn readlink(p: &CString) -> IoResult<Path> {
#[cfg(windows)] #[cfg(windows)]
fn os_readlink(p: &CString) -> IoResult<Path> { fn os_readlink(p: &CString) -> IoResult<Path> {
let handle = unsafe { let handle = unsafe {
do as_utf16_p(p.as_str().unwrap()) |p| { as_utf16_p(p.as_str().unwrap(), |p| {
libc::CreateFileW(p, libc::CreateFileW(p,
libc::GENERIC_READ, libc::GENERIC_READ,
libc::FILE_SHARE_READ, libc::FILE_SHARE_READ,
@ -677,15 +671,15 @@ pub fn readlink(p: &CString) -> IoResult<Path> {
libc::OPEN_EXISTING, libc::OPEN_EXISTING,
libc::FILE_ATTRIBUTE_NORMAL, libc::FILE_ATTRIBUTE_NORMAL,
ptr::mut_null()) ptr::mut_null())
} })
}; };
if handle == ptr::mut_null() { return Err(super::last_error()) } if handle == ptr::mut_null() { return Err(super::last_error()) }
let ret = do fill_utf16_buf_and_decode |buf, sz| { let ret = fill_utf16_buf_and_decode(|buf, sz| {
unsafe { unsafe {
libc::GetFinalPathNameByHandleW(handle, buf as *u16, sz, libc::GetFinalPathNameByHandleW(handle, buf as *u16, sz,
libc::VOLUME_NAME_NT) libc::VOLUME_NAME_NT)
} }
}; });
let ret = match ret { let ret = match ret {
Some(s) => Ok(Path::new(s)), Some(s) => Ok(Path::new(s)),
None => Err(super::last_error()), None => Err(super::last_error()),
@ -722,11 +716,11 @@ pub fn symlink(src: &CString, dst: &CString) -> IoResult<()> {
#[cfg(windows)] #[cfg(windows)]
fn os_symlink(src: &CString, dst: &CString) -> IoResult<()> { fn os_symlink(src: &CString, dst: &CString) -> IoResult<()> {
super::mkerr_winbool(do as_utf16_p(src.as_str().unwrap()) |src| { super::mkerr_winbool(as_utf16_p(src.as_str().unwrap(), |src| {
do as_utf16_p(dst.as_str().unwrap()) |dst| { as_utf16_p(dst.as_str().unwrap(), |dst| {
unsafe { libc::CreateSymbolicLinkW(dst, src, 0) } unsafe { libc::CreateSymbolicLinkW(dst, src, 0) }
} })
}) }))
} }
#[cfg(unix)] #[cfg(unix)]
@ -742,11 +736,11 @@ pub fn link(src: &CString, dst: &CString) -> IoResult<()> {
#[cfg(windows)] #[cfg(windows)]
fn os_link(src: &CString, dst: &CString) -> IoResult<()> { fn os_link(src: &CString, dst: &CString) -> IoResult<()> {
super::mkerr_winbool(do as_utf16_p(src.as_str().unwrap()) |src| { super::mkerr_winbool(as_utf16_p(src.as_str().unwrap(), |src| {
do as_utf16_p(dst.as_str().unwrap()) |dst| { as_utf16_p(dst.as_str().unwrap(), |dst| {
unsafe { libc::CreateHardLinkW(dst, src, ptr::mut_null()) } unsafe { libc::CreateHardLinkW(dst, src, ptr::mut_null()) }
} })
}) }))
} }
#[cfg(unix)] #[cfg(unix)]
@ -851,12 +845,12 @@ pub fn stat(p: &CString) -> IoResult<io::FileStat> {
#[cfg(windows)] #[cfg(windows)]
fn os_stat(p: &CString) -> IoResult<io::FileStat> { fn os_stat(p: &CString) -> IoResult<io::FileStat> {
let mut stat: libc::stat = unsafe { intrinsics::uninit() }; let mut stat: libc::stat = unsafe { intrinsics::uninit() };
do as_utf16_p(p.as_str().unwrap()) |up| { as_utf16_p(p.as_str().unwrap(), |up| {
match unsafe { libc::wstat(up, &mut stat) } { match unsafe { libc::wstat(up, &mut stat) } {
0 => Ok(mkstat(&stat, p)), 0 => Ok(mkstat(&stat, p)),
_ => Err(super::last_error()), _ => Err(super::last_error()),
} }
} })
} }
#[cfg(unix)] #[cfg(unix)]
@ -898,9 +892,7 @@ pub fn utime(p: &CString, atime: u64, mtime: u64) -> IoResult<()> {
modtime: (mtime / 1000) as libc::time64_t, modtime: (mtime / 1000) as libc::time64_t,
}; };
unsafe { unsafe {
do as_utf16_p(p.as_str().unwrap()) |p| { as_utf16_p(p.as_str().unwrap(), |p| libc::wutime(p, &buf))
libc::wutime(p, &buf)
}
} }
} }

View file

@ -234,18 +234,18 @@ fn spawn_process_os(prog: &str, args: &[~str],
let mut pi = zeroed_process_information(); let mut pi = zeroed_process_information();
let mut create_err = None; let mut create_err = None;
do with_envp(env) |envp| { with_envp(env, |envp| {
do with_dirp(dir) |dirp| { with_dirp(dir, |dirp| {
do cmd.with_c_str |cmdp| { cmd.with_c_str(|cmdp| {
let created = CreateProcessA(ptr::null(), cast::transmute(cmdp), let created = CreateProcessA(ptr::null(), cast::transmute(cmdp),
ptr::mut_null(), ptr::mut_null(), TRUE, ptr::mut_null(), ptr::mut_null(), TRUE,
0, envp, dirp, &mut si, &mut pi); 0, envp, dirp, &mut si, &mut pi);
if created == FALSE { if created == FALSE {
create_err = Some(os::last_os_error()); create_err = Some(os::last_os_error());
} }
} })
} })
} });
CloseHandle(si.hStdInput); CloseHandle(si.hStdInput);
CloseHandle(si.hStdOutput); CloseHandle(si.hStdOutput);
@ -411,22 +411,22 @@ fn spawn_process_os(prog: &str, args: &[~str],
close(fd as c_int); close(fd as c_int);
} }
do with_dirp(dir) |dirp| { with_dirp(dir, |dirp| {
if !dirp.is_null() && chdir(dirp) == -1 { if !dirp.is_null() && chdir(dirp) == -1 {
fail!("failure in chdir: {}", os::last_os_error()); fail!("failure in chdir: {}", os::last_os_error());
} }
} });
do with_envp(env) |envp| { with_envp(env, |envp| {
if !envp.is_null() { if !envp.is_null() {
set_environ(envp); set_environ(envp);
} }
do with_argv(prog, args) |argv| { with_argv(prog, args, |argv| {
execvp(*argv, argv); execvp(*argv, argv);
// execvp only returns if an error occurred // execvp only returns if an error occurred
fail!("failure in execvp: {}", os::last_os_error()); fail!("failure in execvp: {}", os::last_os_error());
} })
} })
} }
} }
@ -448,9 +448,7 @@ fn with_argv<T>(prog: &str, args: &[~str], cb: |**libc::c_char| -> T) -> T {
// Next, convert each of the byte strings into a pointer. This is // Next, convert each of the byte strings into a pointer. This is
// technically unsafe as the caller could leak these pointers out of our // technically unsafe as the caller could leak these pointers out of our
// scope. // scope.
let mut ptrs = do tmps.map |tmp| { let mut ptrs = tmps.map(|tmp| tmp.with_ref(|buf| buf));
tmp.with_ref(|buf| buf)
};
// Finally, make sure we add a null pointer. // Finally, make sure we add a null pointer.
ptrs.push(ptr::null()); ptrs.push(ptr::null());
@ -475,14 +473,10 @@ fn with_envp<T>(env: Option<~[(~str, ~str)]>, cb: |*c_void| -> T) -> T {
} }
// Once again, this is unsafe. // Once again, this is unsafe.
let mut ptrs = do tmps.map |tmp| { let mut ptrs = tmps.map(|tmp| tmp.with_ref(|buf| buf));
tmp.with_ref(|buf| buf)
};
ptrs.push(ptr::null()); ptrs.push(ptr::null());
do ptrs.as_imm_buf |buf, _| { ptrs.as_imm_buf(|buf, _| unsafe { cb(cast::transmute(buf)) })
unsafe { cb(cast::transmute(buf)) }
}
} }
_ => cb(ptr::null()) _ => cb(ptr::null())
} }
@ -505,9 +499,7 @@ fn with_envp<T>(env: Option<~[(~str, ~str)]>, cb: |*mut c_void| -> T) -> T {
blk.push(0); blk.push(0);
do blk.as_imm_buf |p, _len| { blk.as_imm_buf(|p, _len| unsafe { cb(cast::transmute(p)) });
unsafe { cb(cast::transmute(p)) }
}
} }
_ => cb(ptr::mut_null()) _ => cb(ptr::mut_null())
} }

View file

@ -97,7 +97,7 @@ pub fn get_host_addresses(host: &str) -> Option<~[IpAddr]> {
/// consumption just yet. /// consumption just yet.
fn lookup(hostname: Option<&str>, servname: Option<&str>, fn lookup(hostname: Option<&str>, servname: Option<&str>,
hint: Option<Hint>) -> Option<~[Info]> { hint: Option<Hint>) -> Option<~[Info]> {
do with_local_io |io| { with_local_io(|io| {
match io.get_host_addresses(hostname, servname, hint) { match io.get_host_addresses(hostname, servname, hint) {
Ok(i) => Some(i), Ok(i) => Some(i),
Err(ioerr) => { Err(ioerr) => {
@ -105,7 +105,7 @@ fn lookup(hostname: Option<&str>, servname: Option<&str>,
None None
} }
} }
} })
} }
#[cfg(test)] #[cfg(test)]

View file

@ -94,9 +94,7 @@ impl<'self> Parser<'self> {
// Commit only if parser read till EOF // Commit only if parser read till EOF
fn read_till_eof<T>(&mut self, cb: |&mut Parser| -> Option<T>) fn read_till_eof<T>(&mut self, cb: |&mut Parser| -> Option<T>)
-> Option<T> { -> Option<T> {
do self.read_atomically |p| { self.read_atomically(|p| cb(p).filtered(|_| p.is_eof()))
cb(p).filtered(|_| p.is_eof())
}
} }
// Return result of first successful parser // Return result of first successful parser
@ -120,7 +118,7 @@ impl<'self> Parser<'self> {
pb: |&mut Parser| -> Option<B>, pb: |&mut Parser| -> Option<B>,
pc: |&mut Parser| -> Option<C>) pc: |&mut Parser| -> Option<C>)
-> Option<(A, B, C)> { -> Option<(A, B, C)> {
do self.read_atomically |p| { self.read_atomically(|p| {
let a = pa(p); let a = pa(p);
let b = if a.is_some() { pb(p) } else { None }; let b = if a.is_some() { pb(p) } else { None };
let c = if b.is_some() { pc(p) } else { None }; let c = if b.is_some() { pc(p) } else { None };
@ -128,7 +126,7 @@ impl<'self> Parser<'self> {
(Some(a), Some(b), Some(c)) => Some((a, b, c)), (Some(a), Some(b), Some(c)) => Some((a, b, c)),
_ => None _ => None
} }
} })
} }
// Read next char // Read next char
@ -144,9 +142,9 @@ impl<'self> Parser<'self> {
// Return char and advance iff next char is equal to requested // Return char and advance iff next char is equal to requested
fn read_given_char(&mut self, c: char) -> Option<char> { fn read_given_char(&mut self, c: char) -> Option<char> {
do self.read_atomically |p| { self.read_atomically(|p| {
p.read_char().filtered(|&next| next == c) p.read_char().filtered(|&next| next == c)
} })
} }
// Read digit // Read digit
@ -165,9 +163,9 @@ impl<'self> Parser<'self> {
} }
} }
do self.read_atomically |p| { self.read_atomically(|p| {
p.read_char().and_then(|c| parse_digit(c, radix)) p.read_char().and_then(|c| parse_digit(c, radix))
} })
} }
fn read_number_impl(&mut self, radix: u8, max_digits: u32, upto: u32) -> Option<u32> { fn read_number_impl(&mut self, radix: u8, max_digits: u32, upto: u32) -> Option<u32> {
@ -195,9 +193,7 @@ impl<'self> Parser<'self> {
// Read number, failing if max_digits of number value exceeded // Read number, failing if max_digits of number value exceeded
fn read_number(&mut self, radix: u8, max_digits: u32, upto: u32) -> Option<u32> { fn read_number(&mut self, radix: u8, max_digits: u32, upto: u32) -> Option<u32> {
do self.read_atomically |p| { self.read_atomically(|p| p.read_number_impl(radix, max_digits, upto))
p.read_number_impl(radix, max_digits, upto)
}
} }
fn read_ipv4_addr_impl(&mut self) -> Option<IpAddr> { fn read_ipv4_addr_impl(&mut self) -> Option<IpAddr> {
@ -220,9 +216,7 @@ impl<'self> Parser<'self> {
// Read IPv4 address // Read IPv4 address
fn read_ipv4_addr(&mut self) -> Option<IpAddr> { fn read_ipv4_addr(&mut self) -> Option<IpAddr> {
do self.read_atomically |p| { self.read_atomically(|p| p.read_ipv4_addr_impl())
p.read_ipv4_addr_impl()
}
} }
fn read_ipv6_addr_impl(&mut self) -> Option<IpAddr> { fn read_ipv6_addr_impl(&mut self) -> Option<IpAddr> {
@ -238,13 +232,13 @@ impl<'self> Parser<'self> {
let mut i = 0; let mut i = 0;
while i < limit { while i < limit {
if i < limit - 1 { if i < limit - 1 {
let ipv4 = do p.read_atomically |p| { let ipv4 = p.read_atomically(|p| {
if i == 0 || p.read_given_char(':').is_some() { if i == 0 || p.read_given_char(':').is_some() {
p.read_ipv4_addr() p.read_ipv4_addr()
} else { } else {
None None
} }
}; });
match ipv4 { match ipv4 {
Some(Ipv4Addr(a, b, c, d)) => { Some(Ipv4Addr(a, b, c, d)) => {
groups[i + 0] = (a as u16 << 8) | (b as u16); groups[i + 0] = (a as u16 << 8) | (b as u16);
@ -255,13 +249,13 @@ impl<'self> Parser<'self> {
} }
} }
let group = do p.read_atomically |p| { let group = p.read_atomically(|p| {
if i == 0 || p.read_given_char(':').is_some() { if i == 0 || p.read_given_char(':').is_some() {
p.read_number(16, 4, 0x10000).map(|n| n as u16) p.read_number(16, 4, 0x10000).map(|n| n as u16)
} else { } else {
None None
} }
}; });
match group { match group {
Some(g) => groups[i] = g, Some(g) => groups[i] = g,
None => return (i, false) None => return (i, false)
@ -296,9 +290,7 @@ impl<'self> Parser<'self> {
} }
fn read_ipv6_addr(&mut self) -> Option<IpAddr> { fn read_ipv6_addr(&mut self) -> Option<IpAddr> {
do self.read_atomically |p| { self.read_atomically(|p| p.read_ipv6_addr_impl())
p.read_ipv6_addr_impl()
}
} }
fn read_ip_addr(&mut self) -> Option<IpAddr> { fn read_ip_addr(&mut self) -> Option<IpAddr> {
@ -330,17 +322,13 @@ impl<'self> Parser<'self> {
impl FromStr for IpAddr { impl FromStr for IpAddr {
fn from_str(s: &str) -> Option<IpAddr> { fn from_str(s: &str) -> Option<IpAddr> {
do Parser::new(s).read_till_eof |p| { Parser::new(s).read_till_eof(|p| p.read_ip_addr())
p.read_ip_addr()
}
} }
} }
impl FromStr for SocketAddr { impl FromStr for SocketAddr {
fn from_str(s: &str) -> Option<SocketAddr> { fn from_str(s: &str) -> Option<SocketAddr> {
do Parser::new(s).read_till_eof |p| { Parser::new(s).read_till_eof(|p| p.read_socket_addr())
p.read_socket_addr()
}
} }
} }

View file

@ -26,7 +26,7 @@ impl TcpStream {
} }
pub fn connect(addr: SocketAddr) -> Option<TcpStream> { pub fn connect(addr: SocketAddr) -> Option<TcpStream> {
do with_local_io |io| { with_local_io(|io| {
match io.tcp_connect(addr) { match io.tcp_connect(addr) {
Ok(s) => Some(TcpStream::new(s)), Ok(s) => Some(TcpStream::new(s)),
Err(ioerr) => { Err(ioerr) => {
@ -34,7 +34,7 @@ impl TcpStream {
None None
} }
} }
} })
} }
pub fn peer_name(&mut self) -> Option<SocketAddr> { pub fn peer_name(&mut self) -> Option<SocketAddr> {
@ -92,7 +92,7 @@ pub struct TcpListener {
impl TcpListener { impl TcpListener {
pub fn bind(addr: SocketAddr) -> Option<TcpListener> { pub fn bind(addr: SocketAddr) -> Option<TcpListener> {
do with_local_io |io| { with_local_io(|io| {
match io.tcp_bind(addr) { match io.tcp_bind(addr) {
Ok(l) => Some(TcpListener { obj: l }), Ok(l) => Some(TcpListener { obj: l }),
Err(ioerr) => { Err(ioerr) => {
@ -100,7 +100,7 @@ impl TcpListener {
None None
} }
} }
} })
} }
pub fn socket_name(&mut self) -> Option<SocketAddr> { pub fn socket_name(&mut self) -> Option<SocketAddr> {

View file

@ -21,7 +21,7 @@ pub struct UdpSocket {
impl UdpSocket { impl UdpSocket {
pub fn bind(addr: SocketAddr) -> Option<UdpSocket> { pub fn bind(addr: SocketAddr) -> Option<UdpSocket> {
do with_local_io |io| { with_local_io(|io| {
match io.udp_bind(addr) { match io.udp_bind(addr) {
Ok(s) => Some(UdpSocket { obj: s }), Ok(s) => Some(UdpSocket { obj: s }),
Err(ioerr) => { Err(ioerr) => {
@ -29,7 +29,7 @@ impl UdpSocket {
None None
} }
} }
} })
} }
pub fn recvfrom(&mut self, buf: &mut [u8]) -> Option<(uint, SocketAddr)> { pub fn recvfrom(&mut self, buf: &mut [u8]) -> Option<(uint, SocketAddr)> {
@ -84,13 +84,13 @@ impl UdpStream {
impl Reader for UdpStream { impl Reader for UdpStream {
fn read(&mut self, buf: &mut [u8]) -> Option<uint> { fn read(&mut self, buf: &mut [u8]) -> Option<uint> {
let peer = self.connectedTo; let peer = self.connectedTo;
do self.as_socket |sock| { self.as_socket(|sock| {
match sock.recvfrom(buf) { match sock.recvfrom(buf) {
Some((_nread, src)) if src != peer => Some(0), Some((_nread, src)) if src != peer => Some(0),
Some((nread, _src)) => Some(nread), Some((nread, _src)) => Some(nread),
None => None, None => None,
} }
} })
} }
fn eof(&mut self) -> bool { fail!() } fn eof(&mut self) -> bool { fail!() }
@ -98,9 +98,7 @@ impl Reader for UdpStream {
impl Writer for UdpStream { impl Writer for UdpStream {
fn write(&mut self, buf: &[u8]) { fn write(&mut self, buf: &[u8]) {
do self.as_socket |sock| { self.as_socket(|sock| sock.sendto(buf, self.connectedTo));
sock.sendto(buf, self.connectedTo);
}
} }
} }

View file

@ -59,7 +59,7 @@ impl UnixStream {
/// stream.write([1, 2, 3]); /// stream.write([1, 2, 3]);
/// ///
pub fn connect<P: ToCStr>(path: &P) -> Option<UnixStream> { pub fn connect<P: ToCStr>(path: &P) -> Option<UnixStream> {
do with_local_io |io| { with_local_io(|io| {
match io.unix_connect(&path.to_c_str()) { match io.unix_connect(&path.to_c_str()) {
Ok(s) => Some(UnixStream::new(s)), Ok(s) => Some(UnixStream::new(s)),
Err(ioerr) => { Err(ioerr) => {
@ -67,7 +67,7 @@ impl UnixStream {
None None
} }
} }
} })
} }
} }
@ -108,7 +108,7 @@ impl UnixListener {
/// } /// }
/// ///
pub fn bind<P: ToCStr>(path: &P) -> Option<UnixListener> { pub fn bind<P: ToCStr>(path: &P) -> Option<UnixListener> {
do with_local_io |io| { with_local_io(|io| {
match io.unix_bind(&path.to_c_str()) { match io.unix_bind(&path.to_c_str()) {
Ok(s) => Some(UnixListener{ obj: s }), Ok(s) => Some(UnixListener{ obj: s }),
Err(ioerr) => { Err(ioerr) => {
@ -116,7 +116,7 @@ impl UnixListener {
None None
} }
} }
} })
} }
} }

View file

@ -44,7 +44,7 @@ impl PipeStream {
/// If the pipe cannot be created, an error will be raised on the /// If the pipe cannot be created, an error will be raised on the
/// `io_error` condition. /// `io_error` condition.
pub fn open(fd: file::fd_t) -> Option<PipeStream> { pub fn open(fd: file::fd_t) -> Option<PipeStream> {
do with_local_io |io| { with_local_io(|io| {
match io.pipe_open(fd) { match io.pipe_open(fd) {
Ok(obj) => Some(PipeStream { obj: obj }), Ok(obj) => Some(PipeStream { obj: obj }),
Err(e) => { Err(e) => {
@ -52,7 +52,7 @@ impl PipeStream {
None None
} }
} }
} })
} }
pub fn new(inner: ~RtioPipe) -> PipeStream { pub fn new(inner: ~RtioPipe) -> PipeStream {

View file

@ -121,7 +121,7 @@ impl Process {
/// source/destination /// source/destination
pub fn new(config: ProcessConfig) -> Option<Process> { pub fn new(config: ProcessConfig) -> Option<Process> {
let config = Cell::new(config); let config = Cell::new(config);
do with_local_io |io| { with_local_io(|io| {
match io.spawn(config.take()) { match io.spawn(config.take()) {
Ok((p, io)) => Some(Process{ Ok((p, io)) => Some(Process{
handle: p, handle: p,
@ -134,7 +134,7 @@ impl Process {
None None
} }
} }
} })
} }
/// Returns the process id of this child process /// Returns the process id of this child process

View file

@ -123,7 +123,7 @@ impl Listener {
if self.handles.contains_key(&signum) { if self.handles.contains_key(&signum) {
return true; // self is already listening to signum, so succeed return true; // self is already listening to signum, so succeed
} }
do with_local_io |io| { with_local_io(|io| {
match io.signal(signum, self.chan.clone()) { match io.signal(signum, self.chan.clone()) {
Ok(w) => { Ok(w) => {
self.handles.insert(signum, w); self.handles.insert(signum, w);
@ -134,7 +134,7 @@ impl Listener {
None None
} }
} }
}.is_some() }).is_some()
} }
/// Unregisters a signal. If this listener currently had a handler /// Unregisters a signal. If this listener currently had a handler
@ -212,13 +212,13 @@ mod test {
use super::User1; use super::User1;
let mut s = Listener::new(); let mut s = Listener::new();
let mut called = false; let mut called = false;
do io::io_error::cond.trap(|_| { io::io_error::cond.trap(|_| {
called = true; called = true;
}).inside { }).inside(|| {
if s.register(User1) { if s.register(User1) {
fail!("Unexpected successful registry of signum {:?}", User1); fail!("Unexpected successful registry of signum {:?}", User1);
} }
} });
assert!(called); assert!(called);
} }
} }

View file

@ -70,7 +70,7 @@ enum StdSource {
} }
fn src<T>(fd: libc::c_int, readable: bool, f: |StdSource| -> T) -> T { fn src<T>(fd: libc::c_int, readable: bool, f: |StdSource| -> T) -> T {
do with_local_io |io| { with_local_io(|io| {
let fd = unsafe { libc::dup(fd) }; let fd = unsafe { libc::dup(fd) };
match io.tty_open(fd, readable) { match io.tty_open(fd, readable) {
Ok(tty) => Some(f(TTY(tty))), Ok(tty) => Some(f(TTY(tty))),
@ -84,14 +84,14 @@ fn src<T>(fd: libc::c_int, readable: bool, f: |StdSource| -> T) -> T {
Some(f(File(io.fs_from_raw_fd(fd, CloseAsynchronously)))) Some(f(File(io.fs_from_raw_fd(fd, CloseAsynchronously))))
} }
} }
}.unwrap() }).unwrap()
} }
/// Creates a new non-blocking handle to the stdin of the current process. /// Creates a new non-blocking handle to the stdin of the current process.
/// ///
/// See `stdout()` for notes about this function. /// See `stdout()` for notes about this function.
pub fn stdin() -> StdReader { pub fn stdin() -> StdReader {
do src(libc::STDIN_FILENO, true) |src| { StdReader { inner: src } } src(libc::STDIN_FILENO, true, |src| StdReader { inner: src })
} }
/// Creates a new non-blocking handle to the stdout of the current process. /// Creates a new non-blocking handle to the stdout of the current process.
@ -101,14 +101,14 @@ pub fn stdin() -> StdReader {
/// task context because the stream returned will be a non-blocking object using /// task context because the stream returned will be a non-blocking object using
/// the local scheduler to perform the I/O. /// the local scheduler to perform the I/O.
pub fn stdout() -> StdWriter { pub fn stdout() -> StdWriter {
do src(libc::STDOUT_FILENO, false) |src| { StdWriter { inner: src } } src(libc::STDOUT_FILENO, false, |src| StdWriter { inner: src })
} }
/// Creates a new non-blocking handle to the stderr of the current process. /// Creates a new non-blocking handle to the stderr of the current process.
/// ///
/// See `stdout()` for notes about this function. /// See `stdout()` for notes about this function.
pub fn stderr() -> StdWriter { pub fn stderr() -> StdWriter {
do src(libc::STDERR_FILENO, false) |src| { StdWriter { inner: src } } src(libc::STDERR_FILENO, false, |src| StdWriter { inner: src })
} }
// Helper to access the local task's stdout handle // Helper to access the local task's stdout handle
@ -116,11 +116,11 @@ pub fn stderr() -> StdWriter {
// Note that this is not a safe function to expose because you can create an // Note that this is not a safe function to expose because you can create an
// aliased pointer very easily: // aliased pointer very easily:
// //
// do with_task_stdout |io1| { // with_task_stdout(|io1| {
// do with_task_stdout |io2| { // with_task_stdout(|io2| {
// // io1 aliases io2 // // io1 aliases io2
// } // })
// } // })
fn with_task_stdout(f: |&mut Writer|) { fn with_task_stdout(f: |&mut Writer|) {
use rt::local::Local; use rt::local::Local;
use rt::task::Task; use rt::task::Task;
@ -158,42 +158,34 @@ fn with_task_stdout(f: |&mut Writer|) {
/// will emit output to stderr, and while they are line buffered the log /// will emit output to stderr, and while they are line buffered the log
/// messages are always terminated in a newline (no need to flush). /// messages are always terminated in a newline (no need to flush).
pub fn flush() { pub fn flush() {
do with_task_stdout |io| { with_task_stdout(|io| io.flush())
io.flush();
}
} }
/// Prints a string to the stdout of the current process. No newline is emitted /// Prints a string to the stdout of the current process. No newline is emitted
/// after the string is printed. /// after the string is printed.
pub fn print(s: &str) { pub fn print(s: &str) {
do with_task_stdout |io| { with_task_stdout(|io| io.write(s.as_bytes()))
io.write(s.as_bytes());
}
} }
/// Prints a string as a line. to the stdout of the current process. A literal /// Prints a string as a line. to the stdout of the current process. A literal
/// `\n` character is printed to the console after the string. /// `\n` character is printed to the console after the string.
pub fn println(s: &str) { pub fn println(s: &str) {
do with_task_stdout |io| { with_task_stdout(|io| {
io.write(s.as_bytes()); io.write(s.as_bytes());
io.write(['\n' as u8]); io.write(['\n' as u8]);
} })
} }
/// Similar to `print`, but takes a `fmt::Arguments` structure to be compatible /// Similar to `print`, but takes a `fmt::Arguments` structure to be compatible
/// with the `format_args!` macro. /// with the `format_args!` macro.
pub fn print_args(fmt: &fmt::Arguments) { pub fn print_args(fmt: &fmt::Arguments) {
do with_task_stdout |io| { with_task_stdout(|io| fmt::write(io, fmt))
fmt::write(io, fmt);
}
} }
/// Similar to `println`, but takes a `fmt::Arguments` structure to be /// Similar to `println`, but takes a `fmt::Arguments` structure to be
/// compatible with the `format_args!` macro. /// compatible with the `format_args!` macro.
pub fn println_args(fmt: &fmt::Arguments) { pub fn println_args(fmt: &fmt::Arguments) {
do with_task_stdout |io| { with_task_stdout(|io| fmt::writeln(io, fmt))
fmt::writeln(io, fmt);
}
} }
/// Representation of a reader of a standard input stream /// Representation of a reader of a standard input stream

View file

@ -60,7 +60,7 @@ impl Timer {
/// for a number of milliseconds, or to possibly create channels which will /// for a number of milliseconds, or to possibly create channels which will
/// get notified after an amount of time has passed. /// get notified after an amount of time has passed.
pub fn new() -> Option<Timer> { pub fn new() -> Option<Timer> {
do with_local_io |io| { with_local_io(|io| {
match io.timer_init() { match io.timer_init() {
Ok(t) => Some(Timer { obj: t }), Ok(t) => Some(Timer { obj: t }),
Err(ioerr) => { Err(ioerr) => {
@ -70,7 +70,7 @@ impl Timer {
} }
} }
} })
} }
/// Blocks the current task for `msecs` milliseconds. /// Blocks the current task for `msecs` milliseconds.

View file

@ -189,7 +189,7 @@ pub fn get<T: 'static, U>(key: Key<T>, f: |Option<&T>| -> U) -> U {
/// on loan via this or the `get` methods. This is similar to how it's a runtime /// on loan via this or the `get` methods. This is similar to how it's a runtime
/// error to take two mutable loans on an `@mut` box. /// error to take two mutable loans on an `@mut` box.
pub fn get_mut<T: 'static, U>(key: Key<T>, f: |Option<&mut T>| -> U) -> U { pub fn get_mut<T: 'static, U>(key: Key<T>, f: |Option<&mut T>| -> U) -> U {
do get_with(key, MutLoan) |x| { get_with(key, MutLoan, |x| {
match x { match x {
None => f(None), None => f(None),
// We're violating a lot of compiler guarantees with this // We're violating a lot of compiler guarantees with this
@ -199,7 +199,7 @@ pub fn get_mut<T: 'static, U>(key: Key<T>, f: |Option<&mut T>| -> U) -> U {
// there is no need to be upset! // there is no need to be upset!
Some(x) => { f(Some(unsafe { cast::transmute_mut(x) })) } Some(x) => { f(Some(unsafe { cast::transmute_mut(x) })) }
} }
} })
} }
fn get_with<T:'static, fn get_with<T:'static,

View file

@ -420,10 +420,10 @@ pub fn to_str_bytes<U>(n: $T, radix: uint, f: |v: &[u8]| -> U) -> U {
// base 2 number, and then we need another for a possible '-' character. // base 2 number, and then we need another for a possible '-' character.
let mut buf = [0u8, ..65]; let mut buf = [0u8, ..65];
let mut cur = 0; let mut cur = 0;
do strconv::int_to_str_bytes_common(n, radix, strconv::SignNeg) |i| { strconv::int_to_str_bytes_common(n, radix, strconv::SignNeg, |i| {
buf[cur] = i; buf[cur] = i;
cur += 1; cur += 1;
} });
f(buf.slice(0, cur)) f(buf.slice(0, cur))
} }
@ -440,9 +440,9 @@ impl ToStrRadix for $T {
#[inline] #[inline]
fn to_str_radix(&self, radix: uint) -> ~str { fn to_str_radix(&self, radix: uint) -> ~str {
let mut buf: ~[u8] = ~[]; let mut buf: ~[u8] = ~[];
do strconv::int_to_str_bytes_common(*self, radix, strconv::SignNeg) |i| { strconv::int_to_str_bytes_common(*self, radix, strconv::SignNeg, |i| {
buf.push(i); buf.push(i);
} });
// We know we generated valid utf-8, so we don't need to go through that // We know we generated valid utf-8, so we don't need to go through that
// check. // check.
unsafe { str::raw::from_utf8_owned(buf) } unsafe { str::raw::from_utf8_owned(buf) }

View file

@ -271,10 +271,10 @@ pub fn to_str_bytes<U>(n: $T, radix: uint, f: |v: &[u8]| -> U) -> U {
// base 2 number. // base 2 number.
let mut buf = [0u8, ..64]; let mut buf = [0u8, ..64];
let mut cur = 0; let mut cur = 0;
do strconv::int_to_str_bytes_common(n, radix, strconv::SignNone) |i| { strconv::int_to_str_bytes_common(n, radix, strconv::SignNone, |i| {
buf[cur] = i; buf[cur] = i;
cur += 1; cur += 1;
} });
f(buf.slice(0, cur)) f(buf.slice(0, cur))
} }
@ -291,9 +291,9 @@ impl ToStrRadix for $T {
#[inline] #[inline]
fn to_str_radix(&self, radix: uint) -> ~str { fn to_str_radix(&self, radix: uint) -> ~str {
let mut buf = ~[]; let mut buf = ~[];
do strconv::int_to_str_bytes_common(*self, radix, strconv::SignNone) |i| { strconv::int_to_str_bytes_common(*self, radix, strconv::SignNone, |i| {
buf.push(i); buf.push(i);
} });
// We know we generated valid utf-8, so we don't need to go through that // We know we generated valid utf-8, so we don't need to go through that
// check. // check.
unsafe { str::raw::from_utf8_owned(buf) } unsafe { str::raw::from_utf8_owned(buf) }

View file

@ -58,7 +58,7 @@ static BUF_BYTES : uint = 2048u;
#[cfg(unix)] #[cfg(unix)]
pub fn getcwd() -> Path { pub fn getcwd() -> Path {
let mut buf = [0 as libc::c_char, ..BUF_BYTES]; let mut buf = [0 as libc::c_char, ..BUF_BYTES];
do buf.as_mut_buf |buf, len| { buf.as_mut_buf(|buf, len| {
unsafe { unsafe {
if libc::getcwd(buf, len as size_t).is_null() { if libc::getcwd(buf, len as size_t).is_null() {
fail!() fail!()
@ -66,7 +66,7 @@ pub fn getcwd() -> Path {
Path::new(CString::new(buf as *c_char, false)) Path::new(CString::new(buf as *c_char, false))
} }
} })
} }
#[cfg(windows)] #[cfg(windows)]
@ -74,13 +74,13 @@ pub fn getcwd() -> Path {
use libc::DWORD; use libc::DWORD;
use libc::GetCurrentDirectoryW; use libc::GetCurrentDirectoryW;
let mut buf = [0 as u16, ..BUF_BYTES]; let mut buf = [0 as u16, ..BUF_BYTES];
do buf.as_mut_buf |buf, len| { buf.as_mut_buf(|buf, len| {
unsafe { unsafe {
if libc::GetCurrentDirectoryW(len as DWORD, buf) == 0 as DWORD { if libc::GetCurrentDirectoryW(len as DWORD, buf) == 0 as DWORD {
fail!(); fail!();
} }
} }
} });
Path::new(str::from_utf16(buf)) Path::new(str::from_utf16(buf))
} }
@ -104,7 +104,7 @@ pub mod win32 {
while !done { while !done {
let mut k: DWORD = 0; let mut k: DWORD = 0;
let mut buf = vec::from_elem(n as uint, 0u16); let mut buf = vec::from_elem(n as uint, 0u16);
do buf.as_mut_buf |b, _sz| { buf.as_mut_buf(|b, _sz| {
k = f(b, TMPBUF_SZ as DWORD); k = f(b, TMPBUF_SZ as DWORD);
if k == (0 as DWORD) { if k == (0 as DWORD) {
done = true; done = true;
@ -115,7 +115,7 @@ pub mod win32 {
} else { } else {
done = true; done = true;
} }
} });
if k != 0 && done { if k != 0 && done {
let sub = buf.slice(0, k as uint); let sub = buf.slice(0, k as uint);
res = option::Some(str::from_utf16(sub)); res = option::Some(str::from_utf16(sub));
@ -144,12 +144,10 @@ fn with_env_lock<T>(f: || -> T) -> T {
static mut lock: Mutex = MUTEX_INIT; static mut lock: Mutex = MUTEX_INIT;
unsafe { unsafe {
return do (|| { return (|| {
lock.lock(); lock.lock();
f() f()
}).finally { }).finally(|| lock.unlock());
lock.unlock();
};
} }
} }
@ -172,9 +170,9 @@ pub fn env() -> ~[(~str,~str)] {
os::last_os_error()); os::last_os_error());
} }
let mut result = ~[]; let mut result = ~[];
do c_str::from_c_multistring(ch as *libc::c_char, None) |cstr| { c_str::from_c_multistring(ch as *libc::c_char, None, |cstr| {
result.push(cstr.as_str().unwrap().to_owned()); result.push(cstr.as_str().unwrap().to_owned());
}; });
FreeEnvironmentStringsA(ch); FreeEnvironmentStringsA(ch);
result result
} }
@ -207,10 +205,10 @@ pub fn env() -> ~[(~str,~str)] {
} }
pairs pairs
} }
do with_env_lock { with_env_lock(|| {
let unparsed_environ = get_env_pairs(); let unparsed_environ = get_env_pairs();
env_convert(unparsed_environ) env_convert(unparsed_environ)
} })
} }
} }
@ -219,16 +217,14 @@ pub fn env() -> ~[(~str,~str)] {
/// None if the variable isn't set. /// None if the variable isn't set.
pub fn getenv(n: &str) -> Option<~str> { pub fn getenv(n: &str) -> Option<~str> {
unsafe { unsafe {
do with_env_lock { with_env_lock(|| {
let s = do n.with_c_str |buf| { let s = n.with_c_str(|buf| libc::getenv(buf));
libc::getenv(buf)
};
if s.is_null() { if s.is_null() {
None None
} else { } else {
Some(str::raw::from_c_str(s)) Some(str::raw::from_c_str(s))
} }
} })
} }
} }
@ -237,14 +233,14 @@ pub fn getenv(n: &str) -> Option<~str> {
/// None if the variable isn't set. /// None if the variable isn't set.
pub fn getenv(n: &str) -> Option<~str> { pub fn getenv(n: &str) -> Option<~str> {
unsafe { unsafe {
do with_env_lock { with_env_lock(|| {
use os::win32::{as_utf16_p, fill_utf16_buf_and_decode}; use os::win32::{as_utf16_p, fill_utf16_buf_and_decode};
do as_utf16_p(n) |u| { as_utf16_p(n, |u| {
do fill_utf16_buf_and_decode() |buf, sz| { fill_utf16_buf_and_decode(|buf, sz| {
libc::GetEnvironmentVariableW(u, buf, sz) libc::GetEnvironmentVariableW(u, buf, sz)
} })
} })
} })
} }
} }
@ -254,13 +250,13 @@ pub fn getenv(n: &str) -> Option<~str> {
/// process /// process
pub fn setenv(n: &str, v: &str) { pub fn setenv(n: &str, v: &str) {
unsafe { unsafe {
do with_env_lock { with_env_lock(|| {
do n.with_c_str |nbuf| { n.with_c_str(|nbuf| {
do v.with_c_str |vbuf| { v.with_c_str(|vbuf| {
libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1); libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1);
} })
} })
} })
} }
} }
@ -270,14 +266,14 @@ pub fn setenv(n: &str, v: &str) {
/// process /// process
pub fn setenv(n: &str, v: &str) { pub fn setenv(n: &str, v: &str) {
unsafe { unsafe {
do with_env_lock { with_env_lock(|| {
use os::win32::as_utf16_p; use os::win32::as_utf16_p;
do as_utf16_p(n) |nbuf| { as_utf16_p(n, |nbuf| {
do as_utf16_p(v) |vbuf| { as_utf16_p(v, |vbuf| {
libc::SetEnvironmentVariableW(nbuf, vbuf); libc::SetEnvironmentVariableW(nbuf, vbuf);
} })
} })
} })
} }
} }
@ -286,22 +282,22 @@ pub fn unsetenv(n: &str) {
#[cfg(unix)] #[cfg(unix)]
fn _unsetenv(n: &str) { fn _unsetenv(n: &str) {
unsafe { unsafe {
do with_env_lock { with_env_lock(|| {
do n.with_c_str |nbuf| { n.with_c_str(|nbuf| {
libc::funcs::posix01::unistd::unsetenv(nbuf); libc::funcs::posix01::unistd::unsetenv(nbuf);
} })
} })
} }
} }
#[cfg(windows)] #[cfg(windows)]
fn _unsetenv(n: &str) { fn _unsetenv(n: &str) {
unsafe { unsafe {
do with_env_lock { with_env_lock(|| {
use os::win32::as_utf16_p; use os::win32::as_utf16_p;
do as_utf16_p(n) |nbuf| { as_utf16_p(n, |nbuf| {
libc::SetEnvironmentVariableW(nbuf, ptr::null()); libc::SetEnvironmentVariableW(nbuf, ptr::null());
} })
} })
} }
} }
@ -372,10 +368,10 @@ pub fn self_exe_path() -> Option<Path> {
if err != 0 { return None; } if err != 0 { return None; }
if sz == 0 { return None; } if sz == 0 { return None; }
let mut v: ~[u8] = vec::with_capacity(sz as uint); let mut v: ~[u8] = vec::with_capacity(sz as uint);
let err = do v.as_mut_buf |buf,_| { let err = v.as_mut_buf(|buf,_| {
sysctl(vec::raw::to_ptr(mib), mib.len() as ::libc::c_uint, sysctl(vec::raw::to_ptr(mib), mib.len() as ::libc::c_uint,
buf as *mut c_void, &mut sz, ptr::null(), 0u as size_t) buf as *mut c_void, &mut sz, ptr::null(), 0u as size_t)
}; });
if err != 0 { return None; } if err != 0 { return None; }
if sz == 0 { return None; } if sz == 0 { return None; }
vec::raw::set_len(&mut v, sz as uint - 1); // chop off trailing NUL vec::raw::set_len(&mut v, sz as uint - 1); // chop off trailing NUL
@ -403,9 +399,9 @@ pub fn self_exe_path() -> Option<Path> {
_NSGetExecutablePath(ptr::mut_null(), &mut sz); _NSGetExecutablePath(ptr::mut_null(), &mut sz);
if sz == 0 { return None; } if sz == 0 { return None; }
let mut v: ~[u8] = vec::with_capacity(sz as uint); let mut v: ~[u8] = vec::with_capacity(sz as uint);
let err = do v.as_mut_buf |buf,_| { let err = v.as_mut_buf(|buf, _| {
_NSGetExecutablePath(buf as *mut i8, &mut sz) _NSGetExecutablePath(buf as *mut i8, &mut sz)
}; });
if err != 0 { return None; } if err != 0 { return None; }
vec::raw::set_len(&mut v, sz as uint - 1); // chop off trailing NUL vec::raw::set_len(&mut v, sz as uint - 1); // chop off trailing NUL
Some(v) Some(v)
@ -416,9 +412,9 @@ pub fn self_exe_path() -> Option<Path> {
fn load_self() -> Option<~[u8]> { fn load_self() -> Option<~[u8]> {
unsafe { unsafe {
use os::win32::fill_utf16_buf_and_decode; use os::win32::fill_utf16_buf_and_decode;
do fill_utf16_buf_and_decode() |buf, sz| { fill_utf16_buf_and_decode(|buf, sz| {
libc::GetModuleFileNameW(0u as libc::DWORD, buf, sz) libc::GetModuleFileNameW(0u as libc::DWORD, buf, sz)
}.map(|s| s.into_bytes()) }).map(|s| s.into_bytes())
} }
} }
@ -452,13 +448,13 @@ pub fn homedir() -> Option<Path> {
#[cfg(windows)] #[cfg(windows)]
fn secondary() -> Option<Path> { fn secondary() -> Option<Path> {
do getenv("USERPROFILE").and_then |p| { getenv("USERPROFILE").and_then(|p| {
if !p.is_empty() { if !p.is_empty() {
Path::new_opt(p) Path::new_opt(p)
} else { } else {
None None
} }
} })
} }
} }
@ -536,19 +532,19 @@ pub fn change_dir(p: &Path) -> bool {
fn chdir(p: &Path) -> bool { fn chdir(p: &Path) -> bool {
unsafe { unsafe {
use os::win32::as_utf16_p; use os::win32::as_utf16_p;
return do as_utf16_p(p.as_str().unwrap()) |buf| { return as_utf16_p(p.as_str().unwrap(), |buf| {
libc::SetCurrentDirectoryW(buf) != (0 as libc::BOOL) libc::SetCurrentDirectoryW(buf) != (0 as libc::BOOL)
}; });
} }
} }
#[cfg(unix)] #[cfg(unix)]
fn chdir(p: &Path) -> bool { fn chdir(p: &Path) -> bool {
do p.with_c_str |buf| { p.with_c_str(|buf| {
unsafe { unsafe {
libc::chdir(buf) == (0 as c_int) libc::chdir(buf) == (0 as c_int)
} }
} })
} }
} }
@ -637,7 +633,7 @@ pub fn last_os_error() -> ~str {
let mut buf = [0 as c_char, ..TMPBUF_SZ]; let mut buf = [0 as c_char, ..TMPBUF_SZ];
do buf.as_mut_buf |buf, len| { buf.as_mut_buf(|buf, len| {
unsafe { unsafe {
if strerror_r(errno() as c_int, buf, len as size_t) < 0 { if strerror_r(errno() as c_int, buf, len as size_t) < 0 {
fail!("strerror_r failure"); fail!("strerror_r failure");
@ -645,7 +641,7 @@ pub fn last_os_error() -> ~str {
str::raw::from_c_str(buf as *c_char) str::raw::from_c_str(buf as *c_char)
} }
} })
} }
#[cfg(windows)] #[cfg(windows)]
@ -678,7 +674,7 @@ pub fn last_os_error() -> ~str {
let mut buf = [0 as WCHAR, ..TMPBUF_SZ]; let mut buf = [0 as WCHAR, ..TMPBUF_SZ];
unsafe { unsafe {
do buf.as_mut_buf |buf, len| { buf.as_mut_buf(|buf, len| {
let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS, FORMAT_MESSAGE_IGNORE_INSERTS,
ptr::mut_null(), ptr::mut_null(),
@ -690,7 +686,7 @@ pub fn last_os_error() -> ~str {
if res == 0 { if res == 0 {
fail!("[{}] FormatMessage failure", errno()); fail!("[{}] FormatMessage failure", errno());
} }
} });
str::from_utf16(buf) str::from_utf16(buf)
} }
@ -1466,13 +1462,11 @@ mod tests {
let size = MemoryMap::granularity() * 2; let size = MemoryMap::granularity() * 2;
let fd = unsafe { let fd = unsafe {
let fd = do path.with_c_str |path| { let fd = path.with_c_str(|path| {
open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR) open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR)
}; });
lseek_(fd, size); lseek_(fd, size);
do "x".with_c_str |x| { "x".with_c_str(|x| assert!(write(fd, x as *c_void, 1) == 1));
assert!(write(fd, x as *c_void, 1) == 1);
}
fd fd
}; };
let chunk = match MemoryMap::new(size / 2, [ let chunk = match MemoryMap::new(size / 2, [
@ -1491,7 +1485,7 @@ mod tests {
assert!(*chunk.data == 0xbe); assert!(*chunk.data == 0xbe);
close(fd); close(fd);
} }
do io::ignore_io_error { fs::unlink(&path); } io::ignore_io_error(|| fs::unlink(&path));
} }
// More recursive_mkdir tests are in extra::tempfile // More recursive_mkdir tests are in extra::tempfile

View file

@ -530,9 +530,7 @@ pub struct Display<'self, P> {
impl<'self, P: GenericPath> fmt::Default for Display<'self, P> { impl<'self, P: GenericPath> fmt::Default for Display<'self, P> {
fn fmt(d: &Display<P>, f: &mut fmt::Formatter) { fn fmt(d: &Display<P>, f: &mut fmt::Formatter) {
do d.with_str |s| { d.with_str(|s| f.pad(s))
f.pad(s)
}
} }
} }

View file

@ -51,9 +51,9 @@ impl IsaacRng {
unsafe { unsafe {
let ptr = raw::to_mut_ptr(rng.rsl); let ptr = raw::to_mut_ptr(rng.rsl);
do raw::mut_buf_as_slice(ptr as *mut u8, mem::size_of_val(&rng.rsl)) |slice| { raw::mut_buf_as_slice(ptr as *mut u8, mem::size_of_val(&rng.rsl), |slice| {
OSRng::new().fill_bytes(slice); OSRng::new().fill_bytes(slice);
} })
} }
rng.init(true); rng.init(true);
@ -94,7 +94,7 @@ impl IsaacRng {
}} }}
); );
do 4.times { mix!(); } 4.times(|| mix!());
if use_rsl { if use_rsl {
macro_rules! memloop ( macro_rules! memloop (
@ -256,9 +256,9 @@ impl Isaac64Rng {
unsafe { unsafe {
let ptr = raw::to_mut_ptr(rng.rsl); let ptr = raw::to_mut_ptr(rng.rsl);
do raw::mut_buf_as_slice(ptr as *mut u8, mem::size_of_val(&rng.rsl)) |slice| { raw::mut_buf_as_slice(ptr as *mut u8, mem::size_of_val(&rng.rsl), |slice| {
OSRng::new().fill_bytes(slice); OSRng::new().fill_bytes(slice);
} })
} }
rng.init(true); rng.init(true);

View file

@ -168,6 +168,28 @@ impl<T> Drop for Rc<T> {
} }
} }
impl<T> Clone for RcMut<T> {
/// Return a shallow copy of the reference counted pointer.
#[inline]
fn clone(&self) -> RcMut<T> {
unsafe {
(*self.ptr).count += 1;
RcMut{ptr: self.ptr}
}
}
}
impl<T: DeepClone> DeepClone for RcMut<T> {
/// Return a deep copy of the reference counted pointer.
#[inline]
fn deep_clone(&self) -> RcMut<T> {
self.with_borrow(|x| {
// FIXME: #6497: should avoid freeze (slow)
unsafe { RcMut::new_unchecked(x.deep_clone()) }
})
}
}
#[cfg(test)] #[cfg(test)]
mod test_rc { mod test_rc {
use super::*; use super::*;
@ -177,9 +199,9 @@ mod test_rc {
fn test_clone() { fn test_clone() {
let x = Rc::from_send(RefCell::new(5)); let x = Rc::from_send(RefCell::new(5));
let y = x.clone(); let y = x.clone();
do x.borrow().with_mut |inner| { x.borrow().with_mut(|inner| {
*inner = 20; *inner = 20;
} });
assert_eq!(y.borrow().with(|v| *v), 20); assert_eq!(y.borrow().with(|v| *v), 20);
} }
@ -187,9 +209,9 @@ mod test_rc {
fn test_deep_clone() { fn test_deep_clone() {
let x = Rc::from_send(RefCell::new(5)); let x = Rc::from_send(RefCell::new(5));
let y = x.deep_clone(); let y = x.deep_clone();
do x.borrow().with_mut |inner| { x.borrow().with_mut(|inner| {
*inner = 20; *inner = 20;
} });
assert_eq!(y.borrow().with(|v| *v), 5); assert_eq!(y.borrow().with(|v| *v), 5);
} }

View file

@ -50,16 +50,12 @@ pub fn MovePtrAdaptor<V:TyVisitor + MovePtr>(v: V) -> MovePtrAdaptor<V> {
impl<V:TyVisitor + MovePtr> MovePtrAdaptor<V> { impl<V:TyVisitor + MovePtr> MovePtrAdaptor<V> {
#[inline] #[inline]
pub fn bump(&mut self, sz: uint) { pub fn bump(&mut self, sz: uint) {
do self.inner.move_ptr() |p| { self.inner.move_ptr(|p| ((p as uint) + sz) as *c_void)
((p as uint) + sz) as *c_void
};
} }
#[inline] #[inline]
pub fn align(&mut self, a: uint) { pub fn align(&mut self, a: uint) {
do self.inner.move_ptr() |p| { self.inner.move_ptr(|p| align(p as uint, a) as *c_void)
align(p as uint, a) as *c_void
};
} }
#[inline] #[inline]

View file

@ -53,18 +53,18 @@ impl Repr for bool {
impl Repr for int { impl Repr for int {
fn write_repr(&self, writer: &mut io::Writer) { fn write_repr(&self, writer: &mut io::Writer) {
do ::int::to_str_bytes(*self, 10u) |bits| { ::int::to_str_bytes(*self, 10u, |bits| {
writer.write(bits); writer.write(bits);
} })
} }
} }
macro_rules! int_repr(($ty:ident, $suffix:expr) => (impl Repr for $ty { macro_rules! int_repr(($ty:ident, $suffix:expr) => (impl Repr for $ty {
fn write_repr(&self, writer: &mut io::Writer) { fn write_repr(&self, writer: &mut io::Writer) {
do ::$ty::to_str_bytes(*self, 10u) |bits| { ::$ty::to_str_bytes(*self, 10u, |bits| {
writer.write(bits); writer.write(bits);
writer.write(bytes!($suffix)); writer.write(bytes!($suffix));
} })
} }
})) }))
@ -163,9 +163,9 @@ impl<'self> ReprVisitor<'self> {
#[inline] #[inline]
pub fn write<T:Repr>(&mut self) -> bool { pub fn write<T:Repr>(&mut self) -> bool {
do self.get |this, v:&T| { self.get(|this, v:&T| {
v.write_repr(unsafe { ::cast::transmute_copy(&this.writer) }); v.write_repr(unsafe { ::cast::transmute_copy(&this.writer) });
} })
} }
pub fn write_escaped_slice(&mut self, slice: &str) { pub fn write_escaped_slice(&mut self, slice: &str) {
@ -234,9 +234,9 @@ impl<'self> ReprVisitor<'self> {
} }
'\x20'..'\x7e' => self.writer.write([ch as u8]), '\x20'..'\x7e' => self.writer.write([ch as u8]),
_ => { _ => {
do char::escape_unicode(ch) |c| { char::escape_unicode(ch, |c| {
self.writer.write([c as u8]); self.writer.write([c as u8]);
} })
} }
} }
} }
@ -265,31 +265,29 @@ impl<'self> TyVisitor for ReprVisitor<'self> {
fn visit_f64(&mut self) -> bool { self.write::<f64>() } fn visit_f64(&mut self) -> bool { self.write::<f64>() }
fn visit_char(&mut self) -> bool { fn visit_char(&mut self) -> bool {
do self.get::<char> |this, &ch| { self.get::<char>(|this, &ch| {
this.writer.write(['\'' as u8]); this.writer.write(['\'' as u8]);
this.write_escaped_char(ch, false); this.write_escaped_char(ch, false);
this.writer.write(['\'' as u8]); this.writer.write(['\'' as u8]);
} })
} }
fn visit_estr_box(&mut self) -> bool { fn visit_estr_box(&mut self) -> bool {
do self.get::<@str> |this, s| { self.get::<@str>(|this, s| {
this.writer.write(['@' as u8]); this.writer.write(['@' as u8]);
this.write_escaped_slice(*s); this.write_escaped_slice(*s);
} })
} }
fn visit_estr_uniq(&mut self) -> bool { fn visit_estr_uniq(&mut self) -> bool {
do self.get::<~str> |this, s| { self.get::<~str>(|this, s| {
this.writer.write(['~' as u8]); this.writer.write(['~' as u8]);
this.write_escaped_slice(*s); this.write_escaped_slice(*s);
} })
} }
fn visit_estr_slice(&mut self) -> bool { fn visit_estr_slice(&mut self) -> bool {
do self.get::<&str> |this, s| { self.get::<&str>(|this, s| this.write_escaped_slice(*s))
this.write_escaped_slice(*s);
}
} }
// Type no longer exists, vestigial function. // Type no longer exists, vestigial function.
@ -299,91 +297,91 @@ impl<'self> TyVisitor for ReprVisitor<'self> {
fn visit_box(&mut self, mtbl: uint, inner: *TyDesc) -> bool { fn visit_box(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
self.writer.write(['@' as u8]); self.writer.write(['@' as u8]);
self.write_mut_qualifier(mtbl); self.write_mut_qualifier(mtbl);
do self.get::<&raw::Box<()>> |this, b| { self.get::<&raw::Box<()>>(|this, b| {
let p = ptr::to_unsafe_ptr(&b.data) as *c_void; let p = ptr::to_unsafe_ptr(&b.data) as *c_void;
this.visit_ptr_inner(p, inner); this.visit_ptr_inner(p, inner);
} })
} }
fn visit_uniq(&mut self, _mtbl: uint, inner: *TyDesc) -> bool { fn visit_uniq(&mut self, _mtbl: uint, inner: *TyDesc) -> bool {
self.writer.write(['~' as u8]); self.writer.write(['~' as u8]);
do self.get::<*c_void> |this, b| { self.get::<*c_void>(|this, b| {
this.visit_ptr_inner(*b, inner); this.visit_ptr_inner(*b, inner);
} })
} }
fn visit_uniq_managed(&mut self, _mtbl: uint, inner: *TyDesc) -> bool { fn visit_uniq_managed(&mut self, _mtbl: uint, inner: *TyDesc) -> bool {
self.writer.write(['~' as u8]); self.writer.write(['~' as u8]);
do self.get::<&raw::Box<()>> |this, b| { self.get::<&raw::Box<()>>(|this, b| {
let p = ptr::to_unsafe_ptr(&b.data) as *c_void; let p = ptr::to_unsafe_ptr(&b.data) as *c_void;
this.visit_ptr_inner(p, inner); this.visit_ptr_inner(p, inner);
} })
} }
fn visit_ptr(&mut self, mtbl: uint, _inner: *TyDesc) -> bool { fn visit_ptr(&mut self, mtbl: uint, _inner: *TyDesc) -> bool {
do self.get::<*c_void> |this, p| { self.get::<*c_void>(|this, p| {
write!(this.writer, "({} as *", *p); write!(this.writer, "({} as *", *p);
this.write_mut_qualifier(mtbl); this.write_mut_qualifier(mtbl);
this.writer.write("())".as_bytes()); this.writer.write("())".as_bytes());
} })
} }
fn visit_rptr(&mut self, mtbl: uint, inner: *TyDesc) -> bool { fn visit_rptr(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
self.writer.write(['&' as u8]); self.writer.write(['&' as u8]);
self.write_mut_qualifier(mtbl); self.write_mut_qualifier(mtbl);
do self.get::<*c_void> |this, p| { self.get::<*c_void>(|this, p| {
this.visit_ptr_inner(*p, inner); this.visit_ptr_inner(*p, inner);
} })
} }
// Type no longer exists, vestigial function. // Type no longer exists, vestigial function.
fn visit_vec(&mut self, _mtbl: uint, _inner: *TyDesc) -> bool { fail!(); } fn visit_vec(&mut self, _mtbl: uint, _inner: *TyDesc) -> bool { fail!(); }
fn visit_unboxed_vec(&mut self, mtbl: uint, inner: *TyDesc) -> bool { fn visit_unboxed_vec(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
do self.get::<raw::Vec<()>> |this, b| { self.get::<raw::Vec<()>>(|this, b| {
this.write_unboxed_vec_repr(mtbl, b, inner); this.write_unboxed_vec_repr(mtbl, b, inner);
} })
} }
fn visit_evec_box(&mut self, mtbl: uint, inner: *TyDesc) -> bool { fn visit_evec_box(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
do self.get::<&raw::Box<raw::Vec<()>>> |this, b| { self.get::<&raw::Box<raw::Vec<()>>>(|this, b| {
this.writer.write(['@' as u8]); this.writer.write(['@' as u8]);
this.write_mut_qualifier(mtbl); this.write_mut_qualifier(mtbl);
this.write_unboxed_vec_repr(mtbl, &b.data, inner); this.write_unboxed_vec_repr(mtbl, &b.data, inner);
} })
} }
fn visit_evec_uniq(&mut self, mtbl: uint, inner: *TyDesc) -> bool { fn visit_evec_uniq(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
do self.get::<&raw::Vec<()>> |this, b| { self.get::<&raw::Vec<()>>(|this, b| {
this.writer.write(['~' as u8]); this.writer.write(['~' as u8]);
this.write_unboxed_vec_repr(mtbl, *b, inner); this.write_unboxed_vec_repr(mtbl, *b, inner);
} })
} }
fn visit_evec_uniq_managed(&mut self, mtbl: uint, inner: *TyDesc) -> bool { fn visit_evec_uniq_managed(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
do self.get::<&raw::Box<raw::Vec<()>>> |this, b| { self.get::<&raw::Box<raw::Vec<()>>>(|this, b| {
this.writer.write(['~' as u8]); this.writer.write(['~' as u8]);
this.write_unboxed_vec_repr(mtbl, &b.data, inner); this.write_unboxed_vec_repr(mtbl, &b.data, inner);
} })
} }
fn visit_evec_slice(&mut self, mtbl: uint, inner: *TyDesc) -> bool { fn visit_evec_slice(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
do self.get::<raw::Slice<()>> |this, s| { self.get::<raw::Slice<()>>(|this, s| {
this.writer.write(['&' as u8]); this.writer.write(['&' as u8]);
this.write_mut_qualifier(mtbl); this.write_mut_qualifier(mtbl);
let size = unsafe { let size = unsafe {
if (*inner).size == 0 { 1 } else { (*inner).size } if (*inner).size == 0 { 1 } else { (*inner).size }
}; };
this.write_vec_range(s.data, s.len * size, inner); this.write_vec_range(s.data, s.len * size, inner);
} })
} }
fn visit_evec_fixed(&mut self, n: uint, sz: uint, _align: uint, fn visit_evec_fixed(&mut self, n: uint, sz: uint, _align: uint,
_: uint, inner: *TyDesc) -> bool { _: uint, inner: *TyDesc) -> bool {
let assumed_size = if sz == 0 { n } else { sz }; let assumed_size = if sz == 0 { n } else { sz };
do self.get::<()> |this, b| { self.get::<()>(|this, b| {
this.write_vec_range(ptr::to_unsafe_ptr(b), assumed_size, inner); this.write_vec_range(ptr::to_unsafe_ptr(b), assumed_size, inner);
} })
} }
fn visit_enter_rec(&mut self, _n_fields: uint, fn visit_enter_rec(&mut self, _n_fields: uint,
@ -600,10 +598,10 @@ impl<'self> TyVisitor for ReprVisitor<'self> {
fn visit_opaque_box(&mut self) -> bool { fn visit_opaque_box(&mut self) -> bool {
self.writer.write(['@' as u8]); self.writer.write(['@' as u8]);
do self.get::<&raw::Box<()>> |this, b| { self.get::<&raw::Box<()>>(|this, b| {
let p = ptr::to_unsafe_ptr(&b.data) as *c_void; let p = ptr::to_unsafe_ptr(&b.data) as *c_void;
this.visit_ptr_inner(p, b.type_desc); this.visit_ptr_inner(p, b.type_desc);
} })
} }
fn visit_closure_ptr(&mut self, _ck: uint) -> bool { true } fn visit_closure_ptr(&mut self, _ck: uint) -> bool { true }

View file

@ -71,13 +71,13 @@ impl BasicLoop {
fn remote_work(&mut self) { fn remote_work(&mut self) {
let messages = unsafe { let messages = unsafe {
do self.messages.with |messages| { self.messages.with(|messages| {
if messages.len() > 0 { if messages.len() > 0 {
Some(util::replace(messages, ~[])) Some(util::replace(messages, ~[]))
} else { } else {
None None
} }
} })
}; };
let messages = match messages { let messages = match messages {
Some(m) => m, None => return Some(m) => m, None => return
@ -139,11 +139,11 @@ impl EventLoop for BasicLoop {
unsafe { unsafe {
// We block here if we have no messages to process and we may // We block here if we have no messages to process and we may
// receive a message at a later date // receive a message at a later date
do self.messages.hold_and_wait |messages| { self.messages.hold_and_wait(|messages| {
self.remotes.len() > 0 && self.remotes.len() > 0 &&
messages.len() == 0 && messages.len() == 0 &&
self.work.len() == 0 self.work.len() == 0
} })
} }
} }
} }
@ -189,9 +189,9 @@ impl BasicRemote {
impl RemoteCallback for BasicRemote { impl RemoteCallback for BasicRemote {
fn fire(&mut self) { fn fire(&mut self) {
unsafe { unsafe {
do self.queue.hold_and_signal |queue| { self.queue.hold_and_signal(|queue| {
queue.push(RunRemote(self.id)); queue.push(RunRemote(self.id));
} })
} }
} }
} }
@ -199,9 +199,9 @@ impl RemoteCallback for BasicRemote {
impl Drop for BasicRemote { impl Drop for BasicRemote {
fn drop(&mut self) { fn drop(&mut self) {
unsafe { unsafe {
do self.queue.hold_and_signal |queue| { self.queue.hold_and_signal(|queue| {
queue.push(RemoveRemote(self.id)); queue.push(RemoveRemote(self.id));
} })
} }
} }
} }

View file

@ -35,9 +35,7 @@ pub struct BorrowRecord {
} }
fn try_take_task_borrow_list() -> Option<~[BorrowRecord]> { fn try_take_task_borrow_list() -> Option<~[BorrowRecord]> {
do Local::borrow |task: &mut Task| { Local::borrow(|task: &mut Task| task.borrow_list.take())
task.borrow_list.take()
}
} }
fn swap_task_borrow_list(f: |~[BorrowRecord]| -> ~[BorrowRecord]) { fn swap_task_borrow_list(f: |~[BorrowRecord]| -> ~[BorrowRecord]) {
@ -47,9 +45,7 @@ fn swap_task_borrow_list(f: |~[BorrowRecord]| -> ~[BorrowRecord]) {
}; };
let borrows = f(borrows); let borrows = f(borrows);
let borrows = Cell::new(borrows); let borrows = Cell::new(borrows);
do Local::borrow |task: &mut Task| { Local::borrow(|task: &mut Task| task.borrow_list = Some(borrows.take()))
task.borrow_list = Some(borrows.take());
}
} }
pub fn clear_task_borrow_list() { pub fn clear_task_borrow_list() {
@ -64,9 +60,7 @@ unsafe fn fail_borrowed(box: *mut raw::Box<()>, file: *c_char, line: size_t) ->
match try_take_task_borrow_list() { match try_take_task_borrow_list() {
None => { // not recording borrows None => { // not recording borrows
let msg = "borrowed"; let msg = "borrowed";
do msg.with_c_str |msg_p| { msg.with_c_str(|msg_p| task::begin_unwind_raw(msg_p, file, line))
task::begin_unwind_raw(msg_p, file, line);
}
} }
Some(borrow_list) => { // recording borrows Some(borrow_list) => { // recording borrows
let mut msg = ~"borrowed"; let mut msg = ~"borrowed";
@ -80,9 +74,7 @@ unsafe fn fail_borrowed(box: *mut raw::Box<()>, file: *c_char, line: size_t) ->
sep = " and at "; sep = " and at ";
} }
} }
do msg.with_c_str |msg_p| { msg.with_c_str(|msg_p| task::begin_unwind_raw(msg_p, file, line))
task::begin_unwind_raw(msg_p, file, line)
}
} }
} }
} }
@ -158,33 +150,35 @@ pub unsafe fn record_borrow(a: *u8, old_ref_count: uint,
// was not borrowed before // was not borrowed before
let a = a as *mut raw::Box<()>; let a = a as *mut raw::Box<()>;
debug_borrow("record_borrow:", a, old_ref_count, 0, file, line); debug_borrow("record_borrow:", a, old_ref_count, 0, file, line);
do swap_task_borrow_list |borrow_list| { swap_task_borrow_list(|borrow_list| {
let mut borrow_list = borrow_list; let mut borrow_list = borrow_list;
borrow_list.push(BorrowRecord {box: a, file: file, line: line}); borrow_list.push(BorrowRecord {box: a, file: file, line: line});
borrow_list borrow_list
} })
} }
} }
pub unsafe fn unrecord_borrow(a: *u8, old_ref_count: uint, pub unsafe fn unrecord_borrow(a: *u8,
file: *c_char, line: size_t) { old_ref_count: uint,
file: *c_char,
line: size_t) {
if (old_ref_count & ALL_BITS) == 0 { if (old_ref_count & ALL_BITS) == 0 {
// was not borrowed before, so we should find the record at // was not borrowed before, so we should find the record at
// the end of the list // the end of the list
let a = a as *mut raw::Box<()>; let a = a as *mut raw::Box<()>;
debug_borrow("unrecord_borrow:", a, old_ref_count, 0, file, line); debug_borrow("unrecord_borrow:", a, old_ref_count, 0, file, line);
do swap_task_borrow_list |borrow_list| { swap_task_borrow_list(|borrow_list| {
let mut borrow_list = borrow_list; let mut borrow_list = borrow_list;
assert!(!borrow_list.is_empty()); assert!(!borrow_list.is_empty());
let br = borrow_list.pop(); let br = borrow_list.pop();
if br.box != a || br.file != file || br.line != line { if br.box != a || br.file != file || br.line != line {
let err = format!("wrong borrow found, br={:?}", br); let err = format!("wrong borrow found, br={:?}", br);
do err.with_c_str |msg_p| { err.with_c_str(|msg_p| {
task::begin_unwind_raw(msg_p, file, line) task::begin_unwind_raw(msg_p, file, line)
} })
} }
borrow_list borrow_list
} })
} }
} }

View file

@ -165,14 +165,14 @@ impl<T: Send> ChanOne<T> {
// Port is blocked. Wake it up. // Port is blocked. Wake it up.
let recvr = BlockedTask::cast_from_uint(task_as_state); let recvr = BlockedTask::cast_from_uint(task_as_state);
if do_resched { if do_resched {
do recvr.wake().map |woken_task| { recvr.wake().map(|woken_task| {
Scheduler::run_task(woken_task); Scheduler::run_task(woken_task);
}; });
} else { } else {
let recvr = Cell::new(recvr); let recvr = Cell::new(recvr);
do Local::borrow |sched: &mut Scheduler| { Local::borrow(|sched: &mut Scheduler| {
sched.enqueue_blocked_task(recvr.take()); sched.enqueue_blocked_task(recvr.take());
} })
} }
} }
} }
@ -209,9 +209,9 @@ impl<T: Send> PortOne<T> {
// No data available yet. // No data available yet.
// Switch to the scheduler to put the ~Task into the Packet state. // Switch to the scheduler to put the ~Task into the Packet state.
let sched: ~Scheduler = Local::take(); let sched: ~Scheduler = Local::take();
do sched.deschedule_running_task_and_then |sched, task| { sched.deschedule_running_task_and_then(|sched, task| {
self.block_on(sched, task); self.block_on(sched, task);
} })
} }
// Task resumes. // Task resumes.
@ -230,9 +230,9 @@ impl<T: Send> SelectInner for PortOne<T> {
// The optimistic check is never necessary for correctness. For testing // The optimistic check is never necessary for correctness. For testing
// purposes, making it randomly return false simulates a racing sender. // purposes, making it randomly return false simulates a racing sender.
use rand::{Rand}; use rand::{Rand};
let actually_check = do Local::borrow |sched: &mut Scheduler| { let actually_check = Local::borrow(|sched: &mut Scheduler| {
Rand::rand(&mut sched.rng) Rand::rand(&mut sched.rng)
}; });
if actually_check { if actually_check {
unsafe { (*self.packet()).state.load(Acquire) == STATE_ONE } unsafe { (*self.packet()).state.load(Acquire) == STATE_ONE }
} else { } else {
@ -387,9 +387,9 @@ impl<T: Send> Drop for ChanOne<T> {
// The port is blocked waiting for a message we will never send. Wake it. // The port is blocked waiting for a message we will never send. Wake it.
rtassert!((*self.packet()).payload.is_none()); rtassert!((*self.packet()).payload.is_none());
let recvr = BlockedTask::cast_from_uint(task_as_state); let recvr = BlockedTask::cast_from_uint(task_as_state);
do recvr.wake().map |woken_task| { recvr.wake().map(|woken_task| {
Scheduler::run_task(woken_task); Scheduler::run_task(woken_task);
}; });
} }
} }
} }
@ -491,7 +491,7 @@ impl<T: Send> GenericPort<T> for Port<T> {
fn try_recv(&self) -> Option<T> { fn try_recv(&self) -> Option<T> {
let mut b = self.next.borrow_mut(); let mut b = self.next.borrow_mut();
do b.get().take().map_default(None) |pone| { b.get().take().map_default(None, |pone| {
match pone.try_recv() { match pone.try_recv() {
Some(StreamPayload { val, next }) => { Some(StreamPayload { val, next }) => {
*b.get() = Some(next); *b.get() = Some(next);
@ -499,7 +499,7 @@ impl<T: Send> GenericPort<T> for Port<T> {
} }
None => None None => None
} }
} })
} }
} }
@ -516,7 +516,7 @@ impl<T: Send> Peekable<T> for Port<T> {
impl<'self, T: Send> SelectInner for &'self Port<T> { impl<'self, T: Send> SelectInner for &'self Port<T> {
#[inline] #[inline]
fn optimistic_check(&mut self) -> bool { fn optimistic_check(&mut self) -> bool {
do self.next.with_mut |pone| { pone.get_mut_ref().optimistic_check() } self.next.with_mut(|pone| { pone.get_mut_ref().optimistic_check() })
} }
#[inline] #[inline]
@ -527,7 +527,7 @@ impl<'self, T: Send> SelectInner for &'self Port<T> {
#[inline] #[inline]
fn unblock_from(&mut self) -> bool { fn unblock_from(&mut self) -> bool {
do self.next.with_mut |pone| { pone.get_mut_ref().unblock_from() } self.next.with_mut(|pone| { pone.get_mut_ref().unblock_from() })
} }
} }
@ -871,7 +871,7 @@ mod test {
#[test] #[test]
fn oneshot_multi_thread_close_stress() { fn oneshot_multi_thread_close_stress() {
if util::limit_thread_creation_due_to_osx_and_valgrind() { return; } if util::limit_thread_creation_due_to_osx_and_valgrind() { return; }
do stress_factor().times { stress_factor().times(|| {
do run_in_newsched_task { do run_in_newsched_task {
let (port, chan) = oneshot::<int>(); let (port, chan) = oneshot::<int>();
let port_cell = Cell::new(port); let port_cell = Cell::new(port);
@ -881,13 +881,13 @@ mod test {
let _chan = chan; let _chan = chan;
thread.join(); thread.join();
} }
} })
} }
#[test] #[test]
fn oneshot_multi_thread_send_close_stress() { fn oneshot_multi_thread_send_close_stress() {
if util::limit_thread_creation_due_to_osx_and_valgrind() { return; } if util::limit_thread_creation_due_to_osx_and_valgrind() { return; }
do stress_factor().times { stress_factor().times(|| {
do run_in_newsched_task { do run_in_newsched_task {
let (port, chan) = oneshot::<int>(); let (port, chan) = oneshot::<int>();
let chan_cell = Cell::new(chan); let chan_cell = Cell::new(chan);
@ -902,13 +902,13 @@ mod test {
thread1.join(); thread1.join();
thread2.join(); thread2.join();
} }
} })
} }
#[test] #[test]
fn oneshot_multi_thread_recv_close_stress() { fn oneshot_multi_thread_recv_close_stress() {
if util::limit_thread_creation_due_to_osx_and_valgrind() { return; } if util::limit_thread_creation_due_to_osx_and_valgrind() { return; }
do stress_factor().times { stress_factor().times(|| {
do run_in_newsched_task { do run_in_newsched_task {
let (port, chan) = oneshot::<int>(); let (port, chan) = oneshot::<int>();
let chan_cell = Cell::new(chan); let chan_cell = Cell::new(chan);
@ -929,13 +929,13 @@ mod test {
thread1.join(); thread1.join();
thread2.join(); thread2.join();
} }
} })
} }
#[test] #[test]
fn oneshot_multi_thread_send_recv_stress() { fn oneshot_multi_thread_send_recv_stress() {
if util::limit_thread_creation_due_to_osx_and_valgrind() { return; } if util::limit_thread_creation_due_to_osx_and_valgrind() { return; }
do stress_factor().times { stress_factor().times(|| {
do run_in_newsched_task { do run_in_newsched_task {
let (port, chan) = oneshot::<~int>(); let (port, chan) = oneshot::<~int>();
let chan_cell = Cell::new(chan); let chan_cell = Cell::new(chan);
@ -949,13 +949,13 @@ mod test {
thread1.join(); thread1.join();
thread2.join(); thread2.join();
} }
} })
} }
#[test] #[test]
fn stream_send_recv_stress() { fn stream_send_recv_stress() {
if util::limit_thread_creation_due_to_osx_and_valgrind() { return; } if util::limit_thread_creation_due_to_osx_and_valgrind() { return; }
do stress_factor().times { stress_factor().times(|| {
do run_in_mt_newsched_task { do run_in_mt_newsched_task {
let (port, chan) = stream::<~int>(); let (port, chan) = stream::<~int>();
@ -984,17 +984,17 @@ mod test {
}; };
} }
} }
} })
} }
#[test] #[test]
fn recv_a_lot() { fn recv_a_lot() {
// Regression test that we don't run out of stack in scheduler context // Regression test that we don't run out of stack in scheduler context
do run_in_newsched_task { run_in_newsched_task(|| {
let (port, chan) = stream(); let (port, chan) = stream();
do 10000.times { chan.send(()) } 10000.times(|| { chan.send(()) });
do 10000.times { port.recv() } 10000.times(|| { port.recv() });
} })
} }
#[test] #[test]
@ -1004,16 +1004,16 @@ mod test {
let (port, chan) = stream(); let (port, chan) = stream();
let chan = SharedChan::new(chan); let chan = SharedChan::new(chan);
let total = stress_factor() + 100; let total = stress_factor() + 100;
do total.times { total.times(|| {
let chan_clone = chan.clone(); let chan_clone = chan.clone();
do spawntask_random { do spawntask_random {
chan_clone.send(()); chan_clone.send(());
} }
} });
do total.times { total.times(|| {
port.recv(); port.recv();
} })
} }
} }
@ -1026,22 +1026,22 @@ mod test {
let end_chan = SharedChan::new(end_chan); let end_chan = SharedChan::new(end_chan);
let port = SharedPort::new(port); let port = SharedPort::new(port);
let total = stress_factor() + 100; let total = stress_factor() + 100;
do total.times { total.times(|| {
let end_chan_clone = end_chan.clone(); let end_chan_clone = end_chan.clone();
let port_clone = port.clone(); let port_clone = port.clone();
do spawntask_random { do spawntask_random {
port_clone.recv(); port_clone.recv();
end_chan_clone.send(()); end_chan_clone.send(());
} }
} });
do total.times { total.times(|| {
chan.send(()); chan.send(());
} });
do total.times { total.times(|| {
end_port.recv(); end_port.recv();
} })
} }
} }
@ -1066,29 +1066,29 @@ mod test {
let send_total = 10; let send_total = 10;
let recv_total = 20; let recv_total = 20;
do spawntask_random { do spawntask_random {
do send_total.times { send_total.times(|| {
let chan_clone = chan.clone(); let chan_clone = chan.clone();
do spawntask_random { do spawntask_random {
chan_clone.send(()); chan_clone.send(());
} }
} })
} }
let end_chan_clone = end_chan.clone(); let end_chan_clone = end_chan.clone();
do spawntask_random { do spawntask_random {
do recv_total.times { recv_total.times(|| {
let port_clone = port.clone(); let port_clone = port.clone();
let end_chan_clone = end_chan_clone.clone(); let end_chan_clone = end_chan_clone.clone();
do spawntask_random { do spawntask_random {
let recvd = port_clone.try_recv().is_some(); let recvd = port_clone.try_recv().is_some();
end_chan_clone.send(recvd); end_chan_clone.send(recvd);
} }
} })
} }
let mut recvd = 0; let mut recvd = 0;
do recv_total.times { recv_total.times(|| {
recvd += if end_port.recv() { 1 } else { 0 }; recvd += if end_port.recv() { 1 } else { 0 };
} });
assert!(recvd == send_total); assert!(recvd == send_total);
} }
@ -1107,7 +1107,7 @@ mod test {
let pipe = megapipe(); let pipe = megapipe();
let total = stress_factor() + 10; let total = stress_factor() + 10;
let mut rng = rand::rng(); let mut rng = rand::rng();
do total.times { total.times(|| {
let msgs = rng.gen_range(0u, 10); let msgs = rng.gen_range(0u, 10);
let pipe_clone = pipe.clone(); let pipe_clone = pipe.clone();
let end_chan_clone = end_chan.clone(); let end_chan_clone = end_chan.clone();
@ -1121,11 +1121,11 @@ mod test {
} }
end_chan_clone.send(()); end_chan_clone.send(());
} });
do total.times { total.times(|| {
end_port.recv(); end_port.recv();
} })
} }
} }
@ -1152,13 +1152,13 @@ mod test {
let cs = Cell::new((cone, cstream, cshared, mp)); let cs = Cell::new((cone, cstream, cshared, mp));
unsafe { unsafe {
do atomically { atomically(|| {
let (cone, cstream, cshared, mp) = cs.take(); let (cone, cstream, cshared, mp) = cs.take();
cone.send_deferred(()); cone.send_deferred(());
cstream.send_deferred(()); cstream.send_deferred(());
cshared.send_deferred(()); cshared.send_deferred(());
mp.send_deferred(()); mp.send_deferred(());
} })
} }
} }
} }

View file

@ -257,10 +257,7 @@ impl Death {
/// Collect failure exit codes from children and propagate them to a parent. /// Collect failure exit codes from children and propagate them to a parent.
pub fn collect_failure(&mut self, result: UnwindResult) { pub fn collect_failure(&mut self, result: UnwindResult) {
let result = Cell::new(result); let result = Cell::new(result);
self.on_exit.take().map(|on_exit| on_exit(result.take()));
do self.on_exit.take().map |on_exit| {
on_exit(result.take());
};
} }
/// Enter a possibly-nested "atomic" section of code. Just for assertions. /// Enter a possibly-nested "atomic" section of code. Just for assertions.

View file

@ -34,10 +34,10 @@ impl Local for Task {
let mut res: Option<T> = None; let mut res: Option<T> = None;
let res_ptr: *mut Option<T> = &mut res; let res_ptr: *mut Option<T> = &mut res;
unsafe { unsafe {
do local_ptr::borrow |task| { local_ptr::borrow(|task| {
let result = f(task); let result = f(task);
*res_ptr = Some(result); *res_ptr = Some(result);
} })
} }
match res { match res {
Some(r) => { r } Some(r) => { r }
@ -57,10 +57,10 @@ impl Local for Task {
impl Local for Scheduler { impl Local for Scheduler {
fn put(value: ~Scheduler) { fn put(value: ~Scheduler) {
let value = Cell::new(value); let value = Cell::new(value);
do Local::borrow |task: &mut Task| { Local::borrow(|task: &mut Task| {
let task = task; let task = task;
task.sched = Some(value.take()); task.sched = Some(value.take());
}; });
} }
#[inline] #[inline]
fn take() -> ~Scheduler { fn take() -> ~Scheduler {
@ -71,15 +71,15 @@ impl Local for Scheduler {
} }
} }
fn exists(_: Option<Scheduler>) -> bool { fn exists(_: Option<Scheduler>) -> bool {
do Local::borrow |task: &mut Task| { Local::borrow(|task: &mut Task| {
match task.sched { match task.sched {
Some(ref _task) => true, Some(ref _task) => true,
None => false None => false
} }
} })
} }
fn borrow<T>(f: |&mut Scheduler| -> T) -> T { fn borrow<T>(f: |&mut Scheduler| -> T) -> T {
do Local::borrow |task: &mut Task| { Local::borrow(|task: &mut Task| {
match task.sched { match task.sched {
Some(~ref mut task) => { Some(~ref mut task) => {
f(task) f(task)
@ -88,7 +88,7 @@ impl Local for Scheduler {
rtabort!("no scheduler") rtabort!("no scheduler")
} }
} }
} })
} }
unsafe fn unsafe_take() -> ~Scheduler { rtabort!("unimpl") } unsafe fn unsafe_take() -> ~Scheduler { rtabort!("unimpl") }
unsafe fn unsafe_borrow() -> *mut Scheduler { unsafe fn unsafe_borrow() -> *mut Scheduler {

View file

@ -302,9 +302,7 @@ pub unsafe fn local_free(ptr: *libc::c_char) {
} }
pub fn live_allocs() -> *mut Box { pub fn live_allocs() -> *mut Box {
do Local::borrow |task: &mut Task| { Local::borrow(|task: &mut Task| task.heap.live_allocs)
task.heap.live_allocs
}
} }
#[cfg(test)] #[cfg(test)]
@ -313,15 +311,11 @@ mod bench {
#[bench] #[bench]
fn alloc_managed_small(bh: &mut BenchHarness) { fn alloc_managed_small(bh: &mut BenchHarness) {
do bh.iter { bh.iter(|| @10);
@10;
}
} }
#[bench] #[bench]
fn alloc_managed_big(bh: &mut BenchHarness) { fn alloc_managed_big(bh: &mut BenchHarness) {
do bh.iter { bh.iter(|| @[10, ..1000]);
@[10, ..1000];
}
} }
} }

View file

@ -110,11 +110,7 @@ pub unsafe fn borrow<T>(f: |&mut T|) {
let unsafe_ptr = cast::transmute_mut_region(&mut *value); let unsafe_ptr = cast::transmute_mut_region(&mut *value);
let value_cell = Cell::new(value); let value_cell = Cell::new(value);
do (|| { (|| f(unsafe_ptr)).finally(|| put(value_cell.take()));
f(unsafe_ptr);
}).finally {
put(value_cell.take());
}
} }
/// Borrow a mutable reference to the thread-local value /// Borrow a mutable reference to the thread-local value

View file

@ -142,19 +142,17 @@ fn update_log_settings(crate_map: &CrateMap, settings: ~str) {
if settings.len() > 0 { if settings.len() > 0 {
if settings == ~"::help" || settings == ~"?" { if settings == ~"::help" || settings == ~"?" {
rterrln!("\nCrate log map:\n"); rterrln!("\nCrate log map:\n");
do iter_crate_map(crate_map) |entry| { iter_crate_map(crate_map, |entry| rterrln!(" {}", entry.name));
rterrln!(" {}", entry.name);
}
unsafe { exit(1); } unsafe { exit(1); }
} }
dirs = parse_logging_spec(settings); dirs = parse_logging_spec(settings);
} }
let mut n_matches: u32 = 0; let mut n_matches: u32 = 0;
do iter_crate_map(crate_map) |entry| { iter_crate_map(crate_map, |entry| {
let m = update_entry(dirs, entry); let m = update_entry(dirs, entry);
n_matches += m; n_matches += m;
} });
if n_matches < (dirs.len() as u32) { if n_matches < (dirs.len() as u32) {
rterrln!("warning: got {} RUST_LOG specs but only matched\n\ rterrln!("warning: got {} RUST_LOG specs but only matched\n\

View file

@ -68,9 +68,9 @@ impl<T: Send> State<T> {
} else { } else {
capacity capacity
}; };
let buffer = do vec::from_fn(capacity) |i:uint| { let buffer = vec::from_fn(capacity, |i:uint| {
Node{sequence:AtomicUint::new(i),value:None} Node{sequence:AtomicUint::new(i),value:None}
}; });
State{ State{
pad0: [0, ..64], pad0: [0, ..64],
buffer: buffer, buffer: buffer,

View file

@ -236,9 +236,9 @@ impl Scheduler {
// Our scheduler must be in the task before the event loop // Our scheduler must be in the task before the event loop
// is started. // is started.
let self_sched = Cell::new(self); let self_sched = Cell::new(self);
do Local::borrow |stask: &mut Task| { Local::borrow(|stask: &mut Task| {
stask.sched = Some(self_sched.take()); stask.sched = Some(self_sched.take());
}; });
(*event_loop).run(); (*event_loop).run();
} }
@ -538,9 +538,7 @@ impl Scheduler {
/// As enqueue_task, but with the possibility for the blocked task to /// As enqueue_task, but with the possibility for the blocked task to
/// already have been killed. /// already have been killed.
pub fn enqueue_blocked_task(&mut self, blocked_task: BlockedTask) { pub fn enqueue_blocked_task(&mut self, blocked_task: BlockedTask) {
do blocked_task.wake().map |task| { blocked_task.wake().map(|task| self.enqueue_task(task));
self.enqueue_task(task);
};
} }
// * Core Context Switching Functions // * Core Context Switching Functions
@ -643,9 +641,9 @@ impl Scheduler {
// * Context Swapping Helpers - Here be ugliness! // * Context Swapping Helpers - Here be ugliness!
pub fn resume_task_immediately(~self, task: ~Task) { pub fn resume_task_immediately(~self, task: ~Task) {
do self.change_task_context(task) |sched, stask| { self.change_task_context(task, |sched, stask| {
sched.sched_task = Some(stask); sched.sched_task = Some(stask);
} })
} }
fn resume_task_immediately_cl(sched: ~Scheduler, fn resume_task_immediately_cl(sched: ~Scheduler,
@ -686,15 +684,15 @@ impl Scheduler {
f: |&mut Scheduler, BlockedTask|) { f: |&mut Scheduler, BlockedTask|) {
// This is where we convert the BlockedTask-taking closure into one // This is where we convert the BlockedTask-taking closure into one
// that takes just a Task // that takes just a Task
do self.change_task_context(next_task) |sched, task| { self.change_task_context(next_task, |sched, task| {
f(sched, BlockedTask::block(task)) f(sched, BlockedTask::block(task))
} })
} }
fn switch_task(sched: ~Scheduler, task: ~Task) { fn switch_task(sched: ~Scheduler, task: ~Task) {
do sched.switch_running_tasks_and_then(task) |sched, last_task| { sched.switch_running_tasks_and_then(task, |sched, last_task| {
sched.enqueue_blocked_task(last_task); sched.enqueue_blocked_task(last_task);
}; });
} }
// * Task Context Helpers // * Task Context Helpers
@ -705,10 +703,10 @@ impl Scheduler {
// Similar to deschedule running task and then, but cannot go through // Similar to deschedule running task and then, but cannot go through
// the task-blocking path. The task is already dying. // the task-blocking path. The task is already dying.
let stask = self.sched_task.take_unwrap(); let stask = self.sched_task.take_unwrap();
do self.change_task_context(stask) |sched, mut dead_task| { self.change_task_context(stask, |sched, mut dead_task| {
let coroutine = dead_task.coroutine.take_unwrap(); let coroutine = dead_task.coroutine.take_unwrap();
coroutine.recycle(&mut sched.stack_pool); coroutine.recycle(&mut sched.stack_pool);
} })
} }
pub fn run_task(task: ~Task) { pub fn run_task(task: ~Task) {
@ -718,9 +716,9 @@ impl Scheduler {
pub fn run_task_later(next_task: ~Task) { pub fn run_task_later(next_task: ~Task) {
let next_task = Cell::new(next_task); let next_task = Cell::new(next_task);
do Local::borrow |sched: &mut Scheduler| { Local::borrow(|sched: &mut Scheduler| {
sched.enqueue_task(next_task.take()); sched.enqueue_task(next_task.take());
}; });
} }
/// Yield control to the scheduler, executing another task. This is guaranteed /// Yield control to the scheduler, executing another task. This is guaranteed
@ -731,9 +729,9 @@ impl Scheduler {
self.yield_check_count = reset_yield_check(&mut self.rng); self.yield_check_count = reset_yield_check(&mut self.rng);
// Tell the scheduler to start stealing on the next iteration // Tell the scheduler to start stealing on the next iteration
self.steal_for_yield = true; self.steal_for_yield = true;
do self.deschedule_running_task_and_then |sched, task| { self.deschedule_running_task_and_then(|sched, task| {
sched.enqueue_blocked_task(task); sched.enqueue_blocked_task(task);
} })
} }
pub fn maybe_yield(mut ~self) { pub fn maybe_yield(mut ~self) {
@ -852,9 +850,9 @@ fn new_sched_rng() -> XorShiftRng {
use iter::Iterator; use iter::Iterator;
use rand::SeedableRng; use rand::SeedableRng;
let fd = do "/dev/urandom".with_c_str |name| { let fd = "/dev/urandom".with_c_str(|name| {
unsafe { libc::open(name, libc::O_RDONLY, 0) } unsafe { libc::open(name, libc::O_RDONLY, 0) }
}; });
if fd == -1 { if fd == -1 {
rtabort!("could not open /dev/urandom for reading.") rtabort!("could not open /dev/urandom for reading.")
} }
@ -862,13 +860,13 @@ fn new_sched_rng() -> XorShiftRng {
let mut seeds = [0u32, .. 4]; let mut seeds = [0u32, .. 4];
let size = mem::size_of_val(&seeds); let size = mem::size_of_val(&seeds);
loop { loop {
let nbytes = do seeds.as_mut_buf |buf, _| { let nbytes = seeds.as_mut_buf(|buf, _| {
unsafe { unsafe {
libc::read(fd, libc::read(fd,
buf as *mut libc::c_void, buf as *mut libc::c_void,
size as libc::size_t) size as libc::size_t)
} }
}; });
rtassert!(nbytes as uint == size); rtassert!(nbytes as uint == size);
if !seeds.iter().all(|x| *x == 0) { if !seeds.iter().all(|x| *x == 0) {

View file

@ -142,7 +142,7 @@ impl Task {
-> ~Task { -> ~Task {
let f = Cell::new(f); let f = Cell::new(f);
let home = Cell::new(home); let home = Cell::new(home);
do Local::borrow |running_task: &mut Task| { Local::borrow(|running_task: &mut Task| {
let mut sched = running_task.sched.take_unwrap(); let mut sched = running_task.sched.take_unwrap();
let new_task = ~running_task.new_child_homed(&mut sched.stack_pool, let new_task = ~running_task.new_child_homed(&mut sched.stack_pool,
stack_size, stack_size,
@ -150,7 +150,7 @@ impl Task {
f.take()); f.take());
running_task.sched = Some(sched); running_task.sched = Some(sched);
new_task new_task
} })
} }
pub fn build_child(stack_size: Option<uint>, f: proc()) -> ~Task { pub fn build_child(stack_size: Option<uint>, f: proc()) -> ~Task {
@ -163,7 +163,7 @@ impl Task {
-> ~Task { -> ~Task {
let f = Cell::new(f); let f = Cell::new(f);
let home = Cell::new(home); let home = Cell::new(home);
do Local::borrow |running_task: &mut Task| { Local::borrow(|running_task: &mut Task| {
let mut sched = running_task.sched.take_unwrap(); let mut sched = running_task.sched.take_unwrap();
let new_task = ~Task::new_root_homed(&mut sched.stack_pool, let new_task = ~Task::new_root_homed(&mut sched.stack_pool,
stack_size, stack_size,
@ -171,7 +171,7 @@ impl Task {
f.take()); f.take());
running_task.sched = Some(sched); running_task.sched = Some(sched);
new_task new_task
} })
} }
pub fn build_root(stack_size: Option<uint>, f: proc()) -> ~Task { pub fn build_root(stack_size: Option<uint>, f: proc()) -> ~Task {
@ -280,10 +280,10 @@ impl Task {
// The only try/catch block in the world. Attempt to run the task's // The only try/catch block in the world. Attempt to run the task's
// client-specified code and catch any failures. // client-specified code and catch any failures.
do self.unwinder.try { self.unwinder.try(|| {
// Run the task main function, then do some cleanup. // Run the task main function, then do some cleanup.
do f.finally { f.finally(|| {
// First, destroy task-local storage. This may run user dtors. // First, destroy task-local storage. This may run user dtors.
// //
@ -320,8 +320,8 @@ impl Task {
None => {} None => {}
} }
self.logger.take(); self.logger.take();
} })
} });
// Cleanup the dynamic borrowck debugging info // Cleanup the dynamic borrowck debugging info
borrowck::clear_task_borrow_list(); borrowck::clear_task_borrow_list();
@ -364,7 +364,7 @@ impl Task {
// Grab both the scheduler and the task from TLS and check if the // Grab both the scheduler and the task from TLS and check if the
// task is executing on an appropriate scheduler. // task is executing on an appropriate scheduler.
pub fn on_appropriate_sched() -> bool { pub fn on_appropriate_sched() -> bool {
do Local::borrow |task: &mut Task| { Local::borrow(|task: &mut Task| {
let sched_id = task.sched.get_ref().sched_id(); let sched_id = task.sched.get_ref().sched_id();
let sched_run_anything = task.sched.get_ref().run_anything; let sched_run_anything = task.sched.get_ref().run_anything;
match task.task_type { match task.task_type {
@ -383,7 +383,7 @@ impl Task {
rtabort!("type error: expected: GreenTask, found: SchedTask"); rtabort!("type error: expected: GreenTask, found: SchedTask");
} }
} }
} })
} }
} }
@ -431,9 +431,9 @@ impl Coroutine {
unsafe { unsafe {
// Again - might work while safe, or it might not. // Again - might work while safe, or it might not.
do Local::borrow |sched: &mut Scheduler| { Local::borrow(|sched: &mut Scheduler| {
sched.run_cleanup_job(); sched.run_cleanup_job();
} });
// To call the run method on a task we need a direct // To call the run method on a task we need a direct
// reference to it. The task is in TLS, so we can // reference to it. The task is in TLS, so we can
@ -442,7 +442,7 @@ impl Coroutine {
// need to unsafe_borrow. // need to unsafe_borrow.
let task: *mut Task = Local::unsafe_borrow(); let task: *mut Task = Local::unsafe_borrow();
do (*task).run { (*task).run(|| {
// N.B. Removing `start` from the start wrapper // N.B. Removing `start` from the start wrapper
// closure by emptying a cell is critical for // closure by emptying a cell is critical for
// correctness. The ~Task pointer, and in turn the // correctness. The ~Task pointer, and in turn the
@ -455,7 +455,7 @@ impl Coroutine {
// scope while the task is still running. // scope while the task is still running.
let start = start_cell.take(); let start = start_cell.take();
start(); start();
}; });
} }
// We remove the sched from the Task in TLS right now. // We remove the sched from the Task in TLS right now.
@ -584,7 +584,7 @@ pub extern "C" fn rust_stack_exhausted() {
// #2361 - possible implementation of not using landing pads // #2361 - possible implementation of not using landing pads
if in_green_task_context() { if in_green_task_context() {
do Local::borrow |task: &mut Task| { Local::borrow(|task: &mut Task| {
let n = task.name.as_ref().map(|n| n.as_slice()).unwrap_or("<unnamed>"); let n = task.name.as_ref().map(|n| n.as_slice()).unwrap_or("<unnamed>");
// See the message below for why this is not emitted to the // See the message below for why this is not emitted to the
@ -593,7 +593,7 @@ pub extern "C" fn rust_stack_exhausted() {
// call would happen to initialized it (calling out to libuv), // call would happen to initialized it (calling out to libuv),
// and the FFI call needs 2MB of stack when we just ran out. // and the FFI call needs 2MB of stack when we just ran out.
rterrln!("task '{}' has overflowed its stack", n); rterrln!("task '{}' has overflowed its stack", n);
} })
} else { } else {
rterrln!("stack overflow in non-task context"); rterrln!("stack overflow in non-task context");
} }

View file

@ -68,9 +68,9 @@ impl<T> Tube<T> {
assert!(self.p.refcount() > 1); // There better be somebody to wake us up assert!(self.p.refcount() > 1); // There better be somebody to wake us up
assert!((*state).blocked_task.is_none()); assert!((*state).blocked_task.is_none());
let sched: ~Scheduler = Local::take(); let sched: ~Scheduler = Local::take();
do sched.deschedule_running_task_and_then |_, task| { sched.deschedule_running_task_and_then(|_, task| {
(*state).blocked_task = Some(task); (*state).blocked_task = Some(task);
} });
rtdebug!("waking after tube recv"); rtdebug!("waking after tube recv");
let buf = &mut (*state).buf; let buf = &mut (*state).buf;
assert!(!buf.is_empty()); assert!(!buf.is_empty());

View file

@ -37,25 +37,25 @@ impl<T: Send> WorkQueue<T> {
pub fn pop(&mut self) -> Option<T> { pub fn pop(&mut self) -> Option<T> {
unsafe { unsafe {
do self.queue.with |q| { self.queue.with(|q| {
if !q.is_empty() { if !q.is_empty() {
Some(q.shift()) Some(q.shift())
} else { } else {
None None
} }
} })
} }
} }
pub fn steal(&mut self) -> Option<T> { pub fn steal(&mut self) -> Option<T> {
unsafe { unsafe {
do self.queue.with |q| { self.queue.with(|q| {
if !q.is_empty() { if !q.is_empty() {
Some(q.pop()) Some(q.pop())
} else { } else {
None None
} }
} })
} }
} }

View file

@ -221,20 +221,20 @@ impl Process {
let ch_clone = ch.clone(); let ch_clone = ch.clone();
do spawn { do spawn {
do io::ignore_io_error { io::ignore_io_error(|| {
match error.take() { match error.take() {
Some(ref mut e) => ch.send((2, e.read_to_end())), Some(ref mut e) => ch.send((2, e.read_to_end())),
None => ch.send((2, ~[])) None => ch.send((2, ~[]))
} }
} })
} }
do spawn { do spawn {
do io::ignore_io_error { io::ignore_io_error(|| {
match output.take() { match output.take() {
Some(ref mut e) => ch_clone.send((1, e.read_to_end())), Some(ref mut e) => ch_clone.send((1, e.read_to_end())),
None => ch_clone.send((1, ~[])) None => ch_clone.send((1, ~[]))
} }
} })
} }
let status = self.finish(); let status = self.finish();

View file

@ -59,10 +59,10 @@ pub fn select<A: Select>(ports: &mut [A]) -> uint {
let p = Cell::new(p); let p = Cell::new(p);
let c = Cell::new(c); let c = Cell::new(c);
do (|| { (|| {
let c = Cell::new(c.take()); let c = Cell::new(c.take());
let sched: ~Scheduler = Local::take(); let sched: ~Scheduler = Local::take();
do sched.deschedule_running_task_and_then |sched, task| { sched.deschedule_running_task_and_then(|sched, task| {
let task_handles = task.make_selectable(ports.len()); let task_handles = task.make_selectable(ports.len());
for (index, (port, task_handle)) in for (index, (port, task_handle)) in
@ -77,12 +77,12 @@ pub fn select<A: Select>(ports: &mut [A]) -> uint {
let c = Cell::new(c.take()); let c = Cell::new(c.take());
do sched.event_loop.callback { c.take().send_deferred(()) } do sched.event_loop.callback { c.take().send_deferred(()) }
} }
}).finally { }).finally(|| {
// Unkillable is necessary not because getting killed is dangerous here, // Unkillable is necessary not because getting killed is dangerous here,
// but to force the recv not to use the same kill-flag that we used for // but to force the recv not to use the same kill-flag that we used for
// selecting. Otherwise a user-sender could spuriously wakeup us here. // selecting. Otherwise a user-sender could spuriously wakeup us here.
p.take().recv(); p.take().recv();
} });
// Task resumes. Now unblock ourselves from all the ports we blocked on. // Task resumes. Now unblock ourselves from all the ports we blocked on.
// If the success index wasn't reset, 'take' will just take all of them. // If the success index wasn't reset, 'take' will just take all of them.

View file

@ -410,11 +410,11 @@ impl<'self> Iterator<(uint, char)> for CharOffsetIterator<'self> {
fn next(&mut self) -> Option<(uint, char)> { fn next(&mut self) -> Option<(uint, char)> {
// Compute the byte offset by using the pointer offset between // Compute the byte offset by using the pointer offset between
// the original string slice and the iterator's remaining part // the original string slice and the iterator's remaining part
let offset = do self.string.as_imm_buf |a, _| { let offset = self.string.as_imm_buf(|a, _| {
do self.iter.string.as_imm_buf |b, _| { self.iter.string.as_imm_buf(|b, _| {
b as uint - a as uint b as uint - a as uint
} })
}; });
self.iter.next().map(|ch| (offset, ch)) self.iter.next().map(|ch| (offset, ch))
} }
@ -428,11 +428,11 @@ impl<'self> DoubleEndedIterator<(uint, char)> for CharOffsetIterator<'self> {
#[inline] #[inline]
fn next_back(&mut self) -> Option<(uint, char)> { fn next_back(&mut self) -> Option<(uint, char)> {
self.iter.next_back().map(|ch| { self.iter.next_back().map(|ch| {
let offset = do self.string.as_imm_buf |a, _| { let offset = self.string.as_imm_buf(|a, _| {
do self.iter.string.as_imm_buf |b, len| { self.iter.string.as_imm_buf(|b, len| {
b as uint - a as uint + len b as uint - a as uint + len
} })
}; });
(offset, ch) (offset, ch)
}) })
} }
@ -716,14 +716,14 @@ impl<'self> Iterator<char> for NormalizationIterator<'self> {
if !self.sorted { if !self.sorted {
for ch in self.iter { for ch in self.iter {
do decomposer(ch) |d| { decomposer(ch, |d| {
let class = canonical_combining_class(d); let class = canonical_combining_class(d);
if class == 0 && !self.sorted { if class == 0 && !self.sorted {
canonical_sort(self.buffer); canonical_sort(self.buffer);
self.sorted = true; self.sorted = true;
} }
self.buffer.push((d, class)); self.buffer.push((d, class));
} });
if self.sorted { break } if self.sorted { break }
} }
} }
@ -781,8 +781,8 @@ Section: Comparing strings
#[lang="str_eq"] #[lang="str_eq"]
#[inline] #[inline]
pub fn eq_slice(a: &str, b: &str) -> bool { pub fn eq_slice(a: &str, b: &str) -> bool {
do a.as_imm_buf |ap, alen| { a.as_imm_buf(|ap, alen| {
do b.as_imm_buf |bp, blen| { b.as_imm_buf(|bp, blen| {
if (alen != blen) { false } if (alen != blen) { false }
else { else {
unsafe { unsafe {
@ -791,16 +791,16 @@ pub fn eq_slice(a: &str, b: &str) -> bool {
alen as libc::size_t) == 0 alen as libc::size_t) == 0
} }
} }
} })
} })
} }
/// Bytewise slice equality /// Bytewise slice equality
#[cfg(test)] #[cfg(test)]
#[inline] #[inline]
pub fn eq_slice(a: &str, b: &str) -> bool { pub fn eq_slice(a: &str, b: &str) -> bool {
do a.as_imm_buf |ap, alen| { a.as_imm_buf(|ap, alen| {
do b.as_imm_buf |bp, blen| { b.as_imm_buf(|bp, blen| {
if (alen != blen) { false } if (alen != blen) { false }
else { else {
unsafe { unsafe {
@ -809,8 +809,8 @@ pub fn eq_slice(a: &str, b: &str) -> bool {
alen as libc::size_t) == 0 alen as libc::size_t) == 0
} }
} }
} })
} })
} }
/// Bytewise string equality /// Bytewise string equality
@ -1029,9 +1029,7 @@ pub mod raw {
/// Create a Rust string from a *u8 buffer of the given length /// Create a Rust string from a *u8 buffer of the given length
pub unsafe fn from_buf_len(buf: *u8, len: uint) -> ~str { pub unsafe fn from_buf_len(buf: *u8, len: uint) -> ~str {
let mut v: ~[u8] = vec::with_capacity(len); let mut v: ~[u8] = vec::with_capacity(len);
do v.as_mut_buf |vbuf, _len| { v.as_mut_buf(|vbuf, _len| ptr::copy_memory(vbuf, buf as *u8, len));
ptr::copy_memory(vbuf, buf as *u8, len)
};
vec::raw::set_len(&mut v, len); vec::raw::set_len(&mut v, len);
assert!(is_utf8(v)); assert!(is_utf8(v));
@ -1059,9 +1057,7 @@ pub mod raw {
/// Converts a vector of bytes to a new owned string. /// Converts a vector of bytes to a new owned string.
pub unsafe fn from_utf8(v: &[u8]) -> ~str { pub unsafe fn from_utf8(v: &[u8]) -> ~str {
do v.as_imm_buf |buf, len| { v.as_imm_buf(|buf, len| from_buf_len(buf, len))
from_buf_len(buf, len)
}
} }
/// Converts an owned vector of bytes to a new owned string. This assumes /// Converts an owned vector of bytes to a new owned string. This assumes
@ -1112,12 +1108,12 @@ pub mod raw {
/// Caller must check slice boundaries! /// Caller must check slice boundaries!
#[inline] #[inline]
pub unsafe fn slice_unchecked<'a>(s: &'a str, begin: uint, end: uint) -> &'a str { pub unsafe fn slice_unchecked<'a>(s: &'a str, begin: uint, end: uint) -> &'a str {
do s.as_imm_buf |sbuf, _n| { s.as_imm_buf(|sbuf, _n| {
cast::transmute(Slice { cast::transmute(Slice {
data: sbuf.offset(begin as int), data: sbuf.offset(begin as int),
len: end - begin, len: end - begin,
}) })
} })
} }
/// Appends a byte to a string. /// Appends a byte to a string.
@ -1351,7 +1347,7 @@ impl<'self> Str for @str {
impl<'self> Container for &'self str { impl<'self> Container for &'self str {
#[inline] #[inline]
fn len(&self) -> uint { fn len(&self) -> uint {
do self.as_imm_buf |_p, n| { n } self.as_imm_buf(|_p, n| n)
} }
} }
@ -1876,11 +1872,11 @@ impl<'self> StrSlice<'self> for &'self str {
} }
fn lines_any(&self) -> AnyLineIterator<'self> { fn lines_any(&self) -> AnyLineIterator<'self> {
do self.lines().map |line| { self.lines().map(|line| {
let l = line.len(); let l = line.len();
if l > 0 && line[l - 1] == '\r' as u8 { line.slice(0, l - 1) } if l > 0 && line[l - 1] == '\r' as u8 { line.slice(0, l - 1) }
else { line } else { line }
} })
} }
#[inline] #[inline]
@ -1973,9 +1969,7 @@ impl<'self> StrSlice<'self> for &'self str {
let mut out: ~str = ~""; let mut out: ~str = ~"";
out.reserve_at_least(self.len()); out.reserve_at_least(self.len());
for c in self.chars() { for c in self.chars() {
do c.escape_default |c| { c.escape_default(|c| out.push_char(c));
out.push_char(c);
}
} }
out out
} }
@ -1984,9 +1978,7 @@ impl<'self> StrSlice<'self> for &'self str {
let mut out: ~str = ~""; let mut out: ~str = ~"";
out.reserve_at_least(self.len()); out.reserve_at_least(self.len());
for c in self.chars() { for c in self.chars() {
do c.escape_unicode |c| { c.escape_unicode(|c| out.push_char(c));
out.push_char(c);
}
} }
out out
} }
@ -2044,17 +2036,15 @@ impl<'self> StrSlice<'self> for &'self str {
#[inline] #[inline]
fn to_owned(&self) -> ~str { fn to_owned(&self) -> ~str {
do self.as_imm_buf |src, len| { self.as_imm_buf(|src, len| {
unsafe { unsafe {
let mut v = vec::with_capacity(len); let mut v = vec::with_capacity(len);
do v.as_mut_buf |dst, _| { v.as_mut_buf(|dst, _| ptr::copy_memory(dst, src, len));
ptr::copy_memory(dst, src, len);
}
vec::raw::set_len(&mut v, len); vec::raw::set_len(&mut v, len);
::cast::transmute(v) ::cast::transmute(v)
} }
} })
} }
#[inline] #[inline]
@ -2250,8 +2240,8 @@ impl<'self> StrSlice<'self> for &'self str {
} }
fn subslice_offset(&self, inner: &str) -> uint { fn subslice_offset(&self, inner: &str) -> uint {
do self.as_imm_buf |a, a_len| { self.as_imm_buf(|a, a_len| {
do inner.as_imm_buf |b, b_len| { inner.as_imm_buf(|b, b_len| {
let a_start: uint; let a_start: uint;
let a_end: uint; let a_end: uint;
let b_start: uint; let b_start: uint;
@ -2263,8 +2253,8 @@ impl<'self> StrSlice<'self> for &'self str {
assert!(a_start <= b_start); assert!(a_start <= b_start);
assert!(b_end <= a_end); assert!(b_end <= a_end);
b_start - a_start b_start - a_start
} })
} })
} }
#[inline] #[inline]
@ -2382,11 +2372,11 @@ impl OwnedStr for ~str {
// Attempt to not use an intermediate buffer by just pushing bytes // Attempt to not use an intermediate buffer by just pushing bytes
// directly onto this string. // directly onto this string.
let used = do self.as_mut_buf |buf, _| { let used = self.as_mut_buf(|buf, _| {
do vec::raw::mut_buf_as_slice(buf.offset(cur_len as int), 4) |slc| { vec::raw::mut_buf_as_slice(buf.offset(cur_len as int), 4, |slc| {
c.encode_utf8(slc) c.encode_utf8(slc)
} })
}; });
raw::set_len(self, cur_len + used); raw::set_len(self, cur_len + used);
} }
} }
@ -3156,13 +3146,11 @@ mod tests {
0x6d_u8]; 0x6d_u8];
let mut error_happened = false; let mut error_happened = false;
let _x = do cond.trap(|err| { let _x = cond.trap(|err| {
assert_eq!(err, ~"from_utf8: input is not UTF-8; first bad byte is 255"); assert_eq!(err, ~"from_utf8: input is not UTF-8; first bad byte is 255");
error_happened = true; error_happened = true;
~"" ~""
}).inside { }).inside(|| from_utf8(bb));
from_utf8(bb)
};
assert!(error_happened); assert!(error_happened);
} }
@ -3201,11 +3189,9 @@ mod tests {
#[test] #[test]
fn test_as_imm_buf() { fn test_as_imm_buf() {
do "".as_imm_buf |_, len| { "".as_imm_buf(|_, len| assert_eq!(len, 0));
assert_eq!(len, 0);
}
do "hello".as_imm_buf |buf, len| { "hello".as_imm_buf(|buf, len| {
assert_eq!(len, 5); assert_eq!(len, 5);
unsafe { unsafe {
assert_eq!(*ptr::offset(buf, 0), 'h' as u8); assert_eq!(*ptr::offset(buf, 0), 'h' as u8);
@ -3214,7 +3200,7 @@ mod tests {
assert_eq!(*ptr::offset(buf, 3), 'l' as u8); assert_eq!(*ptr::offset(buf, 3), 'l' as u8);
assert_eq!(*ptr::offset(buf, 4), 'o' as u8); assert_eq!(*ptr::offset(buf, 4), 'o' as u8);
} }
} })
} }
#[test] #[test]
@ -3864,9 +3850,7 @@ mod bench {
let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb"; let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
let len = s.char_len(); let len = s.char_len();
do bh.iter { bh.iter(|| assert_eq!(s.chars().len(), len));
assert_eq!(s.chars().len(), len);
}
} }
#[bench] #[bench]
@ -3879,9 +3863,7 @@ mod bench {
Mary had a little lamb, Little lamb"; Mary had a little lamb, Little lamb";
let len = s.char_len(); let len = s.char_len();
do bh.iter { bh.iter(|| assert_eq!(s.chars().len(), len));
assert_eq!(s.chars().len(), len);
}
} }
#[bench] #[bench]
@ -3889,9 +3871,7 @@ mod bench {
let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb"; let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
let len = s.char_len(); let len = s.char_len();
do bh.iter { bh.iter(|| assert_eq!(s.chars_rev().len(), len));
assert_eq!(s.chars_rev().len(), len);
}
} }
#[bench] #[bench]
@ -3899,9 +3879,7 @@ mod bench {
let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb"; let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
let len = s.char_len(); let len = s.char_len();
do bh.iter { bh.iter(|| assert_eq!(s.char_indices().len(), len));
assert_eq!(s.char_indices().len(), len);
}
} }
#[bench] #[bench]
@ -3909,18 +3887,14 @@ mod bench {
let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb"; let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
let len = s.char_len(); let len = s.char_len();
do bh.iter { bh.iter(|| assert_eq!(s.char_indices_rev().len(), len));
assert_eq!(s.char_indices_rev().len(), len);
}
} }
#[bench] #[bench]
fn split_unicode_ascii(bh: &mut BenchHarness) { fn split_unicode_ascii(bh: &mut BenchHarness) {
let s = "ประเทศไทย中华Việt Namประเทศไทย中华Việt Nam"; let s = "ประเทศไทย中华Việt Namประเทศไทย中华Việt Nam";
do bh.iter { bh.iter(|| assert_eq!(s.split('V').len(), 3));
assert_eq!(s.split('V').len(), 3);
}
} }
#[bench] #[bench]
@ -3934,9 +3908,7 @@ mod bench {
} }
let s = "ประเทศไทย中华Việt Namประเทศไทย中华Việt Nam"; let s = "ประเทศไทย中华Việt Namประเทศไทย中华Việt Nam";
do bh.iter { bh.iter(|| assert_eq!(s.split(NotAscii('V')).len(), 3));
assert_eq!(s.split(NotAscii('V')).len(), 3);
}
} }
@ -3945,9 +3917,7 @@ mod bench {
let s = "Mary had a little lamb, Little lamb, little-lamb."; let s = "Mary had a little lamb, Little lamb, little-lamb.";
let len = s.split(' ').len(); let len = s.split(' ').len();
do bh.iter { bh.iter(|| assert_eq!(s.split(' ').len(), len));
assert_eq!(s.split(' ').len(), len);
}
} }
#[bench] #[bench]
@ -3961,9 +3931,7 @@ mod bench {
let s = "Mary had a little lamb, Little lamb, little-lamb."; let s = "Mary had a little lamb, Little lamb, little-lamb.";
let len = s.split(' ').len(); let len = s.split(' ').len();
do bh.iter { bh.iter(|| assert_eq!(s.split(NotAscii(' ')).len(), len));
assert_eq!(s.split(NotAscii(' ')).len(), len);
}
} }
#[bench] #[bench]
@ -3972,9 +3940,7 @@ mod bench {
let len = s.split(' ').len(); let len = s.split(' ').len();
fn pred(c: char) -> bool { c == ' ' } fn pred(c: char) -> bool { c == ' ' }
do bh.iter { bh.iter(|| assert_eq!(s.split(pred).len(), len));
assert_eq!(s.split(pred).len(), len);
}
} }
#[bench] #[bench]
@ -3982,9 +3948,7 @@ mod bench {
let s = "Mary had a little lamb, Little lamb, little-lamb."; let s = "Mary had a little lamb, Little lamb, little-lamb.";
let len = s.split(' ').len(); let len = s.split(' ').len();
do bh.iter { bh.iter(|| assert_eq!(s.split(|c: char| c == ' ').len(), len));
assert_eq!(s.split(|c: char| c == ' ').len(), len);
}
} }
#[bench] #[bench]
@ -3992,9 +3956,7 @@ mod bench {
let s = "Mary had a little lamb, Little lamb, little-lamb."; let s = "Mary had a little lamb, Little lamb, little-lamb.";
let len = s.split(' ').len(); let len = s.split(' ').len();
do bh.iter { bh.iter(|| assert_eq!(s.split(&[' ']).len(), len));
assert_eq!(s.split(&[' ']).len(), len);
}
} }
#[bench] #[bench]
@ -4004,34 +3966,28 @@ mod bench {
Lorem ipsum dolor sit amet, consectetur. "); Lorem ipsum dolor sit amet, consectetur. ");
assert_eq!(100, s.len()); assert_eq!(100, s.len());
do bh.iter { bh.iter(|| is_utf8(s));
is_utf8(s);
}
} }
#[bench] #[bench]
fn is_utf8_100_multibyte(bh: &mut BenchHarness) { fn is_utf8_100_multibyte(bh: &mut BenchHarness) {
let s = bytes!("𐌀𐌖𐌋𐌄𐌑𐌉ปรدولة الكويتทศไทย中华𐍅𐌿𐌻𐍆𐌹𐌻𐌰"); let s = bytes!("𐌀𐌖𐌋𐌄𐌑𐌉ปรدولة الكويتทศไทย中华𐍅𐌿𐌻𐍆𐌹𐌻𐌰");
assert_eq!(100, s.len()); assert_eq!(100, s.len());
do bh.iter { bh.iter(|| is_utf8(s));
is_utf8(s);
}
} }
#[bench] #[bench]
fn bench_with_capacity(bh: &mut BenchHarness) { fn bench_with_capacity(bh: &mut BenchHarness) {
do bh.iter { bh.iter(|| with_capacity(100));
with_capacity(100);
}
} }
#[bench] #[bench]
fn bench_push_str(bh: &mut BenchHarness) { fn bench_push_str(bh: &mut BenchHarness) {
let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb"; let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
do bh.iter { bh.iter(|| {
let mut r = ~""; let mut r = ~"";
r.push_str(s); r.push_str(s);
} });
} }
#[bench] #[bench]
@ -4039,8 +3995,8 @@ mod bench {
let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb"; let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
let sep = ""; let sep = "";
let v = [s, s, s, s, s, s, s, s, s, s]; let v = [s, s, s, s, s, s, s, s, s, s];
do bh.iter { bh.iter(|| {
assert_eq!(v.connect(sep).len(), s.len() * 10 + sep.len() * 9); assert_eq!(v.connect(sep).len(), s.len() * 10 + sep.len() * 9);
} })
} }
} }

View file

@ -432,12 +432,12 @@ pub fn with_task_name<U>(blk: |Option<&str>| -> U) -> U {
use rt::task::Task; use rt::task::Task;
if in_green_task_context() { if in_green_task_context() {
do Local::borrow |task: &mut Task| { Local::borrow(|task: &mut Task| {
match task.name { match task.name {
Some(ref name) => blk(Some(name.as_slice())), Some(ref name) => blk(Some(name.as_slice())),
None => blk(None) None => blk(None)
} }
} })
} else { } else {
fail!("no task name exists in non-green task context") fail!("no task name exists in non-green task context")
} }
@ -459,9 +459,7 @@ pub fn failing() -> bool {
use rt::task::Task; use rt::task::Task;
do Local::borrow |local: &mut Task| { Local::borrow(|local: &mut Task| local.unwinder.unwinding)
local.unwinder.unwinding
}
} }
// The following 8 tests test the following 2^3 combinations: // The following 8 tests test the following 2^3 combinations:

View file

@ -369,12 +369,12 @@ impl<A:IterBytes> ToBytes for A {
use io::mem; use io::mem;
use io::Writer; use io::Writer;
do mem::with_mem_writer |wr| { mem::with_mem_writer(|wr| {
do self.iter_bytes(lsb0) |bytes| { self.iter_bytes(lsb0, |bytes| {
wr.write(bytes); wr.write(bytes);
true true
}; });
} })
} }
} }

View file

@ -489,7 +489,7 @@ pub struct TrieSetIterator<'self> {
impl<'self> Iterator<uint> for TrieSetIterator<'self> { impl<'self> Iterator<uint> for TrieSetIterator<'self> {
fn next(&mut self) -> Option<uint> { fn next(&mut self) -> Option<uint> {
do self.iter.next().map |(key, _)| { key } self.iter.next().map(|(key, _)| key)
} }
fn size_hint(&self) -> (uint, Option<uint>) { fn size_hint(&self) -> (uint, Option<uint>) {
@ -594,12 +594,12 @@ mod test_map {
assert!(m.insert(1, 2)); assert!(m.insert(1, 2));
let mut n = 0; let mut n = 0;
do m.each |k, v| { m.each(|k, v| {
assert_eq!(*k, n); assert_eq!(*k, n);
assert_eq!(*v, n * 2); assert_eq!(*v, n * 2);
n += 1; n += 1;
true true
}; });
} }
#[test] #[test]
@ -611,7 +611,7 @@ mod test_map {
} }
let mut n = uint::max_value - 10000; let mut n = uint::max_value - 10000;
do m.each |k, v| { m.each(|k, v| {
if n == uint::max_value - 5000 { false } else { if n == uint::max_value - 5000 { false } else {
assert!(n < uint::max_value - 5000); assert!(n < uint::max_value - 5000);
@ -620,7 +620,7 @@ mod test_map {
n += 1; n += 1;
true true
} }
}; });
} }
#[test] #[test]
@ -634,12 +634,12 @@ mod test_map {
assert!(m.insert(1, 2)); assert!(m.insert(1, 2));
let mut n = 4; let mut n = 4;
do m.each_reverse |k, v| { m.each_reverse(|k, v| {
assert_eq!(*k, n); assert_eq!(*k, n);
assert_eq!(*v, n * 2); assert_eq!(*v, n * 2);
n -= 1; n -= 1;
true true
}; });
} }
#[test] #[test]
@ -651,7 +651,7 @@ mod test_map {
} }
let mut n = uint::max_value - 1; let mut n = uint::max_value - 1;
do m.each_reverse |k, v| { m.each_reverse(|k, v| {
if n == uint::max_value - 5000 { false } else { if n == uint::max_value - 5000 { false } else {
assert!(n > uint::max_value - 5000); assert!(n > uint::max_value - 5000);
@ -660,7 +660,7 @@ mod test_map {
n -= 1; n -= 1;
true true
} }
}; });
} }
#[test] #[test]
@ -777,11 +777,11 @@ mod test_set {
let mut i = 0; let mut i = 0;
do trie.each |x| { trie.each(|x| {
assert_eq!(expected[i], *x); assert_eq!(expected[i], *x);
i += 1; i += 1;
true true
}; });
} }
#[test] #[test]

View file

@ -19,11 +19,11 @@ pub mod general_category {
use cmp::{Equal, Less, Greater}; use cmp::{Equal, Less, Greater};
use vec::ImmutableVector; use vec::ImmutableVector;
use option::None; use option::None;
(do r.bsearch |&(lo,hi)| { (r.bsearch(|&(lo,hi)| {
if lo <= c && c <= hi { Equal } if lo <= c && c <= hi { Equal }
else if hi < c { Less } else if hi < c { Less }
else { Greater } else { Greater }
}) != None })) != None
} }
@ -3663,11 +3663,11 @@ pub mod derived_property {
use cmp::{Equal, Less, Greater}; use cmp::{Equal, Less, Greater};
use vec::ImmutableVector; use vec::ImmutableVector;
use option::None; use option::None;
(do r.bsearch |&(lo,hi)| { (r.bsearch(|&(lo,hi)| {
if lo <= c && c <= hi { Equal } if lo <= c && c <= hi { Equal }
else if hi < c { Less } else if hi < c { Less }
else { Greater } else { Greater }
}) != None })) != None
} }

View file

@ -27,11 +27,11 @@ pub struct DynamicLibrary { priv handle: *libc::c_void }
impl Drop for DynamicLibrary { impl Drop for DynamicLibrary {
fn drop(&mut self) { fn drop(&mut self) {
match do dl::check_for_errors_in { match dl::check_for_errors_in(|| {
unsafe { unsafe {
dl::close(self.handle) dl::close(self.handle)
} }
} { }) {
Ok(()) => {}, Ok(()) => {},
Err(str) => fail!("{}", str) Err(str) => fail!("{}", str)
} }
@ -43,12 +43,12 @@ impl DynamicLibrary {
/// handle to the calling process /// handle to the calling process
pub fn open(filename: Option<&path::Path>) -> Result<DynamicLibrary, ~str> { pub fn open(filename: Option<&path::Path>) -> Result<DynamicLibrary, ~str> {
unsafe { unsafe {
let maybe_library = do dl::check_for_errors_in { let maybe_library = dl::check_for_errors_in(|| {
match filename { match filename {
Some(name) => dl::open_external(name), Some(name) => dl::open_external(name),
None => dl::open_internal() None => dl::open_internal()
} }
}; });
// The dynamic library must not be constructed if there is // The dynamic library must not be constructed if there is
// an error opening the library so the destructor does not // an error opening the library so the destructor does not
@ -65,11 +65,11 @@ impl DynamicLibrary {
// This function should have a lifetime constraint of 'self on // This function should have a lifetime constraint of 'self on
// T but that feature is still unimplemented // T but that feature is still unimplemented
let maybe_symbol_value = do dl::check_for_errors_in { let maybe_symbol_value = dl::check_for_errors_in(|| {
do symbol.with_c_str |raw_string| { symbol.with_c_str(|raw_string| {
dl::symbol(self.handle, raw_string) dl::symbol(self.handle, raw_string)
} })
}; });
// The value must not be constructed if there is an error so // The value must not be constructed if there is an error so
// the destructor does not run. // the destructor does not run.
@ -144,9 +144,9 @@ pub mod dl {
use result::*; use result::*;
pub unsafe fn open_external(filename: &path::Path) -> *libc::c_void { pub unsafe fn open_external(filename: &path::Path) -> *libc::c_void {
do filename.with_c_str |raw_name| { filename.with_c_str(|raw_name| {
dlopen(raw_name, Lazy as libc::c_int) dlopen(raw_name, Lazy as libc::c_int)
} })
} }
pub unsafe fn open_internal() -> *libc::c_void { pub unsafe fn open_internal() -> *libc::c_void {
@ -162,7 +162,7 @@ pub mod dl {
// would cause this task to be descheduled, which could deadlock // would cause this task to be descheduled, which could deadlock
// the scheduler if it happens while the lock is held. // the scheduler if it happens while the lock is held.
// FIXME #9105 use a Rust mutex instead of C++ mutexes. // FIXME #9105 use a Rust mutex instead of C++ mutexes.
do atomically { atomically(|| {
lock.lock(); lock.lock();
let _old_error = dlerror(); let _old_error = dlerror();
@ -176,7 +176,7 @@ pub mod dl {
}; };
lock.unlock(); lock.unlock();
ret ret
} })
} }
} }
@ -213,9 +213,9 @@ pub mod dl {
use result::*; use result::*;
pub unsafe fn open_external(filename: &path::Path) -> *libc::c_void { pub unsafe fn open_external(filename: &path::Path) -> *libc::c_void {
do os::win32::as_utf16_p(filename.as_str().unwrap()) |raw_name| { os::win32::as_utf16_p(filename.as_str().unwrap(), |raw_name| {
LoadLibraryW(raw_name) LoadLibraryW(raw_name)
} })
} }
pub unsafe fn open_internal() -> *libc::c_void { pub unsafe fn open_internal() -> *libc::c_void {
@ -226,7 +226,7 @@ pub mod dl {
pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, ~str> { pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, ~str> {
unsafe { unsafe {
do atomically { atomically(|| {
SetLastError(0); SetLastError(0);
let result = f(); let result = f();
@ -237,7 +237,7 @@ pub mod dl {
} else { } else {
Err(format!("Error code {}", error)) Err(format!("Error code {}", error))
} }
} })
} }
} }

View file

@ -27,9 +27,7 @@ pub fn fail_(expr: *c_char, file: *c_char, line: size_t) -> ! {
pub fn fail_bounds_check(file: *c_char, line: size_t, index: size_t, len: size_t) -> ! { pub fn fail_bounds_check(file: *c_char, line: size_t, index: size_t, len: size_t) -> ! {
let msg = format!("index out of bounds: the len is {} but the index is {}", let msg = format!("index out of bounds: the len is {} but the index is {}",
len as uint, index as uint); len as uint, index as uint);
do msg.with_c_str |buf| { msg.with_c_str(|buf| fail_(buf, file, line))
fail_(buf, file, line);
}
} }
#[lang="malloc"] #[lang="malloc"]

View file

@ -134,9 +134,8 @@ impl<T: Send> UnsafeArc<T> {
/// If called when the task is already unkillable, unwrap will unkillably /// If called when the task is already unkillable, unwrap will unkillably
/// block; otherwise, an unwrapping task can be killed by linked failure. /// block; otherwise, an unwrapping task can be killed by linked failure.
pub fn unwrap(self) -> T { pub fn unwrap(self) -> T {
let this = Cell::new(self); // argh
unsafe { unsafe {
let mut this = this.take(); let mut this = this;
// The ~ dtor needs to run if this code succeeds. // The ~ dtor needs to run if this code succeeds.
let mut data: ~ArcData<T> = cast::transmute(this.data); let mut data: ~ArcData<T> = cast::transmute(this.data);
// Set up the unwrap protocol. // Set up the unwrap protocol.
@ -164,7 +163,7 @@ impl<T: Send> UnsafeArc<T> {
// Unlike the above one, this cell is necessary. It will get // Unlike the above one, this cell is necessary. It will get
// taken either in the do block or in the finally block. // taken either in the do block or in the finally block.
let c2_and_data = Cell::new((c2,data)); let c2_and_data = Cell::new((c2,data));
do (|| { (|| {
p1.take().recv(); p1.take().recv();
// Got here. Back in the 'unkillable' without getting killed. // Got here. Back in the 'unkillable' without getting killed.
let (c2, data) = c2_and_data.take(); let (c2, data) = c2_and_data.take();
@ -174,7 +173,7 @@ impl<T: Send> UnsafeArc<T> {
// user_data // user_data
let mut data = data; let mut data = data;
data.data.take_unwrap() data.data.take_unwrap()
}).finally { }).finally(|| {
if task::failing() { if task::failing() {
// Killed during wait. Because this might happen while // Killed during wait. Because this might happen while
// someone else still holds a reference, we can't free // someone else still holds a reference, we can't free
@ -185,7 +184,7 @@ impl<T: Send> UnsafeArc<T> {
} else { } else {
assert!(c2_and_data.is_empty()); assert!(c2_and_data.is_empty());
} }
} })
} }
} else { } else {
// If 'put' returns the server end back to us, we were rejected; // If 'put' returns the server end back to us, we were rejected;
@ -193,7 +192,7 @@ impl<T: Send> UnsafeArc<T> {
cast::forget(data); cast::forget(data);
fail!("Another task is already unwrapping this Arc!"); fail!("Another task is already unwrapping this Arc!");
} }
} })
} }
/// As unwrap above, but without blocking. Returns 'UnsafeArcSelf(self)' if this is /// As unwrap above, but without blocking. Returns 'UnsafeArcSelf(self)' if this is
@ -256,8 +255,6 @@ impl<T> Drop for UnsafeArc<T>{
// *awake* task with the data. // *awake* task with the data.
match data.unwrapper.take(Acquire) { match data.unwrapper.take(Acquire) {
Some(~(message,response)) => { Some(~(message,response)) => {
let cell = Cell::new((message, response, data));
let (message, response, data) = cell.take();
// Send 'ready' and wait for a response. // Send 'ready' and wait for a response.
message.send(()); message.send(());
// Unkillable wait. Message guaranteed to come. // Unkillable wait. Message guaranteed to come.
@ -301,12 +298,10 @@ pub unsafe fn atomically<U>(f: || -> U) -> U {
Some(t) => { Some(t) => {
match (*t).task_type { match (*t).task_type {
GreenTask(_) => { GreenTask(_) => {
do (|| { (|| {
(*t).death.inhibit_deschedule(); (*t).death.inhibit_deschedule();
f() f()
}).finally { }).finally(|| (*t).death.allow_deschedule())
(*t).death.allow_deschedule();
}
} }
SchedTask => f() SchedTask => f()
} }
@ -425,9 +420,7 @@ impl<T:Send> Exclusive<T> {
#[inline] #[inline]
pub unsafe fn with_imm<U>(&self, f: |x: &T| -> U) -> U { pub unsafe fn with_imm<U>(&self, f: |x: &T| -> U) -> U {
do self.with |x| { self.with(|x| f(cast::transmute_immut(x)))
f(cast::transmute_immut(x))
}
} }
#[inline] #[inline]
@ -469,7 +462,6 @@ impl<T:Send> Exclusive<T> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use cell::Cell;
use comm; use comm;
use option::*; use option::*;
use prelude::*; use prelude::*;
@ -489,7 +481,7 @@ mod tests {
fn test_atomically() { fn test_atomically() {
// NB. The whole runtime will abort on an 'atomic-sleep' violation, // NB. The whole runtime will abort on an 'atomic-sleep' violation,
// so we can't really test for the converse behaviour. // so we can't really test for the converse behaviour.
unsafe { do atomically { } } task::deschedule(); // oughtn't fail unsafe { atomically(|| ()) } task::deschedule(); // oughtn't fail
} }
#[test] #[test]
@ -509,9 +501,7 @@ mod tests {
do task::spawn || { do task::spawn || {
for _ in range(0u, count) { for _ in range(0u, count) {
do total.with |count| { total.with(|count| **count += 1);
**count += 1;
}
} }
chan.send(()); chan.send(());
} }
@ -519,9 +509,7 @@ mod tests {
for f in futures.iter() { f.recv() } for f in futures.iter() { f.recv() }
do total.with |total| { total.with(|total| assert!(**total == num_tasks * count));
assert!(**total == num_tasks * count)
};
} }
} }
@ -533,13 +521,9 @@ mod tests {
let x = Exclusive::new(1); let x = Exclusive::new(1);
let x2 = x.clone(); let x2 = x.clone();
do task::try || { do task::try || {
do x2.with |one| { x2.with(|one| assert_eq!(*one, 2))
assert_eq!(*one, 2);
}
}; };
do x.with |one| { x.with(|one| assert_eq!(*one, 1));
assert_eq!(*one, 1);
}
} }
} }
@ -595,11 +579,11 @@ mod tests {
fn arclike_try_unwrap_unwrap_race() { fn arclike_try_unwrap_unwrap_race() {
// When an unwrap and a try_unwrap race, the unwrapper should always win. // When an unwrap and a try_unwrap race, the unwrapper should always win.
let x = UnsafeArc::new(~~"hello"); let x = UnsafeArc::new(~~"hello");
let x2 = Cell::new(x.clone()); let x2 = x.clone();
let (p,c) = comm::stream(); let (p,c) = comm::stream();
do task::spawn { do task::spawn {
c.send(()); c.send(());
assert!(x2.take().unwrap() == ~~"hello"); assert!(x2.unwrap() == ~~"hello");
c.send(()); c.send(());
} }
p.recv(); p.recv();
@ -620,21 +604,19 @@ mod tests {
#[test] #[test]
fn exclusive_new_unwrap_contended() { fn exclusive_new_unwrap_contended() {
let x = Exclusive::new(~~"hello"); let x = Exclusive::new(~~"hello");
let x2 = Cell::new(x.clone()); let x2 = x.clone();
do task::spawn { do task::spawn {
let x2 = x2.take(); unsafe { x2.with(|_hello| ()); }
unsafe { do x2.with |_hello| { } }
task::deschedule(); task::deschedule();
} }
assert!(x.unwrap() == ~~"hello"); assert!(x.unwrap() == ~~"hello");
// Now try the same thing, but with the child task blocking. // Now try the same thing, but with the child task blocking.
let x = Exclusive::new(~~"hello"); let x = Exclusive::new(~~"hello");
let x2 = Cell::new(x.clone()); let x2 = x.clone();
let mut builder = task::task(); let mut builder = task::task();
let res = builder.future_result(); let res = builder.future_result();
do builder.spawn { do builder.spawn {
let x2 = x2.take();
assert!(x2.unwrap() == ~~"hello"); assert!(x2.unwrap() == ~~"hello");
} }
// Have to get rid of our reference before blocking. // Have to get rid of our reference before blocking.
@ -645,11 +627,10 @@ mod tests {
#[test] #[should_fail] #[test] #[should_fail]
fn exclusive_new_unwrap_conflict() { fn exclusive_new_unwrap_conflict() {
let x = Exclusive::new(~~"hello"); let x = Exclusive::new(~~"hello");
let x2 = Cell::new(x.clone()); let x2 = x.clone();
let mut builder = task::task(); let mut builder = task::task();
let res = builder.future_result(); let res = builder.future_result();
do builder.spawn { do builder.spawn {
let x2 = x2.take();
assert!(x2.unwrap() == ~~"hello"); assert!(x2.unwrap() == ~~"hello");
} }
assert!(x.unwrap() == ~~"hello"); assert!(x.unwrap() == ~~"hello");

View file

@ -137,14 +137,14 @@ pub fn from_fn<T>(n_elts: uint, op: |uint| -> T) -> ~[T] {
let mut v = with_capacity(n_elts); let mut v = with_capacity(n_elts);
let p = raw::to_mut_ptr(v); let p = raw::to_mut_ptr(v);
let mut i: uint = 0u; let mut i: uint = 0u;
do (|| { (|| {
while i < n_elts { while i < n_elts {
intrinsics::move_val_init(&mut(*ptr::mut_offset(p, i as int)), op(i)); intrinsics::move_val_init(&mut(*ptr::mut_offset(p, i as int)), op(i));
i += 1u; i += 1u;
} }
}).finally { }).finally(|| {
raw::set_len(&mut v, i); raw::set_len(&mut v, i);
} });
v v
} }
} }
@ -164,14 +164,14 @@ pub fn from_elem<T:Clone>(n_elts: uint, t: T) -> ~[T] {
let mut v = with_capacity(n_elts); let mut v = with_capacity(n_elts);
let p = raw::to_mut_ptr(v); let p = raw::to_mut_ptr(v);
let mut i = 0u; let mut i = 0u;
do (|| { (|| {
while i < n_elts { while i < n_elts {
intrinsics::move_val_init(&mut(*ptr::mut_offset(p, i as int)), t.clone()); intrinsics::move_val_init(&mut(*ptr::mut_offset(p, i as int)), t.clone());
i += 1u; i += 1u;
} }
}).finally { }).finally(|| {
raw::set_len(&mut v, i); raw::set_len(&mut v, i);
} });
v v
} }
} }
@ -982,14 +982,14 @@ impl<'self,T> ImmutableVector<'self, T> for &'self [T] {
fn slice(&self, start: uint, end: uint) -> &'self [T] { fn slice(&self, start: uint, end: uint) -> &'self [T] {
assert!(start <= end); assert!(start <= end);
assert!(end <= self.len()); assert!(end <= self.len());
do self.as_imm_buf |p, _len| { self.as_imm_buf(|p, _len| {
unsafe { unsafe {
cast::transmute(Slice { cast::transmute(Slice {
data: ptr::offset(p, start as int), data: ptr::offset(p, start as int),
len: (end - start) len: (end - start)
}) })
} }
} })
} }
#[inline] #[inline]
@ -1639,7 +1639,7 @@ impl<T> OwnedVector<T> for ~[T] {
self.pop() self.pop()
} }
fn truncate(&mut self, newlen: uint) { fn truncate(&mut self, newlen: uint) {
do self.as_mut_buf |p, oldlen| { self.as_mut_buf(|p, oldlen| {
assert!(newlen <= oldlen); assert!(newlen <= oldlen);
unsafe { unsafe {
// This loop is optimized out for non-drop types. // This loop is optimized out for non-drop types.
@ -1647,7 +1647,7 @@ impl<T> OwnedVector<T> for ~[T] {
ptr::read_and_zero_ptr(ptr::mut_offset(p, i as int)); ptr::read_and_zero_ptr(ptr::mut_offset(p, i as int));
} }
} }
} });
unsafe { raw::set_len(self, newlen); } unsafe { raw::set_len(self, newlen); }
} }
@ -1932,14 +1932,14 @@ impl<'self,T> MutableVector<'self, T> for &'self mut [T] {
fn mut_slice(self, start: uint, end: uint) -> &'self mut [T] { fn mut_slice(self, start: uint, end: uint) -> &'self mut [T] {
assert!(start <= end); assert!(start <= end);
assert!(end <= self.len()); assert!(end <= self.len());
do self.as_mut_buf |p, _len| { self.as_mut_buf(|p, _len| {
unsafe { unsafe {
cast::transmute(Slice { cast::transmute(Slice {
data: ptr::mut_offset(p, start as int) as *T, data: ptr::mut_offset(p, start as int) as *T,
len: (end - start) len: (end - start)
}) })
} }
} })
} }
#[inline] #[inline]
@ -2153,10 +2153,10 @@ pub mod raw {
#[inline] #[inline]
pub unsafe fn init_elem<T>(v: &mut [T], i: uint, val: T) { pub unsafe fn init_elem<T>(v: &mut [T], i: uint, val: T) {
let mut box = Some(val); let mut box = Some(val);
do v.as_mut_buf |p, _len| { v.as_mut_buf(|p, _len| {
intrinsics::move_val_init(&mut(*ptr::mut_offset(p, i as int)), intrinsics::move_val_init(&mut(*ptr::mut_offset(p, i as int)),
box.take_unwrap()); box.take_unwrap());
} })
} }
/** /**
@ -2188,11 +2188,11 @@ pub mod raw {
assert!(dst.len() >= count); assert!(dst.len() >= count);
assert!(src.len() >= count); assert!(src.len() >= count);
do dst.as_mut_buf |p_dst, _len_dst| { dst.as_mut_buf(|p_dst, _len_dst| {
do src.as_imm_buf |p_src, _len_src| { src.as_imm_buf(|p_src, _len_src| {
ptr::copy_memory(p_dst, p_src, count) ptr::copy_memory(p_dst, p_src, count)
} })
} })
} }
} }
@ -2213,9 +2213,9 @@ pub mod bytes {
impl<'self> MutableByteVector for &'self mut [u8] { impl<'self> MutableByteVector for &'self mut [u8] {
#[inline] #[inline]
fn set_memory(self, value: u8) { fn set_memory(self, value: u8) {
do self.as_mut_buf |p, len| { self.as_mut_buf(|p, len| {
unsafe { ptr::set_memory(p, value, len) }; unsafe { ptr::set_memory(p, value, len) };
} })
} }
} }
@ -2278,11 +2278,11 @@ pub mod bytes {
let old_len = dst.len(); let old_len = dst.len();
dst.reserve_additional(src.len()); dst.reserve_additional(src.len());
unsafe { unsafe {
do dst.as_mut_buf |p_dst, len_dst| { dst.as_mut_buf(|p_dst, len_dst| {
do src.as_imm_buf |p_src, len_src| { src.as_imm_buf(|p_src, len_src| {
ptr::copy_memory(p_dst.offset(len_dst as int), p_src, len_src) ptr::copy_memory(p_dst.offset(len_dst as int), p_src, len_src)
} })
} });
vec::raw::set_len(dst, old_len + src.len()); vec::raw::set_len(dst, old_len + src.len());
} }
} }
@ -3276,10 +3276,10 @@ mod tests {
#[test] #[test]
#[should_fail] #[should_fail]
fn test_from_fn_fail() { fn test_from_fn_fail() {
do from_fn(100) |v| { from_fn(100, |v| {
if v == 50 { fail!() } if v == 50 { fail!() }
(~0, @0) (~0, @0)
}; });
} }
#[test] #[test]
@ -3308,25 +3308,25 @@ mod tests {
#[test] #[test]
#[should_fail] #[should_fail]
fn test_build_fail() { fn test_build_fail() {
do build(None) |push| { build(None, |push| {
push((~0, @0)); push((~0, @0));
push((~0, @0)); push((~0, @0));
push((~0, @0)); push((~0, @0));
push((~0, @0)); push((~0, @0));
fail!(); fail!();
}; });
} }
#[test] #[test]
#[should_fail] #[should_fail]
fn test_grow_fn_fail() { fn test_grow_fn_fail() {
let mut v = ~[]; let mut v = ~[];
do v.grow_fn(100) |i| { v.grow_fn(100, |i| {
if i == 50 { if i == 50 {
fail!() fail!()
} }
(~0, @0) (~0, @0)
} })
} }
#[test] #[test]
@ -3334,13 +3334,13 @@ mod tests {
fn test_map_fail() { fn test_map_fail() {
let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)]; let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
let mut i = 0; let mut i = 0;
do v.map |_elt| { v.map(|_elt| {
if i == 2 { if i == 2 {
fail!() fail!()
} }
i += 1; i += 1;
~[(~0, @0)] ~[(~0, @0)]
}; });
} }
#[test] #[test]
@ -3348,13 +3348,13 @@ mod tests {
fn test_flat_map_fail() { fn test_flat_map_fail() {
let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)]; let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
let mut i = 0; let mut i = 0;
do flat_map(v) |_elt| { flat_map(v, |_elt| {
if i == 2 { if i == 2 {
fail!() fail!()
} }
i += 1; i += 1;
~[(~0, @0)] ~[(~0, @0)]
}; });
} }
#[test] #[test]
@ -3374,18 +3374,18 @@ mod tests {
#[should_fail] #[should_fail]
fn test_as_imm_buf_fail() { fn test_as_imm_buf_fail() {
let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)]; let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
do v.as_imm_buf |_buf, _i| { v.as_imm_buf(|_buf, _i| {
fail!() fail!()
} })
} }
#[test] #[test]
#[should_fail] #[should_fail]
fn test_as_mut_buf_fail() { fn test_as_mut_buf_fail() {
let mut v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)]; let mut v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
do v.as_mut_buf |_buf, _i| { v.as_mut_buf(|_buf, _i| {
fail!() fail!()
} })
} }
#[test] #[test]
@ -3843,52 +3843,48 @@ mod bench {
// out. // out.
let v = vec::from_fn(100, |i| i ^ (i << 1) ^ (i >> 1)); let v = vec::from_fn(100, |i| i ^ (i << 1) ^ (i >> 1));
do bh.iter { bh.iter(|| {
let mut sum = 0; let mut sum = 0;
for x in v.iter() { for x in v.iter() {
sum += *x; sum += *x;
} }
// sum == 11806, to stop dead code elimination. // sum == 11806, to stop dead code elimination.
if sum == 0 {fail!()} if sum == 0 {fail!()}
} })
} }
#[bench] #[bench]
fn mut_iterator(bh: &mut BenchHarness) { fn mut_iterator(bh: &mut BenchHarness) {
let mut v = vec::from_elem(100, 0); let mut v = vec::from_elem(100, 0);
do bh.iter { bh.iter(|| {
let mut i = 0; let mut i = 0;
for x in v.mut_iter() { for x in v.mut_iter() {
*x = i; *x = i;
i += 1; i += 1;
} }
} })
} }
#[bench] #[bench]
fn add(bh: &mut BenchHarness) { fn add(bh: &mut BenchHarness) {
let xs: &[int] = [5, ..10]; let xs: &[int] = [5, ..10];
let ys: &[int] = [5, ..10]; let ys: &[int] = [5, ..10];
do bh.iter() { bh.iter(|| {
xs + ys; xs + ys;
} });
} }
#[bench] #[bench]
fn concat(bh: &mut BenchHarness) { fn concat(bh: &mut BenchHarness) {
let xss: &[~[uint]] = vec::from_fn(100, |i| range(0, i).collect()); let xss: &[~[uint]] = vec::from_fn(100, |i| range(0, i).collect());
do bh.iter { bh.iter(|| xss.concat_vec());
xss.concat_vec();
}
} }
#[bench] #[bench]
fn connect(bh: &mut BenchHarness) { fn connect(bh: &mut BenchHarness) {
let xss: &[~[uint]] = vec::from_fn(100, |i| range(0, i).collect()); let xss: &[~[uint]] = vec::from_fn(100, |i| range(0, i).collect());
do bh.iter { bh.iter(|| xss.connect_vec(&0));
xss.connect_vec(&0);
}
} }
#[bench] #[bench]