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]
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.
#[inline]
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() {
push((*x).clone());
}
for elt in rhs.iter() {
push(elt.clone());
}
}
})
}
/// 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] {
do build(Some(v.len())) |push| {
build(Some(v.len()), |push| {
for elem in v.iter() {
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`.
*/
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;
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`.
*/
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;
while i < n_elts {
push(t.clone());
i += 1u;
}
}
})
}
/**
@ -137,11 +137,11 @@ impl<T> Clone for @[T] {
impl<A> FromIterator<A> for @[A] {
fn from_iterator<T: Iterator<A>>(iterator: &mut T) -> @[A] {
let (lower, _) = iterator.size_hint();
do build(Some(lower)) |push| {
build(Some(lower), |push| {
for x in *iterator {
push(x);
}
}
})
}
}
@ -259,9 +259,9 @@ pub mod raw {
use rt::local::Local;
use rt::task::Task;
do Local::borrow |task: &mut Task| {
Local::borrow(|task: &mut Task| {
task.heap.realloc(ptr as *mut Box<()>, size) as *()
}
})
}
}
@ -295,11 +295,11 @@ mod test {
fn test() {
// Some code that could use that, then:
fn seq_range(lo: uint, hi: uint) -> @[uint] {
do build(None) |push| {
build(None, |push| {
for i in range(lo, hi) {
push(i);
}
}
})
}
assert_eq!(seq_range(10, 15), @[10, 11, 12, 13, 14]);
@ -333,9 +333,7 @@ mod test {
#[bench]
fn bench_capacity(b: &mut bh) {
let x = @[1, 2, 3];
do b.iter {
capacity(x);
}
b.iter(|| capacity(x));
}
#[bench]
@ -359,54 +357,42 @@ mod test {
fn bench_append(b: &mut bh) {
let lhs = @[7, ..128];
let rhs = range(0, 256).to_owned_vec();
do b.iter {
append(lhs, rhs);
}
b.iter(|| append(lhs, rhs))
}
#[bench]
fn bench_map(b: &mut bh) {
let elts = range(0, 256).to_owned_vec();
do b.iter {
map(elts, |x| x*2);
}
b.iter(|| map(elts, |x| x*2))
}
#[bench]
fn bench_from_fn(b: &mut bh) {
do b.iter {
from_fn(1024, |x| x);
}
b.iter(|| from_fn(1024, |x| x));
}
#[bench]
fn bench_from_elem(b: &mut bh) {
do b.iter {
from_elem(1024, 0u64);
}
b.iter(|| from_elem(1024, 0u64));
}
#[bench]
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
to_managed_move(elts);
}
})
}
#[bench]
fn bench_to_managed(b: &mut bh) {
let elts = range(0, 1024).to_owned_vec();
do b.iter {
to_managed(elts);
}
b.iter(|| to_managed(elts));
}
#[bench]
fn bench_clone(b: &mut bh) {
let elts = to_managed(range(0, 1024).to_owned_vec());
do b.iter {
elts.clone();
}
b.iter(|| 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
// `c_buffer` pointer will be deallocated when `my_c_string` goes out of scope.
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); }
}
})
// Don't save off the allocation of the C string, the `c_buffer` will be
// deallocated when this block returns!
do my_string.with_c_str |c_buffer| {
my_string.with_c_str(|c_buffer| {
unsafe { puts(c_buffer); }
}
})
```
*/
@ -262,14 +262,12 @@ static BUF_LEN: uint = 128;
impl<'self> ToCStr for &'self [u8] {
fn to_c_str(&self) -> CString {
let mut cs = unsafe { self.to_c_str_unchecked() };
do cs.with_mut_ref |buf| {
check_for_null(*self, buf);
}
cs.with_mut_ref(|buf| check_for_null(*self, buf));
cs
}
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;
if buf.is_null() {
fail!("failed to allocate memory!");
@ -279,7 +277,7 @@ impl<'self> ToCStr for &'self [u8] {
*ptr::mut_offset(buf, self_len as int) = 0;
CString::new(buf as *libc::c_char, true)
}
})
}
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());
buf[v.len()] = 0;
do buf.as_mut_buf |buf, _| {
buf.as_mut_buf(|buf, _| {
if checked {
check_for_null(v, buf as *mut libc::c_char);
}
f(buf as *libc::c_char)
}
})
} else if checked {
v.to_c_str().with_ref(f)
} else {
@ -390,10 +388,10 @@ mod tests {
let ptr = vec::raw::to_ptr(input);
let expected = ["zero", "one"];
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());
assert_eq!(cbytes, it.next().unwrap().as_bytes());
};
});
assert_eq!(result, 2);
assert!(it.next().is_none());
}
@ -401,13 +399,13 @@ mod tests {
#[test]
fn test_str_to_c_str() {
do "".to_c_str().with_ref |buf| {
"".to_c_str().with_ref(|buf| {
unsafe {
assert_eq!(*ptr::offset(buf, 0), 0);
}
}
});
do "hello".to_c_str().with_ref |buf| {
"hello".to_c_str().with_ref(|buf| {
unsafe {
assert_eq!(*ptr::offset(buf, 0), 'h' 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, 5), 0);
}
}
})
}
#[test]
fn test_vec_to_c_str() {
let b: &[u8] = [];
do b.to_c_str().with_ref |buf| {
b.to_c_str().with_ref(|buf| {
unsafe {
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 {
assert_eq!(*ptr::offset(buf, 0), 'h' 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, 5), 0);
}
}
});
do bytes!("foo", 0xff).to_c_str().with_ref |buf| {
let _ = bytes!("foo", 0xff).to_c_str().with_ref(|buf| {
unsafe {
assert_eq!(*ptr::offset(buf, 0), 'f' 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, 4), 0);
}
}
});
}
#[test]
@ -500,18 +498,16 @@ mod tests {
use c_str::null_byte::cond;
let mut error_happened = false;
do cond.trap(|err| {
cond.trap(|err| {
assert_eq!(err, bytes!("he", 0, "llo").to_owned())
error_happened = true;
Truncate
}).inside {
"he\x00llo".to_c_str()
};
}).inside(|| "he\x00llo".to_c_str());
assert!(error_happened);
do cond.trap(|_| {
cond.trap(|_| {
ReplaceWith('?' as libc::c_char)
}).inside(|| "he\x00llo".to_c_str()).with_ref |buf| {
}).inside(|| "he\x00llo".to_c_str()).with_ref(|buf| {
unsafe {
assert_eq!(*buf.offset(0), 'h' 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(6), 0);
}
}
})
}
#[test]
fn test_to_c_str_unchecked() {
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(1), 'e' as libc::c_char);
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(5), 'o' as libc::c_char);
assert_eq!(*buf.offset(6), 0);
}
})
}
}
@ -579,7 +575,7 @@ mod bench {
#[inline]
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) {
unsafe {
assert_eq!(
@ -587,7 +583,7 @@ mod bench {
*ptr::offset(c_str, i as int));
}
}
}
})
}
static s_short: &'static str = "Mary";
@ -601,12 +597,10 @@ mod bench {
Mary had a little lamb, Little lamb";
fn bench_to_str(bh: &mut BenchHarness, s: &str) {
do bh.iter {
bh.iter(|| {
let c_str = s.to_c_str();
do c_str.with_ref |c_str_buf| {
check(s, c_str_buf)
}
}
c_str.with_ref(|c_str_buf| check(s, c_str_buf))
})
}
#[bench]
@ -625,12 +619,10 @@ mod bench {
}
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() };
do c_str.with_ref |c_str_buf| {
check(s, c_str_buf)
}
}
c_str.with_ref(|c_str_buf| check(s, c_str_buf))
})
}
#[bench]
@ -649,11 +641,9 @@ mod bench {
}
fn bench_with_c_str(bh: &mut BenchHarness, s: &str) {
do bh.iter {
do s.with_c_str |c_str_buf| {
check(s, c_str_buf)
}
}
bh.iter(|| {
s.with_c_str(|c_str_buf| check(s, c_str_buf))
})
}
#[bench]
@ -672,13 +662,11 @@ mod bench {
}
fn bench_with_c_str_unchecked(bh: &mut BenchHarness, s: &str) {
do bh.iter {
bh.iter(|| {
unsafe {
do s.with_c_str_unchecked |c_str_buf| {
check(s, c_str_buf)
}
s.with_c_str_unchecked(|c_str_buf| check(s, c_str_buf))
}
}
})
}
#[bench]

View file

