use iter::IteratorExt;
use kinds::Copy;
use mem;
+use ops::FnMut;
use option::Option;
use option::Option::{Some, None};
use slice::{SlicePrelude, AsSlice};
/// - Any other chars are given hex escapes.
/// - Unicode escapes are never generated by this function.
#[unstable = "needs to be updated to use an iterator"]
-pub fn escape_default(c: u8, f: |u8|) {
+pub fn escape_default<F>(c: u8, mut f: F) where
+ F: FnMut(u8),
+{
match c {
b'\t' => { f(b'\\'); f(b't'); }
b'\r' => { f(b'\\'); f(b'r'); }
use kinds::Sized;
use mem::{mod, replace};
use num::{Int, UnsignedInt};
-use ops::{Deref, Index, IndexMut};
+use ops::{Deref, FnMut, Index, IndexMut};
use option::Option;
use option::Option::{Some, None};
use result::Result;
}
/// Search for a pre-hashed key.
-fn search_hashed<K, V, M: Deref<RawTable<K, V>>>(table: M,
- hash: &SafeHash,
- is_match: |&K| -> bool)
- -> SearchResult<K, V, M> {
+fn search_hashed<K, V, M, F>(table: M,
+ hash: &SafeHash,
+ mut is_match: F)
+ -> SearchResult<K, V, M> where
+ M: Deref<RawTable<K, V>>,
+ F: FnMut(&K) -> bool,
+{
let size = table.size();
let mut probe = Bucket::new(table, hash);
let ib = probe.index();
self.insert_or_replace_with(hash, k, v, |_, _, _| ())
}
- fn insert_or_replace_with<'a>(&'a mut self,
- hash: SafeHash,
- k: K,
- v: V,
- found_existing: |&mut K, &mut V, V|)
- -> &'a mut V {
+ fn insert_or_replace_with<'a, F>(&'a mut self,
+ hash: SafeHash,
+ k: K,
+ v: V,
+ mut found_existing: F)
+ -> &'a mut V where
+ F: FnMut(&mut K, &mut V, V),
+ {
// Worst case, we'll find one empty bucket among `size + 1` buckets.
let size = self.table.size();
let mut probe = Bucket::new(&mut self.table, &hash);
use c_str::{CString, ToCStr};
use libc;
use kinds::Copy;
+ use ops::FnOnce;
use ptr;
use result::*;
use result::Result::{Err, Ok};
dlopen(ptr::null(), Lazy as libc::c_int) as *mut u8
}
- pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, String> {
+ pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where
+ F: FnOnce() -> T,
+ {
use sync::{StaticMutex, MUTEX_INIT};
static LOCK: StaticMutex = MUTEX_INIT;
unsafe {
handle as *mut u8
}
- pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, String> {
+ pub fn check_for_errors_in<T, F>(f: F) -> Result<T, String> where
+ F: FnOnce() -> T,
+ {
unsafe {
SetLastError(0);
use io;
use iter::Iterator;
use num::Int;
+use ops::FnOnce;
use option::Option;
use option::Option::{Some, None};
use ptr::RawPtr;
/// * `f`: A callback that receives the value.
///
/// This function returns the value returned by the callback, for convenience.
-pub fn u64_to_le_bytes<T>(n: u64, size: uint, f: |v: &[u8]| -> T) -> T {
+pub fn u64_to_le_bytes<T, F>(n: u64, size: uint, f: F) -> T where
+ F: FnOnce(&[u8]) -> T,
+{
use mem::transmute;
// LLVM fails to properly optimize this when using shifts instead of the to_le* intrinsics
/// * `f`: A callback that receives the value.
///
/// This function returns the value returned by the callback, for convenience.
-pub fn u64_to_be_bytes<T>(n: u64, size: uint, f: |v: &[u8]| -> T) -> T {
+pub fn u64_to_be_bytes<T, F>(n: u64, size: uint, f: F) -> T where
+ F: FnOnce(&[u8]) -> T,
+{
use mem::transmute;
// LLVM fails to properly optimize this when using shifts instead of the to_be* intrinsics
use iter::{Iterator, IteratorExt};
use kinds::Copy;
use mem::transmute;
-use ops::{BitOr, BitXor, BitAnd, Sub, Not};
+use ops::{BitOr, BitXor, BitAnd, Sub, Not, FnOnce};
use option::Option;
use option::Option::{Some, None};
use os;
/// A trait that lets you add a `detail` to an IoError easily
trait UpdateIoError<T> {
/// Returns an IoError with updated description and detail
- fn update_err(self, desc: &'static str, detail: |&IoError| -> String) -> Self;
+ fn update_err<D>(self, desc: &'static str, detail: D) -> Self where
+ D: FnOnce(&IoError) -> String;
/// Returns an IoError with updated detail
- fn update_detail(self, detail: |&IoError| -> String) -> Self;
+ fn update_detail<D>(self, detail: D) -> Self where
+ D: FnOnce(&IoError) -> String;
/// Returns an IoError with update description
fn update_desc(self, desc: &'static str) -> Self;
}
impl<T> UpdateIoError<T> for IoResult<T> {
- fn update_err(self, desc: &'static str, detail: |&IoError| -> String) -> IoResult<T> {
- self.map_err(|mut e| {
+ fn update_err<D>(self, desc: &'static str, detail: D) -> IoResult<T> where
+ D: FnOnce(&IoError) -> String,
+ {
+ self.map_err(move |mut e| {
let detail = detail(&e);
e.desc = desc;
e.detail = Some(detail);
})
}
- fn update_detail(self, detail: |&IoError| -> String) -> IoResult<T> {
- self.map_err(|mut e| { e.detail = Some(detail(&e)); e })
+ fn update_detail<D>(self, detail: D) -> IoResult<T> where
+ D: FnOnce(&IoError) -> String,
+ {
+ self.map_err(move |mut e| { e.detail = Some(detail(&e)); e })
}
fn update_desc(self, desc: &'static str) -> IoResult<T> {
use io::{mod, IoResult, IoError};
use io::net;
use iter::{Iterator, IteratorExt};
+use ops::FnOnce;
use option::Option;
use option::Option::{None, Some};
use result::Result::{Ok, Err};
}
// Commit only if parser returns Some
- fn read_atomically<T>(&mut self, cb: |&mut Parser| -> Option<T>)
- -> Option<T> {
+ fn read_atomically<T, F>(&mut self, cb: F) -> Option<T> where
+ F: FnOnce(&mut Parser) -> Option<T>,
+ {
let pos = self.pos;
let r = cb(self);
if r.is_none() {
}
// Commit only if parser read till EOF
- fn read_till_eof<T>(&mut self, cb: |&mut Parser| -> Option<T>)
- -> Option<T> {
- self.read_atomically(|p| {
+ fn read_till_eof<T, F>(&mut self, cb: F) -> Option<T> where
+ F: FnOnce(&mut Parser) -> Option<T>,
+ {
+ self.read_atomically(move |p| {
match cb(p) {
Some(x) => if p.is_eof() {Some(x)} else {None},
None => None,
}
// Apply 3 parsers sequentially
- fn read_seq_3<A,
- B,
- C>(
- &mut self,
- pa: |&mut Parser| -> Option<A>,
- pb: |&mut Parser| -> Option<B>,
- pc: |&mut Parser| -> Option<C>)
- -> Option<(A, B, C)> {
- self.read_atomically(|p| {
+ fn read_seq_3<A, B, C, PA, PB, PC>(&mut self,
+ pa: PA,
+ pb: PB,
+ pc: PC)
+ -> Option<(A, B, C)> where
+ PA: FnOnce(&mut Parser) -> Option<A>,
+ PB: FnOnce(&mut Parser) -> Option<B>,
+ PC: FnOnce(&mut Parser) -> Option<C>,
+ {
+ self.read_atomically(move |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 };
}
fn read_socket_addr(&mut self) -> Option<SocketAddr> {
- let ip_addr = |p: &mut Parser| {
+ let ip_addr = |&: p: &mut Parser| {
let ipv4_p = |p: &mut Parser| p.read_ip_addr();
let ipv6_p = |p: &mut Parser| {
- let open_br = |p: &mut Parser| p.read_given_char('[');
- let ip_addr = |p: &mut Parser| p.read_ipv6_addr();
- let clos_br = |p: &mut Parser| p.read_given_char(']');
- p.read_seq_3::<char, IpAddr, char>(open_br, ip_addr, clos_br)
+ let open_br = |&: p: &mut Parser| p.read_given_char('[');
+ let ip_addr = |&: p: &mut Parser| p.read_ipv6_addr();
+ let clos_br = |&: p: &mut Parser| p.read_given_char(']');
+ p.read_seq_3::<char, IpAddr, char, _, _, _>(open_br, ip_addr, clos_br)
.map(|t| match t { (_, ip, _) => ip })
};
p.read_or(&mut [ipv4_p, ipv6_p])
};
- let colon = |p: &mut Parser| p.read_given_char(':');
- let port = |p: &mut Parser| p.read_number(10, 5, 0x10000).map(|n| n as u16);
+ let colon = |&: p: &mut Parser| p.read_given_char(':');
+ let port = |&: p: &mut Parser| p.read_number(10, 5, 0x10000).map(|n| n as u16);
// host, colon, port
- self.read_seq_3::<IpAddr, char, u16>(ip_addr, colon, port)
+ self.read_seq_3::<IpAddr, char, u16, _, _, _>(ip_addr, colon, port)
.map(|t| match t { (ip, _, port) => SocketAddr { ip: ip, port: port } })
}
}
//! Networking I/O
use io::{IoError, IoResult, InvalidInput};
+use ops::FnMut;
use option::Option::None;
use result::Result::{Ok, Err};
use self::ip::{SocketAddr, ToSocketAddr};
pub mod ip;
pub mod pipe;
-fn with_addresses<A: ToSocketAddr, T>(addr: A, action: |SocketAddr| -> IoResult<T>)
- -> IoResult<T> {
+fn with_addresses<A, T, F>(addr: A, mut action: F) -> IoResult<T> where
+ A: ToSocketAddr,
+ F: FnMut(SocketAddr) -> IoResult<T>,
+{
const DEFAULT_ERROR: IoError = IoError {
kind: InvalidInput,
desc: "no addresses found for hostname",
use clone::Clone;
use io::net::ip::{SocketAddr, IpAddr, ToSocketAddr};
use io::{Reader, Writer, IoResult};
+use ops::FnOnce;
use option::Option;
use result::Result::{Ok, Err};
use sys::udp::UdpSocket as UdpSocketImp;
/// Allows access to the underlying UDP socket owned by this stream. This
/// is useful to, for example, use the socket to send data to hosts other
/// than the one that this stream is connected to.
- pub fn as_socket<T>(&mut self, f: |&mut UdpSocket| -> T) -> T {
+ pub fn as_socket<T, F>(&mut self, f: F) -> T where
+ F: FnOnce(&mut UdpSocket) -> T,
+ {
f(&mut self.socket)
}
use mem;
use option::Option;
use option::Option::{Some, None};
-use ops::{Deref, DerefMut};
+use ops::{Deref, DerefMut, FnOnce};
use result::Result::{Ok, Err};
use rustrt;
use rustrt::local::Local;
File(fs::FileDesc),
}
-fn src<T>(fd: libc::c_int, _readable: bool, f: |StdSource| -> T) -> T {
+fn src<T, F>(fd: libc::c_int, _readable: bool, f: F) -> T where
+ F: FnOnce(StdSource) -> T,
+{
match tty::TTY::new(fd) {
Ok(tty) => f(TTY(tty)),
Err(_) => f(File(fs::FileDesc::new(fd, false))),
// // io1 aliases io2
// })
// })
-fn with_task_stdout(f: |&mut Writer| -> IoResult<()>) {
+fn with_task_stdout<F>(f: F) where
+ F: FnOnce(&mut Writer) -> IoResult<()>,
+{
let result = if Local::exists(None::<Task>) {
let mut my_stdout = LOCAL_STDOUT.with(|slot| {
slot.borrow_mut().take()
use kinds::Copy;
use num;
use num::{Int, Float, FPNaN, FPInfinite, ToPrimitive};
+use ops::FnMut;
use slice::{SlicePrelude, CloneSliceAllocPrelude};
use str::StrPrelude;
use string::String;
/// # Panics
///
/// - Panics if `radix` < 2 or `radix` > 36.
-fn int_to_str_bytes_common<T: Int>(num: T, radix: uint, sign: SignFormat, f: |u8|) {
+fn int_to_str_bytes_common<T, F>(num: T, radix: uint, sign: SignFormat, mut f: F) where
+ T: Int,
+ F: FnMut(u8),
+{
assert!(2 <= radix && radix <= 36);
let _0: T = Int::zero();
pub use core::u16::{BITS, BYTES, MIN, MAX};
+use ops::FnOnce;
+
uint_module!(u16)
pub use core::u32::{BITS, BYTES, MIN, MAX};
+use ops::FnOnce;
+
uint_module!(u32)
pub use core::u64::{BITS, BYTES, MIN, MAX};
+use ops::FnOnce;
+
uint_module!(u64)
pub use core::u8::{BITS, BYTES, MIN, MAX};
+use ops::FnOnce;
+
uint_module!(u8)
pub use core::uint::{BITS, BYTES, MIN, MAX};
+use ops::FnOnce;
+
uint_module!(uint)
/// ```
#[inline]
#[deprecated = "just use .to_string(), or a BufWriter with write! if you mustn't allocate"]
-pub fn to_str_bytes<U>(n: $T, radix: uint, f: |v: &[u8]| -> U) -> U {
+pub fn to_str_bytes<U, F>(n: $T, radix: uint, f: F) -> U where
+ F: FnOnce(&[u8]) -> U,
+{
use io::{Writer, Seek};
// The radix can be as low as 2, so we need at least 64 characters for a
// base 2 number, and then we need another for a possible '-' character.
use libc::{c_void, c_int};
use libc;
use boxed::Box;
-use ops::Drop;
+use ops::{Drop, FnOnce};
use option::Option;
use option::Option::{Some, None};
use os;
use str::StrPrelude;
use vec::Vec;
- pub fn fill_utf16_buf_and_decode(f: |*mut u16, DWORD| -> DWORD)
- -> Option<String> {
+ pub fn fill_utf16_buf_and_decode<F>(mut f: F) -> Option<String> where
+ F: FnMut(*mut u16, DWORD) -> DWORD,
+ {
unsafe {
let mut n = TMPBUF_SZ as DWORD;
Accessing environment variables is not generally threadsafe.
Serialize access through a global lock.
*/
-fn with_env_lock<T>(f: || -> T) -> T {
+fn with_env_lock<T, F>(f: F) -> T where
+ F: FnOnce() -> T,
+{
use sync::{StaticMutex, MUTEX_INIT};
static LOCK: StaticMutex = MUTEX_INIT;
use int;
use mem::drop;
+use ops::FnOnce;
use sync::atomic;
use sync::{StaticMutex, MUTEX_INIT};
///
/// When this function returns, it is guaranteed that some initialization
/// has run and completed (it may not be the closure specified).
- pub fn doit(&'static self, f: ||) {
+ pub fn doit<F>(&'static self, f: F) where F: FnOnce() {
// Optimize common path: load is much cheaper than fetch_add.
if self.cnt.load(atomic::SeqCst) < 0 {
return
/// passed to the helper thread in a separate task.
///
/// This function is safe to be called many times.
- pub fn boot<T: Send>(&'static self,
- f: || -> T,
- helper: fn(helper_signal::signal, Receiver<M>, T)) {
+ pub fn boot<T, F>(&'static self, f: F, helper: fn(helper_signal::signal, Receiver<M>, T)) where
+ T: Send,
+ F: FnOnce() -> T,
+ {
unsafe {
let _guard = self.lock.lock();
if !*self.initialized.get() {
}
}
-pub fn keep_going(data: &[u8], f: |*const u8, uint| -> i64) -> i64 {
+pub fn keep_going<F>(data: &[u8], mut f: F) -> i64 where
+ F: FnMut(*const u8, uint) -> i64,
+{
let origamt = data.len();
let mut data = data.as_ptr();
let mut amt = origamt;
// [1] http://twistedmatrix.com/pipermail/twisted-commits/2012-April/034692.html
// [2] http://stackoverflow.com/questions/19819198/does-send-msg-dontwait
-pub fn read<T>(fd: sock_t,
- deadline: u64,
- lock: || -> T,
- read: |bool| -> libc::c_int) -> IoResult<uint> {
+pub fn read<T, L, R>(fd: sock_t, deadline: u64, mut lock: L, mut read: R) -> IoResult<uint> where
+ L: FnMut() -> T,
+ R: FnMut(bool) -> libc::c_int,
+{
let mut ret = -1;
if deadline == 0 {
ret = retry(|| read(false));
}
}
-pub fn write<T>(fd: sock_t,
- deadline: u64,
- buf: &[u8],
- write_everything: bool,
- lock: || -> T,
- write: |bool, *const u8, uint| -> i64) -> IoResult<uint> {
+pub fn write<T, L, W>(fd: sock_t,
+ deadline: u64,
+ buf: &[u8],
+ write_everything: bool,
+ mut lock: L,
+ mut write: W) -> IoResult<uint> where
+ L: FnMut() -> T,
+ W: FnMut(bool, *const u8, uint) -> i64,
+{
let mut ret = -1;
let mut written = 0;
if deadline == 0 {
pub fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
let fd = self.fd();
- let dolock = || self.lock_nonblocking();
- let doread = |nb| unsafe {
+ let dolock = |&:| self.lock_nonblocking();
+ let doread = |&mut: nb| unsafe {
let flags = if nb {c::MSG_DONTWAIT} else {0};
libc::recv(fd,
buf.as_mut_ptr() as *mut libc::c_void,
pub fn write(&mut self, buf: &[u8]) -> IoResult<()> {
let fd = self.fd();
- let dolock = || self.lock_nonblocking();
- let dowrite = |nb: bool, buf: *const u8, len: uint| unsafe {
+ let dolock = |&:| self.lock_nonblocking();
+ let dowrite = |&: nb: bool, buf: *const u8, len: uint| unsafe {
let flags = if nb {c::MSG_DONTWAIT} else {0};
libc::send(fd,
buf as *const _,
let mut addrlen: libc::socklen_t =
mem::size_of::<libc::sockaddr_storage>() as libc::socklen_t;
- let dolock = || self.lock_nonblocking();
+ let dolock = |&:| self.lock_nonblocking();
let n = try!(read(fd, self.read_deadline, dolock, |nb| unsafe {
let flags = if nb {c::MSG_DONTWAIT} else {0};
libc::recvfrom(fd,
let dstp = &storage as *const _ as *const libc::sockaddr;
let fd = self.fd();
- let dolock = || self.lock_nonblocking();
- let dowrite = |nb, buf: *const u8, len: uint| unsafe {
+ let dolock = |&: | self.lock_nonblocking();
+ let dowrite = |&mut: nb, buf: *const u8, len: uint| unsafe {
let flags = if nb {c::MSG_DONTWAIT} else {0};
libc::sendto(fd,
buf as *const libc::c_void,
}
#[inline]
-pub fn retry<T: SignedInt> (f: || -> T) -> T {
+pub fn retry<T, F> (mut f: F) -> T where
+ T: SignedInt,
+ F: FnMut() -> T,
+{
let one: T = Int::one();
loop {
let n = f();
pub fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
let fd = self.fd();
- let dolock = || self.lock_nonblocking();
- let doread = |nb| unsafe {
+ let dolock = |&:| self.lock_nonblocking();
+ let doread = |&mut: nb| unsafe {
let flags = if nb {c::MSG_DONTWAIT} else {0};
libc::recv(fd,
buf.as_mut_ptr() as *mut libc::c_void,
pub fn write(&mut self, buf: &[u8]) -> IoResult<()> {
let fd = self.fd();
- let dolock = || self.lock_nonblocking();
- let dowrite = |nb: bool, buf: *const u8, len: uint| unsafe {
+ let dolock = |&: | self.lock_nonblocking();
+ let dowrite = |&: nb: bool, buf: *const u8, len: uint| unsafe {
let flags = if nb {c::MSG_DONTWAIT} else {0};
libc::send(fd,
buf as *const _,
}
#[inline]
-pub fn retry<I> (f: || -> I) -> I { f() } // PR rust-lang/rust/#17020
+pub fn retry<I, F>(f: F) -> I where F: FnOnce() -> I { f() } // PR rust-lang/rust/#17020
pub fn ms_to_timeval(ms: u64) -> libc::timeval {
libc::timeval {
}
}
-fn with_envp<K, V, T>(env: Option<&collections::HashMap<K, V>>,
- cb: |*mut c_void| -> T) -> T
- where K: BytesContainer + Eq + Hash, V: BytesContainer
+fn with_envp<K, V, T, F>(env: Option<&collections::HashMap<K, V>>, cb: F) -> T where
+ K: BytesContainer + Eq + Hash, V: BytesContainer, F: FnOnce(*mut c_void) -> T,
{
// On Windows we pass an "environment block" which is not a char**, but
// rather a concatenation of null-terminated k=v\0 sequences, with a final
}
}
-fn with_dirp<T>(d: Option<&CString>, cb: |*const u16| -> T) -> T {
+fn with_dirp<T, F>(d: Option<&CString>, cb: F) -> T where
+ F: FnOnce(*const u16) -> T,
+{
match d {
Some(dir) => {
let dir_str = dir.as_str()
rx.recv();
}
- fn avoid_copying_the_body(spawnfn: |v: proc():Send|) {
+ fn avoid_copying_the_body<F>(spawnfn: F) where
+ F: FnOnce(proc():Send),
+ {
let (tx, rx) = channel::<uint>();
let x = box 1;
/// This function will `panic!()` if the key currently has its
/// destructor running, and it **may** panic if the destructor has
/// previously been run for this thread.
- pub fn with<R>(&'static self, f: |&T| -> R) -> R {
+ pub fn with<R, F>(&'static self, f: F) -> R where
+ F: FnOnce(&T) -> R,
+ {
let slot = (self.inner)();
unsafe {
let slot = slot.get().expect("cannot access a TLS value during or \
/// assert_eq!(val, 100);
/// });
/// ```
- pub fn set<R>(&'static self, t: &T, cb: || -> R) -> R {
+ pub fn set<R, F>(&'static self, t: &T, cb: F) -> R where
+ F: FnOnce() -> R,
+ {
struct Reset<'a, T: 'a> {
key: &'a KeyInner<T>,
val: *mut T,
/// // work with `slot`
/// });
/// ```
- pub fn with<R>(&'static self, cb: |&T| -> R) -> R {
+ pub fn with<R, F>(&'static self, cb: F) -> R where
+ F: FnOnce(&T) -> R
+ {
unsafe {
let ptr = self.inner.get();
assert!(!ptr.is_null(), "cannot access a scoped thread local \
use {fmt, i64};
use kinds::Copy;
-use ops::{Add, Sub, Mul, Div, Neg};
+use ops::{Add, Sub, Mul, Div, Neg, FnOnce};
use option::Option;
use option::Option::{Some, None};
use num::Int;
/// Runs a closure, returning the duration of time it took to run the
/// closure.
- pub fn span(f: ||) -> Duration {
+ pub fn span<F>(f: F) -> Duration where F: FnOnce() {
let before = super::precise_time_ns();
f();
Duration::nanoseconds((super::precise_time_ns() - before) as i64)