@ -82,6 +82,7 @@ pub struct RefCell<T> {
priv nc: NonCopyable
}
<<<<<<< HEAD
// Values [1, MAX-1] represent the number of `Ref` active
// (will not outgrow its range since `uint` is the size of the address space)
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
// 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;
if uniq {
stats.n_unique_boxes += 1;
@ -90,21 +90,21 @@ pub unsafe fn annihilate() {
(*box).ref_count = managed::RC_IMMORTAL;
}
true
};
});
// Pass 2: Drop all boxes.
//
// In this pass, unique-managed boxes may get freed, but not
// managed boxes, so we must read the `next` field *after* the
// callback, as the original value may have been freed.
do each_live_alloc(false) |box, uniq| {
each_live_alloc(false, |box, uniq| {
if !uniq {
let tydesc = (*box).type_desc;
let data = &(*box).data as *();
((*tydesc).drop_glue)(data as *i8);
}
true
};
});
// Pass 3: Free all boxes.
//
@ -112,7 +112,7 @@ pub unsafe fn annihilate() {
// unique-managed boxes, though I think that none of those are
// left), so we must read the `next` field before, since it will
// not be valid after.
do each_live_alloc(true) |box, uniq| {
each_live_alloc(true, |box, uniq| {
if !uniq {
stats.n_bytes_freed +=
(*((*box).type_desc)).size
@ -120,7 +120,7 @@ pub unsafe fn annihilate() {
local_free(box as *i8);
}
true
};
});
if debug_mem() {
// 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
pub fn lefts<L, R, Iter: Iterator<Either<L, R>>>(eithers: Iter)
-> Lefts<L, R, Iter> {
do eithers.filter_map |elt| {
eithers.filter_map(|elt| {
match elt {
Left(x) => Some(x),
_ => None,
}
}
})
}
/// Extracts all the right values
pub fn rights<L, R, Iter: Iterator<Either<L, R>>>(eithers: Iter)
-> Rights<L, R, Iter> {
do eithers.filter_map |elt| {
eithers.filter_map(|elt| {
match elt {
Right(x) => Some(x),
_ => None,
}
}
})
}

View file

@ -801,12 +801,12 @@ impl<'self> Formatter<'self> {
}
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);
for piece in pieces.iter() {
self.run(piece, Some(valuestr));
}
}
})
}
// Helper methods used for padding and processing formatting arguments that
@ -868,9 +868,9 @@ impl<'self> Formatter<'self> {
self.fill = '0';
sign(self);
}
do self.with_padding(min - actual_len, parse::AlignRight) |me| {
self.with_padding(min - actual_len, parse::AlignRight, |me| {
emit(me);
}
})
}
}
}
@ -924,9 +924,9 @@ impl<'self> Formatter<'self> {
// If we're under both the maximum and the minimum width, then fill
// up the minimum width with the specified string + some alignment.
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());
}
})
}
}
}
@ -1007,18 +1007,18 @@ macro_rules! int_base(($ty:ident, $into:ident, $base:expr,
$name:ident, $prefix:expr) => {
impl $name for $ty {
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);
}
})
}
}
})
macro_rules! upper_hex(($ty:ident, $into:ident) => {
impl UpperHex for $ty {
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);
}
})
}
}
})
@ -1045,9 +1045,9 @@ macro_rules! integer(($signed:ident, $unsigned:ident) => {
// nothing else should do that, however.
impl Signed for $signed {
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);
}
})
}
}
int_base!($signed, $unsigned, 2, Binary, "0b")
@ -1104,9 +1104,9 @@ impl<T> Poly for T {
impl<T> Pointer for *T {
fn fmt(t: &*T, f: &mut Formatter) {
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);
}
})
}
}
impl<T> Pointer for *mut T {

View file

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

View file

@ -110,7 +110,7 @@ impl<K:Hash + Eq,V> HashMap<K, V> {
k: &K)
-> SearchResult {
let mut ret = TableFull;
do self.bucket_sequence(hash) |i| {
self.bucket_sequence(hash, |i| {
match self.buckets[i] {
Some(ref bkt) if bkt.hash == hash && *k == bkt.key => {
ret = FoundEntry(i); false
@ -118,7 +118,7 @@ impl<K:Hash + Eq,V> HashMap<K, V> {
None => { ret = FoundHole(i); false }
_ => true,
}
};
});
ret
}
@ -128,7 +128,7 @@ impl<K:Hash + Eq,V> HashMap<K, V> {
k: &Q)
-> SearchResult {
let mut ret = TableFull;
do self.bucket_sequence(hash) |i| {
self.bucket_sequence(hash, |i| {
match self.buckets[i] {
Some(ref bkt) if bkt.hash == hash && k.equiv(&bkt.key) => {
ret = FoundEntry(i); false
@ -136,7 +136,7 @@ impl<K:Hash + Eq,V> HashMap<K, V> {
None => { ret = FoundHole(i); false }
_ => true,
}
};
});
ret
}
@ -236,9 +236,7 @@ impl<K:Hash + Eq,V> HashMap<K, V> {
let len_buckets = self.buckets.len();
let bucket = self.buckets[idx].take();
let value = do bucket.map |bucket| {
bucket.value
};
let value = bucket.map(|bucket| bucket.value);
/* re-inserting buckets may cause changes in size, so remember
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 {
if self.len() != other.len() { return false; }
do self.iter().all |(key, value)| {
self.iter().all(|(key, value)| {
match other.find(key) {
None => false,
Some(v) => value == v
}
}
})
}
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> {
do with_local_io |io| {
with_local_io(|io| {
match f(io) {
Ok(t) => Some(t),
Err(ioerr) => {
@ -84,7 +84,7 @@ fn io_raise<T>(f: |io: &mut IoFactory| -> Result<T, IoError>) -> Option<T> {
None
}
}
}
})
}
impl File {
@ -97,9 +97,9 @@ impl File {
///
/// let p = Path::new("/some/file/path.txt");
///
/// do io_error::cond.trap(|_| {
/// io_error::cond.trap(|_| {
/// // hoo-boy...
/// }).inside {
/// }).inside(|| {
/// let file = match File::open_mode(&p, Open, ReadWrite) {
/// Some(s) => s,
/// None => fail!("whoops! I'm sure this raised, anyways..")
@ -107,7 +107,7 @@ impl File {
/// // do some stuff with that file
///
/// // the file will be closed at the end of this block
/// }
/// })
/// // ..
///
/// `FileMode` and `FileAccess` provide information about the permissions
@ -132,7 +132,7 @@ impl File {
pub fn open_mode(path: &Path,
mode: FileMode,
access: FileAccess) -> Option<File> {
do with_local_io |io| {
with_local_io(|io| {
match io.fs_open(&path.to_c_str(), mode, access) {
Ok(fd) => Some(File {
path: path.clone(),
@ -144,7 +144,7 @@ impl File {
None
}
}
}
})
}
/// 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
/// other filesystem-level error occurs.
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,
@ -272,9 +272,7 @@ pub fn unlink(path: &Path) {
/// requisite permissions to perform a `stat` call on the given path or if
/// there is no entry in the filesystem at the provided path.
pub fn stat(path: &Path) -> FileStat {
do io_raise |io| {
io.fs_stat(&path.to_c_str())
}.unwrap_or_else(dummystat)
io_raise(|io| io.fs_stat(&path.to_c_str())).unwrap_or_else(dummystat)
}
fn dummystat() -> FileStat {
@ -310,9 +308,7 @@ fn dummystat() -> FileStat {
///
/// See `stat`
pub fn lstat(path: &Path) -> FileStat {
do io_raise |io| {
io.fs_lstat(&path.to_c_str())
}.unwrap_or_else(dummystat)
io_raise(|io| io.fs_lstat(&path.to_c_str())).unwrap_or_else(dummystat)
}
/// 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
/// intermittent I/O error occurs.
pub fn rename(from: &Path, to: &Path) {
do io_raise |io| {
io.fs_rename(&from.to_c_str(), &to.to_c_str())
};
io_raise(|io| io.fs_rename(&from.to_c_str(), &to.to_c_str()));
}
/// 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
/// change the attributes of a file or the file not existing.
pub fn chmod(path: &Path, mode: io::FilePermission) {
do io_raise |io| {
io.fs_chmod(&path.to_c_str(), mode)
};
io_raise(|io| io.fs_chmod(&path.to_c_str(), mode));
}
/// 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.
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
@ -425,7 +417,7 @@ pub fn chown(path: &Path, uid: int, gid: int) {
///
/// This function will raise on the `io_error` condition on failure.
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
@ -435,7 +427,7 @@ pub fn link(src: &Path, dst: &Path) {
///
/// This function will raise on the `io_error` condition on failure.
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.
@ -446,7 +438,7 @@ pub fn symlink(src: &Path, dst: &Path) {
/// conditions include reading a file that does not exist or reading a file
/// which is not a symlink.
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
@ -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
/// exists.
pub fn mkdir(path: &Path, mode: FilePermission) {
do io_raise |io| {
io.fs_mkdir(&path.to_c_str(), mode)
};
io_raise(|io| io.fs_mkdir(&path.to_c_str(), mode));
}
/// 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
/// empty.
pub fn rmdir(path: &Path) {
do io_raise |io| {
io.fs_rmdir(&path.to_c_str())
};
io_raise(|io| io.fs_rmdir(&path.to_c_str()));
}
/// 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
/// at a non-directory file
pub fn readdir(path: &Path) -> ~[Path] {
do io_raise |io| {
io.fs_readdir(&path.to_c_str(), 0)
}.unwrap_or_else(|| ~[])
io_raise(|io| io.fs_readdir(&path.to_c_str(), 0)).unwrap_or_else(|| ~[])
}
/// Returns an iterator which will recursively walk the directory structure
@ -599,9 +585,7 @@ pub fn rmdir_recursive(path: &Path) {
/// happens.
// FIXME(#10301) these arguments should not be u64
pub fn change_file_times(path: &Path, atime: u64, mtime: u64) {
do io_raise |io| {
io.fs_utime(&path.to_c_str(), atime, mtime)
};
io_raise(|io| io.fs_utime(&path.to_c_str(), atime, mtime));
}
impl Reader for File {
@ -797,12 +781,12 @@ mod test {
let tmpdir = tmpdir();
let filename = &tmpdir.join("file_that_does_not_exist.txt");
let mut called = false;
do io_error::cond.trap(|_| {
io_error::cond.trap(|_| {
called = true;
}).inside {
}).inside(|| {
let result = File::open_mode(filename, Open, Read);
assert!(result.is_none());
}
});
assert!(called);
})
@ -810,11 +794,9 @@ mod test {
let tmpdir = tmpdir();
let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
let mut called = false;
do io_error::cond.trap(|_| {
io_error::cond.trap(|_| {
called = true;
}).inside {
unlink(filename);
}
}).inside(|| unlink(filename));
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
do File::open("message.txt").each_line |line| {
File::open("message.txt").each_line(|line| {
println(line)
}
})
* Pull the lines of a file into a vector of strings
@ -395,13 +395,11 @@ condition! {
/// Helper for wrapper calls where you want to
/// ignore any io_errors that might be raised
pub fn ignore_io_error<T>(cb: || -> T) -> T {
do io_error::cond.trap(|_| {
io_error::cond.trap(|_| {
// just swallow the error.. downstream users
// who can make a decision based on a None result
// won't care
}).inside {
cb()
}
}).inside(|| cb())
}
/// 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);
vec::raw::set_len(buf, start_len + len);
do (|| {
(|| {
while total_read < len {
let len = buf.len();
let slice = buf.mut_slice(start_len + total_read, len);
@ -515,9 +513,7 @@ pub trait Reader {
}
}
}
}).finally {
vec::raw::set_len(buf, start_len + total_read);
}
}).finally(|| vec::raw::set_len(buf, start_len + total_read))
}
}
@ -542,17 +538,17 @@ pub trait Reader {
fn read_to_end(&mut self) -> ~[u8] {
let mut buf = vec::with_capacity(DEFAULT_BUF_SIZE);
let mut keep_reading = true;
do io_error::cond.trap(|e| {
io_error::cond.trap(|e| {
if e.kind == EndOfFile {
keep_reading = false;
} else {
io_error::cond.raise(e)
}
}).inside {
}).inside(|| {
while keep_reading {
self.push_bytes(&mut buf, DEFAULT_BUF_SIZE)
}
}
});
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(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 amt = origamt;
while amt > 0 {
@ -83,11 +83,11 @@ impl FileDesc {
fn inner_read(&mut self, buf: &mut [u8]) -> Result<uint, IoError> {
#[cfg(windows)] type rlen = libc::c_uint;
#[cfg(not(windows))] type rlen = libc::size_t;
let ret = do keep_going(buf) |buf, len| {
let ret = keep_going(buf, |buf, len| {
unsafe {
libc::read(self.fd, buf as *mut libc::c_void, len as rlen) as i64
}
};
});
if ret == 0 {
Err(io::standard_error(io::EndOfFile))
} else if ret < 0 {
@ -99,11 +99,11 @@ impl FileDesc {
fn inner_write(&mut self, buf: &[u8]) -> Result<(), IoError> {
#[cfg(windows)] type wlen = libc::c_uint;
#[cfg(not(windows))] type wlen = libc::size_t;
let ret = do keep_going(buf) |buf, len| {
let ret = keep_going(buf, |buf, len| {
unsafe {
libc::write(self.fd, buf as *libc::c_void, len as wlen) as i64
}
};
});
if ret < 0 {
Err(super::last_error())
} else {
@ -344,12 +344,12 @@ impl CFile {
impl rtio::RtioFileStream for CFile {
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 {
libc::fread(buf as *mut libc::c_void, 1, len as libc::size_t,
self.file) as i64
}
};
});
if ret == 0 {
Err(io::standard_error(io::EndOfFile))
} else if ret < 0 {
@ -360,12 +360,12 @@ impl rtio::RtioFileStream for CFile {
}
fn write(&mut self, buf: &[u8]) -> Result<(), IoError> {
let ret = do keep_going(buf) |buf, len| {
let ret = keep_going(buf, |buf, len| {
unsafe {
libc::fwrite(buf as *libc::c_void, 1, len as libc::size_t,
self.file) as i64
}
};
});
if ret < 0 {
Err(super::last_error())
} else {
@ -445,9 +445,9 @@ pub fn open(path: &CString, fm: io::FileMode, fa: io::FileAccess)
#[cfg(windows)]
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) }
}
})
}
#[cfg(unix)]
@ -463,9 +463,9 @@ pub fn mkdir(p: &CString, mode: io::FilePermission) -> IoResult<()> {
fn os_mkdir(p: &CString, _mode: c_int) -> IoResult<()> {
super::mkerr_winbool(unsafe {
// 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())
}
})
})
}
@ -497,9 +497,7 @@ pub fn readdir(p: &CString) -> IoResult<~[Path]> {
}
debug!("os::list_dir -- BEFORE OPENDIR");
let dir_ptr = do p.with_ref |buf| {
opendir(buf)
};
let dir_ptr = p.with_ref(|buf| opendir(buf));
if (dir_ptr as uint != 0) {
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 = Path::new(p);
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 find_handle = FindFirstFileW(path_ptr, wfd_ptr as HANDLE);
if find_handle as libc::c_int != INVALID_HANDLE_VALUE {
@ -565,7 +563,7 @@ pub fn readdir(p: &CString) -> IoResult<~[Path]> {
} else {
Err(super::last_error())
}
}
})
}
get_list(p).map(|paths| prune(p, paths))
@ -578,9 +576,7 @@ pub fn unlink(p: &CString) -> IoResult<()> {
#[cfg(windows)]
fn os_unlink(p: &CString) -> IoResult<()> {
super::mkerr_winbool(unsafe {
do as_utf16_p(p.as_str().unwrap()) |buf| {
libc::DeleteFileW(buf)
}
as_utf16_p(p.as_str().unwrap(), |buf| libc::DeleteFileW(buf));
})
}
@ -596,11 +592,11 @@ pub fn rename(old: &CString, new: &CString) -> IoResult<()> {
#[cfg(windows)]
fn os_rename(old: &CString, new: &CString) -> IoResult<()> {
super::mkerr_winbool(unsafe {
do as_utf16_p(old.as_str().unwrap()) |old| {
do as_utf16_p(new.as_str().unwrap()) |new| {
as_utf16_p(old.as_str().unwrap(), |old| {
as_utf16_p(new.as_str().unwrap(), |new| {
libc::MoveFileExW(old, new, libc::MOVEFILE_REPLACE_EXISTING)
}
}
})
})
})
}
@ -618,9 +614,7 @@ pub fn chmod(p: &CString, mode: io::FilePermission) -> IoResult<()> {
#[cfg(windows)]
fn os_chmod(p: &CString, mode: c_int) -> c_int {
unsafe {
do as_utf16_p(p.as_str().unwrap()) |p| {
libc::wchmod(p, mode)
}
as_utf16_p(p.as_str().unwrap(), |p| libc::wchmod(p, mode))
}
}
@ -636,7 +630,7 @@ pub fn rmdir(p: &CString) -> IoResult<()> {
#[cfg(windows)]
fn os_rmdir(p: &CString) -> c_int {
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)]
fn os_readlink(p: &CString) -> IoResult<Path> {
let handle = unsafe {
do as_utf16_p(p.as_str().unwrap()) |p| {
as_utf16_p(p.as_str().unwrap(), |p| {
libc::CreateFileW(p,
libc::GENERIC_READ,
libc::FILE_SHARE_READ,
@ -677,15 +671,15 @@ pub fn readlink(p: &CString) -> IoResult<Path> {
libc::OPEN_EXISTING,
libc::FILE_ATTRIBUTE_NORMAL,
ptr::mut_null())
}
})
};
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 {
libc::GetFinalPathNameByHandleW(handle, buf as *u16, sz,
libc::VOLUME_NAME_NT)
}
};
});
let ret = match ret {
Some(s) => Ok(Path::new(s)),
None => Err(super::last_error()),
@ -722,11 +716,11 @@ pub fn symlink(src: &CString, dst: &CString) -> IoResult<()> {
#[cfg(windows)]
fn os_symlink(src: &CString, dst: &CString) -> IoResult<()> {
super::mkerr_winbool(do as_utf16_p(src.as_str().unwrap()) |src| {
do as_utf16_p(dst.as_str().unwrap()) |dst| {
super::mkerr_winbool(as_utf16_p(src.as_str().unwrap(), |src| {
as_utf16_p(dst.as_str().unwrap(), |dst| {
unsafe { libc::CreateSymbolicLinkW(dst, src, 0) }
}
})
})
}))
}
#[cfg(unix)]
@ -742,11 +736,11 @@ pub fn link(src: &CString, dst: &CString) -> IoResult<()> {
#[cfg(windows)]
fn os_link(src: &CString, dst: &CString) -> IoResult<()> {
super::mkerr_winbool(do as_utf16_p(src.as_str().unwrap()) |src| {
do as_utf16_p(dst.as_str().unwrap()) |dst| {
super::mkerr_winbool(as_utf16_p(src.as_str().unwrap(), |src| {
as_utf16_p(dst.as_str().unwrap(), |dst| {
unsafe { libc::CreateHardLinkW(dst, src, ptr::mut_null()) }
}
})
})
}))
}
#[cfg(unix)]
@ -851,12 +845,12 @@ pub fn stat(p: &CString) -> IoResult<io::FileStat> {
#[cfg(windows)]
fn os_stat(p: &CString) -> IoResult<io::FileStat> {
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) } {
0 => Ok(mkstat(&stat, p)),
_ => Err(super::last_error()),
}
}
})
}
#[cfg(unix)]
@ -898,9 +892,7 @@ pub fn utime(p: &CString, atime: u64, mtime: u64) -> IoResult<()> {
modtime: (mtime / 1000) as libc::time64_t,
};
unsafe {
do as_utf16_p(p.as_str().unwrap()) |p| {
libc::wutime(p, &buf)
}
as_utf16_p(p.as_str().unwrap(), |p| 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 create_err = None;
do with_envp(env) |envp| {
do with_dirp(dir) |dirp| {
do cmd.with_c_str |cmdp| {
with_envp(env, |envp| {
with_dirp(dir, |dirp| {
cmd.with_c_str(|cmdp| {
let created = CreateProcessA(ptr::null(), cast::transmute(cmdp),
ptr::mut_null(), ptr::mut_null(), TRUE,
0, envp, dirp, &mut si, &mut pi);
if created == FALSE {
create_err = Some(os::last_os_error());
}
}
}
}
})
})
});
CloseHandle(si.hStdInput);
CloseHandle(si.hStdOutput);
@ -411,22 +411,22 @@ fn spawn_process_os(prog: &str, args: &[~str],
close(fd as c_int);
}
do with_dirp(dir) |dirp| {
with_dirp(dir, |dirp| {
if !dirp.is_null() && chdir(dirp) == -1 {
fail!("failure in chdir: {}", os::last_os_error());
}
}
});
do with_envp(env) |envp| {
with_envp(env, |envp| {
if !envp.is_null() {
set_environ(envp);
}
do with_argv(prog, args) |argv| {
with_argv(prog, args, |argv| {
execvp(*argv, argv);
// execvp only returns if an error occurred
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
// technically unsafe as the caller could leak these pointers out of our
// scope.
let mut ptrs = do tmps.map |tmp| {
tmp.with_ref(|buf| buf)
};
let mut ptrs = tmps.map(|tmp| tmp.with_ref(|buf| buf));
// Finally, make sure we add a null pointer.
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.
let mut ptrs = do tmps.map |tmp| {
tmp.with_ref(|buf| buf)
};
let mut ptrs = tmps.map(|tmp| tmp.with_ref(|buf| buf));
ptrs.push(ptr::null());
do ptrs.as_imm_buf |buf, _| {
unsafe { cb(cast::transmute(buf)) }
}
ptrs.as_imm_buf(|buf, _| unsafe { cb(cast::transmute(buf)) })
}
_ => cb(ptr::null())
}
@ -505,9 +499,7 @@ fn with_envp<T>(env: Option<~[(~str, ~str)]>, cb: |*mut c_void| -> T) -> T {
blk.push(0);
do blk.as_imm_buf |p, _len| {
unsafe { cb(cast::transmute(p)) }
}
blk.as_imm_buf(|p, _len| unsafe { cb(cast::transmute(p)) });
}
_ => cb(ptr::mut_null())
}

View file

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

View file

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

View file

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

View file

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

View file

@ -59,7 +59,7 @@ impl UnixStream {
/// stream.write([1, 2, 3]);
///
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()) {
Ok(s) => Some(UnixStream::new(s)),
Err(ioerr) => {
@ -67,7 +67,7 @@ impl UnixStream {
None
}
}
}
})
}
}
@ -108,7 +108,7 @@ impl 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()) {
Ok(s) => Some(UnixListener{ obj: s }),
Err(ioerr) => {
@ -116,7 +116,7 @@ impl UnixListener {
None
}
}
}
})
}
}

View file

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

View file

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

View file

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

View file

@ -70,7 +70,7 @@ enum StdSource {
}
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) };
match io.tty_open(fd, readable) {
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))))
}
}
}.unwrap()
}).unwrap()
}
/// Creates a new non-blocking handle to the stdin of the current process.
///
/// See `stdout()` for notes about this function.
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.
@ -101,14 +101,14 @@ pub fn stdin() -> StdReader {
/// task context because the stream returned will be a non-blocking object using
/// the local scheduler to perform the I/O.
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.
///
/// See `stdout()` for notes about this function.
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
@ -116,11 +116,11 @@ pub fn stderr() -> StdWriter {
// Note that this is not a safe function to expose because you can create an
// aliased pointer very easily:
//
// do with_task_stdout |io1| {
// do with_task_stdout |io2| {
// with_task_stdout(|io1| {
// with_task_stdout(|io2| {
// // io1 aliases io2
// }
// }
// })
// })
fn with_task_stdout(f: |&mut Writer|) {
use rt::local::Local;
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
/// messages are always terminated in a newline (no need to flush).
pub fn flush() {
do with_task_stdout |io| {
io.flush();
}
with_task_stdout(|io| io.flush())
}
/// Prints a string to the stdout of the current process. No newline is emitted
/// after the string is printed.
pub fn print(s: &str) {
do with_task_stdout |io| {
io.write(s.as_bytes());
}
with_task_stdout(|io| io.write(s.as_bytes()))
}
/// 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.
pub fn println(s: &str) {
do with_task_stdout |io| {
with_task_stdout(|io| {
io.write(s.as_bytes());
io.write(['\n' as u8]);
}
})
}
/// Similar to `print`, but takes a `fmt::Arguments` structure to be compatible
/// with the `format_args!` macro.
pub fn print_args(fmt: &fmt::Arguments) {
do with_task_stdout |io| {
fmt::write(io, fmt);
}
with_task_stdout(|io| fmt::write(io, fmt))
}
/// Similar to `println`, but takes a `fmt::Arguments` structure to be
/// compatible with the `format_args!` macro.
pub fn println_args(fmt: &fmt::Arguments) {
do with_task_stdout |io| {
fmt::writeln(io, fmt);
}
with_task_stdout(|io| fmt::writeln(io, fmt))
}
/// 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
/// get notified after an amount of time has passed.
pub fn new() -> Option<Timer> {
do with_local_io |io| {
with_local_io(|io| {
match io.timer_init() {
Ok(t) => Some(Timer { obj: t }),
Err(ioerr) => {
@ -70,7 +70,7 @@ impl Timer {
}
}
}
})
}
/// 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
/// 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 {
do get_with(key, MutLoan) |x| {
get_with(key, MutLoan, |x| {
match x {
None => f(None),
// 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!
Some(x) => { f(Some(unsafe { cast::transmute_mut(x) })) }
}
}
})
}
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.
let mut buf = [0u8, ..65];
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;
cur += 1;
}
});
f(buf.slice(0, cur))
}
@ -440,9 +440,9 @@ impl ToStrRadix for $T {
#[inline]
fn to_str_radix(&self, radix: uint) -> ~str {
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);
}
});
// We know we generated valid utf-8, so we don't need to go through that
// check.
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.
let mut buf = [0u8, ..64];
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;
cur += 1;
}
});
f(buf.slice(0, cur))
}
@ -291,9 +291,9 @@ impl ToStrRadix for $T {
#[inline]
fn to_str_radix(&self, radix: uint) -> ~str {
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);
}
});
// We know we generated valid utf-8, so we don't need to go through that
// check.
unsafe { str::raw::from_utf8_owned(buf) }

View file

@ -58,7 +58,7 @@ static BUF_BYTES : uint = 2048u;
#[cfg(unix)]
pub fn getcwd() -> Path {
let mut buf = [0 as libc::c_char, ..BUF_BYTES];
do buf.as_mut_buf |buf, len| {
buf.as_mut_buf(|buf, len| {
unsafe {
if libc::getcwd(buf, len as size_t).is_null() {
fail!()
@ -66,7 +66,7 @@ pub fn getcwd() -> Path {
Path::new(CString::new(buf as *c_char, false))
}
}
})
}
#[cfg(windows)]
@ -74,13 +74,13 @@ pub fn getcwd() -> Path {
use libc::DWORD;
use libc::GetCurrentDirectoryW;
let mut buf = [0 as u16, ..BUF_BYTES];
do buf.as_mut_buf |buf, len| {
buf.as_mut_buf(|buf, len| {
unsafe {
if libc::GetCurrentDirectoryW(len as DWORD, buf) == 0 as DWORD {
fail!();
}
}
}
});
Path::new(str::from_utf16(buf))
}
@ -104,7 +104,7 @@ pub mod win32 {
while !done {
let mut k: DWORD = 0;
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);
if k == (0 as DWORD) {
done = true;
@ -115,7 +115,7 @@ pub mod win32 {
} else {
done = true;
}
}
});
if k != 0 && done {
let sub = buf.slice(0, k as uint);
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;
unsafe {
return do (|| {
return (|| {
lock.lock();
f()
}).finally {
lock.unlock();
};
}).finally(|| lock.unlock());
}
}
@ -172,9 +170,9 @@ pub fn env() -> ~[(~str,~str)] {
os::last_os_error());
}
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());
};
});
FreeEnvironmentStringsA(ch);
result
}
@ -207,10 +205,10 @@ pub fn env() -> ~[(~str,~str)] {
}
pairs
}
do with_env_lock {
with_env_lock(|| {
let unparsed_environ = get_env_pairs();
env_convert(unparsed_environ)
}
})
}
}
@ -219,16 +217,14 @@ pub fn env() -> ~[(~str,~str)] {
/// None if the variable isn't set.
pub fn getenv(n: &str) -> Option<~str> {
unsafe {
do with_env_lock {
let s = do n.with_c_str |buf| {
libc::getenv(buf)
};
with_env_lock(|| {
let s = n.with_c_str(|buf| libc::getenv(buf));
if s.is_null() {
None
} else {
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.
pub fn getenv(n: &str) -> Option<~str> {
unsafe {
do with_env_lock {
with_env_lock(|| {
use os::win32::{as_utf16_p, fill_utf16_buf_and_decode};
do as_utf16_p(n) |u| {
do fill_utf16_buf_and_decode() |buf, sz| {
as_utf16_p(n, |u| {
fill_utf16_buf_and_decode(|buf, sz| {
libc::GetEnvironmentVariableW(u, buf, sz)
}
}
}
})
})
})
}
}
@ -254,13 +250,13 @@ pub fn getenv(n: &str) -> Option<~str> {
/// process
pub fn setenv(n: &str, v: &str) {
unsafe {
do with_env_lock {
do n.with_c_str |nbuf| {
do v.with_c_str |vbuf| {
with_env_lock(|| {
n.with_c_str(|nbuf| {
v.with_c_str(|vbuf| {
libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1);
}
}
}
})
})
})
}
}
@ -270,14 +266,14 @@ pub fn setenv(n: &str, v: &str) {
/// process
pub fn setenv(n: &str, v: &str) {
unsafe {
do with_env_lock {
with_env_lock(|| {
use os::win32::as_utf16_p;
do as_utf16_p(n) |nbuf| {
do as_utf16_p(v) |vbuf| {
as_utf16_p(n, |nbuf| {
as_utf16_p(v, |vbuf| {
libc::SetEnvironmentVariableW(nbuf, vbuf);
}
}
}
})
})
})
}
}
@ -286,22 +282,22 @@ pub fn unsetenv(n: &str) {
#[cfg(unix)]
fn _unsetenv(n: &str) {
unsafe {
do with_env_lock {
do n.with_c_str |nbuf| {
with_env_lock(|| {
n.with_c_str(|nbuf| {
libc::funcs::posix01::unistd::unsetenv(nbuf);
}
}
})
})
}
}
#[cfg(windows)]
fn _unsetenv(n: &str) {
unsafe {
do with_env_lock {
with_env_lock(|| {
use os::win32::as_utf16_p;
do as_utf16_p(n) |nbuf| {
as_utf16_p(n, |nbuf| {
libc::SetEnvironmentVariableW(nbuf, ptr::null());
}
}
})
})
}
}
@ -372,10 +368,10 @@ pub fn self_exe_path() -> Option<Path> {
if err != 0 { return None; }
if sz == 0 { return None; }
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,
buf as *mut c_void, &mut sz, ptr::null(), 0u as size_t)
};
});
if err != 0 { return None; }
if sz == 0 { return None; }
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);
if sz == 0 { return None; }
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)
};
});
if err != 0 { return None; }
vec::raw::set_len(&mut v, sz as uint - 1); // chop off trailing NUL
Some(v)
@ -416,9 +412,9 @@ pub fn self_exe_path() -> Option<Path> {
fn load_self() -> Option<~[u8]> {
unsafe {
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)
}.map(|s| s.into_bytes())
}).map(|s| s.into_bytes())
}
}
@ -452,13 +448,13 @@ pub fn homedir() -> Option<Path> {
#[cfg(windows)]
fn secondary() -> Option<Path> {
do getenv("USERPROFILE").and_then |p| {
getenv("USERPROFILE").and_then(|p| {
if !p.is_empty() {
Path::new_opt(p)
} else {
None
}
}
})
}
}
@ -536,19 +532,19 @@ pub fn change_dir(p: &Path) -> bool {
fn chdir(p: &Path) -> bool {
unsafe {
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)
};
});
}
}
#[cfg(unix)]
fn chdir(p: &Path) -> bool {
do p.with_c_str |buf| {
p.with_c_str(|buf| {
unsafe {
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];
do buf.as_mut_buf |buf, len| {
buf.as_mut_buf(|buf, len| {
unsafe {
if strerror_r(errno() as c_int, buf, len as size_t) < 0 {
fail!("strerror_r failure");
@ -645,7 +641,7 @@ pub fn last_os_error() -> ~str {
str::raw::from_c_str(buf as *c_char)
}
}
})
}
#[cfg(windows)]
@ -678,7 +674,7 @@ pub fn last_os_error() -> ~str {
let mut buf = [0 as WCHAR, ..TMPBUF_SZ];
unsafe {
do buf.as_mut_buf |buf, len| {
buf.as_mut_buf(|buf, len| {
let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
ptr::mut_null(),
@ -690,7 +686,7 @@ pub fn last_os_error() -> ~str {
if res == 0 {
fail!("[{}] FormatMessage failure", errno());
}
}
});
str::from_utf16(buf)
}
@ -1466,13 +1462,11 @@ mod tests {
let size = MemoryMap::granularity() * 2;
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)
};
});
lseek_(fd, size);
do "x".with_c_str |x| {
assert!(write(fd, x as *c_void, 1) == 1);
}
"x".with_c_str(|x| assert!(write(fd, x as *c_void, 1) == 1));
fd
};
let chunk = match MemoryMap::new(size / 2, [
@ -1491,7 +1485,7 @@ mod tests {
assert!(*chunk.data == 0xbe);
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

View file

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

View file

@ -51,9 +51,9 @@ impl IsaacRng {
unsafe {
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);
}
})
}
rng.init(true);
@ -94,7 +94,7 @@ impl IsaacRng {
}}
);
do 4.times { mix!(); }
4.times(|| mix!());
if use_rsl {
macro_rules! memloop (
@ -256,9 +256,9 @@ impl Isaac64Rng {
unsafe {
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);
}
})
}
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)]
mod test_rc {
use super::*;
@ -177,9 +199,9 @@ mod test_rc {
fn test_clone() {
let x = Rc::from_send(RefCell::new(5));
let y = x.clone();
do x.borrow().with_mut |inner| {
x.borrow().with_mut(|inner| {
*inner = 20;
}
});
assert_eq!(y.borrow().with(|v| *v), 20);
}
@ -187,9 +209,9 @@ mod test_rc {
fn test_deep_clone() {
let x = Rc::from_send(RefCell::new(5));
let y = x.deep_clone();
do x.borrow().with_mut |inner| {
x.borrow().with_mut(|inner| {
*inner = 20;
}
});
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> {
#[inline]
pub fn bump(&mut self, sz: uint) {
do self.inner.move_ptr() |p| {
((p as uint) + sz) as *c_void
};
self.inner.move_ptr(|p| ((p as uint) + sz) as *c_void)
}
#[inline]
pub fn align(&mut self, a: uint) {
do self.inner.move_ptr() |p| {
align(p as uint, a) as *c_void
};
self.inner.move_ptr(|p| align(p as uint, a) as *c_void)
}
#[inline]

View file

@ -53,18 +53,18 @@ impl Repr for bool {
impl Repr for int {
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);
}
})
}
}
macro_rules! int_repr(($ty:ident, $suffix:expr) => (impl Repr for $ty {
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(bytes!($suffix));
}
})
}
}))
@ -163,9 +163,9 @@ impl<'self> ReprVisitor<'self> {
#[inline]
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) });
}
})
}
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]),
_ => {
do char::escape_unicode(ch) |c| {
char::escape_unicode(ch, |c| {
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_char(&mut self) -> bool {
do self.get::<char> |this, &ch| {
self.get::<char>(|this, &ch| {
this.writer.write(['\'' as u8]);
this.write_escaped_char(ch, false);
this.writer.write(['\'' as u8]);
}
})
}
fn visit_estr_box(&mut self) -> bool {
do self.get::<@str> |this, s| {
self.get::<@str>(|this, s| {
this.writer.write(['@' as u8]);
this.write_escaped_slice(*s);
}
})
}
fn visit_estr_uniq(&mut self) -> bool {
do self.get::<~str> |this, s| {
self.get::<~str>(|this, s| {
this.writer.write(['~' as u8]);
this.write_escaped_slice(*s);
}
})
}
fn visit_estr_slice(&mut self) -> bool {
do self.get::<&str> |this, s| {
this.write_escaped_slice(*s);
}
self.get::<&str>(|this, s| this.write_escaped_slice(*s))
}
// 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 {
self.writer.write(['@' as u8]);
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;
this.visit_ptr_inner(p, inner);
}
})
}
fn visit_uniq(&mut self, _mtbl: uint, inner: *TyDesc) -> bool {
self.writer.write(['~' as u8]);
do self.get::<*c_void> |this, b| {
self.get::<*c_void>(|this, b| {
this.visit_ptr_inner(*b, inner);
}
})
}
fn visit_uniq_managed(&mut self, _mtbl: uint, inner: *TyDesc) -> bool {
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;
this.visit_ptr_inner(p, inner);
}
})
}
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);
this.write_mut_qualifier(mtbl);
this.writer.write("())".as_bytes());
}
})
}
fn visit_rptr(&mut self, mtbl: uint, inner: *TyDesc) -> bool {
self.writer.write(['&' as u8]);
self.write_mut_qualifier(mtbl);
do self.get::<*c_void> |this, p| {
self.get::<*c_void>(|this, p| {
this.visit_ptr_inner(*p, inner);
}
})
}
// Type no longer exists, vestigial function.
fn visit_vec(&mut self, _mtbl: uint, _inner: *TyDesc) -> bool { fail!(); }
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);
}
})
}
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.write_mut_qualifier(mtbl);
this.write_unboxed_vec_repr(mtbl, &b.data, inner);
}
})
}
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.write_unboxed_vec_repr(mtbl, *b, inner);
}
})
}
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.write_unboxed_vec_repr(mtbl, &b.data, inner);
}
})
}
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.write_mut_qualifier(mtbl);
let size = unsafe {
if (*inner).size == 0 { 1 } else { (*inner).size }
};
this.write_vec_range(s.data, s.len * size, inner);
}
})
}
fn visit_evec_fixed(&mut self, n: uint, sz: uint, _align: uint,
_: uint, inner: *TyDesc) -> bool {
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);
}
})
}
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 {
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;
this.visit_ptr_inner(p, b.type_desc);
}
})
}
fn visit_closure_ptr(&mut self, _ck: uint) -> bool { true }

View file

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

View file

@ -35,9 +35,7 @@ pub struct BorrowRecord {
}
fn try_take_task_borrow_list() -> Option<~[BorrowRecord]> {
do Local::borrow |task: &mut Task| {
task.borrow_list.take()
}
Local::borrow(|task: &mut Task| task.borrow_list.take())
}
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 = Cell::new(borrows);
do Local::borrow |task: &mut Task| {
task.borrow_list = Some(borrows.take());
}
Local::borrow(|task: &mut Task| task.borrow_list = Some(borrows.take()))
}
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() {
None => { // not recording borrows
let msg = "borrowed";
do msg.with_c_str |msg_p| {
task::begin_unwind_raw(msg_p, file, line);
}
msg.with_c_str(|msg_p| task::begin_unwind_raw(msg_p, file, line))
}
Some(borrow_list) => { // recording borrows
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 ";
}
}
do msg.with_c_str |msg_p| {
task::begin_unwind_raw(msg_p, file, line)
}
msg.with_c_str(|msg_p| 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
let a = a as *mut raw::Box<()>;
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;
borrow_list.push(BorrowRecord {box: a, file: file, line: line});
borrow_list
}
})
}
}
pub unsafe fn unrecord_borrow(a: *u8, old_ref_count: uint,
file: *c_char, line: size_t) {
pub unsafe fn unrecord_borrow(a: *u8,
old_ref_count: uint,
file: *c_char,
line: size_t) {
if (old_ref_count & ALL_BITS) == 0 {
// was not borrowed before, so we should find the record at
// the end of the list
let a = a as *mut raw::Box<()>;
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;
assert!(!borrow_list.is_empty());
let br = borrow_list.pop();
if br.box != a || br.file != file || br.line != line {
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)
}
})
}
borrow_list
}
})
}
}

View file

@ -165,14 +165,14 @@ impl<T: Send> ChanOne<T> {
// Port is blocked. Wake it up.
let recvr = BlockedTask::cast_from_uint(task_as_state);
if do_resched {
do recvr.wake().map |woken_task| {
recvr.wake().map(|woken_task| {
Scheduler::run_task(woken_task);
};
});
} else {
let recvr = Cell::new(recvr);
do Local::borrow |sched: &mut Scheduler| {
Local::borrow(|sched: &mut Scheduler| {
sched.enqueue_blocked_task(recvr.take());
}
})
}
}
}
@ -209,9 +209,9 @@ impl<T: Send> PortOne<T> {
// No data available yet.
// Switch to the scheduler to put the ~Task into the Packet state.
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);
}
})
}
// Task resumes.
@ -230,9 +230,9 @@ impl<T: Send> SelectInner for PortOne<T> {
// The optimistic check is never necessary for correctness. For testing
// purposes, making it randomly return false simulates a racing sender.
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)
};
});
if actually_check {
unsafe { (*self.packet()).state.load(Acquire) == STATE_ONE }
} 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.
rtassert!((*self.packet()).payload.is_none());
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);
};
});
}
}
}
@ -491,7 +491,7 @@ impl<T: Send> GenericPort<T> for Port<T> {
fn try_recv(&self) -> Option<T> {
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() {
Some(StreamPayload { val, next }) => {
*b.get() = Some(next);
@ -499,7 +499,7 @@ impl<T: Send> GenericPort<T> for Port<T> {
}
None => None
}
}
})
}
}
@ -516,7 +516,7 @@ impl<T: Send> Peekable<T> for Port<T> {
impl<'self, T: Send> SelectInner for &'self Port<T> {
#[inline]
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]
@ -527,7 +527,7 @@ impl<'self, T: Send> SelectInner for &'self Port<T> {
#[inline]
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]
fn oneshot_multi_thread_close_stress() {
if util::limit_thread_creation_due_to_osx_and_valgrind() { return; }
do stress_factor().times {
stress_factor().times(|| {
do run_in_newsched_task {
let (port, chan) = oneshot::<int>();
let port_cell = Cell::new(port);
@ -881,13 +881,13 @@ mod test {
let _chan = chan;
thread.join();
}
}
})
}
#[test]
fn oneshot_multi_thread_send_close_stress() {
if util::limit_thread_creation_due_to_osx_and_valgrind() { return; }
do stress_factor().times {
stress_factor().times(|| {
do run_in_newsched_task {
let (port, chan) = oneshot::<int>();
let chan_cell = Cell::new(chan);
@ -902,13 +902,13 @@ mod test {
thread1.join();
thread2.join();
}
}
})
}
#[test]
fn oneshot_multi_thread_recv_close_stress() {
if util::limit_thread_creation_due_to_osx_and_valgrind() { return; }
do stress_factor().times {
stress_factor().times(|| {
do run_in_newsched_task {
let (port, chan) = oneshot::<int>();
let chan_cell = Cell::new(chan);
@ -929,13 +929,13 @@ mod test {
thread1.join();
thread2.join();
}
}
})
}
#[test]
fn oneshot_multi_thread_send_recv_stress() {
if util::limit_thread_creation_due_to_osx_and_valgrind() { return; }
do stress_factor().times {
stress_factor().times(|| {
do run_in_newsched_task {
let (port, chan) = oneshot::<~int>();
let chan_cell = Cell::new(chan);
@ -949,13 +949,13 @@ mod test {
thread1.join();
thread2.join();
}
}
})
}
#[test]
fn stream_send_recv_stress() {
if util::limit_thread_creation_due_to_osx_and_valgrind() { return; }
do stress_factor().times {
stress_factor().times(|| {
do run_in_mt_newsched_task {
let (port, chan) = stream::<~int>();
@ -984,17 +984,17 @@ mod test {
};
}
}
}
})
}
#[test]
fn recv_a_lot() {
// 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();
do 10000.times { chan.send(()) }
do 10000.times { port.recv() }
}
10000.times(|| { chan.send(()) });
10000.times(|| { port.recv() });
})
}
#[test]
@ -1004,16 +1004,16 @@ mod test {
let (port, chan) = stream();
let chan = SharedChan::new(chan);
let total = stress_factor() + 100;
do total.times {
total.times(|| {
let chan_clone = chan.clone();
do spawntask_random {
chan_clone.send(());
}
}
});
do total.times {
total.times(|| {
port.recv();
}
})
}
}
@ -1026,22 +1026,22 @@ mod test {
let end_chan = SharedChan::new(end_chan);
let port = SharedPort::new(port);
let total = stress_factor() + 100;
do total.times {
total.times(|| {
let end_chan_clone = end_chan.clone();
let port_clone = port.clone();
do spawntask_random {
port_clone.recv();
end_chan_clone.send(());
}
}
});
do total.times {
total.times(|| {
chan.send(());
}
});
do total.times {
total.times(|| {
end_port.recv();
}
})
}
}
@ -1066,29 +1066,29 @@ mod test {
let send_total = 10;
let recv_total = 20;
do spawntask_random {
do send_total.times {
send_total.times(|| {
let chan_clone = chan.clone();
do spawntask_random {
chan_clone.send(());
}
}
})
}
let end_chan_clone = end_chan.clone();
do spawntask_random {
do recv_total.times {
recv_total.times(|| {
let port_clone = port.clone();
let end_chan_clone = end_chan_clone.clone();
do spawntask_random {
let recvd = port_clone.try_recv().is_some();
end_chan_clone.send(recvd);
}
}
})
}
let mut recvd = 0;
do recv_total.times {
recv_total.times(|| {
recvd += if end_port.recv() { 1 } else { 0 };
}
});
assert!(recvd == send_total);
}
@ -1107,7 +1107,7 @@ mod test {
let pipe = megapipe();
let total = stress_factor() + 10;
let mut rng = rand::rng();
do total.times {
total.times(|| {
let msgs = rng.gen_range(0u, 10);
let pipe_clone = pipe.clone();
let end_chan_clone = end_chan.clone();
@ -1121,11 +1121,11 @@ mod test {
}
end_chan_clone.send(());
}
});
do total.times {
total.times(|| {
end_port.recv();
}
})
}
}
@ -1152,13 +1152,13 @@ mod test {
let cs = Cell::new((cone, cstream, cshared, mp));
unsafe {
do atomically {
atomically(|| {
let (cone, cstream, cshared, mp) = cs.take();
cone.send_deferred(());
cstream.send_deferred(());
cshared.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.
pub fn collect_failure(&mut self, result: UnwindResult) {
let result = Cell::new(result);
do self.on_exit.take().map |on_exit| {
on_exit(result.take());
};
self.on_exit.take().map(|on_exit| on_exit(result.take()));
}
/// 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 res_ptr: *mut Option<T> = &mut res;
unsafe {
do local_ptr::borrow |task| {
local_ptr::borrow(|task| {
let result = f(task);
*res_ptr = Some(result);
}
})
}
match res {
Some(r) => { r }
@ -57,10 +57,10 @@ impl Local for Task {
impl Local for Scheduler {
fn put(value: ~Scheduler) {
let value = Cell::new(value);
do Local::borrow |task: &mut Task| {
Local::borrow(|task: &mut Task| {
let task = task;
task.sched = Some(value.take());
};
});
}
#[inline]
fn take() -> ~Scheduler {
@ -71,15 +71,15 @@ impl Local for Scheduler {
}
}
fn exists(_: Option<Scheduler>) -> bool {
do Local::borrow |task: &mut Task| {
Local::borrow(|task: &mut Task| {
match task.sched {
Some(ref _task) => true,
None => false
}
}
})
}
fn borrow<T>(f: |&mut Scheduler| -> T) -> T {
do Local::borrow |task: &mut Task| {
Local::borrow(|task: &mut Task| {
match task.sched {
Some(~ref mut task) => {
f(task)
@ -88,7 +88,7 @@ impl Local for Scheduler {
rtabort!("no scheduler")
}
}
}
})
}
unsafe fn unsafe_take() -> ~Scheduler { rtabort!("unimpl") }
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 {
do Local::borrow |task: &mut Task| {
task.heap.live_allocs
}
Local::borrow(|task: &mut Task| task.heap.live_allocs)
}
#[cfg(test)]
@ -313,15 +311,11 @@ mod bench {
#[bench]
fn alloc_managed_small(bh: &mut BenchHarness) {
do bh.iter {
@10;
}
bh.iter(|| @10);
}
#[bench]
fn alloc_managed_big(bh: &mut BenchHarness) {
do bh.iter {
@[10, ..1000];
}
bh.iter(|| @[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 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

View file

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

View file

@ -68,9 +68,9 @@ impl<T: Send> State<T> {
} else {
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}
};
});
State{
pad0: [0, ..64],
buffer: buffer,

View file

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

View file

@ -142,7 +142,7 @@ impl Task {
-> ~Task {
let f = Cell::new(f);
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 new_task = ~running_task.new_child_homed(&mut sched.stack_pool,
stack_size,
@ -150,7 +150,7 @@ impl Task {
f.take());
running_task.sched = Some(sched);
new_task
}
})
}
pub fn build_child(stack_size: Option<uint>, f: proc()) -> ~Task {
@ -163,7 +163,7 @@ impl Task {
-> ~Task {
let f = Cell::new(f);
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 new_task = ~Task::new_root_homed(&mut sched.stack_pool,
stack_size,
@ -171,7 +171,7 @@ impl Task {
f.take());
running_task.sched = Some(sched);
new_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
// client-specified code and catch any failures.
do self.unwinder.try {
self.unwinder.try(|| {
// Run the task main function, then do some cleanup.
do f.finally {
f.finally(|| {
// First, destroy task-local storage. This may run user dtors.
//
@ -320,8 +320,8 @@ impl Task {
None => {}
}
self.logger.take();
}
}
})
});
// Cleanup the dynamic borrowck debugging info
borrowck::clear_task_borrow_list();
@ -364,7 +364,7 @@ impl Task {
// Grab both the scheduler and the task from TLS and check if the
// task is executing on an appropriate scheduler.
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_run_anything = task.sched.get_ref().run_anything;
match task.task_type {
@ -383,7 +383,7 @@ impl Task {
rtabort!("type error: expected: GreenTask, found: SchedTask");
}
}
}
})
}
}
@ -431,9 +431,9 @@ impl Coroutine {
unsafe {
// Again - might work while safe, or it might not.
do Local::borrow |sched: &mut Scheduler| {
Local::borrow(|sched: &mut Scheduler| {
sched.run_cleanup_job();
}
});
// To call the run method on a task we need a direct
// reference to it. The task is in TLS, so we can
@ -442,7 +442,7 @@ impl Coroutine {
// need to unsafe_borrow.
let task: *mut Task = Local::unsafe_borrow();
do (*task).run {
(*task).run(|| {
// N.B. Removing `start` from the start wrapper
// closure by emptying a cell is critical for
// correctness. The ~Task pointer, and in turn the
@ -455,7 +455,7 @@ impl Coroutine {
// scope while the task is still running.
let start = start_cell.take();
start();
};
});
}
// 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
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>");
// 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),
// and the FFI call needs 2MB of stack when we just ran out.
rterrln!("task '{}' has overflowed its stack", n);
}
})
} else {
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!((*state).blocked_task.is_none());
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);
}
});
rtdebug!("waking after tube recv");
let buf = &mut (*state).buf;
assert!(!buf.is_empty());

View file

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

View file

@ -221,20 +221,20 @@ impl Process {
let ch_clone = ch.clone();
do spawn {
do io::ignore_io_error {
io::ignore_io_error(|| {
match error.take() {
Some(ref mut e) => ch.send((2, e.read_to_end())),
None => ch.send((2, ~[]))
}
}
})
}
do spawn {
do io::ignore_io_error {
io::ignore_io_error(|| {
match output.take() {
Some(ref mut e) => ch_clone.send((1, e.read_to_end())),
None => ch_clone.send((1, ~[]))
}
}
})
}
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 c = Cell::new(c);
do (|| {
(|| {
let c = Cell::new(c.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());
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());
do sched.event_loop.callback { c.take().send_deferred(()) }
}
}).finally {
}).finally(|| {
// 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
// selecting. Otherwise a user-sender could spuriously wakeup us here.
p.take().recv();
}
});
// 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.

View file

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

View file

@ -432,12 +432,12 @@ pub fn with_task_name<U>(blk: |Option<&str>| -> U) -> U {
use rt::task::Task;
if in_green_task_context() {
do Local::borrow |task: &mut Task| {
Local::borrow(|task: &mut Task| {
match task.name {
Some(ref name) => blk(Some(name.as_slice())),
None => blk(None)
}
}
})
} else {
fail!("no task name exists in non-green task context")
}
@ -459,9 +459,7 @@ pub fn failing() -> bool {
use rt::task::Task;
do Local::borrow |local: &mut Task| {
local.unwinder.unwinding
}
Local::borrow(|local: &mut Task| local.unwinder.unwinding)
}
// 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::Writer;
do mem::with_mem_writer |wr| {
do self.iter_bytes(lsb0) |bytes| {
mem::with_mem_writer(|wr| {
self.iter_bytes(lsb0, |bytes| {
wr.write(bytes);
true
};
}
});
})
}
}

View file

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

View file

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

View file

@ -27,11 +27,11 @@ pub struct DynamicLibrary { priv handle: *libc::c_void }
impl Drop for DynamicLibrary {
fn drop(&mut self) {
match do dl::check_for_errors_in {
match dl::check_for_errors_in(|| {
unsafe {
dl::close(self.handle)
}
} {
}) {
Ok(()) => {},
Err(str) => fail!("{}", str)
}
@ -43,12 +43,12 @@ impl DynamicLibrary {
/// handle to the calling process
pub fn open(filename: Option<&path::Path>) -> Result<DynamicLibrary, ~str> {
unsafe {
let maybe_library = do dl::check_for_errors_in {
let maybe_library = dl::check_for_errors_in(|| {
match filename {
Some(name) => dl::open_external(name),
None => dl::open_internal()
}
};
});
// The dynamic library must not be constructed if there is
// 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
// T but that feature is still unimplemented
let maybe_symbol_value = do dl::check_for_errors_in {
do symbol.with_c_str |raw_string| {
let maybe_symbol_value = dl::check_for_errors_in(|| {
symbol.with_c_str(|raw_string| {
dl::symbol(self.handle, raw_string)
}
};
})
});
// The value must not be constructed if there is an error so
// the destructor does not run.
@ -144,9 +144,9 @@ pub mod dl {
use result::*;
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)
}
})
}
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
// the scheduler if it happens while the lock is held.
// FIXME #9105 use a Rust mutex instead of C++ mutexes.
do atomically {
atomically(|| {
lock.lock();
let _old_error = dlerror();
@ -176,7 +176,7 @@ pub mod dl {
};
lock.unlock();
ret
}
})
}
}
@ -213,9 +213,9 @@ pub mod dl {
use result::*;
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)
}
})
}
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> {
unsafe {
do atomically {
atomically(|| {
SetLastError(0);
let result = f();
@ -237,7 +237,7 @@ pub mod dl {
} else {
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) -> ! {
let msg = format!("index out of bounds: the len is {} but the index is {}",
len as uint, index as uint);
do msg.with_c_str |buf| {
fail_(buf, file, line);
}
msg.with_c_str(|buf| fail_(buf, file, line))
}
#[lang="malloc"]

View file

@ -134,9 +134,8 @@ impl<T: Send> UnsafeArc<T> {
/// If called when the task is already unkillable, unwrap will unkillably
/// block; otherwise, an unwrapping task can be killed by linked failure.
pub fn unwrap(self) -> T {
let this = Cell::new(self); // argh
unsafe {
let mut this = this.take();
let mut this = this;
// The ~ dtor needs to run if this code succeeds.
let mut data: ~ArcData<T> = cast::transmute(this.data);
// 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
// taken either in the do block or in the finally block.
let c2_and_data = Cell::new((c2,data));
do (|| {
(|| {
p1.take().recv();
// Got here. Back in the 'unkillable' without getting killed.
let (c2, data) = c2_and_data.take();
@ -174,7 +173,7 @@ impl<T: Send> UnsafeArc<T> {
// user_data
let mut data = data;
data.data.take_unwrap()
}).finally {
}).finally(|| {
if task::failing() {
// Killed during wait. Because this might happen while
// someone else still holds a reference, we can't free
@ -185,7 +184,7 @@ impl<T: Send> UnsafeArc<T> {
} else {
assert!(c2_and_data.is_empty());
}
}
})
}
} else {
// If 'put' returns the server end back to us, we were rejected;
@ -193,7 +192,7 @@ impl<T: Send> UnsafeArc<T> {
cast::forget(data);
fail!("Another task is already unwrapping this Arc!");
}
}
})
}
/// 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.
match data.unwrapper.take(Acquire) {
Some(~(message,response)) => {
let cell = Cell::new((message, response, data));
let (message, response, data) = cell.take();
// Send 'ready' and wait for a response.
message.send(());
// Unkillable wait. Message guaranteed to come.
@ -301,12 +298,10 @@ pub unsafe fn atomically<U>(f: || -> U) -> U {
Some(t) => {
match (*t).task_type {
GreenTask(_) => {
do (|| {
(|| {
(*t).death.inhibit_deschedule();
f()
}).finally {
(*t).death.allow_deschedule();
}
}).finally(|| (*t).death.allow_deschedule())
}
SchedTask => f()
}
@ -425,9 +420,7 @@ impl<T:Send> Exclusive<T> {
#[inline]
pub unsafe fn with_imm<U>(&self, f: |x: &T| -> U) -> U {
do self.with |x| {
f(cast::transmute_immut(x))
}
self.with(|x| f(cast::transmute_immut(x)))
}
#[inline]
@ -469,7 +462,6 @@ impl<T:Send> Exclusive<T> {
#[cfg(test)]
mod tests {
use cell::Cell;
use comm;
use option::*;
use prelude::*;
@ -489,7 +481,7 @@ mod tests {
fn test_atomically() {
// NB. The whole runtime will abort on an 'atomic-sleep' violation,
// 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]
@ -509,9 +501,7 @@ mod tests {
do task::spawn || {
for _ in range(0u, count) {
do total.with |count| {
**count += 1;
}
total.with(|count| **count += 1);
}
chan.send(());
}
@ -519,9 +509,7 @@ mod tests {
for f in futures.iter() { f.recv() }
do total.with |total| {
assert!(**total == num_tasks * count)
};
total.with(|total| assert!(**total == num_tasks * count));
}
}
@ -533,13 +521,9 @@ mod tests {
let x = Exclusive::new(1);
let x2 = x.clone();
do task::try || {
do x2.with |one| {
assert_eq!(*one, 2);
}
x2.with(|one| assert_eq!(*one, 2))
};
do x.with |one| {
assert_eq!(*one, 1);
}
x.with(|one| assert_eq!(*one, 1));
}
}
@ -595,11 +579,11 @@ mod tests {
fn arclike_try_unwrap_unwrap_race() {
// When an unwrap and a try_unwrap race, the unwrapper should always win.
let x = UnsafeArc::new(~~"hello");
let x2 = Cell::new(x.clone());
let x2 = x.clone();
let (p,c) = comm::stream();
do task::spawn {
c.send(());
assert!(x2.take().unwrap() == ~~"hello");
assert!(x2.unwrap() == ~~"hello");
c.send(());
}
p.recv();
@ -620,21 +604,19 @@ mod tests {
#[test]
fn exclusive_new_unwrap_contended() {
let x = Exclusive::new(~~"hello");
let x2 = Cell::new(x.clone());
let x2 = x.clone();
do task::spawn {
let x2 = x2.take();
unsafe { do x2.with |_hello| { } }
unsafe { x2.with(|_hello| ()); }
task::deschedule();
}
assert!(x.unwrap() == ~~"hello");
// Now try the same thing, but with the child task blocking.
let x = Exclusive::new(~~"hello");
let x2 = Cell::new(x.clone());
let x2 = x.clone();
let mut builder = task::task();
let res = builder.future_result();
do builder.spawn {
let x2 = x2.take();
assert!(x2.unwrap() == ~~"hello");
}
// Have to get rid of our reference before blocking.
@ -645,11 +627,10 @@ mod tests {
#[test] #[should_fail]
fn exclusive_new_unwrap_conflict() {
let x = Exclusive::new(~~"hello");
let x2 = Cell::new(x.clone());
let x2 = x.clone();
let mut builder = task::task();
let res = builder.future_result();
do builder.spawn {
let x2 = x2.take();
assert!(x2.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 p = raw::to_mut_ptr(v);
let mut i: uint = 0u;
do (|| {
(|| {
while i < n_elts {
intrinsics::move_val_init(&mut(*ptr::mut_offset(p, i as int)), op(i));
i += 1u;
}
}).finally {
}).finally(|| {
raw::set_len(&mut v, i);
}
});
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 p = raw::to_mut_ptr(v);
let mut i = 0u;
do (|| {
(|| {
while i < n_elts {
intrinsics::move_val_init(&mut(*ptr::mut_offset(p, i as int)), t.clone());
i += 1u;
}
}).finally {
}).finally(|| {
raw::set_len(&mut v, i);
}
});
v
}
}
@ -982,14 +982,14 @@ impl<'self,T> ImmutableVector<'self, T> for &'self [T] {
fn slice(&self, start: uint, end: uint) -> &'self [T] {
assert!(start <= end);
assert!(end <= self.len());
do self.as_imm_buf |p, _len| {
self.as_imm_buf(|p, _len| {
unsafe {
cast::transmute(Slice {
data: ptr::offset(p, start as int),
len: (end - start)
})
}
}
})
}
#[inline]
@ -1639,7 +1639,7 @@ impl<T> OwnedVector<T> for ~[T] {
self.pop()
}
fn truncate(&mut self, newlen: uint) {
do self.as_mut_buf |p, oldlen| {
self.as_mut_buf(|p, oldlen| {
assert!(newlen <= oldlen);
unsafe {
// 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));
}
}
}
});
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] {
assert!(start <= end);
assert!(end <= self.len());
do self.as_mut_buf |p, _len| {
self.as_mut_buf(|p, _len| {
unsafe {
cast::transmute(Slice {
data: ptr::mut_offset(p, start as int) as *T,
len: (end - start)
})
}
}
})
}
#[inline]
@ -2153,10 +2153,10 @@ pub mod raw {
#[inline]
pub unsafe fn init_elem<T>(v: &mut [T], i: uint, val: T) {
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)),
box.take_unwrap());
}
})
}
/**
@ -2188,11 +2188,11 @@ pub mod raw {
assert!(dst.len() >= count);
assert!(src.len() >= count);
do dst.as_mut_buf |p_dst, _len_dst| {
do src.as_imm_buf |p_src, _len_src| {
dst.as_mut_buf(|p_dst, _len_dst| {
src.as_imm_buf(|p_src, _len_src| {
ptr::copy_memory(p_dst, p_src, count)
}
}
})
})
}
}
@ -2213,9 +2213,9 @@ pub mod bytes {
impl<'self> MutableByteVector for &'self mut [u8] {
#[inline]
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) };
}
})
}
}
@ -2278,11 +2278,11 @@ pub mod bytes {
let old_len = dst.len();
dst.reserve_additional(src.len());
unsafe {
do dst.as_mut_buf |p_dst, len_dst| {
do src.as_imm_buf |p_src, len_src| {
dst.as_mut_buf(|p_dst, len_dst| {
src.as_imm_buf(|p_src, len_src| {
ptr::copy_memory(p_dst.offset(len_dst as int), p_src, len_src)
}
}
})
});
vec::raw::set_len(dst, old_len + src.len());
}
}
@ -3276,10 +3276,10 @@ mod tests {
#[test]
#[should_fail]
fn test_from_fn_fail() {
do from_fn(100) |v| {
from_fn(100, |v| {
if v == 50 { fail!() }
(~0, @0)
};
});
}
#[test]
@ -3308,25 +3308,25 @@ mod tests {
#[test]
#[should_fail]
fn test_build_fail() {
do build(None) |push| {
build(None, |push| {
push((~0, @0));
push((~0, @0));
push((~0, @0));
push((~0, @0));
fail!();
};
});
}
#[test]
#[should_fail]
fn test_grow_fn_fail() {
let mut v = ~[];
do v.grow_fn(100) |i| {
v.grow_fn(100, |i| {
if i == 50 {
fail!()
}
(~0, @0)
}
})
}
#[test]
@ -3334,13 +3334,13 @@ mod tests {
fn test_map_fail() {
let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
let mut i = 0;
do v.map |_elt| {
v.map(|_elt| {
if i == 2 {
fail!()
}
i += 1;
~[(~0, @0)]
};
});
}
#[test]
@ -3348,13 +3348,13 @@ mod tests {
fn test_flat_map_fail() {
let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
let mut i = 0;
do flat_map(v) |_elt| {
flat_map(v, |_elt| {
if i == 2 {
fail!()
}
i += 1;
~[(~0, @0)]
};
});
}
#[test]
@ -3374,18 +3374,18 @@ mod tests {
#[should_fail]
fn test_as_imm_buf_fail() {
let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
do v.as_imm_buf |_buf, _i| {
v.as_imm_buf(|_buf, _i| {
fail!()
}
})
}
#[test]
#[should_fail]
fn test_as_mut_buf_fail() {
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!()
}
})
}
#[test]
@ -3843,52 +3843,48 @@ mod bench {
// out.
let v = vec::from_fn(100, |i| i ^ (i << 1) ^ (i >> 1));
do bh.iter {
bh.iter(|| {
let mut sum = 0;
for x in v.iter() {
sum += *x;
}
// sum == 11806, to stop dead code elimination.
if sum == 0 {fail!()}
}
})
}
#[bench]
fn mut_iterator(bh: &mut BenchHarness) {
let mut v = vec::from_elem(100, 0);
do bh.iter {
bh.iter(|| {
let mut i = 0;
for x in v.mut_iter() {
*x = i;
i += 1;
}
}
})
}
#[bench]
fn add(bh: &mut BenchHarness) {
let xs: &[int] = [5, ..10];
let ys: &[int] = [5, ..10];
do bh.iter() {
bh.iter(|| {
xs + ys;
}
});
}
#[bench]
fn concat(bh: &mut BenchHarness) {
let xss: &[~[uint]] = vec::from_fn(100, |i| range(0, i).collect());
do bh.iter {
xss.concat_vec();
}
bh.iter(|| xss.concat_vec());
}
#[bench]
fn connect(bh: &mut BenchHarness) {
let xss: &[~[uint]] = vec::from_fn(100, |i| range(0, i).collect());
do bh.iter {
xss.connect_vec(&0);
}
bh.iter(|| xss.connect_vec(&0));
}
#[bench]