From a2c2cb942ebb443bfbc864a4606cc2784c850882 Mon Sep 17 00:00:00 2001 From: ville-h Date: Sat, 3 Jan 2015 23:22:09 +0200 Subject: rename std::sync::RWLock to RwLock --- src/libstd/sync/rwlock.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'src/libstd/sync') diff --git a/src/libstd/sync/rwlock.rs b/src/libstd/sync/rwlock.rs index 431aeb9cae9..af102fc7402 100644 --- a/src/libstd/sync/rwlock.rs +++ b/src/libstd/sync/rwlock.rs @@ -59,13 +59,13 @@ use sys_common::rwlock as sys; /// } // write lock is dropped here /// ``` #[stable] -pub struct RWLock { +pub struct RwLock { inner: Box, data: UnsafeCell, } -unsafe impl Send for RWLock {} -unsafe impl Sync for RWLock {} +unsafe impl Send for RwLock {} +unsafe impl Sync for RwLock {} /// Structure representing a statically allocated RWLock. /// @@ -127,11 +127,11 @@ pub struct RWLockWriteGuard<'a, T: 'a> { __marker: marker::NoSend, } -impl RWLock { +impl RwLock { /// Creates a new instance of an RWLock which is unlocked and read to go. #[stable] - pub fn new(t: T) -> RWLock { - RWLock { inner: box RWLOCK_INIT, data: UnsafeCell::new(t) } + pub fn new(t: T) -> RwLock { + RwLock { inner: box RWLOCK_INIT, data: UnsafeCell::new(t) } } /// Locks this rwlock with shared read access, blocking the current thread @@ -228,7 +228,7 @@ impl RWLock { } #[unsafe_destructor] -impl Drop for RWLock { +impl Drop for RwLock { fn drop(&mut self) { unsafe { self.inner.lock.destroy() } } -- cgit 1.4.1-3-g733a5 From b2ab5d7658435f8710acc0b0a99ce858af36bd9a Mon Sep 17 00:00:00 2001 From: ville-h Date: Sun, 4 Jan 2015 01:58:35 +0200 Subject: fix code and comments referencing RwLock --- src/libstd/sync/mod.rs | 2 +- src/libstd/sync/rwlock.rs | 62 +++++++++++++++++++++++------------------------ 2 files changed, 32 insertions(+), 32 deletions(-) (limited to 'src/libstd/sync') diff --git a/src/libstd/sync/mod.rs b/src/libstd/sync/mod.rs index c09c3b45d3e..3410976a6e4 100644 --- a/src/libstd/sync/mod.rs +++ b/src/libstd/sync/mod.rs @@ -21,7 +21,7 @@ pub use alloc::arc::{Arc, Weak}; pub use self::mutex::{Mutex, MutexGuard, StaticMutex}; pub use self::mutex::MUTEX_INIT; -pub use self::rwlock::{RWLock, StaticRWLock, RWLOCK_INIT}; +pub use self::rwlock::{RwLock, StaticRWLock, RWLOCK_INIT}; pub use self::rwlock::{RWLockReadGuard, RWLockWriteGuard}; pub use self::condvar::{Condvar, StaticCondvar, CONDVAR_INIT}; pub use self::once::{Once, ONCE_INIT}; diff --git a/src/libstd/sync/rwlock.rs b/src/libstd/sync/rwlock.rs index af102fc7402..087281d6ce6 100644 --- a/src/libstd/sync/rwlock.rs +++ b/src/libstd/sync/rwlock.rs @@ -31,17 +31,17 @@ use sys_common::rwlock as sys; /// /// # Poisoning /// -/// RWLocks, like Mutexes, will become poisoned on panics. Note, however, that -/// an RWLock may only be poisoned if a panic occurs while it is locked +/// RwLocks, like Mutexes, will become poisoned on panics. Note, however, that +/// an RwLock may only be poisoned if a panic occurs while it is locked /// exclusively (write mode). If a panic occurs in any reader, then the lock /// will not be poisoned. /// /// # Examples /// /// ``` -/// use std::sync::RWLock; +/// use std::sync::RwLock; /// -/// let lock = RWLock::new(5i); +/// let lock = RwLock::new(5i); /// /// // many reader locks can be held at once /// { @@ -67,11 +67,11 @@ pub struct RwLock { unsafe impl Send for RwLock {} unsafe impl Sync for RwLock {} -/// Structure representing a statically allocated RWLock. +/// Structure representing a statically allocated RwLock. /// /// This structure is intended to be used inside of a `static` and will provide /// automatic global access as well as lazy initialization. The internal -/// resources of this RWLock, however, must be manually deallocated. +/// resources of this RwLock, however, must be manually deallocated. /// /// # Example /// @@ -90,7 +90,7 @@ unsafe impl Sync for RwLock {} /// } /// unsafe { LOCK.destroy() } // free all resources /// ``` -#[unstable = "may be merged with RWLock in the future"] +#[unstable = "may be merged with RwLock in the future"] pub struct StaticRWLock { lock: sys::RWLock, poison: poison::Flag, @@ -100,7 +100,7 @@ unsafe impl Send for StaticRWLock {} unsafe impl Sync for StaticRWLock {} /// Constant initialization for a statically-initialized rwlock. -#[unstable = "may be merged with RWLock in the future"] +#[unstable = "may be merged with RwLock in the future"] pub const RWLOCK_INIT: StaticRWLock = StaticRWLock { lock: sys::RWLOCK_INIT, poison: poison::FLAG_INIT, @@ -128,7 +128,7 @@ pub struct RWLockWriteGuard<'a, T: 'a> { } impl RwLock { - /// Creates a new instance of an RWLock which is unlocked and read to go. + /// Creates a new instance of an RwLock which is unlocked and read to go. #[stable] pub fn new(t: T) -> RwLock { RwLock { inner: box RWLOCK_INIT, data: UnsafeCell::new(t) } @@ -148,7 +148,7 @@ impl RwLock { /// /// # Failure /// - /// This function will return an error if the RWLock is poisoned. An RWLock + /// This function will return an error if the RwLock is poisoned. An RwLock /// is poisoned whenever a writer panics while holding an exclusive lock. /// The failure will occur immediately after the lock has been acquired. #[inline] @@ -169,7 +169,7 @@ impl RwLock { /// /// # Failure /// - /// This function will return an error if the RWLock is poisoned. An RWLock + /// This function will return an error if the RwLock is poisoned. An RwLock /// is poisoned whenever a writer panics while holding an exclusive lock. An /// error will only be returned if the lock would have otherwise been /// acquired. @@ -194,7 +194,7 @@ impl RwLock { /// /// # Failure /// - /// This function will return an error if the RWLock is poisoned. An RWLock + /// This function will return an error if the RwLock is poisoned. An RwLock /// is poisoned whenever a writer panics while holding an exclusive lock. /// An error will be returned when the lock is acquired. #[inline] @@ -212,7 +212,7 @@ impl RwLock { /// /// # Failure /// - /// This function will return an error if the RWLock is poisoned. An RWLock + /// This function will return an error if the RwLock is poisoned. An RwLock /// is poisoned whenever a writer panics while holding an exclusive lock. An /// error will only be returned if the lock would have otherwise been /// acquired. @@ -242,9 +242,9 @@ impl StaticRWLock { /// Locks this rwlock with shared read access, blocking the current thread /// until it can be acquired. /// - /// See `RWLock::read`. + /// See `RwLock::read`. #[inline] - #[unstable = "may be merged with RWLock in the future"] + #[unstable = "may be merged with RwLock in the future"] pub fn read(&'static self) -> LockResult> { unsafe { self.lock.read() } RWLockReadGuard::new(self, &DUMMY.0) @@ -252,9 +252,9 @@ impl StaticRWLock { /// Attempt to acquire this lock with shared read access. /// - /// See `RWLock::try_read`. + /// See `RwLock::try_read`. #[inline] - #[unstable = "may be merged with RWLock in the future"] + #[unstable = "may be merged with RwLock in the future"] pub fn try_read(&'static self) -> TryLockResult> { if unsafe { self.lock.try_read() } { @@ -267,9 +267,9 @@ impl StaticRWLock { /// Lock this rwlock with exclusive write access, blocking the current /// thread until it can be acquired. /// - /// See `RWLock::write`. + /// See `RwLock::write`. #[inline] - #[unstable = "may be merged with RWLock in the future"] + #[unstable = "may be merged with RwLock in the future"] pub fn write(&'static self) -> LockResult> { unsafe { self.lock.write() } RWLockWriteGuard::new(self, &DUMMY.0) @@ -277,9 +277,9 @@ impl StaticRWLock { /// Attempt to lock this rwlock with exclusive write access. /// - /// See `RWLock::try_write`. + /// See `RwLock::try_write`. #[inline] - #[unstable = "may be merged with RWLock in the future"] + #[unstable = "may be merged with RwLock in the future"] pub fn try_write(&'static self) -> TryLockResult> { if unsafe { self.lock.try_write() } { @@ -295,7 +295,7 @@ impl StaticRWLock { /// active users of the lock, and this also doesn't prevent any future users /// of this lock. This method is required to be called to not leak memory on /// all platforms. - #[unstable = "may be merged with RWLock in the future"] + #[unstable = "may be merged with RwLock in the future"] pub unsafe fn destroy(&'static self) { self.lock.destroy() } @@ -365,11 +365,11 @@ mod tests { use rand::{mod, Rng}; use sync::mpsc::channel; use thread::Thread; - use sync::{Arc, RWLock, StaticRWLock, RWLOCK_INIT}; + use sync::{Arc, RwLock, StaticRWLock, RWLOCK_INIT}; #[test] fn smoke() { - let l = RWLock::new(()); + let l = RwLock::new(()); drop(l.read().unwrap()); drop(l.write().unwrap()); drop((l.read().unwrap(), l.read().unwrap())); @@ -414,7 +414,7 @@ mod tests { #[test] fn test_rw_arc_poison_wr() { - let arc = Arc::new(RWLock::new(1i)); + let arc = Arc::new(RwLock::new(1i)); let arc2 = arc.clone(); let _: Result = Thread::spawn(move|| { let _lock = arc2.write().unwrap(); @@ -425,7 +425,7 @@ mod tests { #[test] fn test_rw_arc_poison_ww() { - let arc = Arc::new(RWLock::new(1i)); + let arc = Arc::new(RwLock::new(1i)); let arc2 = arc.clone(); let _: Result = Thread::spawn(move|| { let _lock = arc2.write().unwrap(); @@ -436,7 +436,7 @@ mod tests { #[test] fn test_rw_arc_no_poison_rr() { - let arc = Arc::new(RWLock::new(1i)); + let arc = Arc::new(RwLock::new(1i)); let arc2 = arc.clone(); let _: Result = Thread::spawn(move|| { let _lock = arc2.read().unwrap(); @@ -447,7 +447,7 @@ mod tests { } #[test] fn test_rw_arc_no_poison_rw() { - let arc = Arc::new(RWLock::new(1i)); + let arc = Arc::new(RwLock::new(1i)); let arc2 = arc.clone(); let _: Result = Thread::spawn(move|| { let _lock = arc2.read().unwrap(); @@ -459,7 +459,7 @@ mod tests { #[test] fn test_rw_arc() { - let arc = Arc::new(RWLock::new(0i)); + let arc = Arc::new(RwLock::new(0i)); let arc2 = arc.clone(); let (tx, rx) = channel(); @@ -497,11 +497,11 @@ mod tests { #[test] fn test_rw_arc_access_in_unwind() { - let arc = Arc::new(RWLock::new(1i)); + let arc = Arc::new(RwLock::new(1i)); let arc2 = arc.clone(); let _ = Thread::spawn(move|| -> () { struct Unwinder { - i: Arc>, + i: Arc>, } impl Drop for Unwinder { fn drop(&mut self) { -- cgit 1.4.1-3-g733a5 From fedbde66239d4a7a7551938975d4e3894d778332 Mon Sep 17 00:00:00 2001 From: ville-h Date: Sun, 4 Jan 2015 02:03:09 +0200 Subject: rename std::sync::StaticRWLock to StaticRwLock --- src/libstd/sync/rwlock.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src/libstd/sync') diff --git a/src/libstd/sync/rwlock.rs b/src/libstd/sync/rwlock.rs index 087281d6ce6..5743386e055 100644 --- a/src/libstd/sync/rwlock.rs +++ b/src/libstd/sync/rwlock.rs @@ -91,13 +91,13 @@ unsafe impl Sync for RwLock {} /// unsafe { LOCK.destroy() } // free all resources /// ``` #[unstable = "may be merged with RwLock in the future"] -pub struct StaticRWLock { +pub struct StaticRwLock { lock: sys::RWLock, poison: poison::Flag, } -unsafe impl Send for StaticRWLock {} -unsafe impl Sync for StaticRWLock {} +unsafe impl Send for StaticRwLock {} +unsafe impl Sync for StaticRwLock {} /// Constant initialization for a statically-initialized rwlock. #[unstable = "may be merged with RwLock in the future"] @@ -238,7 +238,7 @@ struct Dummy(UnsafeCell<()>); unsafe impl Sync for Dummy {} static DUMMY: Dummy = Dummy(UnsafeCell { value: () }); -impl StaticRWLock { +impl StaticRwLock { /// Locks this rwlock with shared read access, blocking the current thread /// until it can be acquired. /// -- cgit 1.4.1-3-g733a5 From 817f75d2fbc15dd152c9473e012ec5271cb5e94b Mon Sep 17 00:00:00 2001 From: ville-h Date: Sun, 4 Jan 2015 08:59:06 +0200 Subject: fix code and comments referencing StaticRwLock --- src/libstd/sync/mod.rs | 2 +- src/libstd/sync/rwlock.rs | 22 +++++++++++----------- 2 files changed, 12 insertions(+), 12 deletions(-) (limited to 'src/libstd/sync') diff --git a/src/libstd/sync/mod.rs b/src/libstd/sync/mod.rs index 3410976a6e4..0e2b0a441e6 100644 --- a/src/libstd/sync/mod.rs +++ b/src/libstd/sync/mod.rs @@ -21,7 +21,7 @@ pub use alloc::arc::{Arc, Weak}; pub use self::mutex::{Mutex, MutexGuard, StaticMutex}; pub use self::mutex::MUTEX_INIT; -pub use self::rwlock::{RwLock, StaticRWLock, RWLOCK_INIT}; +pub use self::rwlock::{RwLock, StaticRwLock, RWLOCK_INIT}; pub use self::rwlock::{RWLockReadGuard, RWLockWriteGuard}; pub use self::condvar::{Condvar, StaticCondvar, CONDVAR_INIT}; pub use self::once::{Once, ONCE_INIT}; diff --git a/src/libstd/sync/rwlock.rs b/src/libstd/sync/rwlock.rs index 5743386e055..04efbf893ea 100644 --- a/src/libstd/sync/rwlock.rs +++ b/src/libstd/sync/rwlock.rs @@ -60,7 +60,7 @@ use sys_common::rwlock as sys; /// ``` #[stable] pub struct RwLock { - inner: Box, + inner: Box, data: UnsafeCell, } @@ -76,9 +76,9 @@ unsafe impl Sync for RwLock {} /// # Example /// /// ``` -/// use std::sync::{StaticRWLock, RWLOCK_INIT}; +/// use std::sync::{StaticRwLock, RWLOCK_INIT}; /// -/// static LOCK: StaticRWLock = RWLOCK_INIT; +/// static LOCK: StaticRwLock = RWLOCK_INIT; /// /// { /// let _g = LOCK.read().unwrap(); @@ -101,7 +101,7 @@ unsafe impl Sync for StaticRwLock {} /// Constant initialization for a statically-initialized rwlock. #[unstable = "may be merged with RwLock in the future"] -pub const RWLOCK_INIT: StaticRWLock = StaticRWLock { +pub const RWLOCK_INIT: StaticRwLock = StaticRwLock { lock: sys::RWLOCK_INIT, poison: poison::FLAG_INIT, }; @@ -111,7 +111,7 @@ pub const RWLOCK_INIT: StaticRWLock = StaticRWLock { #[must_use] #[stable] pub struct RWLockReadGuard<'a, T: 'a> { - __lock: &'a StaticRWLock, + __lock: &'a StaticRwLock, __data: &'a UnsafeCell, __marker: marker::NoSend, } @@ -121,7 +121,7 @@ pub struct RWLockReadGuard<'a, T: 'a> { #[must_use] #[stable] pub struct RWLockWriteGuard<'a, T: 'a> { - __lock: &'a StaticRWLock, + __lock: &'a StaticRwLock, __data: &'a UnsafeCell, __poison: poison::Guard, __marker: marker::NoSend, @@ -302,7 +302,7 @@ impl StaticRwLock { } impl<'rwlock, T> RWLockReadGuard<'rwlock, T> { - fn new(lock: &'rwlock StaticRWLock, data: &'rwlock UnsafeCell) + fn new(lock: &'rwlock StaticRwLock, data: &'rwlock UnsafeCell) -> LockResult> { poison::map_result(lock.poison.borrow(), |_| { RWLockReadGuard { @@ -314,7 +314,7 @@ impl<'rwlock, T> RWLockReadGuard<'rwlock, T> { } } impl<'rwlock, T> RWLockWriteGuard<'rwlock, T> { - fn new(lock: &'rwlock StaticRWLock, data: &'rwlock UnsafeCell) + fn new(lock: &'rwlock StaticRwLock, data: &'rwlock UnsafeCell) -> LockResult> { poison::map_result(lock.poison.borrow(), |guard| { RWLockWriteGuard { @@ -365,7 +365,7 @@ mod tests { use rand::{mod, Rng}; use sync::mpsc::channel; use thread::Thread; - use sync::{Arc, RwLock, StaticRWLock, RWLOCK_INIT}; + use sync::{Arc, RwLock, StaticRwLock, RWLOCK_INIT}; #[test] fn smoke() { @@ -378,7 +378,7 @@ mod tests { #[test] fn static_smoke() { - static R: StaticRWLock = RWLOCK_INIT; + static R: StaticRwLock = RWLOCK_INIT; drop(R.read().unwrap()); drop(R.write().unwrap()); drop((R.read().unwrap(), R.read().unwrap())); @@ -388,7 +388,7 @@ mod tests { #[test] fn frob() { - static R: StaticRWLock = RWLOCK_INIT; + static R: StaticRwLock = RWLOCK_INIT; static N: uint = 10; static M: uint = 1000; -- cgit 1.4.1-3-g733a5 From 5344ae2d4f66f5e8392b325320eeec0af29f503c Mon Sep 17 00:00:00 2001 From: ville-h Date: Sun, 4 Jan 2015 09:03:27 +0200 Subject: rename std::sync::RWLOCK_INIT to RW_LOCK_INIT --- src/libstd/sync/rwlock.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/libstd/sync') diff --git a/src/libstd/sync/rwlock.rs b/src/libstd/sync/rwlock.rs index 04efbf893ea..7b673838339 100644 --- a/src/libstd/sync/rwlock.rs +++ b/src/libstd/sync/rwlock.rs @@ -101,7 +101,7 @@ unsafe impl Sync for StaticRwLock {} /// Constant initialization for a statically-initialized rwlock. #[unstable = "may be merged with RwLock in the future"] -pub const RWLOCK_INIT: StaticRwLock = StaticRwLock { +pub const RW_LOCK_INIT: StaticRwLock = StaticRwLock { lock: sys::RWLOCK_INIT, poison: poison::FLAG_INIT, }; -- cgit 1.4.1-3-g733a5 From c3dcf9b6bf7b3de4b7b4f51725f2ab814cbdfd38 Mon Sep 17 00:00:00 2001 From: ville-h Date: Sun, 4 Jan 2015 10:57:05 +0200 Subject: fix code and comments referencing RW_LOCK_INIT --- src/libstd/sync/mod.rs | 2 +- src/libstd/sync/rwlock.rs | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) (limited to 'src/libstd/sync') diff --git a/src/libstd/sync/mod.rs b/src/libstd/sync/mod.rs index 0e2b0a441e6..3bb0e257577 100644 --- a/src/libstd/sync/mod.rs +++ b/src/libstd/sync/mod.rs @@ -21,7 +21,7 @@ pub use alloc::arc::{Arc, Weak}; pub use self::mutex::{Mutex, MutexGuard, StaticMutex}; pub use self::mutex::MUTEX_INIT; -pub use self::rwlock::{RwLock, StaticRwLock, RWLOCK_INIT}; +pub use self::rwlock::{RwLock, StaticRwLock, RW_LOCK_INIT}; pub use self::rwlock::{RWLockReadGuard, RWLockWriteGuard}; pub use self::condvar::{Condvar, StaticCondvar, CONDVAR_INIT}; pub use self::once::{Once, ONCE_INIT}; diff --git a/src/libstd/sync/rwlock.rs b/src/libstd/sync/rwlock.rs index 7b673838339..f6fffd49dee 100644 --- a/src/libstd/sync/rwlock.rs +++ b/src/libstd/sync/rwlock.rs @@ -76,9 +76,9 @@ unsafe impl Sync for RwLock {} /// # Example /// /// ``` -/// use std::sync::{StaticRwLock, RWLOCK_INIT}; +/// use std::sync::{StaticRwLock, RW_LOCK_INIT}; /// -/// static LOCK: StaticRwLock = RWLOCK_INIT; +/// static LOCK: StaticRwLock = RW_LOCK_INIT; /// /// { /// let _g = LOCK.read().unwrap(); @@ -131,7 +131,7 @@ impl RwLock { /// Creates a new instance of an RwLock which is unlocked and read to go. #[stable] pub fn new(t: T) -> RwLock { - RwLock { inner: box RWLOCK_INIT, data: UnsafeCell::new(t) } + RwLock { inner: box RW_LOCK_INIT, data: UnsafeCell::new(t) } } /// Locks this rwlock with shared read access, blocking the current thread @@ -365,7 +365,7 @@ mod tests { use rand::{mod, Rng}; use sync::mpsc::channel; use thread::Thread; - use sync::{Arc, RwLock, StaticRwLock, RWLOCK_INIT}; + use sync::{Arc, RwLock, StaticRwLock, RW_LOCK_INIT}; #[test] fn smoke() { @@ -378,7 +378,7 @@ mod tests { #[test] fn static_smoke() { - static R: StaticRwLock = RWLOCK_INIT; + static R: StaticRwLock = RW_LOCK_INIT; drop(R.read().unwrap()); drop(R.write().unwrap()); drop((R.read().unwrap(), R.read().unwrap())); @@ -388,7 +388,7 @@ mod tests { #[test] fn frob() { - static R: StaticRwLock = RWLOCK_INIT; + static R: StaticRwLock = RW_LOCK_INIT; static N: uint = 10; static M: uint = 1000; -- cgit 1.4.1-3-g733a5 From 2dcbdc1edac50af0f1a2796b1dfe2dd082f8190c Mon Sep 17 00:00:00 2001 From: ville-h Date: Sun, 4 Jan 2015 11:43:14 +0200 Subject: rename std::sync::RWLockReadGuard to RwLockReadGuard --- src/libstd/sync/rwlock.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'src/libstd/sync') diff --git a/src/libstd/sync/rwlock.rs b/src/libstd/sync/rwlock.rs index f6fffd49dee..37b9f5dc68d 100644 --- a/src/libstd/sync/rwlock.rs +++ b/src/libstd/sync/rwlock.rs @@ -110,7 +110,7 @@ pub const RW_LOCK_INIT: StaticRwLock = StaticRwLock { /// dropped. #[must_use] #[stable] -pub struct RWLockReadGuard<'a, T: 'a> { +pub struct RwLockReadGuard<'a, T: 'a> { __lock: &'a StaticRwLock, __data: &'a UnsafeCell, __marker: marker::NoSend, @@ -301,11 +301,11 @@ impl StaticRwLock { } } -impl<'rwlock, T> RWLockReadGuard<'rwlock, T> { +impl<'rwlock, T> RwLockReadGuard<'rwlock, T> { fn new(lock: &'rwlock StaticRwLock, data: &'rwlock UnsafeCell) - -> LockResult> { + -> LockResult> { poison::map_result(lock.poison.borrow(), |_| { - RWLockReadGuard { + RwLockReadGuard { __lock: lock, __data: data, __marker: marker::NoSend, @@ -327,7 +327,7 @@ impl<'rwlock, T> RWLockWriteGuard<'rwlock, T> { } } -impl<'rwlock, T> Deref for RWLockReadGuard<'rwlock, T> { +impl<'rwlock, T> Deref for RwLockReadGuard<'rwlock, T> { type Target = T; fn deref(&self) -> &T { unsafe { &*self.__data.get() } } @@ -344,7 +344,7 @@ impl<'rwlock, T> DerefMut for RWLockWriteGuard<'rwlock, T> { } #[unsafe_destructor] -impl<'a, T> Drop for RWLockReadGuard<'a, T> { +impl<'a, T> Drop for RwLockReadGuard<'a, T> { fn drop(&mut self) { unsafe { self.__lock.lock.read_unlock(); } } -- cgit 1.4.1-3-g733a5 From 956cab6f97c1841e6f3f00acb6386f07eddfc25e Mon Sep 17 00:00:00 2001 From: ville-h Date: Sun, 4 Jan 2015 11:45:31 +0200 Subject: fix code referencing RwLockReadGuard --- src/libstd/sync/mod.rs | 2 +- src/libstd/sync/rwlock.rs | 16 ++++++++-------- 2 files changed, 9 insertions(+), 9 deletions(-) (limited to 'src/libstd/sync') diff --git a/src/libstd/sync/mod.rs b/src/libstd/sync/mod.rs index 3bb0e257577..71ff3c7d172 100644 --- a/src/libstd/sync/mod.rs +++ b/src/libstd/sync/mod.rs @@ -22,7 +22,7 @@ pub use alloc::arc::{Arc, Weak}; pub use self::mutex::{Mutex, MutexGuard, StaticMutex}; pub use self::mutex::MUTEX_INIT; pub use self::rwlock::{RwLock, StaticRwLock, RW_LOCK_INIT}; -pub use self::rwlock::{RWLockReadGuard, RWLockWriteGuard}; +pub use self::rwlock::{RwLockReadGuard, RWLockWriteGuard}; pub use self::condvar::{Condvar, StaticCondvar, CONDVAR_INIT}; pub use self::once::{Once, ONCE_INIT}; pub use self::semaphore::{Semaphore, SemaphoreGuard}; diff --git a/src/libstd/sync/rwlock.rs b/src/libstd/sync/rwlock.rs index 37b9f5dc68d..0a8bf6f0aa7 100644 --- a/src/libstd/sync/rwlock.rs +++ b/src/libstd/sync/rwlock.rs @@ -153,9 +153,9 @@ impl RwLock { /// The failure will occur immediately after the lock has been acquired. #[inline] #[stable] - pub fn read(&self) -> LockResult> { + pub fn read(&self) -> LockResult> { unsafe { self.inner.lock.read() } - RWLockReadGuard::new(&*self.inner, &self.data) + RwLockReadGuard::new(&*self.inner, &self.data) } /// Attempt to acquire this lock with shared read access. @@ -175,9 +175,9 @@ impl RwLock { /// acquired. #[inline] #[stable] - pub fn try_read(&self) -> TryLockResult> { + pub fn try_read(&self) -> TryLockResult> { if unsafe { self.inner.lock.try_read() } { - Ok(try!(RWLockReadGuard::new(&*self.inner, &self.data))) + Ok(try!(RwLockReadGuard::new(&*self.inner, &self.data))) } else { Err(TryLockError::WouldBlock) } @@ -245,9 +245,9 @@ impl StaticRwLock { /// See `RwLock::read`. #[inline] #[unstable = "may be merged with RwLock in the future"] - pub fn read(&'static self) -> LockResult> { + pub fn read(&'static self) -> LockResult> { unsafe { self.lock.read() } - RWLockReadGuard::new(self, &DUMMY.0) + RwLockReadGuard::new(self, &DUMMY.0) } /// Attempt to acquire this lock with shared read access. @@ -256,9 +256,9 @@ impl StaticRwLock { #[inline] #[unstable = "may be merged with RwLock in the future"] pub fn try_read(&'static self) - -> TryLockResult> { + -> TryLockResult> { if unsafe { self.lock.try_read() } { - Ok(try!(RWLockReadGuard::new(self, &DUMMY.0))) + Ok(try!(RwLockReadGuard::new(self, &DUMMY.0))) } else { Err(TryLockError::WouldBlock) } -- cgit 1.4.1-3-g733a5 From 98e6d12017da5e323612108c81accb1f437f7137 Mon Sep 17 00:00:00 2001 From: ville-h Date: Sun, 4 Jan 2015 12:36:27 +0200 Subject: rename std::sync::RWLockWriteGuard to RwLockWriteGuard --- src/libstd/sync/rwlock.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'src/libstd/sync') diff --git a/src/libstd/sync/rwlock.rs b/src/libstd/sync/rwlock.rs index 0a8bf6f0aa7..6c2def11ce5 100644 --- a/src/libstd/sync/rwlock.rs +++ b/src/libstd/sync/rwlock.rs @@ -120,7 +120,7 @@ pub struct RwLockReadGuard<'a, T: 'a> { /// dropped. #[must_use] #[stable] -pub struct RWLockWriteGuard<'a, T: 'a> { +pub struct RwLockWriteGuard<'a, T: 'a> { __lock: &'a StaticRwLock, __data: &'a UnsafeCell, __poison: poison::Guard, @@ -313,11 +313,11 @@ impl<'rwlock, T> RwLockReadGuard<'rwlock, T> { }) } } -impl<'rwlock, T> RWLockWriteGuard<'rwlock, T> { +impl<'rwlock, T> RwLockWriteGuard<'rwlock, T> { fn new(lock: &'rwlock StaticRwLock, data: &'rwlock UnsafeCell) - -> LockResult> { + -> LockResult> { poison::map_result(lock.poison.borrow(), |guard| { - RWLockWriteGuard { + RwLockWriteGuard { __lock: lock, __data: data, __poison: guard, @@ -332,12 +332,12 @@ impl<'rwlock, T> Deref for RwLockReadGuard<'rwlock, T> { fn deref(&self) -> &T { unsafe { &*self.__data.get() } } } -impl<'rwlock, T> Deref for RWLockWriteGuard<'rwlock, T> { +impl<'rwlock, T> Deref for RwLockWriteGuard<'rwlock, T> { type Target = T; fn deref(&self) -> &T { unsafe { &*self.__data.get() } } } -impl<'rwlock, T> DerefMut for RWLockWriteGuard<'rwlock, T> { +impl<'rwlock, T> DerefMut for RwLockWriteGuard<'rwlock, T> { fn deref_mut(&mut self) -> &mut T { unsafe { &mut *self.__data.get() } } @@ -351,7 +351,7 @@ impl<'a, T> Drop for RwLockReadGuard<'a, T> { } #[unsafe_destructor] -impl<'a, T> Drop for RWLockWriteGuard<'a, T> { +impl<'a, T> Drop for RwLockWriteGuard<'a, T> { fn drop(&mut self) { self.__lock.poison.done(&self.__poison); unsafe { self.__lock.lock.write_unlock(); } -- cgit 1.4.1-3-g733a5 From 44b3ddef8df7fa5392ce3608cbe1977f119337ee Mon Sep 17 00:00:00 2001 From: ville-h Date: Sun, 4 Jan 2015 13:12:17 +0200 Subject: fix code referencing RwLockWriteGuard --- src/libstd/sync/mod.rs | 2 +- src/libstd/sync/rwlock.rs | 16 ++++++++-------- 2 files changed, 9 insertions(+), 9 deletions(-) (limited to 'src/libstd/sync') diff --git a/src/libstd/sync/mod.rs b/src/libstd/sync/mod.rs index 71ff3c7d172..a2e1eb6c65a 100644 --- a/src/libstd/sync/mod.rs +++ b/src/libstd/sync/mod.rs @@ -22,7 +22,7 @@ pub use alloc::arc::{Arc, Weak}; pub use self::mutex::{Mutex, MutexGuard, StaticMutex}; pub use self::mutex::MUTEX_INIT; pub use self::rwlock::{RwLock, StaticRwLock, RW_LOCK_INIT}; -pub use self::rwlock::{RwLockReadGuard, RWLockWriteGuard}; +pub use self::rwlock::{RwLockReadGuard, RwLockWriteGuard}; pub use self::condvar::{Condvar, StaticCondvar, CONDVAR_INIT}; pub use self::once::{Once, ONCE_INIT}; pub use self::semaphore::{Semaphore, SemaphoreGuard}; diff --git a/src/libstd/sync/rwlock.rs b/src/libstd/sync/rwlock.rs index 6c2def11ce5..bc068d0e637 100644 --- a/src/libstd/sync/rwlock.rs +++ b/src/libstd/sync/rwlock.rs @@ -199,9 +199,9 @@ impl RwLock { /// An error will be returned when the lock is acquired. #[inline] #[stable] - pub fn write(&self) -> LockResult> { + pub fn write(&self) -> LockResult> { unsafe { self.inner.lock.write() } - RWLockWriteGuard::new(&*self.inner, &self.data) + RwLockWriteGuard::new(&*self.inner, &self.data) } /// Attempt to lock this rwlock with exclusive write access. @@ -218,9 +218,9 @@ impl RwLock { /// acquired. #[inline] #[stable] - pub fn try_write(&self) -> TryLockResult> { + pub fn try_write(&self) -> TryLockResult> { if unsafe { self.inner.lock.try_read() } { - Ok(try!(RWLockWriteGuard::new(&*self.inner, &self.data))) + Ok(try!(RwLockWriteGuard::new(&*self.inner, &self.data))) } else { Err(TryLockError::WouldBlock) } @@ -270,9 +270,9 @@ impl StaticRwLock { /// See `RwLock::write`. #[inline] #[unstable = "may be merged with RwLock in the future"] - pub fn write(&'static self) -> LockResult> { + pub fn write(&'static self) -> LockResult> { unsafe { self.lock.write() } - RWLockWriteGuard::new(self, &DUMMY.0) + RwLockWriteGuard::new(self, &DUMMY.0) } /// Attempt to lock this rwlock with exclusive write access. @@ -281,9 +281,9 @@ impl StaticRwLock { #[inline] #[unstable = "may be merged with RwLock in the future"] pub fn try_write(&'static self) - -> TryLockResult> { + -> TryLockResult> { if unsafe { self.lock.try_write() } { - Ok(try!(RWLockWriteGuard::new(self, &DUMMY.0))) + Ok(try!(RwLockWriteGuard::new(self, &DUMMY.0))) } else { Err(TryLockError::WouldBlock) } -- cgit 1.4.1-3-g733a5 From fee1f2ade962c913ba2da81f7a97ab39c6f66989 Mon Sep 17 00:00:00 2001 From: ville-h Date: Sun, 4 Jan 2015 13:26:25 +0200 Subject: fix comment referencing RwLock --- src/libstd/sync/poison.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/libstd/sync') diff --git a/src/libstd/sync/poison.rs b/src/libstd/sync/poison.rs index 6e4df118209..385df45b400 100644 --- a/src/libstd/sync/poison.rs +++ b/src/libstd/sync/poison.rs @@ -49,7 +49,7 @@ pub struct Guard { /// A type of error which can be returned whenever a lock is acquired. /// -/// Both Mutexes and RWLocks are poisoned whenever a task fails while the lock +/// Both Mutexes and RwLocks are poisoned whenever a task fails while the lock /// is held. The precise semantics for when a lock is poisoned is documented on /// each lock, but once a lock is poisoned then all future acquisitions will /// return this error. -- cgit 1.4.1-3-g733a5 From 177f8bc55c544d5a5f35ffb19f47125d001e48c4 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Sun, 4 Jan 2015 23:34:42 -0800 Subject: std: Fix missing stability in sync * The `sync` module is stable * The `sync::mpsc` module is stable * The `Sender::send` method is stable. * The `Once::doit` method is now removed. * Deprecated atomic initializers are removed. * Renamed atomic initializers are now stable. --- src/libcore/atomic.rs | 16 +++------------- src/libstd/sync/mod.rs | 2 +- src/libstd/sync/mpsc/mod.rs | 3 +++ src/libstd/sync/once.rs | 4 ---- 4 files changed, 7 insertions(+), 18 deletions(-) (limited to 'src/libstd/sync') diff --git a/src/libcore/atomic.rs b/src/libcore/atomic.rs index 0ac0dc396cc..fbb8f9d8cf7 100644 --- a/src/libcore/atomic.rs +++ b/src/libcore/atomic.rs @@ -146,28 +146,18 @@ pub enum Ordering { } /// An `AtomicBool` initialized to `false`. -#[unstable = "may be renamed, pending conventions for static initalizers"] +#[stable] pub const ATOMIC_BOOL_INIT: AtomicBool = AtomicBool { v: UnsafeCell { value: 0 } }; /// An `AtomicInt` initialized to `0`. -#[unstable = "may be renamed, pending conventions for static initalizers"] +#[stable] pub const ATOMIC_INT_INIT: AtomicInt = AtomicInt { v: UnsafeCell { value: 0 } }; /// An `AtomicUint` initialized to `0`. -#[unstable = "may be renamed, pending conventions for static initalizers"] +#[stable] pub const ATOMIC_UINT_INIT: AtomicUint = AtomicUint { v: UnsafeCell { value: 0, } }; -/// Deprecated -#[deprecated = "renamed to ATOMIC_BOOL_INIT"] -pub const INIT_ATOMIC_BOOL: AtomicBool = ATOMIC_BOOL_INIT; -/// Deprecated -#[deprecated = "renamed to ATOMIC_INT_INIT"] -pub const INIT_ATOMIC_INT: AtomicInt = ATOMIC_INT_INIT; -/// Deprecated -#[deprecated = "renamed to ATOMIC_UINT_INIT"] -pub const INIT_ATOMIC_UINT: AtomicUint = ATOMIC_UINT_INIT; - // NB: Needs to be -1 (0b11111111...) to make fetch_nand work correctly const UINT_TRUE: uint = -1; diff --git a/src/libstd/sync/mod.rs b/src/libstd/sync/mod.rs index 6ce278726e9..44671b52ba0 100644 --- a/src/libstd/sync/mod.rs +++ b/src/libstd/sync/mod.rs @@ -15,7 +15,7 @@ //! and/or blocking at all, but rather provide the necessary tools to build //! other types of concurrent primitives. -#![experimental] +#![stable] pub use alloc::arc::{Arc, Weak}; pub use core::atomic; diff --git a/src/libstd/sync/mpsc/mod.rs b/src/libstd/sync/mpsc/mod.rs index 6bc3f561bb3..84284ae6d66 100644 --- a/src/libstd/sync/mpsc/mod.rs +++ b/src/libstd/sync/mpsc/mod.rs @@ -163,6 +163,8 @@ //! } //! ``` +#![stable] + // A description of how Rust's channel implementation works // // Channels are supposed to be the basic building block for all other @@ -565,6 +567,7 @@ impl Sender { /// drop(rx); /// assert_eq!(tx.send(1i).err().unwrap().0, 1); /// ``` + #[stable] pub fn send(&self, t: T) -> Result<(), SendError> { let (new_inner, ret) = match *unsafe { self.inner() } { Flavor::Oneshot(ref p) => { diff --git a/src/libstd/sync/once.rs b/src/libstd/sync/once.rs index 08e323c9cb4..aa2d957a3eb 100644 --- a/src/libstd/sync/once.rs +++ b/src/libstd/sync/once.rs @@ -121,10 +121,6 @@ impl Once { unsafe { self.mutex.destroy() } } } - - /// Deprecated - #[deprecated = "renamed to `call_once`"] - pub fn doit(&'static self, f: F) where F: FnOnce() { self.call_once(f) } } #[cfg(test)] -- cgit 1.4.1-3-g733a5 From c6f4a03d12d97162e2775c14ab006d355b04126d Mon Sep 17 00:00:00 2001 From: Aaron Turon Date: Sun, 4 Jan 2015 16:16:55 -0800 Subject: Stabilization of impls and fallout from stabilization --- src/liballoc/arc.rs | 6 +++--- src/liballoc/boxed.rs | 2 ++ src/liballoc/rc.rs | 6 +++--- src/libcollections/binary_heap.rs | 4 ++++ src/libcollections/lib.rs | 3 +-- src/libcollections/slice.rs | 1 + src/libcollections/str.rs | 6 ++++++ src/libcollections/string.rs | 8 ++++---- src/libcollections/vec.rs | 19 +++++++++++++++---- src/libcore/borrow.rs | 1 + src/libcore/cell.rs | 6 +++--- src/libcore/char.rs | 2 ++ src/libcore/iter.rs | 2 +- src/libcore/ops.rs | 4 ++++ src/libcore/option.rs | 9 +++++++++ src/libcore/prelude.rs | 3 +-- src/libcore/result.rs | 9 +++++++++ src/libcore/slice.rs | 31 ++++++++++++++++--------------- src/libcore/str/mod.rs | 30 +++++++++++++++++++++++------- src/libstd/collections/hash/set.rs | 2 +- src/libstd/io/buffered.rs | 2 +- src/libstd/prelude/v1.rs | 2 -- src/libstd/sync/condvar.rs | 1 + src/libstd/sync/mpsc/mod.rs | 5 ++++- src/libstd/sync/mpsc/mpsc_queue.rs | 1 + src/libstd/sync/mutex.rs | 4 ++++ src/libstd/sync/rwlock.rs | 6 ++++++ src/libstd/sync/semaphore.rs | 1 + src/libstd/thread.rs | 1 + 29 files changed, 128 insertions(+), 49 deletions(-) (limited to 'src/libstd/sync') diff --git a/src/liballoc/arc.rs b/src/liballoc/arc.rs index 88f02d6573e..25f80ad11bd 100644 --- a/src/liballoc/arc.rs +++ b/src/liballoc/arc.rs @@ -246,7 +246,7 @@ impl BorrowFrom> for T { } } -#[experimental = "Deref is experimental."] +#[stable] impl Deref for Arc { type Target = T; @@ -290,7 +290,7 @@ impl Arc { } #[unsafe_destructor] -#[experimental = "waiting on stability of Drop"] +#[stable] impl Drop for Arc { /// Drops the `Arc`. /// @@ -418,7 +418,7 @@ impl Clone for Weak { } #[unsafe_destructor] -#[experimental = "Weak pointers may not belong in this module."] +#[stable] impl Drop for Weak { /// Drops the `Weak`. /// diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index 2c318181b09..33d1cc7f4c7 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -155,12 +155,14 @@ impl fmt::Show for Box { } } +#[stable] impl Deref for Box { type Target = T; fn deref(&self) -> &T { &**self } } +#[stable] impl DerefMut for Box { fn deref_mut(&mut self) -> &mut T { &mut **self } } diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index c4b455aff5c..175bba4e71d 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -354,7 +354,7 @@ impl BorrowFrom> for T { } } -#[experimental = "Deref is experimental."] +#[stable] impl Deref for Rc { type Target = T; @@ -365,7 +365,7 @@ impl Deref for Rc { } #[unsafe_destructor] -#[experimental = "Drop is experimental."] +#[stable] impl Drop for Rc { /// Drops the `Rc`. /// @@ -656,7 +656,7 @@ impl Weak { } #[unsafe_destructor] -#[experimental = "Weak pointers may not belong in this module."] +#[stable] impl Drop for Weak { /// Drops the `Weak`. /// diff --git a/src/libcollections/binary_heap.rs b/src/libcollections/binary_heap.rs index 619a6e94271..01693391abe 100644 --- a/src/libcollections/binary_heap.rs +++ b/src/libcollections/binary_heap.rs @@ -562,11 +562,13 @@ impl BinaryHeap { } /// `BinaryHeap` iterator. +#[stable] pub struct Iter <'a, T: 'a> { iter: slice::Iter<'a, T>, } // FIXME(#19839) Remove in favor of `#[derive(Clone)]` +#[stable] impl<'a, T> Clone for Iter<'a, T> { fn clone(&self) -> Iter<'a, T> { Iter { iter: self.iter.clone() } @@ -594,6 +596,7 @@ impl<'a, T> DoubleEndedIterator for Iter<'a, T> { impl<'a, T> ExactSizeIterator for Iter<'a, T> {} /// An iterator that moves out of a `BinaryHeap`. +#[stable] pub struct IntoIter { iter: vec::IntoIter, } @@ -619,6 +622,7 @@ impl DoubleEndedIterator for IntoIter { impl ExactSizeIterator for IntoIter {} /// An iterator that drains a `BinaryHeap`. +#[unstable = "recent addition"] pub struct Drain<'a, T: 'a> { iter: vec::Drain<'a, T>, } diff --git a/src/libcollections/lib.rs b/src/libcollections/lib.rs index 72cdae8ba31..c9b090bfb23 100644 --- a/src/libcollections/lib.rs +++ b/src/libcollections/lib.rs @@ -113,8 +113,7 @@ mod prelude { pub use core::iter::range; pub use core::iter::{FromIterator, Extend, IteratorExt}; pub use core::iter::{Iterator, DoubleEndedIterator, RandomAccessIterator}; - pub use core::iter::{IteratorCloneExt, CloneIteratorExt}; - pub use core::iter::{IteratorOrdExt, MutableDoubleEndedIterator, ExactSizeIterator}; + pub use core::iter::{ExactSizeIterator}; pub use core::kinds::{Copy, Send, Sized, Sync}; pub use core::mem::drop; pub use core::ops::{Drop, Fn, FnMut, FnOnce}; diff --git a/src/libcollections/slice.rs b/src/libcollections/slice.rs index ceccca561ae..e3bf5d63b1d 100644 --- a/src/libcollections/slice.rs +++ b/src/libcollections/slice.rs @@ -1092,6 +1092,7 @@ struct SizeDirection { dir: Direction, } +#[stable] impl Iterator for ElementSwaps { type Item = (uint, uint); diff --git a/src/libcollections/str.rs b/src/libcollections/str.rs index ecf17820d2d..9f3ab6dd5c0 100644 --- a/src/libcollections/str.rs +++ b/src/libcollections/str.rs @@ -165,6 +165,7 @@ enum DecompositionType { /// External iterator for a string's decomposition's characters. /// Use with the `std::iter` module. #[derive(Clone)] +#[unstable] pub struct Decompositions<'a> { kind: DecompositionType, iter: Chars<'a>, @@ -172,6 +173,7 @@ pub struct Decompositions<'a> { sorted: bool } +#[stable] impl<'a> Iterator for Decompositions<'a> { type Item = char; @@ -253,6 +255,7 @@ enum RecompositionState { /// External iterator for a string's recomposition's characters. /// Use with the `std::iter` module. #[derive(Clone)] +#[unstable] pub struct Recompositions<'a> { iter: Decompositions<'a>, state: RecompositionState, @@ -261,6 +264,7 @@ pub struct Recompositions<'a> { last_ccc: Option } +#[stable] impl<'a> Iterator for Recompositions<'a> { type Item = char; @@ -348,10 +352,12 @@ impl<'a> Iterator for Recompositions<'a> { /// External iterator for a string's UTF16 codeunits. /// Use with the `std::iter` module. #[derive(Clone)] +#[unstable] pub struct Utf16Units<'a> { encoder: Utf16Encoder> } +#[stable] impl<'a> Iterator for Utf16Units<'a> { type Item = u16; diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index e7451331908..8ffca7e57b2 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -711,7 +711,7 @@ impl fmt::Show for FromUtf16Error { } } -#[experimental = "waiting on FromIterator stabilization"] +#[stable] impl FromIterator for String { fn from_iter>(iterator: I) -> String { let mut buf = String::new(); @@ -720,7 +720,7 @@ impl FromIterator for String { } } -#[experimental = "waiting on FromIterator stabilization"] +#[stable] impl<'a> FromIterator<&'a str> for String { fn from_iter>(iterator: I) -> String { let mut buf = String::new(); @@ -832,7 +832,7 @@ impl hash::Hash for String { } } -#[experimental = "waiting on Add stabilization"] +#[unstable = "recent addition, needs more experience"] impl<'a> Add<&'a str> for String { type Output = String; @@ -864,7 +864,7 @@ impl ops::Slice for String { } } -#[experimental = "waiting on Deref stabilization"] +#[stable] impl ops::Deref for String { type Target = str; diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs index b8f97799c97..b8bcba84cee 100644 --- a/src/libcollections/vec.rs +++ b/src/libcollections/vec.rs @@ -1272,19 +1272,19 @@ impl ops::SliceMut for Vec { } } -#[experimental = "waiting on Deref stability"] +#[stable] impl ops::Deref for Vec { type Target = [T]; fn deref<'a>(&'a self) -> &'a [T] { self.as_slice() } } -#[experimental = "waiting on DerefMut stability"] +#[stable] impl ops::DerefMut for Vec { fn deref_mut<'a>(&'a mut self) -> &'a mut [T] { self.as_mut_slice() } } -#[experimental = "waiting on FromIterator stability"] +#[stable] impl FromIterator for Vec { #[inline] fn from_iter>(mut iterator: I) -> Vec { @@ -1414,6 +1414,7 @@ impl AsSlice for Vec { } } +#[unstable = "recent addition, needs more experience"] impl<'a, T: Clone> Add<&'a [T]> for Vec { type Output = Vec; @@ -1425,6 +1426,7 @@ impl<'a, T: Clone> Add<&'a [T]> for Vec { } #[unsafe_destructor] +#[stable] impl Drop for Vec { fn drop(&mut self) { // This is (and should always remain) a no-op if the fields are @@ -1470,6 +1472,7 @@ impl<'a> fmt::Writer for Vec { /// A clone-on-write vector pub type CowVec<'a, T> = Cow<'a, Vec, [T]>; +#[unstable] impl<'a, T> FromIterator for CowVec<'a, T> where T: Clone { fn from_iter>(it: I) -> CowVec<'a, T> { Cow::Owned(FromIterator::from_iter(it)) @@ -1515,6 +1518,7 @@ impl IntoIter { } } +#[stable] impl Iterator for IntoIter { type Item = T; @@ -1551,6 +1555,7 @@ impl Iterator for IntoIter { } } +#[stable] impl DoubleEndedIterator for IntoIter { #[inline] fn next_back<'a>(&'a mut self) -> Option { @@ -1574,9 +1579,11 @@ impl DoubleEndedIterator for IntoIter { } } +#[stable] impl ExactSizeIterator for IntoIter {} #[unsafe_destructor] +#[stable] impl Drop for IntoIter { fn drop(&mut self) { // destroy the remaining elements @@ -1598,6 +1605,7 @@ pub struct Drain<'a, T> { marker: ContravariantLifetime<'a>, } +#[stable] impl<'a, T> Iterator for Drain<'a, T> { type Item = T; @@ -1634,6 +1642,7 @@ impl<'a, T> Iterator for Drain<'a, T> { } } +#[stable] impl<'a, T> DoubleEndedIterator for Drain<'a, T> { #[inline] fn next_back(&mut self) -> Option { @@ -1657,9 +1666,11 @@ impl<'a, T> DoubleEndedIterator for Drain<'a, T> { } } +#[stable] impl<'a, T> ExactSizeIterator for Drain<'a, T> {} #[unsafe_destructor] +#[stable] impl<'a, T> Drop for Drain<'a, T> { fn drop(&mut self) { // self.ptr == self.end == null if drop has already been called, @@ -1692,7 +1703,7 @@ impl<'a, T> Deref for DerefVec<'a, T> { // Prevent the inner `Vec` from attempting to deallocate memory. #[unsafe_destructor] -#[experimental] +#[stable] impl<'a, T> Drop for DerefVec<'a, T> { fn drop(&mut self) { self.x.len = 0; diff --git a/src/libcore/borrow.rs b/src/libcore/borrow.rs index 7e4d73d598d..63b3be00f55 100644 --- a/src/libcore/borrow.rs +++ b/src/libcore/borrow.rs @@ -191,6 +191,7 @@ impl<'a, T, Sized? B> Cow<'a, T, B> where B: ToOwned { } } +#[stable] impl<'a, T, Sized? B> Deref for Cow<'a, T, B> where B: ToOwned { type Target = B; diff --git a/src/libcore/cell.rs b/src/libcore/cell.rs index eb772388dce..fd18d6ac3f3 100644 --- a/src/libcore/cell.rs +++ b/src/libcore/cell.rs @@ -419,7 +419,7 @@ pub struct Ref<'b, T:'b> { _borrow: BorrowRef<'b>, } -#[unstable = "waiting for `Deref` to become stable"] +#[stable] impl<'b, T> Deref for Ref<'b, T> { type Target = T; @@ -477,7 +477,7 @@ pub struct RefMut<'b, T:'b> { _borrow: BorrowRefMut<'b>, } -#[unstable = "waiting for `Deref` to become stable"] +#[stable] impl<'b, T> Deref for RefMut<'b, T> { type Target = T; @@ -487,7 +487,7 @@ impl<'b, T> Deref for RefMut<'b, T> { } } -#[unstable = "waiting for `DerefMut` to become stable"] +#[stable] impl<'b, T> DerefMut for RefMut<'b, T> { #[inline] fn deref_mut<'a>(&'a mut self) -> &'a mut T { diff --git a/src/libcore/char.rs b/src/libcore/char.rs index 291b7f2ece4..caac894c0da 100644 --- a/src/libcore/char.rs +++ b/src/libcore/char.rs @@ -314,6 +314,7 @@ pub struct EscapeUnicode { } #[derive(Clone)] +#[unstable] enum EscapeUnicodeState { Backslash, Type, @@ -375,6 +376,7 @@ pub struct EscapeDefault { } #[derive(Clone)] +#[unstable] enum EscapeDefaultState { Backslash(char), Char(char), diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs index 4782a763dc8..e5753f6cc2e 100644 --- a/src/libcore/iter.rs +++ b/src/libcore/iter.rs @@ -2401,7 +2401,7 @@ impl Unfold where F: FnMut(&mut St) -> Option { } } -#[experimental] +#[stable] impl Iterator for Unfold where F: FnMut(&mut St) -> Option { type Item = A; diff --git a/src/libcore/ops.rs b/src/libcore/ops.rs index da2e95832e7..74702c66f7b 100644 --- a/src/libcore/ops.rs +++ b/src/libcore/ops.rs @@ -984,6 +984,7 @@ pub struct Range { // FIXME(#19391) needs a snapshot //impl> Iterator for Range { +#[unstable = "API still in development"] impl Iterator for Range { type Item = Idx; @@ -1008,6 +1009,7 @@ impl Iterator for Range { } } +#[unstable = "API still in development"] impl DoubleEndedIterator for Range { #[inline] fn next_back(&mut self) -> Option { @@ -1020,6 +1022,7 @@ impl DoubleEndedIterator for Range { } } +#[unstable = "API still in development"] impl ExactSizeIterator for Range {} /// A range which is only bounded below. @@ -1031,6 +1034,7 @@ pub struct RangeFrom { pub start: Idx, } +#[unstable = "API still in development"] impl Iterator for RangeFrom { type Item = Idx; diff --git a/src/libcore/option.rs b/src/libcore/option.rs index a9a1857ec97..39d0f024d4d 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -807,6 +807,7 @@ impl ExactSizeIterator for Item {} #[stable] pub struct Iter<'a, A: 'a> { inner: Item<&'a A> } +#[stable] impl<'a, A> Iterator for Iter<'a, A> { type Item = &'a A; @@ -816,11 +817,13 @@ impl<'a, A> Iterator for Iter<'a, A> { fn size_hint(&self) -> (uint, Option) { self.inner.size_hint() } } +#[stable] impl<'a, A> DoubleEndedIterator for Iter<'a, A> { #[inline] fn next_back(&mut self) -> Option<&'a A> { self.inner.next_back() } } +#[stable] impl<'a, A> ExactSizeIterator for Iter<'a, A> {} #[stable] @@ -834,6 +837,7 @@ impl<'a, A> Clone for Iter<'a, A> { #[stable] pub struct IterMut<'a, A: 'a> { inner: Item<&'a mut A> } +#[stable] impl<'a, A> Iterator for IterMut<'a, A> { type Item = &'a mut A; @@ -843,17 +847,20 @@ impl<'a, A> Iterator for IterMut<'a, A> { fn size_hint(&self) -> (uint, Option) { self.inner.size_hint() } } +#[stable] impl<'a, A> DoubleEndedIterator for IterMut<'a, A> { #[inline] fn next_back(&mut self) -> Option<&'a mut A> { self.inner.next_back() } } +#[stable] impl<'a, A> ExactSizeIterator for IterMut<'a, A> {} /// An iterator over the item contained inside an Option. #[stable] pub struct IntoIter { inner: Item } +#[stable] impl Iterator for IntoIter { type Item = A; @@ -863,11 +870,13 @@ impl Iterator for IntoIter { fn size_hint(&self) -> (uint, Option) { self.inner.size_hint() } } +#[stable] impl DoubleEndedIterator for IntoIter { #[inline] fn next_back(&mut self) -> Option { self.inner.next_back() } } +#[stable] impl ExactSizeIterator for IntoIter {} ///////////////////////////////////////////////////////////////////////////// diff --git a/src/libcore/prelude.rs b/src/libcore/prelude.rs index d4aca1bb73c..e88cb73c8a9 100644 --- a/src/libcore/prelude.rs +++ b/src/libcore/prelude.rs @@ -43,8 +43,7 @@ pub use clone::Clone; pub use cmp::{PartialEq, PartialOrd, Eq, Ord}; pub use iter::{Extend, IteratorExt}; pub use iter::{Iterator, DoubleEndedIterator}; -pub use iter::{IteratorCloneExt, CloneIteratorExt}; -pub use iter::{IteratorOrdExt, ExactSizeIterator}; +pub use iter::{ExactSizeIterator}; pub use option::Option::{self, Some, None}; pub use ptr::{PtrExt, MutPtrExt}; pub use result::Result::{self, Ok, Err}; diff --git a/src/libcore/result.rs b/src/libcore/result.rs index 7135faaa765..7293ed6455b 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -807,6 +807,7 @@ impl AsSlice for Result { #[stable] pub struct Iter<'a, T: 'a> { inner: Option<&'a T> } +#[stable] impl<'a, T> Iterator for Iter<'a, T> { type Item = &'a T; @@ -819,11 +820,13 @@ impl<'a, T> Iterator for Iter<'a, T> { } } +#[stable] impl<'a, T> DoubleEndedIterator for Iter<'a, T> { #[inline] fn next_back(&mut self) -> Option<&'a T> { self.inner.take() } } +#[stable] impl<'a, T> ExactSizeIterator for Iter<'a, T> {} impl<'a, T> Clone for Iter<'a, T> { @@ -834,6 +837,7 @@ impl<'a, T> Clone for Iter<'a, T> { #[stable] pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> } +#[stable] impl<'a, T> Iterator for IterMut<'a, T> { type Item = &'a mut T; @@ -846,17 +850,20 @@ impl<'a, T> Iterator for IterMut<'a, T> { } } +#[stable] impl<'a, T> DoubleEndedIterator for IterMut<'a, T> { #[inline] fn next_back(&mut self) -> Option<&'a mut T> { self.inner.take() } } +#[stable] impl<'a, T> ExactSizeIterator for IterMut<'a, T> {} /// An iterator over the value in a `Ok` variant of a `Result`. #[stable] pub struct IntoIter { inner: Option } +#[stable] impl Iterator for IntoIter { type Item = T; @@ -869,11 +876,13 @@ impl Iterator for IntoIter { } } +#[stable] impl DoubleEndedIterator for IntoIter { #[inline] fn next_back(&mut self) -> Option { self.inner.take() } } +#[stable] impl ExactSizeIterator for IntoIter {} ///////////////////////////////////////////////////////////////////////////// diff --git a/src/libcore/slice.rs b/src/libcore/slice.rs index 8174596e65e..7161bfdcd5a 100644 --- a/src/libcore/slice.rs +++ b/src/libcore/slice.rs @@ -672,7 +672,7 @@ impl<'a, T> Default for &'a [T] { // The shared definition of the `Iter` and `IterMut` iterators macro_rules! iterator { (struct $name:ident -> $ptr:ty, $elem:ty) => { - #[experimental = "needs review"] + #[stable] impl<'a, T> Iterator for $name<'a, T> { type Item = $elem; @@ -710,7 +710,7 @@ macro_rules! iterator { } } - #[experimental = "needs review"] + #[stable] impl<'a, T> DoubleEndedIterator for $name<'a, T> { #[inline] fn next_back(&mut self) -> Option<$elem> { @@ -793,7 +793,7 @@ impl<'a,T> Copy for Iter<'a,T> {} iterator!{struct Iter -> *const T, &'a T} -#[experimental = "needs review"] +#[stable] impl<'a, T> ExactSizeIterator for Iter<'a, T> {} #[stable] @@ -801,7 +801,7 @@ impl<'a, T> Clone for Iter<'a, T> { fn clone(&self) -> Iter<'a, T> { *self } } -#[experimental = "needs review"] +#[experimental = "trait is experimental"] impl<'a, T> RandomAccessIterator for Iter<'a, T> { #[inline] fn indexable(&self) -> uint { @@ -887,7 +887,7 @@ impl<'a, T> IterMut<'a, T> { iterator!{struct IterMut -> *mut T, &'a mut T} -#[experimental = "needs review"] +#[stable] impl<'a, T> ExactSizeIterator for IterMut<'a, T> {} /// An internal abstraction over the splitting iterators, so that @@ -919,7 +919,7 @@ impl<'a, T, P> Clone for Split<'a, T, P> where P: Clone + FnMut(&T) -> bool { } } -#[experimental = "needs review"] +#[stable] impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool { type Item = &'a [T]; @@ -947,7 +947,7 @@ impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool { } } -#[experimental = "needs review"] +#[stable] impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool { #[inline] fn next_back(&mut self) -> Option<&'a [T]> { @@ -992,7 +992,7 @@ impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool { } } -#[experimental = "needs review"] +#[stable] impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool { type Item = &'a mut [T]; @@ -1027,7 +1027,7 @@ impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool { } } -#[experimental = "needs review"] +#[stable] impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool, { @@ -1060,7 +1060,6 @@ struct GenericSplitN { invert: bool } -#[experimental = "needs review"] impl> Iterator for GenericSplitN { type Item = T; @@ -1113,6 +1112,7 @@ pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool { macro_rules! forward_iterator { ($name:ident: $elem:ident, $iter_of:ty) => { + #[stable] impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where P: FnMut(&T) -> bool { @@ -1144,6 +1144,7 @@ pub struct Windows<'a, T:'a> { size: uint } +#[stable] impl<'a, T> Iterator for Windows<'a, T> { type Item = &'a [T]; @@ -1181,7 +1182,7 @@ pub struct Chunks<'a, T:'a> { size: uint } -#[experimental = "needs review"] +#[stable] impl<'a, T> Iterator for Chunks<'a, T> { type Item = &'a [T]; @@ -1210,7 +1211,7 @@ impl<'a, T> Iterator for Chunks<'a, T> { } } -#[experimental = "needs review"] +#[stable] impl<'a, T> DoubleEndedIterator for Chunks<'a, T> { #[inline] fn next_back(&mut self) -> Option<&'a [T]> { @@ -1226,7 +1227,7 @@ impl<'a, T> DoubleEndedIterator for Chunks<'a, T> { } } -#[experimental = "needs review"] +#[experimental = "trait is experimental"] impl<'a, T> RandomAccessIterator for Chunks<'a, T> { #[inline] fn indexable(&self) -> uint { @@ -1256,7 +1257,7 @@ pub struct ChunksMut<'a, T:'a> { chunk_size: uint } -#[experimental = "needs review"] +#[stable] impl<'a, T> Iterator for ChunksMut<'a, T> { type Item = &'a mut [T]; @@ -1286,7 +1287,7 @@ impl<'a, T> Iterator for ChunksMut<'a, T> { } } -#[experimental = "needs review"] +#[stable] impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> { #[inline] fn next_back(&mut self) -> Option<&'a mut [T]> { diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index d069744f8da..a3c6a3fe470 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -37,11 +37,8 @@ use uint; macro_rules! delegate_iter { (exact $te:ty in $ti:ty) => { delegate_iter!{$te in $ti} + #[stable] impl<'a> ExactSizeIterator for $ti { - #[inline] - fn rposition

(&mut self, predicate: P) -> Option where P: FnMut($te) -> bool{ - self.0.rposition(predicate) - } #[inline] fn len(&self) -> uint { self.0.len() @@ -49,6 +46,7 @@ macro_rules! delegate_iter { } }; ($te:ty in $ti:ty) => { + #[stable] impl<'a> Iterator for $ti { type Item = $te; @@ -61,6 +59,7 @@ macro_rules! delegate_iter { self.0.size_hint() } } + #[stable] impl<'a> DoubleEndedIterator for $ti { #[inline] fn next_back(&mut self) -> Option<$te> { @@ -69,6 +68,7 @@ macro_rules! delegate_iter { } }; (pattern $te:ty in $ti:ty) => { + #[stable] impl<'a, P: CharEq> Iterator for $ti { type Item = $te; @@ -81,6 +81,7 @@ macro_rules! delegate_iter { self.0.size_hint() } } + #[stable] impl<'a, P: CharEq> DoubleEndedIterator for $ti { #[inline] fn next_back(&mut self) -> Option<$te> { @@ -89,6 +90,7 @@ macro_rules! delegate_iter { } }; (pattern forward $te:ty in $ti:ty) => { + #[stable] impl<'a, P: CharEq> Iterator for $ti { type Item = $te; @@ -275,6 +277,7 @@ fn unwrap_or_0(opt: Option<&u8>) -> u8 { } } +#[stable] impl<'a> Iterator for Chars<'a> { type Item = char; @@ -320,6 +323,7 @@ impl<'a> Iterator for Chars<'a> { } } +#[stable] impl<'a> DoubleEndedIterator for Chars<'a> { #[inline] fn next_back(&mut self) -> Option { @@ -356,11 +360,13 @@ impl<'a> DoubleEndedIterator for Chars<'a> { /// External iterator for a string's characters and their byte offsets. /// Use with the `std::iter` module. #[derive(Clone)] +#[stable] pub struct CharIndices<'a> { front_offset: uint, iter: Chars<'a>, } +#[stable] impl<'a> Iterator for CharIndices<'a> { type Item = (uint, char); @@ -384,6 +390,7 @@ impl<'a> Iterator for CharIndices<'a> { } } +#[stable] impl<'a> DoubleEndedIterator for CharIndices<'a> { #[inline] fn next_back(&mut self) -> Option<(uint, char)> { @@ -465,6 +472,7 @@ impl<'a, Sep> CharSplits<'a, Sep> { } } +#[stable] impl<'a, Sep: CharEq> Iterator for CharSplits<'a, Sep> { type Item = &'a str; @@ -499,6 +507,7 @@ impl<'a, Sep: CharEq> Iterator for CharSplits<'a, Sep> { } } +#[stable] impl<'a, Sep: CharEq> DoubleEndedIterator for CharSplits<'a, Sep> { #[inline] fn next_back(&mut self) -> Option<&'a str> { @@ -540,6 +549,7 @@ impl<'a, Sep: CharEq> DoubleEndedIterator for CharSplits<'a, Sep> { } } +#[stable] impl<'a, Sep: CharEq> Iterator for CharSplitsN<'a, Sep> { type Item = &'a str; @@ -865,6 +875,7 @@ pub struct SplitStr<'a> { finished: bool } +#[stable] impl<'a> Iterator for MatchIndices<'a> { type Item = (uint, uint); @@ -881,6 +892,7 @@ impl<'a> Iterator for MatchIndices<'a> { } } +#[stable] impl<'a> Iterator for SplitStr<'a> { type Item = &'a str; @@ -1586,6 +1598,7 @@ impl<'a> Default for &'a str { fn default() -> &'a str { "" } } +#[stable] impl<'a> Iterator for Lines<'a> { type Item = &'a str; @@ -1593,11 +1606,13 @@ impl<'a> Iterator for Lines<'a> { fn next(&mut self) -> Option<&'a str> { self.inner.next() } #[inline] fn size_hint(&self) -> (uint, Option) { self.inner.size_hint() } -} + +#[stable]} impl<'a> DoubleEndedIterator for Lines<'a> { #[inline] fn next_back(&mut self) -> Option<&'a str> { self.inner.next_back() } -} + +#[stable]} impl<'a> Iterator for LinesAny<'a> { type Item = &'a str; @@ -1605,7 +1620,8 @@ impl<'a> Iterator for LinesAny<'a> { fn next(&mut self) -> Option<&'a str> { self.inner.next() } #[inline] fn size_hint(&self) -> (uint, Option) { self.inner.size_hint() } -} + +#[stable]} impl<'a> DoubleEndedIterator for LinesAny<'a> { #[inline] fn next_back(&mut self) -> Option<&'a str> { self.inner.next_back() } diff --git a/src/libstd/collections/hash/set.rs b/src/libstd/collections/hash/set.rs index b1824db93aa..c44d6c34cd9 100644 --- a/src/libstd/collections/hash/set.rs +++ b/src/libstd/collections/hash/set.rs @@ -18,7 +18,7 @@ use default::Default; use fmt::Show; use fmt; use hash::{Hash, Hasher, RandomSipHasher}; -use iter::{Iterator, IteratorExt, IteratorCloneExt, FromIterator, Map, Chain, Extend}; +use iter::{Iterator, IteratorExt, FromIterator, Map, Chain, Extend}; use ops::{BitOr, BitAnd, BitXor, Sub}; use option::Option::{Some, None, self}; use result::Result::{Ok, Err}; diff --git a/src/libstd/io/buffered.rs b/src/libstd/io/buffered.rs index c56acd38e81..c4e37264e2a 100644 --- a/src/libstd/io/buffered.rs +++ b/src/libstd/io/buffered.rs @@ -14,7 +14,7 @@ use cmp; use io::{Reader, Writer, Stream, Buffer, DEFAULT_BUF_SIZE, IoResult}; -use iter::ExactSizeIterator; +use iter::{IteratorExt, ExactSizeIterator}; use ops::Drop; use option::Option; use option::Option::{Some, None}; diff --git a/src/libstd/prelude/v1.rs b/src/libstd/prelude/v1.rs index f6bdcd53dff..9e9a483e1a5 100644 --- a/src/libstd/prelude/v1.rs +++ b/src/libstd/prelude/v1.rs @@ -25,11 +25,9 @@ #[stable] #[doc(no_inline)] pub use char::CharExt; #[stable] #[doc(no_inline)] pub use clone::Clone; #[stable] #[doc(no_inline)] pub use cmp::{PartialEq, PartialOrd, Eq, Ord}; -#[stable] #[doc(no_inline)] pub use iter::CloneIteratorExt; #[stable] #[doc(no_inline)] pub use iter::DoubleEndedIterator; #[stable] #[doc(no_inline)] pub use iter::ExactSizeIterator; #[stable] #[doc(no_inline)] pub use iter::{Iterator, IteratorExt, Extend}; -#[stable] #[doc(no_inline)] pub use iter::{IteratorCloneExt, IteratorOrdExt}; #[stable] #[doc(no_inline)] pub use option::Option::{self, Some, None}; #[stable] #[doc(no_inline)] pub use ptr::{PtrExt, MutPtrExt}; #[stable] #[doc(no_inline)] pub use result::Result::{self, Ok, Err}; diff --git a/src/libstd/sync/condvar.rs b/src/libstd/sync/condvar.rs index 7734f655ed2..e97be51fdbc 100644 --- a/src/libstd/sync/condvar.rs +++ b/src/libstd/sync/condvar.rs @@ -188,6 +188,7 @@ impl Condvar { pub fn notify_all(&self) { unsafe { self.inner.inner.notify_all() } } } +#[stable] impl Drop for Condvar { fn drop(&mut self) { unsafe { self.inner.inner.destroy() } diff --git a/src/libstd/sync/mpsc/mod.rs b/src/libstd/sync/mpsc/mod.rs index 6bc3f561bb3..09ff8f440f3 100644 --- a/src/libstd/sync/mpsc/mod.rs +++ b/src/libstd/sync/mpsc/mod.rs @@ -657,6 +657,7 @@ impl Clone for Sender { } #[unsafe_destructor] +#[stable] impl Drop for Sender { fn drop(&mut self) { match *unsafe { self.inner_mut() } { @@ -720,6 +721,7 @@ impl Clone for SyncSender { } #[unsafe_destructor] +#[stable] impl Drop for SyncSender { fn drop(&mut self) { unsafe { (*self.inner.get()).drop_chan(); } @@ -935,7 +937,7 @@ impl select::Packet for Receiver { } } -#[unstable] +#[stable] impl<'a, T: Send> Iterator for Iter<'a, T> { type Item = T; @@ -943,6 +945,7 @@ impl<'a, T: Send> Iterator for Iter<'a, T> { } #[unsafe_destructor] +#[stable] impl Drop for Receiver { fn drop(&mut self) { match *unsafe { self.inner_mut() } { diff --git a/src/libstd/sync/mpsc/mpsc_queue.rs b/src/libstd/sync/mpsc/mpsc_queue.rs index 8f85dc6e043..9ad24a5a11e 100644 --- a/src/libstd/sync/mpsc/mpsc_queue.rs +++ b/src/libstd/sync/mpsc/mpsc_queue.rs @@ -138,6 +138,7 @@ impl Queue { } #[unsafe_destructor] +#[stable] impl Drop for Queue { fn drop(&mut self) { unsafe { diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs index b158bd69c7b..6b3dd89f33b 100644 --- a/src/libstd/sync/mutex.rs +++ b/src/libstd/sync/mutex.rs @@ -228,6 +228,7 @@ impl Mutex { } #[unsafe_destructor] +#[stable] impl Drop for Mutex { fn drop(&mut self) { // This is actually safe b/c we know that there is no further usage of @@ -291,6 +292,7 @@ impl<'mutex, T> MutexGuard<'mutex, T> { } } +#[stable] impl<'mutex, T> Deref for MutexGuard<'mutex, T> { type Target = T; @@ -298,6 +300,7 @@ impl<'mutex, T> Deref for MutexGuard<'mutex, T> { unsafe { &*self.__data.get() } } } +#[stable] impl<'mutex, T> DerefMut for MutexGuard<'mutex, T> { fn deref_mut<'a>(&'a mut self) -> &'a mut T { unsafe { &mut *self.__data.get() } @@ -305,6 +308,7 @@ impl<'mutex, T> DerefMut for MutexGuard<'mutex, T> { } #[unsafe_destructor] +#[stable] impl<'a, T> Drop for MutexGuard<'a, T> { #[inline] fn drop(&mut self) { diff --git a/src/libstd/sync/rwlock.rs b/src/libstd/sync/rwlock.rs index b2367ff8352..c8ca1b02aab 100644 --- a/src/libstd/sync/rwlock.rs +++ b/src/libstd/sync/rwlock.rs @@ -228,6 +228,7 @@ impl RWLock { } #[unsafe_destructor] +#[stable] impl Drop for RWLock { fn drop(&mut self) { unsafe { self.inner.lock.destroy() } @@ -327,16 +328,19 @@ impl<'rwlock, T> RWLockWriteGuard<'rwlock, T> { } } +#[stable] impl<'rwlock, T> Deref for RWLockReadGuard<'rwlock, T> { type Target = T; fn deref(&self) -> &T { unsafe { &*self.__data.get() } } } +#[stable] impl<'rwlock, T> Deref for RWLockWriteGuard<'rwlock, T> { type Target = T; fn deref(&self) -> &T { unsafe { &*self.__data.get() } } } +#[stable] impl<'rwlock, T> DerefMut for RWLockWriteGuard<'rwlock, T> { fn deref_mut(&mut self) -> &mut T { unsafe { &mut *self.__data.get() } @@ -344,6 +348,7 @@ impl<'rwlock, T> DerefMut for RWLockWriteGuard<'rwlock, T> { } #[unsafe_destructor] +#[stable] impl<'a, T> Drop for RWLockReadGuard<'a, T> { fn drop(&mut self) { unsafe { self.__lock.lock.read_unlock(); } @@ -351,6 +356,7 @@ impl<'a, T> Drop for RWLockReadGuard<'a, T> { } #[unsafe_destructor] +#[stable] impl<'a, T> Drop for RWLockWriteGuard<'a, T> { fn drop(&mut self) { self.__lock.poison.done(&self.__poison); diff --git a/src/libstd/sync/semaphore.rs b/src/libstd/sync/semaphore.rs index c0ff674ba0f..505819fbf8a 100644 --- a/src/libstd/sync/semaphore.rs +++ b/src/libstd/sync/semaphore.rs @@ -99,6 +99,7 @@ impl Semaphore { } #[unsafe_destructor] +#[stable] impl<'a> Drop for SemaphoreGuard<'a> { fn drop(&mut self) { self.sem.release(); diff --git a/src/libstd/thread.rs b/src/libstd/thread.rs index 63112327415..cc82d38ae2a 100644 --- a/src/libstd/thread.rs +++ b/src/libstd/thread.rs @@ -423,6 +423,7 @@ impl JoinGuard { } #[unsafe_destructor] +#[stable] impl Drop for JoinGuard { fn drop(&mut self) { if !self.joined { -- cgit 1.4.1-3-g733a5 From f031671c6ea79391eeb3e1ad8f06fe0e436103fb Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Fri, 2 Jan 2015 12:21:00 -0500 Subject: Remove i suffix in docs --- src/liballoc/arc.rs | 52 +- src/liballoc/rc.rs | 54 +- src/libcollections/binary_heap.rs | 22 +- src/libcollections/btree/set.rs | 20 +- src/libcollections/dlist.rs | 10 +- src/libcollections/ring_buf.rs | 72 +- src/libcollections/slice.rs | 800 +++++++++++--------- src/libcollections/vec.rs | 58 +- src/libcore/atomic.rs | 18 +- src/libcore/fmt/num.rs | 2 +- src/libcore/iter.rs | 78 +- src/libcore/mem.rs | 8 +- src/libcore/num/mod.rs | 2 +- src/libcore/option.rs | 12 +- src/liblog/macros.rs | 4 +- src/librand/lib.rs | 4 +- src/libstd/collections/hash/set.rs | 28 +- src/libstd/macros.rs | 20 +- src/libstd/sync/mpsc/mod.rs | 1420 ++++++++++++++++++------------------ src/libstd/sync/rwlock.rs | 2 +- 20 files changed, 1392 insertions(+), 1294 deletions(-) (limited to 'src/libstd/sync') diff --git a/src/liballoc/arc.rs b/src/liballoc/arc.rs index 88f02d6573e..080d34dbda5 100644 --- a/src/liballoc/arc.rs +++ b/src/liballoc/arc.rs @@ -35,7 +35,7 @@ //! use std::sync::Arc; //! use std::thread::Thread; //! -//! let five = Arc::new(5i); +//! let five = Arc::new(5); //! //! for i in range(0u, 10) { //! let five = five.clone(); @@ -52,7 +52,7 @@ //! use std::sync::{Arc, Mutex}; //! use std::thread::Thread; //! -//! let five = Arc::new(Mutex::new(5i)); +//! let five = Arc::new(Mutex::new(5)); //! //! for _ in range(0u, 10) { //! let five = five.clone(); @@ -154,7 +154,7 @@ impl Arc { /// ``` /// use std::sync::Arc; /// - /// let five = Arc::new(5i); + /// let five = Arc::new(5); /// ``` #[inline] #[stable] @@ -176,7 +176,7 @@ impl Arc { /// ``` /// use std::sync::Arc; /// - /// let five = Arc::new(5i); + /// let five = Arc::new(5); /// /// let weak_five = five.downgrade(); /// ``` @@ -220,7 +220,7 @@ impl Clone for Arc { /// ``` /// use std::sync::Arc; /// - /// let five = Arc::new(5i); + /// let five = Arc::new(5); /// /// five.clone(); /// ``` @@ -267,7 +267,7 @@ impl Arc { /// ``` /// use std::sync::Arc; /// - /// let mut five = Arc::new(5i); + /// let mut five = Arc::new(5); /// /// let mut_five = five.make_unique(); /// ``` @@ -303,14 +303,14 @@ impl Drop for Arc { /// use std::sync::Arc; /// /// { - /// let five = Arc::new(5i); + /// let five = Arc::new(5); /// /// // stuff /// /// drop(five); // explict drop /// } /// { - /// let five = Arc::new(5i); + /// let five = Arc::new(5); /// /// // stuff /// @@ -369,7 +369,7 @@ impl Weak { /// ``` /// use std::sync::Arc; /// - /// let five = Arc::new(5i); + /// let five = Arc::new(5); /// /// let weak_five = five.downgrade(); /// @@ -405,7 +405,7 @@ impl Clone for Weak { /// ``` /// use std::sync::Arc; /// - /// let weak_five = Arc::new(5i).downgrade(); + /// let weak_five = Arc::new(5).downgrade(); /// /// weak_five.clone(); /// ``` @@ -430,7 +430,7 @@ impl Drop for Weak { /// use std::sync::Arc; /// /// { - /// let five = Arc::new(5i); + /// let five = Arc::new(5); /// let weak_five = five.downgrade(); /// /// // stuff @@ -438,7 +438,7 @@ impl Drop for Weak { /// drop(weak_five); // explict drop /// } /// { - /// let five = Arc::new(5i); + /// let five = Arc::new(5); /// let weak_five = five.downgrade(); /// /// // stuff @@ -472,9 +472,9 @@ impl PartialEq for Arc { /// ``` /// use std::sync::Arc; /// - /// let five = Arc::new(5i); + /// let five = Arc::new(5); /// - /// five == Arc::new(5i); + /// five == Arc::new(5); /// ``` fn eq(&self, other: &Arc) -> bool { *(*self) == *(*other) } @@ -487,9 +487,9 @@ impl PartialEq for Arc { /// ``` /// use std::sync::Arc; /// - /// let five = Arc::new(5i); + /// let five = Arc::new(5); /// - /// five != Arc::new(5i); + /// five != Arc::new(5); /// ``` fn ne(&self, other: &Arc) -> bool { *(*self) != *(*other) } } @@ -504,9 +504,9 @@ impl PartialOrd for Arc { /// ``` /// use std::sync::Arc; /// - /// let five = Arc::new(5i); + /// let five = Arc::new(5); /// - /// five.partial_cmp(&Arc::new(5i)); + /// five.partial_cmp(&Arc::new(5)); /// ``` fn partial_cmp(&self, other: &Arc) -> Option { (**self).partial_cmp(&**other) @@ -521,9 +521,9 @@ impl PartialOrd for Arc { /// ``` /// use std::sync::Arc; /// - /// let five = Arc::new(5i); + /// let five = Arc::new(5); /// - /// five < Arc::new(5i); + /// five < Arc::new(5); /// ``` fn lt(&self, other: &Arc) -> bool { *(*self) < *(*other) } @@ -536,9 +536,9 @@ impl PartialOrd for Arc { /// ``` /// use std::sync::Arc; /// - /// let five = Arc::new(5i); + /// let five = Arc::new(5); /// - /// five <= Arc::new(5i); + /// five <= Arc::new(5); /// ``` fn le(&self, other: &Arc) -> bool { *(*self) <= *(*other) } @@ -551,9 +551,9 @@ impl PartialOrd for Arc { /// ``` /// use std::sync::Arc; /// - /// let five = Arc::new(5i); + /// let five = Arc::new(5); /// - /// five > Arc::new(5i); + /// five > Arc::new(5); /// ``` fn gt(&self, other: &Arc) -> bool { *(*self) > *(*other) } @@ -566,9 +566,9 @@ impl PartialOrd for Arc { /// ``` /// use std::sync::Arc; /// - /// let five = Arc::new(5i); + /// let five = Arc::new(5); /// - /// five >= Arc::new(5i); + /// five >= Arc::new(5); /// ``` fn ge(&self, other: &Arc) -> bool { *(*self) >= *(*other) } } diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index c4b455aff5c..d9239e93a07 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -187,7 +187,7 @@ impl Rc { /// ``` /// use std::rc::Rc; /// - /// let five = Rc::new(5i); + /// let five = Rc::new(5); /// ``` #[stable] pub fn new(value: T) -> Rc { @@ -214,7 +214,7 @@ impl Rc { /// ``` /// use std::rc::Rc; /// - /// let five = Rc::new(5i); + /// let five = Rc::new(5); /// /// let weak_five = five.downgrade(); /// ``` @@ -247,7 +247,7 @@ pub fn strong_count(this: &Rc) -> uint { this.strong() } /// use std::rc; /// use std::rc::Rc; /// -/// let five = Rc::new(5i); +/// let five = Rc::new(5); /// /// rc::is_unique(&five); /// ``` @@ -329,7 +329,7 @@ impl Rc { /// ``` /// use std::rc::Rc; /// - /// let mut five = Rc::new(5i); + /// let mut five = Rc::new(5); /// /// let mut_five = five.make_unique(); /// ``` @@ -378,14 +378,14 @@ impl Drop for Rc { /// use std::rc::Rc; /// /// { - /// let five = Rc::new(5i); + /// let five = Rc::new(5); /// /// // stuff /// /// drop(five); // explict drop /// } /// { - /// let five = Rc::new(5i); + /// let five = Rc::new(5); /// /// // stuff /// @@ -424,7 +424,7 @@ impl Clone for Rc { /// ``` /// use std::rc::Rc; /// - /// let five = Rc::new(5i); + /// let five = Rc::new(5); /// /// five.clone(); /// ``` @@ -465,9 +465,9 @@ impl PartialEq for Rc { /// ``` /// use std::rc::Rc; /// - /// let five = Rc::new(5i); + /// let five = Rc::new(5); /// - /// five == Rc::new(5i); + /// five == Rc::new(5); /// ``` #[inline(always)] fn eq(&self, other: &Rc) -> bool { **self == **other } @@ -481,9 +481,9 @@ impl PartialEq for Rc { /// ``` /// use std::rc::Rc; /// - /// let five = Rc::new(5i); + /// let five = Rc::new(5); /// - /// five != Rc::new(5i); + /// five != Rc::new(5); /// ``` #[inline(always)] fn ne(&self, other: &Rc) -> bool { **self != **other } @@ -503,9 +503,9 @@ impl PartialOrd for Rc { /// ``` /// use std::rc::Rc; /// - /// let five = Rc::new(5i); + /// let five = Rc::new(5); /// - /// five.partial_cmp(&Rc::new(5i)); + /// five.partial_cmp(&Rc::new(5)); /// ``` #[inline(always)] fn partial_cmp(&self, other: &Rc) -> Option { @@ -521,9 +521,9 @@ impl PartialOrd for Rc { /// ``` /// use std::rc::Rc; /// - /// let five = Rc::new(5i); + /// let five = Rc::new(5); /// - /// five < Rc::new(5i); + /// five < Rc::new(5); /// ``` #[inline(always)] fn lt(&self, other: &Rc) -> bool { **self < **other } @@ -537,9 +537,9 @@ impl PartialOrd for Rc { /// ``` /// use std::rc::Rc; /// - /// let five = Rc::new(5i); + /// let five = Rc::new(5); /// - /// five <= Rc::new(5i); + /// five <= Rc::new(5); /// ``` #[inline(always)] fn le(&self, other: &Rc) -> bool { **self <= **other } @@ -553,9 +553,9 @@ impl PartialOrd for Rc { /// ``` /// use std::rc::Rc; /// - /// let five = Rc::new(5i); + /// let five = Rc::new(5); /// - /// five > Rc::new(5i); + /// five > Rc::new(5); /// ``` #[inline(always)] fn gt(&self, other: &Rc) -> bool { **self > **other } @@ -569,9 +569,9 @@ impl PartialOrd for Rc { /// ``` /// use std::rc::Rc; /// - /// let five = Rc::new(5i); + /// let five = Rc::new(5); /// - /// five >= Rc::new(5i); + /// five >= Rc::new(5); /// ``` #[inline(always)] fn ge(&self, other: &Rc) -> bool { **self >= **other } @@ -588,9 +588,9 @@ impl Ord for Rc { /// ``` /// use std::rc::Rc; /// - /// let five = Rc::new(5i); + /// let five = Rc::new(5); /// - /// five.partial_cmp(&Rc::new(5i)); + /// five.partial_cmp(&Rc::new(5)); /// ``` #[inline] fn cmp(&self, other: &Rc) -> Ordering { (**self).cmp(&**other) } @@ -639,7 +639,7 @@ impl Weak { /// ``` /// use std::rc::Rc; /// - /// let five = Rc::new(5i); + /// let five = Rc::new(5); /// /// let weak_five = five.downgrade(); /// @@ -668,7 +668,7 @@ impl Drop for Weak { /// use std::rc::Rc; /// /// { - /// let five = Rc::new(5i); + /// let five = Rc::new(5); /// let weak_five = five.downgrade(); /// /// // stuff @@ -676,7 +676,7 @@ impl Drop for Weak { /// drop(weak_five); // explict drop /// } /// { - /// let five = Rc::new(5i); + /// let five = Rc::new(5); /// let weak_five = five.downgrade(); /// /// // stuff @@ -710,7 +710,7 @@ impl Clone for Weak { /// ``` /// use std::rc::Rc; /// - /// let weak_five = Rc::new(5i).downgrade(); + /// let weak_five = Rc::new(5).downgrade(); /// /// weak_five.clone(); /// ``` diff --git a/src/libcollections/binary_heap.rs b/src/libcollections/binary_heap.rs index 4a550e5ce27..82002f16133 100644 --- a/src/libcollections/binary_heap.rs +++ b/src/libcollections/binary_heap.rs @@ -211,7 +211,7 @@ impl BinaryHeap { /// /// ``` /// use std::collections::BinaryHeap; - /// let heap = BinaryHeap::from_vec(vec![9i, 1, 2, 7, 3, 2]); + /// let heap = BinaryHeap::from_vec(vec![9, 1, 2, 7, 3, 2]); /// ``` pub fn from_vec(vec: Vec) -> BinaryHeap { let mut heap = BinaryHeap { data: vec }; @@ -230,7 +230,7 @@ impl BinaryHeap { /// /// ``` /// use std::collections::BinaryHeap; - /// let heap = BinaryHeap::from_vec(vec![1i, 2, 3, 4]); + /// let heap = BinaryHeap::from_vec(vec![1, 2, 3, 4]); /// /// // Print 1, 2, 3, 4 in arbitrary order /// for x in heap.iter() { @@ -250,7 +250,7 @@ impl BinaryHeap { /// /// ``` /// use std::collections::BinaryHeap; - /// let heap = BinaryHeap::from_vec(vec![1i, 2, 3, 4]); + /// let heap = BinaryHeap::from_vec(vec![1, 2, 3, 4]); /// /// // Print 1, 2, 3, 4 in arbitrary order /// for x in heap.into_iter() { @@ -272,7 +272,7 @@ impl BinaryHeap { /// let mut heap = BinaryHeap::new(); /// assert_eq!(heap.peek(), None); /// - /// heap.push(1i); + /// heap.push(1); /// heap.push(5); /// heap.push(2); /// assert_eq!(heap.peek(), Some(&5)); @@ -355,7 +355,7 @@ impl BinaryHeap { /// /// ``` /// use std::collections::BinaryHeap; - /// let mut heap = BinaryHeap::from_vec(vec![1i, 3]); + /// let mut heap = BinaryHeap::from_vec(vec![1, 3]); /// /// assert_eq!(heap.pop(), Some(3)); /// assert_eq!(heap.pop(), Some(1)); @@ -379,7 +379,7 @@ impl BinaryHeap { /// ``` /// use std::collections::BinaryHeap; /// let mut heap = BinaryHeap::new(); - /// heap.push(3i); + /// heap.push(3); /// heap.push(5); /// heap.push(1); /// @@ -401,7 +401,7 @@ impl BinaryHeap { /// ``` /// use std::collections::BinaryHeap; /// let mut heap = BinaryHeap::new(); - /// heap.push(1i); + /// heap.push(1); /// heap.push(5); /// /// assert_eq!(heap.push_pop(3), 5); @@ -433,7 +433,7 @@ impl BinaryHeap { /// use std::collections::BinaryHeap; /// let mut heap = BinaryHeap::new(); /// - /// assert_eq!(heap.replace(1i), None); + /// assert_eq!(heap.replace(1), None); /// assert_eq!(heap.replace(3), Some(1)); /// assert_eq!(heap.len(), 1); /// assert_eq!(heap.peek(), Some(&3)); @@ -456,7 +456,7 @@ impl BinaryHeap { /// /// ``` /// use std::collections::BinaryHeap; - /// let heap = BinaryHeap::from_vec(vec![1i, 2, 3, 4, 5, 6, 7]); + /// let heap = BinaryHeap::from_vec(vec![1, 2, 3, 4, 5, 6, 7]); /// let vec = heap.into_vec(); /// /// // Will print in some order @@ -474,12 +474,12 @@ impl BinaryHeap { /// ``` /// use std::collections::BinaryHeap; /// - /// let mut heap = BinaryHeap::from_vec(vec![1i, 2, 4, 5, 7]); + /// let mut heap = BinaryHeap::from_vec(vec![1, 2, 4, 5, 7]); /// heap.push(6); /// heap.push(3); /// /// let vec = heap.into_sorted_vec(); - /// assert_eq!(vec, vec![1i, 2, 3, 4, 5, 6, 7]); + /// assert_eq!(vec, vec![1, 2, 3, 4, 5, 6, 7]); /// ``` pub fn into_sorted_vec(mut self) -> Vec { let mut end = self.len(); diff --git a/src/libcollections/btree/set.rs b/src/libcollections/btree/set.rs index 0406edcdd32..80d01c07547 100644 --- a/src/libcollections/btree/set.rs +++ b/src/libcollections/btree/set.rs @@ -245,7 +245,7 @@ impl BTreeSet { /// /// let mut v = BTreeSet::new(); /// assert_eq!(v.len(), 0); - /// v.insert(1i); + /// v.insert(1); /// assert_eq!(v.len(), 1); /// ``` #[stable] @@ -260,7 +260,7 @@ impl BTreeSet { /// /// let mut v = BTreeSet::new(); /// assert!(v.is_empty()); - /// v.insert(1i); + /// v.insert(1); /// assert!(!v.is_empty()); /// ``` #[stable] @@ -274,7 +274,7 @@ impl BTreeSet { /// use std::collections::BTreeSet; /// /// let mut v = BTreeSet::new(); - /// v.insert(1i); + /// v.insert(1); /// v.clear(); /// assert!(v.is_empty()); /// ``` @@ -294,7 +294,7 @@ impl BTreeSet { /// ``` /// use std::collections::BTreeSet; /// - /// let set: BTreeSet = [1i, 2, 3].iter().map(|&x| x).collect(); + /// let set: BTreeSet = [1, 2, 3].iter().map(|&x| x).collect(); /// assert_eq!(set.contains(&1), true); /// assert_eq!(set.contains(&4), false); /// ``` @@ -311,7 +311,7 @@ impl BTreeSet { /// ``` /// use std::collections::BTreeSet; /// - /// let a: BTreeSet = [1i, 2, 3].iter().map(|&x| x).collect(); + /// let a: BTreeSet = [1, 2, 3].iter().map(|&x| x).collect(); /// let mut b: BTreeSet = BTreeSet::new(); /// /// assert_eq!(a.is_disjoint(&b), true); @@ -332,7 +332,7 @@ impl BTreeSet { /// ``` /// use std::collections::BTreeSet; /// - /// let sup: BTreeSet = [1i, 2, 3].iter().map(|&x| x).collect(); + /// let sup: BTreeSet = [1, 2, 3].iter().map(|&x| x).collect(); /// let mut set: BTreeSet = BTreeSet::new(); /// /// assert_eq!(set.is_subset(&sup), true); @@ -374,7 +374,7 @@ impl BTreeSet { /// ``` /// use std::collections::BTreeSet; /// - /// let sub: BTreeSet = [1i, 2].iter().map(|&x| x).collect(); + /// let sub: BTreeSet = [1, 2].iter().map(|&x| x).collect(); /// let mut set: BTreeSet = BTreeSet::new(); /// /// assert_eq!(set.is_superset(&sub), false); @@ -401,8 +401,8 @@ impl BTreeSet { /// /// let mut set = BTreeSet::new(); /// - /// assert_eq!(set.insert(2i), true); - /// assert_eq!(set.insert(2i), false); + /// assert_eq!(set.insert(2), true); + /// assert_eq!(set.insert(2), false); /// assert_eq!(set.len(), 1); /// ``` #[stable] @@ -424,7 +424,7 @@ impl BTreeSet { /// /// let mut set = BTreeSet::new(); /// - /// set.insert(2i); + /// set.insert(2); /// assert_eq!(set.remove(&2), true); /// assert_eq!(set.remove(&2), false); /// ``` diff --git a/src/libcollections/dlist.rs b/src/libcollections/dlist.rs index ca8e75ac43c..5aec9973c81 100644 --- a/src/libcollections/dlist.rs +++ b/src/libcollections/dlist.rs @@ -230,9 +230,9 @@ impl DList { /// /// let mut a = DList::new(); /// let mut b = DList::new(); - /// a.push_back(1i); + /// a.push_back(1); /// a.push_back(2); - /// b.push_back(3i); + /// b.push_back(3); /// b.push_back(4); /// /// a.append(b); @@ -375,7 +375,7 @@ impl DList { /// use std::collections::DList; /// /// let mut d = DList::new(); - /// d.push_back(1i); + /// d.push_back(1); /// d.push_back(3); /// assert_eq!(3, *d.back().unwrap()); /// ``` @@ -394,7 +394,7 @@ impl DList { /// /// let mut d = DList::new(); /// assert_eq!(d.pop_back(), None); - /// d.push_back(1i); + /// d.push_back(1); /// d.push_back(3); /// assert_eq!(d.pop_back(), Some(3)); /// ``` @@ -551,7 +551,7 @@ impl<'a, A> IterMut<'a, A> { /// } /// { /// let vec: Vec = list.into_iter().collect(); - /// assert_eq!(vec, vec![1i, 2, 3, 4]); + /// assert_eq!(vec, vec![1, 2, 3, 4]); /// } /// ``` #[inline] diff --git a/src/libcollections/ring_buf.rs b/src/libcollections/ring_buf.rs index e86c40bed21..721f9a4a59d 100644 --- a/src/libcollections/ring_buf.rs +++ b/src/libcollections/ring_buf.rs @@ -173,7 +173,7 @@ impl RingBuf { /// use std::collections::RingBuf; /// /// let mut buf = RingBuf::new(); - /// buf.push_back(3i); + /// buf.push_back(3); /// buf.push_back(4); /// buf.push_back(5); /// assert_eq!(buf.get(1).unwrap(), &4); @@ -196,7 +196,7 @@ impl RingBuf { /// use std::collections::RingBuf; /// /// let mut buf = RingBuf::new(); - /// buf.push_back(3i); + /// buf.push_back(3); /// buf.push_back(4); /// buf.push_back(5); /// match buf.get_mut(1) { @@ -230,7 +230,7 @@ impl RingBuf { /// use std::collections::RingBuf; /// /// let mut buf = RingBuf::new(); - /// buf.push_back(3i); + /// buf.push_back(3); /// buf.push_back(4); /// buf.push_back(5); /// buf.swap(0, 2); @@ -379,7 +379,7 @@ impl RingBuf { /// use std::collections::RingBuf; /// /// let mut buf = RingBuf::new(); - /// buf.push_back(5i); + /// buf.push_back(5); /// buf.push_back(3); /// buf.push_back(4); /// let b: &[_] = &[&5, &3, &4]; @@ -402,7 +402,7 @@ impl RingBuf { /// use std::collections::RingBuf; /// /// let mut buf = RingBuf::new(); - /// buf.push_back(5i); + /// buf.push_back(5); /// buf.push_back(3); /// buf.push_back(4); /// for num in buf.iter_mut() { @@ -481,7 +481,7 @@ impl RingBuf { /// /// let mut v = RingBuf::new(); /// assert_eq!(v.len(), 0); - /// v.push_back(1i); + /// v.push_back(1); /// assert_eq!(v.len(), 1); /// ``` #[stable] @@ -496,7 +496,7 @@ impl RingBuf { /// /// let mut v = RingBuf::new(); /// assert!(v.is_empty()); - /// v.push_front(1i); + /// v.push_front(1); /// assert!(!v.is_empty()); /// ``` #[stable] @@ -511,7 +511,7 @@ impl RingBuf { /// use std::collections::RingBuf; /// /// let mut v = RingBuf::new(); - /// v.push_back(1i); + /// v.push_back(1); /// assert_eq!(v.drain().next(), Some(1)); /// assert!(v.is_empty()); /// ``` @@ -531,7 +531,7 @@ impl RingBuf { /// use std::collections::RingBuf; /// /// let mut v = RingBuf::new(); - /// v.push_back(1i); + /// v.push_back(1); /// v.clear(); /// assert!(v.is_empty()); /// ``` @@ -552,9 +552,9 @@ impl RingBuf { /// let mut d = RingBuf::new(); /// assert_eq!(d.front(), None); /// - /// d.push_back(1i); - /// d.push_back(2i); - /// assert_eq!(d.front(), Some(&1i)); + /// d.push_back(1); + /// d.push_back(2); + /// assert_eq!(d.front(), Some(&1)); /// ``` #[stable] pub fn front(&self) -> Option<&T> { @@ -572,13 +572,13 @@ impl RingBuf { /// let mut d = RingBuf::new(); /// assert_eq!(d.front_mut(), None); /// - /// d.push_back(1i); - /// d.push_back(2i); + /// d.push_back(1); + /// d.push_back(2); /// match d.front_mut() { - /// Some(x) => *x = 9i, + /// Some(x) => *x = 9, /// None => (), /// } - /// assert_eq!(d.front(), Some(&9i)); + /// assert_eq!(d.front(), Some(&9)); /// ``` #[stable] pub fn front_mut(&mut self) -> Option<&mut T> { @@ -596,9 +596,9 @@ impl RingBuf { /// let mut d = RingBuf::new(); /// assert_eq!(d.back(), None); /// - /// d.push_back(1i); - /// d.push_back(2i); - /// assert_eq!(d.back(), Some(&2i)); + /// d.push_back(1); + /// d.push_back(2); + /// assert_eq!(d.back(), Some(&2)); /// ``` #[stable] pub fn back(&self) -> Option<&T> { @@ -616,13 +616,13 @@ impl RingBuf { /// let mut d = RingBuf::new(); /// assert_eq!(d.back(), None); /// - /// d.push_back(1i); - /// d.push_back(2i); + /// d.push_back(1); + /// d.push_back(2); /// match d.back_mut() { - /// Some(x) => *x = 9i, + /// Some(x) => *x = 9, /// None => (), /// } - /// assert_eq!(d.back(), Some(&9i)); + /// assert_eq!(d.back(), Some(&9)); /// ``` #[stable] pub fn back_mut(&mut self) -> Option<&mut T> { @@ -639,11 +639,11 @@ impl RingBuf { /// use std::collections::RingBuf; /// /// let mut d = RingBuf::new(); - /// d.push_back(1i); - /// d.push_back(2i); + /// d.push_back(1); + /// d.push_back(2); /// - /// assert_eq!(d.pop_front(), Some(1i)); - /// assert_eq!(d.pop_front(), Some(2i)); + /// assert_eq!(d.pop_front(), Some(1)); + /// assert_eq!(d.pop_front(), Some(2)); /// assert_eq!(d.pop_front(), None); /// ``` #[stable] @@ -665,9 +665,9 @@ impl RingBuf { /// use std::collections::RingBuf; /// /// let mut d = RingBuf::new(); - /// d.push_front(1i); - /// d.push_front(2i); - /// assert_eq!(d.front(), Some(&2i)); + /// d.push_front(1); + /// d.push_front(2); + /// assert_eq!(d.front(), Some(&2)); /// ``` #[stable] pub fn push_front(&mut self, t: T) { @@ -689,7 +689,7 @@ impl RingBuf { /// use std::collections::RingBuf; /// /// let mut buf = RingBuf::new(); - /// buf.push_back(1i); + /// buf.push_back(1); /// buf.push_back(3); /// assert_eq!(3, *buf.back().unwrap()); /// ``` @@ -715,7 +715,7 @@ impl RingBuf { /// /// let mut buf = RingBuf::new(); /// assert_eq!(buf.pop_back(), None); - /// buf.push_back(1i); + /// buf.push_back(1); /// buf.push_back(3); /// assert_eq!(buf.pop_back(), Some(3)); /// ``` @@ -748,7 +748,7 @@ impl RingBuf { /// use std::collections::RingBuf; /// /// let mut buf = RingBuf::new(); - /// buf.push_back(10i); + /// buf.push_back(10); /// buf.push_back(12); /// buf.insert(1,11); /// assert_eq!(Some(&11), buf.get(1)); @@ -950,9 +950,9 @@ impl RingBuf { /// use std::collections::RingBuf; /// /// let mut buf = RingBuf::new(); - /// buf.push_back(5i); - /// buf.push_back(10i); - /// buf.push_back(12i); + /// buf.push_back(5); + /// buf.push_back(10); + /// buf.push_back(12); /// buf.push_back(15); /// buf.remove(2); /// assert_eq!(Some(&15), buf.get(2)); diff --git a/src/libcollections/slice.rs b/src/libcollections/slice.rs index 3602bfc10c3..8050c44f542 100644 --- a/src/libcollections/slice.rs +++ b/src/libcollections/slice.rs @@ -15,7 +15,7 @@ //! //! ```rust //! // slicing a Vec -//! let vec = vec!(1i, 2, 3); +//! let vec = vec!(1, 2, 3); //! let int_slice = vec.as_slice(); //! // coercing an array to a slice //! let str_slice: &[&str] = &["one", "two", "three"]; @@ -26,7 +26,7 @@ //! block of memory that a mutable slice points to: //! //! ```rust -//! let x: &mut[int] = &mut [1i, 2, 3]; +//! let x: &mut[int] = &mut [1, 2, 3]; //! x[1] = 7; //! assert_eq!(x[0], 1); //! assert_eq!(x[1], 7); @@ -54,9 +54,9 @@ //! ```rust //! #![feature(slicing_syntax)] //! fn main() { -//! let numbers = [0i, 1i, 2i]; +//! let numbers = [0, 1, 2]; //! let last_numbers = numbers[1..3]; -//! // last_numbers is now &[1i, 2i] +//! // last_numbers is now &[1, 2] //! } //! ``` //! @@ -76,7 +76,7 @@ //! type of the slice is `int`, the element type of the iterator is `&int`. //! //! ```rust -//! let numbers = [0i, 1i, 2i]; +//! let numbers = [0, 1, 2]; //! for &x in numbers.iter() { //! println!("{} is a number!", x); //! } @@ -89,40 +89,40 @@ use alloc::boxed::Box; use core::borrow::{BorrowFrom, BorrowFromMut, ToOwned}; -use core::clone::Clone; -use core::cmp::Ordering::{self, Greater, Less}; -use core::cmp::{self, Ord, PartialEq}; -use core::iter::{Iterator, IteratorExt}; -use core::iter::{range, range_step, MultiplicativeIterator}; +use core::cmp; +use core::iter::{range_step, MultiplicativeIterator}; use core::kinds::Sized; use core::mem::size_of; use core::mem; -use core::ops::{FnMut, SliceMut}; -use core::option::Option::{self, Some, None}; -use core::ptr::PtrExt; +use core::ops::{FnMut,SliceMut}; +use core::prelude::{Clone, Greater, Iterator, IteratorExt, Less, None, Option}; +use core::prelude::{Ord, Ordering, PtrExt, Some, range, IteratorCloneExt, Result}; use core::ptr; -use core::result::Result; use core::slice as core_slice; use self::Direction::*; use vec::Vec; pub use core::slice::{Chunks, AsSlice, Windows}; -pub use core::slice::{Iter, IterMut}; +pub use core::slice::{Iter, IterMut, PartialEqSliceExt}; pub use core::slice::{IntSliceExt, SplitMut, ChunksMut, Split}; pub use core::slice::{SplitN, RSplitN, SplitNMut, RSplitNMut}; pub use core::slice::{bytes, mut_ref_slice, ref_slice}; pub use core::slice::{from_raw_buf, from_raw_mut_buf}; +#[deprecated = "use Iter instead"] +pub type Items<'a, T:'a> = Iter<'a, T>; + +#[deprecated = "use IterMut instead"] +pub type MutItems<'a, T:'a> = IterMut<'a, T>; + //////////////////////////////////////////////////////////////////////////////// // Basic slice extension methods //////////////////////////////////////////////////////////////////////////////// /// Allocating extension methods for slices. #[unstable = "needs associated types, may merge with other traits"] -pub trait SliceExt for Sized? { - type Item; - +pub trait SliceExt for Sized? { /// Sorts the slice, in place, using `compare` to compare /// elements. /// @@ -132,7 +132,7 @@ pub trait SliceExt for Sized? { /// # Examples /// /// ```rust - /// let mut v = [5i, 4, 1, 3, 2]; + /// let mut v = [5, 4, 1, 3, 2]; /// v.sort_by(|a, b| a.cmp(b)); /// assert!(v == [1, 2, 3, 4, 5]); /// @@ -141,7 +141,7 @@ pub trait SliceExt for Sized? { /// assert!(v == [5, 4, 3, 2, 1]); /// ``` #[stable] - fn sort_by(&mut self, compare: F) where F: FnMut(&Self::Item, &Self::Item) -> Ordering; + fn sort_by(&mut self, compare: F) where F: FnMut(&T, &T) -> Ordering; /// Consumes `src` and moves as many elements as it can into `self` /// from the range [start,end). @@ -158,14 +158,14 @@ pub trait SliceExt for Sized? { /// # Examples /// /// ```rust - /// let mut a = [1i, 2, 3, 4, 5]; - /// let b = vec![6i, 7, 8]; + /// let mut a = [1, 2, 3, 4, 5]; + /// let b = vec![6, 7, 8]; /// let num_moved = a.move_from(b, 0, 3); /// assert_eq!(num_moved, 3); - /// assert!(a == [6i, 7, 8, 4, 5]); + /// assert!(a == [6, 7, 8, 4, 5]); /// ``` #[experimental = "uncertain about this API approach"] - fn move_from(&mut self, src: Vec, start: uint, end: uint) -> uint; + fn move_from(&mut self, src: Vec, start: uint, end: uint) -> uint; /// Returns a subslice spanning the interval [`start`, `end`). /// @@ -174,7 +174,7 @@ pub trait SliceExt for Sized? { /// /// Slicing with `start` equal to `end` yields an empty slice. #[experimental = "will be replaced by slice syntax"] - fn slice(&self, start: uint, end: uint) -> &[Self::Item]; + fn slice(&self, start: uint, end: uint) -> &[T]; /// Returns a subslice from `start` to the end of the slice. /// @@ -182,7 +182,7 @@ pub trait SliceExt for Sized? { /// /// Slicing from `self.len()` yields an empty slice. #[experimental = "will be replaced by slice syntax"] - fn slice_from(&self, start: uint) -> &[Self::Item]; + fn slice_from(&self, start: uint) -> &[T]; /// Returns a subslice from the start of the slice to `end`. /// @@ -190,7 +190,7 @@ pub trait SliceExt for Sized? { /// /// Slicing to `0` yields an empty slice. #[experimental = "will be replaced by slice syntax"] - fn slice_to(&self, end: uint) -> &[Self::Item]; + fn slice_to(&self, end: uint) -> &[T]; /// Divides one slice into two at an index. /// @@ -200,32 +200,32 @@ pub trait SliceExt for Sized? { /// /// Panics if `mid > len`. #[stable] - fn split_at(&self, mid: uint) -> (&[Self::Item], &[Self::Item]); + fn split_at(&self, mid: uint) -> (&[T], &[T]); /// Returns an iterator over the slice #[stable] - fn iter(&self) -> Iter; + fn iter(&self) -> Iter; /// Returns an iterator over subslices separated by elements that match /// `pred`. The matched element is not contained in the subslices. #[stable] - fn split(&self, pred: F) -> Split - where F: FnMut(&Self::Item) -> bool; + fn split(&self, pred: F) -> Split + where F: FnMut(&T) -> bool; /// Returns an iterator over subslices separated by elements that match /// `pred`, limited to splitting at most `n` times. The matched element is /// not contained in the subslices. #[stable] - fn splitn(&self, n: uint, pred: F) -> SplitN - where F: FnMut(&Self::Item) -> bool; + fn splitn(&self, n: uint, pred: F) -> SplitN + where F: FnMut(&T) -> bool; /// Returns an iterator over subslices separated by elements that match /// `pred` limited to splitting at most `n` times. This starts at the end of /// the slice and works backwards. The matched element is not contained in /// the subslices. #[stable] - fn rsplitn(&self, n: uint, pred: F) -> RSplitN - where F: FnMut(&Self::Item) -> bool; + fn rsplitn(&self, n: uint, pred: F) -> RSplitN + where F: FnMut(&T) -> bool; /// Returns an iterator over all contiguous windows of length /// `size`. The windows overlap. If the slice is shorter than @@ -241,13 +241,13 @@ pub trait SliceExt for Sized? { /// `[3,4]`): /// /// ```rust - /// let v = &[1i, 2, 3, 4]; + /// let v = &[1, 2, 3, 4]; /// for win in v.windows(2) { /// println!("{}", win); /// } /// ``` #[stable] - fn windows(&self, size: uint) -> Windows; + fn windows(&self, size: uint) -> Windows; /// Returns an iterator over `size` elements of the slice at a /// time. The chunks do not overlap. If `size` does not divide the @@ -264,39 +264,49 @@ pub trait SliceExt for Sized? { /// `[3,4]`, `[5]`): /// /// ```rust - /// let v = &[1i, 2, 3, 4, 5]; + /// let v = &[1, 2, 3, 4, 5]; /// for win in v.chunks(2) { /// println!("{}", win); /// } /// ``` #[stable] - fn chunks(&self, size: uint) -> Chunks; + fn chunks(&self, size: uint) -> Chunks; /// Returns the element of a slice at the given index, or `None` if the /// index is out of bounds. #[stable] - fn get(&self, index: uint) -> Option<&Self::Item>; + fn get(&self, index: uint) -> Option<&T>; /// Returns the first element of a slice, or `None` if it is empty. #[stable] - fn first(&self) -> Option<&Self::Item>; + fn first(&self) -> Option<&T>; + + /// Deprecated: renamed to `first`. + #[deprecated = "renamed to `first`"] + fn head(&self) -> Option<&T> { self.first() } /// Returns all but the first element of a slice. #[experimental = "likely to be renamed"] - fn tail(&self) -> &[Self::Item]; + fn tail(&self) -> &[T]; /// Returns all but the last element of a slice. #[experimental = "likely to be renamed"] - fn init(&self) -> &[Self::Item]; + fn init(&self) -> &[T]; /// Returns the last element of a slice, or `None` if it is empty. #[stable] - fn last(&self) -> Option<&Self::Item>; + fn last(&self) -> Option<&T>; /// Returns a pointer to the element at the given index, without doing /// bounds checking. #[stable] - unsafe fn get_unchecked(&self, index: uint) -> &Self::Item; + unsafe fn get_unchecked(&self, index: uint) -> &T; + + /// Deprecated: renamed to `get_unchecked`. + #[deprecated = "renamed to get_unchecked"] + unsafe fn unsafe_get(&self, index: uint) -> &T { + self.get_unchecked(index) + } /// Returns an unsafe pointer to the slice's buffer /// @@ -306,7 +316,7 @@ pub trait SliceExt for Sized? { /// Modifying the slice may cause its buffer to be reallocated, which /// would also make any pointers to it invalid. #[stable] - fn as_ptr(&self) -> *const Self::Item; + fn as_ptr(&self) -> *const T; /// Binary search a sorted slice with a comparator function. /// @@ -327,7 +337,7 @@ pub trait SliceExt for Sized? { /// found; the fourth could match any position in `[1,4]`. /// /// ```rust - /// let s = [0i, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; + /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; /// let s = s.as_slice(); /// /// let seek = 13; @@ -342,14 +352,14 @@ pub trait SliceExt for Sized? { /// ``` #[stable] fn binary_search_by(&self, f: F) -> Result where - F: FnMut(&Self::Item) -> Ordering; + F: FnMut(&T) -> Ordering; /// Return the number of elements in the slice /// /// # Example /// /// ``` - /// let a = [1i, 2, 3]; + /// let a = [1, 2, 3]; /// assert_eq!(a.len(), 3); /// ``` #[stable] @@ -360,7 +370,7 @@ pub trait SliceExt for Sized? { /// # Example /// /// ``` - /// let a = [1i, 2, 3]; + /// let a = [1, 2, 3]; /// assert!(!a.is_empty()); /// ``` #[inline] @@ -369,12 +379,12 @@ pub trait SliceExt for Sized? { /// Returns a mutable reference to the element at the given index, /// or `None` if the index is out of bounds #[stable] - fn get_mut(&mut self, index: uint) -> Option<&mut Self::Item>; + fn get_mut(&mut self, index: uint) -> Option<&mut T>; /// Work with `self` as a mut slice. /// Primarily intended for getting a &mut [T] from a [T; N]. #[stable] - fn as_mut_slice(&mut self) -> &mut [Self::Item]; + fn as_mut_slice(&mut self) -> &mut [T]; /// Returns a mutable subslice spanning the interval [`start`, `end`). /// @@ -383,7 +393,7 @@ pub trait SliceExt for Sized? { /// /// Slicing with `start` equal to `end` yields an empty slice. #[experimental = "will be replaced by slice syntax"] - fn slice_mut(&mut self, start: uint, end: uint) -> &mut [Self::Item]; + fn slice_mut(&mut self, start: uint, end: uint) -> &mut [T]; /// Returns a mutable subslice from `start` to the end of the slice. /// @@ -391,7 +401,7 @@ pub trait SliceExt for Sized? { /// /// Slicing from `self.len()` yields an empty slice. #[experimental = "will be replaced by slice syntax"] - fn slice_from_mut(&mut self, start: uint) -> &mut [Self::Item]; + fn slice_from_mut(&mut self, start: uint) -> &mut [T]; /// Returns a mutable subslice from the start of the slice to `end`. /// @@ -399,48 +409,54 @@ pub trait SliceExt for Sized? { /// /// Slicing to `0` yields an empty slice. #[experimental = "will be replaced by slice syntax"] - fn slice_to_mut(&mut self, end: uint) -> &mut [Self::Item]; + fn slice_to_mut(&mut self, end: uint) -> &mut [T]; /// Returns an iterator that allows modifying each value #[stable] - fn iter_mut(&mut self) -> IterMut; + fn iter_mut(&mut self) -> IterMut; /// Returns a mutable pointer to the first element of a slice, or `None` if it is empty #[stable] - fn first_mut(&mut self) -> Option<&mut Self::Item>; + fn first_mut(&mut self) -> Option<&mut T>; + + /// Depreated: renamed to `first_mut`. + #[deprecated = "renamed to first_mut"] + fn head_mut(&mut self) -> Option<&mut T> { + self.first_mut() + } /// Returns all but the first element of a mutable slice #[experimental = "likely to be renamed or removed"] - fn tail_mut(&mut self) -> &mut [Self::Item]; + fn tail_mut(&mut self) -> &mut [T]; /// Returns all but the last element of a mutable slice #[experimental = "likely to be renamed or removed"] - fn init_mut(&mut self) -> &mut [Self::Item]; + fn init_mut(&mut self) -> &mut [T]; /// Returns a mutable pointer to the last item in the slice. #[stable] - fn last_mut(&mut self) -> Option<&mut Self::Item>; + fn last_mut(&mut self) -> Option<&mut T>; /// Returns an iterator over mutable subslices separated by elements that /// match `pred`. The matched element is not contained in the subslices. #[stable] - fn split_mut(&mut self, pred: F) -> SplitMut - where F: FnMut(&Self::Item) -> bool; + fn split_mut(&mut self, pred: F) -> SplitMut + where F: FnMut(&T) -> bool; /// Returns an iterator over subslices separated by elements that match /// `pred`, limited to splitting at most `n` times. The matched element is /// not contained in the subslices. #[stable] - fn splitn_mut(&mut self, n: uint, pred: F) -> SplitNMut - where F: FnMut(&Self::Item) -> bool; + fn splitn_mut(&mut self, n: uint, pred: F) -> SplitNMut + where F: FnMut(&T) -> bool; /// Returns an iterator over subslices separated by elements that match /// `pred` limited to splitting at most `n` times. This starts at the end of /// the slice and works backwards. The matched element is not contained in /// the subslices. #[stable] - fn rsplitn_mut(&mut self, n: uint, pred: F) -> RSplitNMut - where F: FnMut(&Self::Item) -> bool; + fn rsplitn_mut(&mut self, n: uint, pred: F) -> RSplitNMut + where F: FnMut(&T) -> bool; /// Returns an iterator over `chunk_size` elements of the slice at a time. /// The chunks are mutable and do not overlap. If `chunk_size` does @@ -451,7 +467,7 @@ pub trait SliceExt for Sized? { /// /// Panics if `chunk_size` is 0. #[stable] - fn chunks_mut(&mut self, chunk_size: uint) -> ChunksMut; + fn chunks_mut(&mut self, chunk_size: uint) -> ChunksMut; /// Swaps two elements in a slice. /// @@ -487,45 +503,51 @@ pub trait SliceExt for Sized? { /// # Example /// /// ```rust - /// let mut v = [1i, 2, 3, 4, 5, 6]; + /// let mut v = [1, 2, 3, 4, 5, 6]; /// /// // scoped to restrict the lifetime of the borrows /// { /// let (left, right) = v.split_at_mut(0); /// assert!(left == []); - /// assert!(right == [1i, 2, 3, 4, 5, 6]); + /// assert!(right == [1, 2, 3, 4, 5, 6]); /// } /// /// { /// let (left, right) = v.split_at_mut(2); - /// assert!(left == [1i, 2]); - /// assert!(right == [3i, 4, 5, 6]); + /// assert!(left == [1, 2]); + /// assert!(right == [3, 4, 5, 6]); /// } /// /// { /// let (left, right) = v.split_at_mut(6); - /// assert!(left == [1i, 2, 3, 4, 5, 6]); + /// assert!(left == [1, 2, 3, 4, 5, 6]); /// assert!(right == []); /// } /// ``` #[stable] - fn split_at_mut(&mut self, mid: uint) -> (&mut [Self::Item], &mut [Self::Item]); + fn split_at_mut(&mut self, mid: uint) -> (&mut [T], &mut [T]); /// Reverse the order of elements in a slice, in place. /// /// # Example /// /// ```rust - /// let mut v = [1i, 2, 3]; + /// let mut v = [1, 2, 3]; /// v.reverse(); - /// assert!(v == [3i, 2, 1]); + /// assert!(v == [3, 2, 1]); /// ``` #[stable] fn reverse(&mut self); /// Returns an unsafe mutable pointer to the element in index #[stable] - unsafe fn get_unchecked_mut(&mut self, index: uint) -> &mut Self::Item; + unsafe fn get_unchecked_mut(&mut self, index: uint) -> &mut T; + + /// Deprecated: renamed to `get_unchecked_mut`. + #[deprecated = "renamed to get_unchecked_mut"] + unsafe fn unchecked_mut(&mut self, index: uint) -> &mut T { + self.get_unchecked_mut(index) + } /// Return an unsafe mutable pointer to the slice's buffer. /// @@ -536,173 +558,11 @@ pub trait SliceExt for Sized? { /// would also make any pointers to it invalid. #[inline] #[stable] - fn as_mut_ptr(&mut self) -> *mut Self::Item; - - /// Copies `self` into a new `Vec`. - #[stable] - fn to_vec(&self) -> Vec where Self::Item: Clone; - - /// Creates an iterator that yields every possible permutation of the - /// vector in succession. - /// - /// # Examples - /// - /// ```rust - /// let v = [1i, 2, 3]; - /// let mut perms = v.permutations(); - /// - /// for p in perms { - /// println!("{}", p); - /// } - /// ``` - /// - /// Iterating through permutations one by one. - /// - /// ```rust - /// let v = [1i, 2, 3]; - /// let mut perms = v.permutations(); - /// - /// assert_eq!(Some(vec![1i, 2, 3]), perms.next()); - /// assert_eq!(Some(vec![1i, 3, 2]), perms.next()); - /// assert_eq!(Some(vec![3i, 1, 2]), perms.next()); - /// ``` - #[unstable] - fn permutations(&self) -> Permutations where Self::Item: Clone; - - /// Copies as many elements from `src` as it can into `self` (the - /// shorter of `self.len()` and `src.len()`). Returns the number - /// of elements copied. - /// - /// # Example - /// - /// ```rust - /// let mut dst = [0i, 0, 0]; - /// let src = [1i, 2]; - /// - /// assert!(dst.clone_from_slice(&src) == 2); - /// assert!(dst == [1, 2, 0]); - /// - /// let src2 = [3i, 4, 5, 6]; - /// assert!(dst.clone_from_slice(&src2) == 3); - /// assert!(dst == [3i, 4, 5]); - /// ``` - #[experimental] - fn clone_from_slice(&mut self, &[Self::Item]) -> uint where Self::Item: Clone; - - /// Sorts the slice, in place. - /// - /// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`. - /// - /// # Examples - /// - /// ```rust - /// let mut v = [-5i, 4, 1, -3, 2]; - /// - /// v.sort(); - /// assert!(v == [-5i, -3, 1, 2, 4]); - /// ``` - #[stable] - fn sort(&mut self) where Self::Item: Ord; - - /// Binary search a sorted slice for a given element. - /// - /// If the value is found then `Ok` is returned, containing the - /// index of the matching element; if the value is not found then - /// `Err` is returned, containing the index where a matching - /// element could be inserted while maintaining sorted order. - /// - /// # Example - /// - /// Looks up a series of four elements. The first is found, with a - /// uniquely determined position; the second and third are not - /// found; the fourth could match any position in `[1,4]`. - /// - /// ```rust - /// let s = [0i, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; - /// let s = s.as_slice(); - /// - /// assert_eq!(s.binary_search(&13), Ok(9)); - /// assert_eq!(s.binary_search(&4), Err(7)); - /// assert_eq!(s.binary_search(&100), Err(13)); - /// let r = s.binary_search(&1); - /// assert!(match r { Ok(1...4) => true, _ => false, }); - /// ``` - #[stable] - fn binary_search(&self, x: &Self::Item) -> Result where Self::Item: Ord; - - /// Deprecated: use `binary_search` instead. - #[deprecated = "use binary_search instead"] - fn binary_search_elem(&self, x: &Self::Item) -> Result where Self::Item: Ord { - self.binary_search(x) - } - - /// Mutates the slice to the next lexicographic permutation. - /// - /// Returns `true` if successful and `false` if the slice is at the - /// last-ordered permutation. - /// - /// # Example - /// - /// ```rust - /// let v: &mut [_] = &mut [0i, 1, 2]; - /// v.next_permutation(); - /// let b: &mut [_] = &mut [0i, 2, 1]; - /// assert!(v == b); - /// v.next_permutation(); - /// let b: &mut [_] = &mut [1i, 0, 2]; - /// assert!(v == b); - /// ``` - #[unstable = "uncertain if this merits inclusion in std"] - fn next_permutation(&mut self) -> bool where Self::Item: Ord; - - /// Mutates the slice to the previous lexicographic permutation. - /// - /// Returns `true` if successful and `false` if the slice is at the - /// first-ordered permutation. - /// - /// # Example - /// - /// ```rust - /// let v: &mut [_] = &mut [1i, 0, 2]; - /// v.prev_permutation(); - /// let b: &mut [_] = &mut [0i, 2, 1]; - /// assert!(v == b); - /// v.prev_permutation(); - /// let b: &mut [_] = &mut [0i, 1, 2]; - /// assert!(v == b); - /// ``` - #[unstable = "uncertain if this merits inclusion in std"] - fn prev_permutation(&mut self) -> bool where Self::Item: Ord; - - /// Find the first index containing a matching value. - #[experimental] - fn position_elem(&self, t: &Self::Item) -> Option where Self::Item: PartialEq; - - /// Find the last index containing a matching value. - #[experimental] - fn rposition_elem(&self, t: &Self::Item) -> Option where Self::Item: PartialEq; - - /// Return true if the slice contains an element with the given value. - #[stable] - fn contains(&self, x: &Self::Item) -> bool where Self::Item: PartialEq; - - /// Returns true if `needle` is a prefix of the slice. - #[stable] - fn starts_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq; - - /// Returns true if `needle` is a suffix of the slice. - #[stable] - fn ends_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq; - - /// Convert `self` into a vector without clones or allocation. - #[experimental] - fn into_vec(self: Box) -> Vec; + fn as_mut_ptr(&mut self) -> *mut T; } #[unstable = "trait is unstable"] -impl SliceExt for [T] { - type Item = T; - +impl SliceExt for [T] { #[inline] fn sort_by(&mut self, compare: F) where F: FnMut(&T, &T) -> Ordering { merge_sort(self, compare) @@ -917,76 +777,229 @@ impl SliceExt for [T] { fn as_mut_ptr(&mut self) -> *mut T { core_slice::SliceExt::as_mut_ptr(self) } +} + +//////////////////////////////////////////////////////////////////////////////// +// Extension traits for slices over specifc kinds of data +//////////////////////////////////////////////////////////////////////////////// + +/// Extension methods for boxed slices. +#[experimental = "likely to merge into SliceExt if it survives"] +pub trait BoxedSliceExt { + /// Convert `self` into a vector without clones or allocation. + #[experimental] + fn into_vec(self) -> Vec; +} + +#[experimental = "trait is experimental"] +impl BoxedSliceExt for Box<[T]> { + fn into_vec(mut self) -> Vec { + unsafe { + let xs = Vec::from_raw_parts(self.as_mut_ptr(), self.len(), self.len()); + mem::forget(self); + xs + } + } +} + +/// Allocating extension methods for slices containing `Clone` elements. +#[unstable = "likely to be merged into SliceExt"] +pub trait CloneSliceExt for Sized? { + /// Copies `self` into a new `Vec`. + #[stable] + fn to_vec(&self) -> Vec; + + /// Deprecated: use `iter().cloned().partition(f)` instead. + #[deprecated = "use iter().cloned().partition(f) instead"] + fn partitioned(&self, f: F) -> (Vec, Vec) where F: FnMut(&T) -> bool; + /// Creates an iterator that yields every possible permutation of the + /// vector in succession. + /// + /// # Examples + /// + /// ```rust + /// let v = [1, 2, 3]; + /// let mut perms = v.permutations(); + /// + /// for p in perms { + /// println!("{}", p); + /// } + /// ``` + /// + /// Iterating through permutations one by one. + /// + /// ```rust + /// let v = [1, 2, 3]; + /// let mut perms = v.permutations(); + /// + /// assert_eq!(Some(vec![1, 2, 3]), perms.next()); + /// assert_eq!(Some(vec![1, 3, 2]), perms.next()); + /// assert_eq!(Some(vec![3, 1, 2]), perms.next()); + /// ``` + #[unstable] + fn permutations(&self) -> Permutations; + + /// Copies as many elements from `src` as it can into `self` (the + /// shorter of `self.len()` and `src.len()`). Returns the number + /// of elements copied. + /// + /// # Example + /// + /// ```rust + /// let mut dst = [0, 0, 0]; + /// let src = [1, 2]; + /// + /// assert!(dst.clone_from_slice(&src) == 2); + /// assert!(dst == [1, 2, 0]); + /// + /// let src2 = [3, 4, 5, 6]; + /// assert!(dst.clone_from_slice(&src2) == 3); + /// assert!(dst == [3, 4, 5]); + /// ``` + #[experimental] + fn clone_from_slice(&mut self, &[T]) -> uint; +} + + +#[unstable = "trait is unstable"] +impl CloneSliceExt for [T] { /// Returns a copy of `v`. #[inline] - fn to_vec(&self) -> Vec where T: Clone { + fn to_vec(&self) -> Vec { let mut vector = Vec::with_capacity(self.len()); vector.push_all(self); vector } + + #[inline] + fn partitioned(&self, f: F) -> (Vec, Vec) where F: FnMut(&T) -> bool { + self.iter().cloned().partition(f) + } + /// Returns an iterator over all permutations of a vector. - fn permutations(&self) -> Permutations where T: Clone { + fn permutations(&self) -> Permutations { Permutations{ swaps: ElementSwaps::new(self.len()), v: self.to_vec(), } } - fn clone_from_slice(&mut self, src: &[T]) -> uint where T: Clone { - core_slice::SliceExt::clone_from_slice(self, src) - } - - #[inline] - fn sort(&mut self) where T: Ord { - self.sort_by(|a, b| a.cmp(b)) + fn clone_from_slice(&mut self, src: &[T]) -> uint { + core_slice::CloneSliceExt::clone_from_slice(self, src) } +} - fn binary_search(&self, x: &T) -> Result where T: Ord { - core_slice::SliceExt::binary_search(self, x) - } +/// Allocating extension methods for slices on Ord values. +#[unstable = "likely to merge with SliceExt"] +pub trait OrdSliceExt for Sized? { + /// Sorts the slice, in place. + /// + /// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`. + /// + /// # Examples + /// + /// ```rust + /// let mut v = [-5, 4, 1, -3, 2]; + /// + /// v.sort(); + /// assert!(v == [-5, -3, 1, 2, 4]); + /// ``` + #[stable] + fn sort(&mut self); - fn next_permutation(&mut self) -> bool where T: Ord { - core_slice::SliceExt::next_permutation(self) - } + /// Binary search a sorted slice for a given element. + /// + /// If the value is found then `Ok` is returned, containing the + /// index of the matching element; if the value is not found then + /// `Err` is returned, containing the index where a matching + /// element could be inserted while maintaining sorted order. + /// + /// # Example + /// + /// Looks up a series of four elements. The first is found, with a + /// uniquely determined position; the second and third are not + /// found; the fourth could match any position in `[1,4]`. + /// + /// ```rust + /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; + /// let s = s.as_slice(); + /// + /// assert_eq!(s.binary_search(&13), Ok(9)); + /// assert_eq!(s.binary_search(&4), Err(7)); + /// assert_eq!(s.binary_search(&100), Err(13)); + /// let r = s.binary_search(&1); + /// assert!(match r { Ok(1...4) => true, _ => false, }); + /// ``` + #[stable] + fn binary_search(&self, x: &T) -> Result; - fn prev_permutation(&mut self) -> bool where T: Ord { - core_slice::SliceExt::prev_permutation(self) + /// Deprecated: use `binary_search` instead. + #[deprecated = "use binary_search instead"] + fn binary_search_elem(&self, x: &T) -> Result { + self.binary_search(x) } - fn position_elem(&self, t: &T) -> Option where T: PartialEq { - core_slice::SliceExt::position_elem(self, t) - } + /// Mutates the slice to the next lexicographic permutation. + /// + /// Returns `true` if successful and `false` if the slice is at the + /// last-ordered permutation. + /// + /// # Example + /// + /// ```rust + /// let v: &mut [_] = &mut [0, 1, 2]; + /// v.next_permutation(); + /// let b: &mut [_] = &mut [0, 2, 1]; + /// assert!(v == b); + /// v.next_permutation(); + /// let b: &mut [_] = &mut [1, 0, 2]; + /// assert!(v == b); + /// ``` + #[unstable = "uncertain if this merits inclusion in std"] + fn next_permutation(&mut self) -> bool; - fn rposition_elem(&self, t: &T) -> Option where T: PartialEq { - core_slice::SliceExt::rposition_elem(self, t) - } + /// Mutates the slice to the previous lexicographic permutation. + /// + /// Returns `true` if successful and `false` if the slice is at the + /// first-ordered permutation. + /// + /// # Example + /// + /// ```rust + /// let v: &mut [_] = &mut [1, 0, 2]; + /// v.prev_permutation(); + /// let b: &mut [_] = &mut [0, 2, 1]; + /// assert!(v == b); + /// v.prev_permutation(); + /// let b: &mut [_] = &mut [0, 1, 2]; + /// assert!(v == b); + /// ``` + #[unstable = "uncertain if this merits inclusion in std"] + fn prev_permutation(&mut self) -> bool; +} - fn contains(&self, x: &T) -> bool where T: PartialEq { - core_slice::SliceExt::contains(self, x) +#[unstable = "trait is unstable"] +impl OrdSliceExt for [T] { + #[inline] + fn sort(&mut self) { + self.sort_by(|a, b| a.cmp(b)) } - fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq { - core_slice::SliceExt::starts_with(self, needle) + fn binary_search(&self, x: &T) -> Result { + core_slice::OrdSliceExt::binary_search(self, x) } - fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq { - core_slice::SliceExt::ends_with(self, needle) + fn next_permutation(&mut self) -> bool { + core_slice::OrdSliceExt::next_permutation(self) } - fn into_vec(mut self: Box) -> Vec { - unsafe { - let xs = Vec::from_raw_parts(self.as_mut_ptr(), self.len(), self.len()); - mem::forget(self); - xs - } + fn prev_permutation(&mut self) -> bool { + core_slice::OrdSliceExt::prev_permutation(self) } } -//////////////////////////////////////////////////////////////////////////////// -// Extension traits for slices over specifc kinds of data -//////////////////////////////////////////////////////////////////////////////// #[unstable = "U should be an associated type"] /// An extension trait for concatenating slices pub trait SliceConcatExt for Sized? { @@ -994,10 +1007,20 @@ pub trait SliceConcatExt for Sized? { #[stable] fn concat(&self) -> U; + #[deprecated = "renamed to concat"] + fn concat_vec(&self) -> U { + self.concat() + } + /// Flattens a slice of `T` into a single value `U`, placing a /// given seperator between each. #[stable] fn connect(&self, sep: &T) -> U; + + #[deprecated = "renamed to connect"] + fn connect_vec(&self, sep: &T) -> U { + self.connect(sep) + } } impl> SliceConcatExt> for [V] { @@ -1033,7 +1056,7 @@ impl> SliceConcatExt> for [V] { /// The last generated swap is always (0, 1), and it returns the /// sequence to its initial order. #[experimental] -#[derive(Clone)] +#[deriving(Clone)] pub struct ElementSwaps { sdir: Vec, /// If `true`, emit the last swap that returns the sequence to initial @@ -1080,19 +1103,17 @@ impl ToOwned> for [T] { // Iterators //////////////////////////////////////////////////////////////////////////////// -#[derive(Copy, Clone)] +#[deriving(Copy, Clone)] enum Direction { Pos, Neg } /// An `Index` and `Direction` together. -#[derive(Copy, Clone)] +#[deriving(Copy, Clone)] struct SizeDirection { size: uint, dir: Direction, } -impl Iterator for ElementSwaps { - type Item = (uint, uint); - +impl Iterator<(uint, uint)> for ElementSwaps { #[inline] fn next(&mut self) -> Option<(uint, uint)> { fn new_pos(i: uint, s: Direction) -> uint { @@ -1159,9 +1180,7 @@ pub struct Permutations { } #[unstable = "trait is unstable"] -impl Iterator for Permutations { - type Item = Vec; - +impl Iterator> for Permutations { #[inline] fn next(&mut self) -> Option> { match self.swaps.next() { @@ -1388,12 +1407,21 @@ fn merge_sort(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Order } } +/// Deprecated, unsafe operations +#[deprecated] +pub mod raw { + pub use core::slice::raw::{buf_as_slice, mut_buf_as_slice}; + pub use core::slice::raw::{shift_ptr, pop_ptr}; +} + #[cfg(test)] mod tests { + use std::boxed::Box; use prelude::{Some, None, range, Vec, ToString, Clone, Greater, Less, Equal}; - use prelude::{SliceExt, Iterator, IteratorExt}; - use prelude::AsSlice; + use prelude::{SliceExt, Iterator, IteratorExt, DoubleEndedIteratorExt}; + use prelude::{OrdSliceExt, CloneSliceExt, PartialEqSliceExt, AsSlice}; use prelude::{RandomAccessIterator, Ord, SliceConcatExt}; + use core::cell::Cell; use core::default::Default; use core::mem; use std::rand::{Rng, thread_rng}; @@ -1407,7 +1435,7 @@ mod tests { #[test] fn test_from_fn() { // Test on-stack from_fn. - let mut v = range(0, 3).map(square).collect::>(); + let mut v = Vec::from_fn(3u, square); { let v = v.as_slice(); assert_eq!(v.len(), 3u); @@ -1417,7 +1445,7 @@ mod tests { } // Test on-heap from_fn. - v = range(0, 5).map(square).collect::>(); + v = Vec::from_fn(5u, square); { let v = v.as_slice(); assert_eq!(v.len(), 5u); @@ -1432,7 +1460,7 @@ mod tests { #[test] fn test_from_elem() { // Test on-stack from_elem. - let mut v = vec![10u, 10u]; + let mut v = Vec::from_elem(2u, 10u); { let v = v.as_slice(); assert_eq!(v.len(), 2u); @@ -1441,7 +1469,7 @@ mod tests { } // Test on-heap from_elem. - v = vec![20u, 20u, 20u, 20u, 20u, 20u]; + v = Vec::from_elem(6u, 20u); { let v = v.as_slice(); assert_eq!(v[0], 20u); @@ -1483,23 +1511,23 @@ mod tests { } #[test] - fn test_first() { + fn test_head() { let mut a = vec![]; - assert_eq!(a.as_slice().first(), None); + assert_eq!(a.as_slice().head(), None); a = vec![11i]; - assert_eq!(a.as_slice().first().unwrap(), &11); + assert_eq!(a.as_slice().head().unwrap(), &11); a = vec![11i, 12]; - assert_eq!(a.as_slice().first().unwrap(), &11); + assert_eq!(a.as_slice().head().unwrap(), &11); } #[test] - fn test_first_mut() { + fn test_head_mut() { let mut a = vec![]; - assert_eq!(a.first_mut(), None); + assert_eq!(a.head_mut(), None); a = vec![11i]; - assert_eq!(*a.first_mut().unwrap(), 11); + assert_eq!(*a.head_mut().unwrap(), 11); a = vec![11i, 12]; - assert_eq!(*a.first_mut().unwrap(), 11); + assert_eq!(*a.head_mut().unwrap(), 11); } #[test] @@ -1703,6 +1731,42 @@ mod tests { assert_eq!(v.as_slice()[1], 2); } + #[test] + fn test_grow() { + // Test on-stack grow(). + let mut v = vec![]; + v.grow(2u, 1i); + { + let v = v.as_slice(); + assert_eq!(v.len(), 2u); + assert_eq!(v[0], 1); + assert_eq!(v[1], 1); + } + + // Test on-heap grow(). + v.grow(3u, 2i); + { + let v = v.as_slice(); + assert_eq!(v.len(), 5u); + assert_eq!(v[0], 1); + assert_eq!(v[1], 1); + assert_eq!(v[2], 2); + assert_eq!(v[3], 2); + assert_eq!(v[4], 2); + } + } + + #[test] + fn test_grow_fn() { + let mut v = vec![]; + v.grow_fn(3u, square); + let v = v.as_slice(); + assert_eq!(v.len(), 3u); + assert_eq!(v[0], 0u); + assert_eq!(v[1], 1u); + assert_eq!(v[2], 4u); + } + #[test] fn test_truncate() { let mut v = vec![box 6i,box 5,box 4]; @@ -2035,6 +2099,22 @@ mod tests { } } + #[test] + fn test_partition() { + assert_eq!((vec![]).partition(|x: &int| *x < 3), (vec![], vec![])); + assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![])); + assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 2), (vec![1], vec![2, 3])); + assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3])); + } + + #[test] + fn test_partitioned() { + assert_eq!(([]).partitioned(|x: &int| *x < 3), (vec![], vec![])); + assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 4), (vec![1, 2, 3], vec![])); + assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 2), (vec![1], vec![2, 3])); + assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 0), (vec![], vec![1, 2, 3])); + } + #[test] fn test_concat() { let v: [Vec; 0] = []; @@ -2052,14 +2132,14 @@ mod tests { #[test] fn test_connect() { let v: [Vec; 0] = []; - assert_eq!(v.connect(&0), vec![]); - assert_eq!([vec![1i], vec![2i, 3]].connect(&0), vec![1, 0, 2, 3]); - assert_eq!([vec![1i], vec![2i], vec![3i]].connect(&0), vec![1, 0, 2, 0, 3]); + assert_eq!(v.connect_vec(&0), vec![]); + assert_eq!([vec![1i], vec![2i, 3]].connect_vec(&0), vec![1, 0, 2, 3]); + assert_eq!([vec![1i], vec![2i], vec![3i]].connect_vec(&0), vec![1, 0, 2, 0, 3]); let v: [&[int]; 2] = [&[1], &[2, 3]]; - assert_eq!(v.connect(&0), vec![1, 0, 2, 3]); + assert_eq!(v.connect_vec(&0), vec![1, 0, 2, 3]); let v: [&[int]; 3] = [&[1], &[2], &[3]]; - assert_eq!(v.connect(&0), vec![1, 0, 2, 0, 3]); + assert_eq!(v.connect_vec(&0), vec![1, 0, 2, 0, 3]); } #[test] @@ -2132,6 +2212,55 @@ mod tests { assert_eq!(v[1], 3); } + + #[test] + #[should_fail] + fn test_from_fn_fail() { + Vec::from_fn(100, |v| { + if v == 50 { panic!() } + box 0i + }); + } + + #[test] + #[should_fail] + fn test_from_elem_fail() { + + struct S { + f: Cell, + boxes: (Box, Rc) + } + + impl Clone for S { + fn clone(&self) -> S { + self.f.set(self.f.get() + 1); + if self.f.get() == 10 { panic!() } + S { + f: self.f.clone(), + boxes: self.boxes.clone(), + } + } + } + + let s = S { + f: Cell::new(0), + boxes: (box 0, Rc::new(0)), + }; + let _ = Vec::from_elem(100, s); + } + + #[test] + #[should_fail] + fn test_grow_fn_fail() { + let mut v = vec![]; + v.grow_fn(100, |i| { + if i == 50 { + panic!() + } + (box 0i, Rc::new(0i)) + }) + } + #[test] #[should_fail] fn test_permute_fail() { @@ -2549,7 +2678,7 @@ mod tests { assert!(values == [2, 3, 5, 6, 7]); } - #[derive(Clone, PartialEq)] + #[deriving(Clone, PartialEq)] struct Foo; #[test] @@ -2720,7 +2849,6 @@ mod bench { use prelude::*; use core::mem; use core::ptr; - use core::iter::repeat; use std::rand::{weak_rng, Rng}; use test::{Bencher, black_box}; @@ -2728,7 +2856,7 @@ mod bench { fn iterator(b: &mut Bencher) { // peculiar numbers to stop LLVM from optimising the summation // out. - let v = range(0u, 100).map(|i| i ^ (i << 1) ^ (i >> 1)).collect::>(); + let v = Vec::from_fn(100, |i| i ^ (i << 1) ^ (i >> 1)); b.iter(|| { let mut sum = 0; @@ -2742,7 +2870,7 @@ mod bench { #[bench] fn mut_iterator(b: &mut Bencher) { - let mut v = repeat(0i).take(100).collect::>(); + let mut v = Vec::from_elem(100, 0i); b.iter(|| { let mut i = 0i; @@ -2756,7 +2884,7 @@ mod bench { #[bench] fn concat(b: &mut Bencher) { let xss: Vec> = - range(0, 100u).map(|i| range(0, i).collect()).collect(); + Vec::from_fn(100, |i| range(0u, i).collect()); b.iter(|| { xss.as_slice().concat(); }); @@ -2765,9 +2893,9 @@ mod bench { #[bench] fn connect(b: &mut Bencher) { let xss: Vec> = - range(0, 100u).map(|i| range(0, i).collect()).collect(); + Vec::from_fn(100, |i| range(0u, i).collect()); b.iter(|| { - xss.as_slice().connect(&0) + xss.as_slice().connect_vec(&0) }); } @@ -2782,7 +2910,7 @@ mod bench { #[bench] fn starts_with_same_vector(b: &mut Bencher) { - let vec: Vec = range(0, 100).collect(); + let vec: Vec = Vec::from_fn(100, |i| i); b.iter(|| { vec.as_slice().starts_with(vec.as_slice()) }) @@ -2798,8 +2926,8 @@ mod bench { #[bench] fn starts_with_diff_one_element_at_end(b: &mut Bencher) { - let vec: Vec = range(0, 100).collect(); - let mut match_vec: Vec = range(0, 99).collect(); + let vec: Vec = Vec::from_fn(100, |i| i); + let mut match_vec: Vec = Vec::from_fn(99, |i| i); match_vec.push(0); b.iter(|| { vec.as_slice().starts_with(match_vec.as_slice()) @@ -2808,7 +2936,7 @@ mod bench { #[bench] fn ends_with_same_vector(b: &mut Bencher) { - let vec: Vec = range(0, 100).collect(); + let vec: Vec = Vec::from_fn(100, |i| i); b.iter(|| { vec.as_slice().ends_with(vec.as_slice()) }) @@ -2824,8 +2952,8 @@ mod bench { #[bench] fn ends_with_diff_one_element_at_beginning(b: &mut Bencher) { - let vec: Vec = range(0, 100).collect(); - let mut match_vec: Vec = range(0, 100).collect(); + let vec: Vec = Vec::from_fn(100, |i| i); + let mut match_vec: Vec = Vec::from_fn(100, |i| i); match_vec.as_mut_slice()[0] = 200; b.iter(|| { vec.as_slice().starts_with(match_vec.as_slice()) @@ -2834,7 +2962,7 @@ mod bench { #[bench] fn contains_last_element(b: &mut Bencher) { - let vec: Vec = range(0, 100).collect(); + let vec: Vec = Vec::from_fn(100, |i| i); b.iter(|| { vec.contains(&99u) }) @@ -2843,7 +2971,7 @@ mod bench { #[bench] fn zero_1kb_from_elem(b: &mut Bencher) { b.iter(|| { - repeat(0u8).take(1024).collect::>() + Vec::from_elem(1024, 0u8) }); } @@ -2891,24 +3019,24 @@ mod bench { fn random_inserts(b: &mut Bencher) { let mut rng = weak_rng(); b.iter(|| { - let mut v = repeat((0u, 0u)).take(30).collect::>(); - for _ in range(0u, 100) { - let l = v.len(); - v.insert(rng.gen::() % (l + 1), - (1, 1)); - } - }) + let mut v = Vec::from_elem(30, (0u, 0u)); + for _ in range(0u, 100) { + let l = v.len(); + v.insert(rng.gen::() % (l + 1), + (1, 1)); + } + }) } #[bench] fn random_removes(b: &mut Bencher) { let mut rng = weak_rng(); b.iter(|| { - let mut v = repeat((0u, 0u)).take(130).collect::>(); - for _ in range(0u, 100) { - let l = v.len(); - v.remove(rng.gen::() % l); - } - }) + let mut v = Vec::from_elem(130, (0u, 0u)); + for _ in range(0u, 100) { + let l = v.len(); + v.remove(rng.gen::() % l); + } + }) } #[bench] @@ -2943,7 +3071,7 @@ mod bench { #[bench] fn sort_sorted(b: &mut Bencher) { - let mut v = range(0u, 10000).collect::>(); + let mut v = Vec::from_fn(10000, |i| i); b.iter(|| { v.sort(); }); @@ -2987,7 +3115,7 @@ mod bench { #[bench] fn sort_big_sorted(b: &mut Bencher) { - let mut v = range(0, 10000u).map(|i| (i, i, i, i)).collect::>(); + let mut v = Vec::from_fn(10000u, |i| (i, i, i, i)); b.iter(|| { v.sort(); }); diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs index b8f97799c97..027f50791b8 100644 --- a/src/libcollections/vec.rs +++ b/src/libcollections/vec.rs @@ -25,13 +25,13 @@ //! ``` //! let ys: Vec = vec![]; //! -//! let zs = vec![1i32, 2, 3, 4, 5]; +//! let zs = vec![1, 2, 3, 4, 5]; //! ``` //! //! Push: //! //! ``` -//! let mut xs = vec![1i32, 2]; +//! let mut xs = vec![1, 2]; //! //! xs.push(3); //! ``` @@ -39,7 +39,7 @@ //! And pop: //! //! ``` -//! let mut xs = vec![1i32, 2]; +//! let mut xs = vec![1, 2]; //! //! let two = xs.pop(); //! ``` @@ -71,8 +71,8 @@ use core::uint; /// /// ``` /// let mut vec = Vec::new(); -/// vec.push(1i); -/// vec.push(2i); +/// vec.push(1); +/// vec.push(2); /// /// assert_eq!(vec.len(), 2); /// assert_eq!(vec[0], 1); @@ -80,7 +80,7 @@ use core::uint; /// assert_eq!(vec.pop(), Some(2)); /// assert_eq!(vec.len(), 1); /// -/// vec[0] = 7i; +/// vec[0] = 7; /// assert_eq!(vec[0], 7); /// /// vec.push_all(&[1, 2, 3]); @@ -88,13 +88,13 @@ use core::uint; /// for x in vec.iter() { /// println!("{}", x); /// } -/// assert_eq!(vec, vec![7i, 1, 2, 3]); +/// assert_eq!(vec, vec![7, 1, 2, 3]); /// ``` /// /// The `vec!` macro is provided to make initialization more convenient: /// /// ``` -/// let mut vec = vec![1i, 2i, 3i]; +/// let mut vec = vec![1, 2, 3]; /// vec.push(4); /// assert_eq!(vec, vec![1, 2, 3, 4]); /// ``` @@ -104,9 +104,9 @@ use core::uint; /// ``` /// let mut stack = Vec::new(); /// -/// stack.push(1i); -/// stack.push(2i); -/// stack.push(3i); +/// stack.push(1); +/// stack.push(2); +/// stack.push(3); /// /// loop { /// let top = match stack.pop() { @@ -218,7 +218,7 @@ impl Vec { /// use std::mem; /// /// fn main() { - /// let mut v = vec![1i, 2, 3]; + /// let mut v = vec![1, 2, 3]; /// /// // Pull out the various important pieces of information about `v` /// let p = v.as_mut_ptr(); @@ -237,7 +237,7 @@ impl Vec { /// /// // Put everything back together into a Vec /// let rebuilt = Vec::from_raw_parts(p, len, cap); - /// assert_eq!(rebuilt, vec![4i, 5i, 6i]); + /// assert_eq!(rebuilt, vec![4, 5, 6]); /// } /// } /// ``` @@ -392,7 +392,7 @@ impl Vec { /// # Examples /// /// ``` - /// let mut vec = vec![1i, 2, 3, 4]; + /// let mut vec = vec![1, 2, 3, 4]; /// vec.truncate(2); /// assert_eq!(vec, vec![1, 2]); /// ``` @@ -416,7 +416,7 @@ impl Vec { /// ``` /// fn foo(slice: &mut [int]) {} /// - /// let mut vec = vec![1i, 2]; + /// let mut vec = vec![1, 2]; /// foo(vec.as_mut_slice()); /// ``` #[inline] @@ -519,7 +519,7 @@ impl Vec { /// # Examples /// /// ``` - /// let mut vec = vec![1i, 2, 3]; + /// let mut vec = vec![1, 2, 3]; /// vec.insert(1, 4); /// assert_eq!(vec, vec![1, 4, 2, 3]); /// vec.insert(4, 5); @@ -557,7 +557,7 @@ impl Vec { /// # Examples /// /// ``` - /// let mut v = vec![1i, 2, 3]; + /// let mut v = vec![1, 2, 3]; /// assert_eq!(v.remove(1), 2); /// assert_eq!(v, vec![1, 3]); /// ``` @@ -591,7 +591,7 @@ impl Vec { /// # Examples /// /// ``` - /// let mut vec = vec![1i, 2, 3, 4]; + /// let mut vec = vec![1, 2, 3, 4]; /// vec.retain(|&x| x%2 == 0); /// assert_eq!(vec, vec![2, 4]); /// ``` @@ -624,7 +624,7 @@ impl Vec { /// # Examples /// /// ```rust - /// let mut vec = vec!(1i, 2); + /// let mut vec = vec!(1, 2); /// vec.push(3); /// assert_eq!(vec, vec!(1, 2, 3)); /// ``` @@ -662,7 +662,7 @@ impl Vec { /// # Examples /// /// ```rust - /// let mut vec = vec![1i, 2, 3]; + /// let mut vec = vec![1, 2, 3]; /// assert_eq!(vec.pop(), Some(3)); /// assert_eq!(vec, vec![1, 2]); /// ``` @@ -716,7 +716,7 @@ impl Vec { /// # Examples /// /// ``` - /// let mut v = vec![1i, 2, 3]; + /// let mut v = vec![1, 2, 3]; /// /// v.clear(); /// @@ -733,7 +733,7 @@ impl Vec { /// # Examples /// /// ``` - /// let a = vec![1i, 2, 3]; + /// let a = vec![1, 2, 3]; /// assert_eq!(a.len(), 3); /// ``` #[inline] @@ -748,7 +748,7 @@ impl Vec { /// let mut v = Vec::new(); /// assert!(v.is_empty()); /// - /// v.push(1i); + /// v.push(1); /// assert!(!v.is_empty()); /// ``` #[stable] @@ -965,7 +965,7 @@ impl Vec { /// vec.resize(3, "world"); /// assert_eq!(vec, vec!["hello", "world", "world"]); /// - /// let mut vec = vec![1i, 2, 3, 4]; + /// let mut vec = vec![1, 2, 3, 4]; /// vec.resize(2, 0); /// assert_eq!(vec, vec![1, 2]); /// ``` @@ -988,8 +988,8 @@ impl Vec { /// # Examples /// /// ``` - /// let mut vec = vec![1i]; - /// vec.push_all(&[2i, 3, 4]); + /// let mut vec = vec![1]; + /// vec.push_all(&[2, 3, 4]); /// assert_eq!(vec, vec![1, 2, 3, 4]); /// ``` #[inline] @@ -1021,11 +1021,11 @@ impl Vec { /// # Examples /// /// ``` - /// let mut vec = vec![1i, 2, 2, 3, 2]; + /// let mut vec = vec![1, 2, 2, 3, 2]; /// /// vec.dedup(); /// - /// assert_eq!(vec, vec![1i, 2, 3, 2]); + /// assert_eq!(vec, vec![1, 2, 3, 2]); /// ``` #[stable] pub fn dedup(&mut self) { @@ -1399,7 +1399,7 @@ impl AsSlice for Vec { /// ``` /// fn foo(slice: &[int]) {} /// - /// let vec = vec![1i, 2]; + /// let vec = vec![1, 2]; /// foo(vec.as_slice()); /// ``` #[inline] diff --git a/src/libcore/atomic.rs b/src/libcore/atomic.rs index 0ac0dc396cc..ebc01ae14fc 100644 --- a/src/libcore/atomic.rs +++ b/src/libcore/atomic.rs @@ -793,7 +793,7 @@ impl AtomicPtr { /// ``` /// use std::sync::atomic::AtomicPtr; /// - /// let ptr = &mut 5i; + /// let ptr = &mut 5; /// let atomic_ptr = AtomicPtr::new(ptr); /// ``` #[inline] @@ -815,7 +815,7 @@ impl AtomicPtr { /// ``` /// use std::sync::atomic::{AtomicPtr, Ordering}; /// - /// let ptr = &mut 5i; + /// let ptr = &mut 5; /// let some_ptr = AtomicPtr::new(ptr); /// /// let value = some_ptr.load(Ordering::Relaxed); @@ -837,10 +837,10 @@ impl AtomicPtr { /// ``` /// use std::sync::atomic::{AtomicPtr, Ordering}; /// - /// let ptr = &mut 5i; + /// let ptr = &mut 5; /// let some_ptr = AtomicPtr::new(ptr); /// - /// let other_ptr = &mut 10i; + /// let other_ptr = &mut 10; /// /// some_ptr.store(other_ptr, Ordering::Relaxed); /// ``` @@ -863,10 +863,10 @@ impl AtomicPtr { /// ``` /// use std::sync::atomic::{AtomicPtr, Ordering}; /// - /// let ptr = &mut 5i; + /// let ptr = &mut 5; /// let some_ptr = AtomicPtr::new(ptr); /// - /// let other_ptr = &mut 10i; + /// let other_ptr = &mut 10; /// /// let value = some_ptr.swap(other_ptr, Ordering::Relaxed); /// ``` @@ -888,11 +888,11 @@ impl AtomicPtr { /// ``` /// use std::sync::atomic::{AtomicPtr, Ordering}; /// - /// let ptr = &mut 5i; + /// let ptr = &mut 5; /// let some_ptr = AtomicPtr::new(ptr); /// - /// let other_ptr = &mut 10i; - /// let another_ptr = &mut 10i; + /// let other_ptr = &mut 10; + /// let another_ptr = &mut 10; /// /// let value = some_ptr.compare_and_swap(other_ptr, another_ptr, Ordering::Relaxed); /// ``` diff --git a/src/libcore/fmt/num.rs b/src/libcore/fmt/num.rs index e0724fc2da5..c9646bb3d35 100644 --- a/src/libcore/fmt/num.rs +++ b/src/libcore/fmt/num.rs @@ -145,7 +145,7 @@ pub struct RadixFmt(T, R); /// /// ``` /// use std::fmt::radix; -/// assert_eq!(format!("{}", radix(55i, 36)), "1j".to_string()); +/// assert_eq!(format!("{}", radix(55, 36)), "1j".to_string()); /// ``` #[unstable = "may be renamed or move to a different module"] pub fn radix(x: T, base: u8) -> RadixFmt { diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs index 29077deb21d..e7e32cec177 100644 --- a/src/libcore/iter.rs +++ b/src/libcore/iter.rs @@ -33,7 +33,7 @@ //! translated to the `loop` below. //! //! ```rust -//! let values = vec![1i, 2, 3]; +//! let values = vec![1, 2, 3]; //! //! // "Syntactical sugar" taking advantage of an iterator //! for &x in values.iter() { @@ -118,8 +118,8 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [0i]; - /// let b = [1i]; + /// let a = [0]; + /// let b = [1]; /// let mut it = a.iter().chain(b.iter()); /// assert_eq!(it.next().unwrap(), &0); /// assert_eq!(it.next().unwrap(), &1); @@ -141,10 +141,10 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [0i]; - /// let b = [1i]; + /// let a = [0]; + /// let b = [1]; /// let mut it = a.iter().zip(b.iter()); - /// let (x0, x1) = (0i, 1i); + /// let (x0, x1) = (0, 1); /// assert_eq!(it.next().unwrap(), (&x0, &x1)); /// assert!(it.next().is_none()); /// ``` @@ -162,7 +162,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [1i, 2]; + /// let a = [1, 2]; /// let mut it = a.iter().map(|&x| 2 * x); /// assert_eq!(it.next().unwrap(), 2); /// assert_eq!(it.next().unwrap(), 4); @@ -183,7 +183,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [1i, 2]; + /// let a = [1, 2]; /// let mut it = a.iter().filter(|&x| *x > 1); /// assert_eq!(it.next().unwrap(), &2); /// assert!(it.next().is_none()); @@ -203,7 +203,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [1i, 2]; + /// let a = [1, 2]; /// let mut it = a.iter().filter_map(|&x| if x > 1 {Some(2 * x)} else {None}); /// assert_eq!(it.next().unwrap(), 4); /// assert!(it.next().is_none()); @@ -222,9 +222,9 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [100i, 200]; + /// let a = [100, 200]; /// let mut it = a.iter().enumerate(); - /// let (x100, x200) = (100i, 200i); + /// let (x100, x200) = (100, 200); /// assert_eq!(it.next().unwrap(), (0, &x100)); /// assert_eq!(it.next().unwrap(), (1, &x200)); /// assert!(it.next().is_none()); @@ -241,7 +241,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let xs = [100i, 200, 300]; + /// let xs = [100, 200, 300]; /// let mut it = xs.iter().map(|x| *x).peekable(); /// assert_eq!(*it.peek().unwrap(), 100); /// assert_eq!(it.next().unwrap(), 100); @@ -265,7 +265,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [1i, 2, 3, 2, 1]; + /// let a = [1, 2, 3, 2, 1]; /// let mut it = a.iter().skip_while(|&a| *a < 3); /// assert_eq!(it.next().unwrap(), &3); /// assert_eq!(it.next().unwrap(), &2); @@ -287,7 +287,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [1i, 2, 3, 2, 1]; + /// let a = [1, 2, 3, 2, 1]; /// let mut it = a.iter().take_while(|&a| *a < 3); /// assert_eq!(it.next().unwrap(), &1); /// assert_eq!(it.next().unwrap(), &2); @@ -307,7 +307,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [1i, 2, 3, 4, 5]; + /// let a = [1, 2, 3, 4, 5]; /// let mut it = a.iter().skip(3); /// assert_eq!(it.next().unwrap(), &4); /// assert_eq!(it.next().unwrap(), &5); @@ -325,7 +325,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [1i, 2, 3, 4, 5]; + /// let a = [1, 2, 3, 4, 5]; /// let mut it = a.iter().take(3); /// assert_eq!(it.next().unwrap(), &1); /// assert_eq!(it.next().unwrap(), &2); @@ -346,7 +346,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [1i, 2, 3, 4, 5]; + /// let a = [1, 2, 3, 4, 5]; /// let mut it = a.iter().scan(1, |fac, &x| { /// *fac = *fac * x; /// Some(*fac) @@ -419,9 +419,9 @@ pub trait IteratorExt: Iterator + Sized { /// } /// sum /// } - /// let x = vec![1i,2,3,7,8,9]; + /// let x = vec![1,2,3,7,8,9]; /// assert_eq!(process(x.into_iter()), 6); - /// let x = vec![1i,2,3]; + /// let x = vec![1,2,3]; /// assert_eq!(process(x.into_iter()), 1006); /// ``` #[inline] @@ -482,7 +482,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [1i, 2, 3, 4, 5]; + /// let a = [1, 2, 3, 4, 5]; /// let b: Vec = a.iter().map(|&x| x).collect(); /// assert!(a.as_slice() == b.as_slice()); /// ``` @@ -498,7 +498,7 @@ pub trait IteratorExt: Iterator + Sized { /// do not. /// /// ``` - /// let vec = vec![1i, 2i, 3i, 4i]; + /// let vec = vec![1, 2, 3, 4]; /// let (even, odd): (Vec, Vec) = vec.into_iter().partition(|&n| n % 2 == 0); /// assert_eq!(even, vec![2, 4]); /// assert_eq!(odd, vec![1, 3]); @@ -528,7 +528,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [1i, 2, 3, 4, 5]; + /// let a = [1, 2, 3, 4, 5]; /// let mut it = a.iter(); /// assert!(it.nth(2).unwrap() == &3); /// assert!(it.nth(2) == None); @@ -549,7 +549,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [1i, 2, 3, 4, 5]; + /// let a = [1, 2, 3, 4, 5]; /// assert!(a.iter().last().unwrap() == &5); /// ``` #[inline] @@ -566,7 +566,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [1i, 2, 3, 4, 5]; + /// let a = [1, 2, 3, 4, 5]; /// assert!(a.iter().fold(0, |a, &b| a + b) == 15); /// ``` #[inline] @@ -586,7 +586,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [1i, 2, 3, 4, 5]; + /// let a = [1, 2, 3, 4, 5]; /// let mut it = a.iter(); /// assert!(it.count() == 5); /// ``` @@ -601,7 +601,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [1i, 2, 3, 4, 5]; + /// let a = [1, 2, 3, 4, 5]; /// assert!(a.iter().all(|x| *x > 0)); /// assert!(!a.iter().all(|x| *x > 2)); /// ``` @@ -618,7 +618,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [1i, 2, 3, 4, 5]; + /// let a = [1, 2, 3, 4, 5]; /// let mut it = a.iter(); /// assert!(it.any(|x| *x == 3)); /// assert!(!it.any(|x| *x == 3)); @@ -668,7 +668,7 @@ pub trait IteratorExt: Iterator + Sized { /// ```rust /// use core::num::SignedInt; /// - /// let xs = [-3i, 0, 1, 5, -10]; + /// let xs = [-3, 0, 1, 5, -10]; /// assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10); /// ``` #[inline] @@ -697,7 +697,7 @@ pub trait IteratorExt: Iterator + Sized { /// ```rust /// use core::num::SignedInt; /// - /// let xs = [-3i, 0, 1, 5, -10]; + /// let xs = [-3, 0, 1, 5, -10]; /// assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0); /// ``` #[inline] @@ -950,7 +950,7 @@ pub trait AdditiveIterator { /// ```rust /// use std::iter::AdditiveIterator; /// - /// let a = [1i, 2, 3, 4, 5]; + /// let a: [i32] = [1, 2, 3, 4, 5]; /// let mut it = a.iter().map(|&x| x); /// assert!(it.sum() == 15); /// ``` @@ -1033,7 +1033,7 @@ pub trait IteratorOrdExt { /// # Example /// /// ```rust - /// let a = [1i, 2, 3, 4, 5]; + /// let a = [1, 2, 3, 4, 5]; /// assert!(a.iter().max().unwrap() == &5); /// ``` fn max(self) -> Option; @@ -1043,7 +1043,7 @@ pub trait IteratorOrdExt { /// # Example /// /// ```rust - /// let a = [1i, 2, 3, 4, 5]; + /// let a = [1, 2, 3, 4, 5]; /// assert!(a.iter().min().unwrap() == &1); /// ``` fn min(self) -> Option; @@ -1069,16 +1069,16 @@ pub trait IteratorOrdExt { /// let v: [int; 0] = []; /// assert_eq!(v.iter().min_max(), NoElements); /// - /// let v = [1i]; + /// let v = [1]; /// assert!(v.iter().min_max() == OneElement(&1)); /// - /// let v = [1i, 2, 3, 4, 5]; + /// let v = [1, 2, 3, 4, 5]; /// assert!(v.iter().min_max() == MinMax(&1, &5)); /// - /// let v = [1i, 2, 3, 4, 5, 6]; + /// let v = [1, 2, 3, 4, 5, 6]; /// assert!(v.iter().min_max() == MinMax(&1, &6)); /// - /// let v = [1i, 1, 1, 1]; + /// let v = [1, 1, 1, 1]; /// assert!(v.iter().min_max() == MinMax(&1, &1)); /// ``` fn min_max(self) -> MinMaxResult; @@ -1179,10 +1179,10 @@ impl MinMaxResult { /// let r: MinMaxResult = NoElements; /// assert_eq!(r.into_option(), None); /// - /// let r = OneElement(1i); + /// let r = OneElement(1); /// assert_eq!(r.into_option(), Some((1,1))); /// - /// let r = MinMax(1i,2i); + /// let r = MinMax(1, 2); /// assert_eq!(r.into_option(), Some((1,2))); /// ``` pub fn into_option(self) -> Option<(T,T)> { @@ -1261,7 +1261,7 @@ pub trait CloneIteratorExt { /// ```rust /// use std::iter::{CloneIteratorExt, count}; /// - /// let a = count(1i,1i).take(1); + /// let a = count(1, 1).take(1); /// let mut cy = a.cycle(); /// assert_eq!(cy.next(), Some(1)); /// assert_eq!(cy.next(), Some(1)); diff --git a/src/libcore/mem.rs b/src/libcore/mem.rs index 2620928acc1..9cf3433e1ab 100644 --- a/src/libcore/mem.rs +++ b/src/libcore/mem.rs @@ -187,13 +187,13 @@ pub unsafe fn uninitialized() -> T { /// ``` /// use std::mem; /// -/// let x = &mut 5i; -/// let y = &mut 42i; +/// let x = &mut 5; +/// let y = &mut 42; /// /// mem::swap(x, y); /// -/// assert_eq!(42i, *x); -/// assert_eq!(5i, *y); +/// assert_eq!(42, *x); +/// assert_eq!(5, *y); /// ``` #[inline] #[stable] diff --git a/src/libcore/num/mod.rs b/src/libcore/num/mod.rs index 426c858d408..485d320cf5c 100644 --- a/src/libcore/num/mod.rs +++ b/src/libcore/num/mod.rs @@ -336,7 +336,7 @@ pub trait Int /// ```rust /// use std::num::Int; /// - /// assert_eq!(2i.pow(4), 16); + /// assert_eq!(2.pow(4), 16); /// ``` #[inline] fn pow(self, mut exp: uint) -> Self { diff --git a/src/libcore/option.rs b/src/libcore/option.rs index a9a1857ec97..9e55a3aa8c4 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -470,10 +470,10 @@ impl Option { /// /// ``` /// let x = Some("foo"); - /// assert_eq!(x.ok_or(0i), Ok("foo")); + /// assert_eq!(x.ok_or(0), Ok("foo")); /// /// let x: Option<&str> = None; - /// assert_eq!(x.ok_or(0i), Err(0i)); + /// assert_eq!(x.ok_or(0), Err(0)); /// ``` #[inline] #[experimental] @@ -491,10 +491,10 @@ impl Option { /// /// ``` /// let x = Some("foo"); - /// assert_eq!(x.ok_or_else(|| 0i), Ok("foo")); + /// assert_eq!(x.ok_or_else(|| 0), Ok("foo")); /// /// let x: Option<&str> = None; - /// assert_eq!(x.ok_or_else(|| 0i), Err(0i)); + /// assert_eq!(x.ok_or_else(|| 0), Err(0)); /// ``` #[inline] #[experimental] @@ -728,8 +728,8 @@ impl Option { /// let good_year = good_year_from_input.parse().unwrap_or_default(); /// let bad_year = bad_year_from_input.parse().unwrap_or_default(); /// - /// assert_eq!(1909i, good_year); - /// assert_eq!(0i, bad_year); + /// assert_eq!(1909, good_year); + /// assert_eq!(0, bad_year); /// ``` #[inline] #[stable] diff --git a/src/liblog/macros.rs b/src/liblog/macros.rs index 233d1c049f4..f41a4a8b901 100644 --- a/src/liblog/macros.rs +++ b/src/liblog/macros.rs @@ -125,7 +125,7 @@ macro_rules! warn { /// #[phase(plugin, link)] extern crate log; /// /// fn main() { -/// let ret = 3i; +/// let ret = 3; /// info!("this function is about to return: {}", ret); /// } /// ``` @@ -152,7 +152,7 @@ macro_rules! info { /// #[phase(plugin, link)] extern crate log; /// /// fn main() { -/// debug!("x = {x}, y = {y}", x=10i, y=20i); +/// debug!("x = {x}, y = {y}", x=10, y=20); /// } /// ``` /// diff --git a/src/librand/lib.rs b/src/librand/lib.rs index 0f8dbc78cde..1d37b061c97 100644 --- a/src/librand/lib.rs +++ b/src/librand/lib.rs @@ -269,7 +269,7 @@ pub trait Rng : Sized { /// ``` /// use std::rand::{thread_rng, Rng}; /// - /// let choices = [1i, 2, 4, 8, 16, 32]; + /// let choices = [1, 2, 4, 8, 16, 32]; /// let mut rng = thread_rng(); /// println!("{}", rng.choose(&choices)); /// # // replace with slicing syntax when it's stable! @@ -291,7 +291,7 @@ pub trait Rng : Sized { /// use std::rand::{thread_rng, Rng}; /// /// let mut rng = thread_rng(); - /// let mut y = [1i, 2, 3]; + /// let mut y = [1, 2, 3]; /// rng.shuffle(&mut y); /// println!("{}", y.as_slice()); /// rng.shuffle(&mut y); diff --git a/src/libstd/collections/hash/set.rs b/src/libstd/collections/hash/set.rs index b1824db93aa..7877e783ed6 100644 --- a/src/libstd/collections/hash/set.rs +++ b/src/libstd/collections/hash/set.rs @@ -164,7 +164,7 @@ impl, S, H: Hasher> HashSet { /// /// let h = SipHasher::new(); /// let mut set = HashSet::with_capacity_and_hasher(10u, h); - /// set.insert(1i); + /// set.insert(1); /// ``` #[inline] #[unstable = "hasher stuff is unclear"] @@ -283,8 +283,8 @@ impl, S, H: Hasher> HashSet { /// /// ``` /// use std::collections::HashSet; - /// let a: HashSet = [1i, 2, 3].iter().map(|&x| x).collect(); - /// let b: HashSet = [4i, 2, 3, 4].iter().map(|&x| x).collect(); + /// let a: HashSet = [1, 2, 3].iter().map(|&x| x).collect(); + /// let b: HashSet = [4, 2, 3, 4].iter().map(|&x| x).collect(); /// /// // Can be seen as `a - b`. /// for x in a.difference(&b) { @@ -292,12 +292,12 @@ impl, S, H: Hasher> HashSet { /// } /// /// let diff: HashSet = a.difference(&b).map(|&x| x).collect(); - /// assert_eq!(diff, [1i].iter().map(|&x| x).collect()); + /// assert_eq!(diff, [1].iter().map(|&x| x).collect()); /// /// // Note that difference is not symmetric, /// // and `b - a` means something else: /// let diff: HashSet = b.difference(&a).map(|&x| x).collect(); - /// assert_eq!(diff, [4i].iter().map(|&x| x).collect()); + /// assert_eq!(diff, [4].iter().map(|&x| x).collect()); /// ``` #[stable] pub fn difference<'a>(&'a self, other: &'a HashSet) -> Difference<'a, T, H> { @@ -313,8 +313,8 @@ impl, S, H: Hasher> HashSet { /// /// ``` /// use std::collections::HashSet; - /// let a: HashSet = [1i, 2, 3].iter().map(|&x| x).collect(); - /// let b: HashSet = [4i, 2, 3, 4].iter().map(|&x| x).collect(); + /// let a: HashSet = [1, 2, 3].iter().map(|&x| x).collect(); + /// let b: HashSet = [4, 2, 3, 4].iter().map(|&x| x).collect(); /// /// // Print 1, 4 in arbitrary order. /// for x in a.symmetric_difference(&b) { @@ -325,7 +325,7 @@ impl, S, H: Hasher> HashSet { /// let diff2: HashSet = b.symmetric_difference(&a).map(|&x| x).collect(); /// /// assert_eq!(diff1, diff2); - /// assert_eq!(diff1, [1i, 4].iter().map(|&x| x).collect()); + /// assert_eq!(diff1, [1, 4].iter().map(|&x| x).collect()); /// ``` #[stable] pub fn symmetric_difference<'a>(&'a self, other: &'a HashSet) @@ -339,8 +339,8 @@ impl, S, H: Hasher> HashSet { /// /// ``` /// use std::collections::HashSet; - /// let a: HashSet = [1i, 2, 3].iter().map(|&x| x).collect(); - /// let b: HashSet = [4i, 2, 3, 4].iter().map(|&x| x).collect(); + /// let a: HashSet = [1, 2, 3].iter().map(|&x| x).collect(); + /// let b: HashSet = [4, 2, 3, 4].iter().map(|&x| x).collect(); /// /// // Print 2, 3 in arbitrary order. /// for x in a.intersection(&b) { @@ -348,7 +348,7 @@ impl, S, H: Hasher> HashSet { /// } /// /// let diff: HashSet = a.intersection(&b).map(|&x| x).collect(); - /// assert_eq!(diff, [2i, 3].iter().map(|&x| x).collect()); + /// assert_eq!(diff, [2, 3].iter().map(|&x| x).collect()); /// ``` #[stable] pub fn intersection<'a>(&'a self, other: &'a HashSet) -> Intersection<'a, T, H> { @@ -364,8 +364,8 @@ impl, S, H: Hasher> HashSet { /// /// ``` /// use std::collections::HashSet; - /// let a: HashSet = [1i, 2, 3].iter().map(|&x| x).collect(); - /// let b: HashSet = [4i, 2, 3, 4].iter().map(|&x| x).collect(); + /// let a: HashSet = [1, 2, 3].iter().map(|&x| x).collect(); + /// let b: HashSet = [4, 2, 3, 4].iter().map(|&x| x).collect(); /// /// // Print 1, 2, 3, 4 in arbitrary order. /// for x in a.union(&b) { @@ -373,7 +373,7 @@ impl, S, H: Hasher> HashSet { /// } /// /// let diff: HashSet = a.union(&b).map(|&x| x).collect(); - /// assert_eq!(diff, [1i, 2, 3, 4].iter().map(|&x| x).collect()); + /// assert_eq!(diff, [1, 2, 3, 4].iter().map(|&x| x).collect()); /// ``` #[stable] pub fn union<'a>(&'a self, other: &'a HashSet) -> Union<'a, T, H> { diff --git a/src/libstd/macros.rs b/src/libstd/macros.rs index 63fd3209cc0..fb2d23b01b4 100644 --- a/src/libstd/macros.rs +++ b/src/libstd/macros.rs @@ -33,7 +33,7 @@ /// # #![allow(unreachable_code)] /// panic!(); /// panic!("this is a terrible mistake!"); -/// panic!(4i); // panic with the value of 4 to be collected elsewhere +/// panic!(4); // panic with the value of 4 to be collected elsewhere /// panic!("this is a {} {message}", "fancy", message = "message"); /// ``` #[macro_export] @@ -74,7 +74,7 @@ macro_rules! panic { /// // assert with a custom message /// # let x = true; /// assert!(x, "x wasn't true!"); -/// # let a = 3i; let b = 27i; +/// # let a = 3; let b = 27; /// assert!(a + b == 30, "a = {}, b = {}", a, b); /// ``` #[macro_export] @@ -99,8 +99,8 @@ macro_rules! assert { /// # Example /// /// ``` -/// let a = 3i; -/// let b = 1i + 2i; +/// let a = 3; +/// let b = 1 + 2; /// assert_eq!(a, b); /// ``` #[macro_export] @@ -141,7 +141,7 @@ macro_rules! assert_eq { /// // assert with a custom message /// # let x = true; /// debug_assert!(x, "x wasn't true!"); -/// # let a = 3i; let b = 27i; +/// # let a = 3; let b = 27; /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b); /// ``` #[macro_export] @@ -162,8 +162,8 @@ macro_rules! debug_assert { /// # Example /// /// ``` -/// let a = 3i; -/// let b = 1i + 2i; +/// let a = 3; +/// let b = 1 + 2; /// debug_assert_eq!(a, b); /// ``` #[macro_export] @@ -238,7 +238,7 @@ macro_rules! unimplemented { /// ``` /// format!("test"); /// format!("hello {}", "world!"); -/// format!("x = {}, y = {y}", 10i, y = 30i); +/// format!("x = {}, y = {y}", 10, y = 30); /// ``` #[macro_export] #[stable] @@ -338,7 +338,7 @@ macro_rules! vec { /// let (tx1, rx1) = channel(); /// let (tx2, rx2) = channel(); /// # fn long_running_task() {} -/// # fn calculate_the_answer() -> int { 42i } +/// # fn calculate_the_answer() -> int { 42 } /// /// Thread::spawn(move|| { long_running_task(); tx1.send(()) }).detach(); /// Thread::spawn(move|| { tx2.send(calculate_the_answer()) }).detach(); @@ -507,7 +507,7 @@ pub mod builtin { /// # Example /// /// ``` - /// let s = concat!("test", 10i, 'b', true); + /// let s = concat!("test", 10, 'b', true); /// assert_eq!(s, "test10btrue"); /// ``` #[macro_export] diff --git a/src/libstd/sync/mpsc/mod.rs b/src/libstd/sync/mpsc/mod.rs index 6bc3f561bb3..338cadafff7 100644 --- a/src/libstd/sync/mpsc/mod.rs +++ b/src/libstd/sync/mpsc/mod.rs @@ -8,7 +8,12 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! Multi-producer, single-consumer communication primitives threads +//! Communication primitives for concurrent tasks +//! +//! Rust makes it very difficult to share data among tasks to prevent race +//! conditions and to improve parallelism, but there is often a need for +//! communication between concurrent tasks. The primitives defined in this +//! module are the building blocks for synchronization in rust. //! //! This module provides message-based communication over channels, concretely //! defined among three types: @@ -18,10 +23,12 @@ //! * `Receiver` //! //! A `Sender` or `SyncSender` is used to send data to a `Receiver`. Both -//! senders are clone-able (multi-producer) such that many threads can send -//! simultaneously to one receiver (single-consumer). +//! senders are clone-able such that many tasks can send simultaneously to one +//! receiver. These channels are *task blocking*, not *thread blocking*. This +//! means that if one task is blocked on a channel, other tasks can continue to +//! make progress. //! -//! These channels come in two flavors: +//! Rust channels come in one of two flavors: //! //! 1. An asynchronous, infinitely buffered channel. The `channel()` function //! will return a `(Sender, Receiver)` tuple where all sends will be @@ -36,39 +43,36 @@ //! "rendezvous" channel where each sender atomically hands off a message to //! a receiver. //! -//! ## Disconnection +//! ## Panic Propagation //! -//! The send and receive operations on channels will all return a `Result` -//! indicating whether the operation succeeded or not. An unsuccessful operation -//! is normally indicative of the other half of a channel having "hung up" by -//! being dropped in its corresponding thread. +//! In addition to being a core primitive for communicating in rust, channels +//! are the points at which panics are propagated among tasks. Whenever the one +//! half of channel is closed, the other half will have its next operation +//! `panic!`. The purpose of this is to allow propagation of panics among tasks +//! that are linked to one another via channels. //! -//! Once half of a channel has been deallocated, most operations can no longer -//! continue to make progress, so `Err` will be returned. Many applications will -//! continue to `unwrap()` the results returned from this module, instigating a -//! propagation of failure among threads if one unexpectedly dies. +//! There are methods on both of senders and receivers to perform their +//! respective operations without panicking, however. //! -//! # Examples +//! # Example //! //! Simple usage: //! //! ``` //! use std::thread::Thread; -//! use std::sync::mpsc::channel; //! //! // Create a simple streaming channel //! let (tx, rx) = channel(); //! Thread::spawn(move|| { -//! tx.send(10i).unwrap(); +//! tx.send(10); //! }).detach(); -//! assert_eq!(rx.recv().unwrap(), 10i); +//! assert_eq!(rx.recv(), 10); //! ``` //! //! Shared usage: //! //! ``` //! use std::thread::Thread; -//! use std::sync::mpsc::channel; //! //! // Create a shared channel that can be sent along from many threads //! // where tx is the sending half (tx for transmission), and rx is the receiving @@ -77,40 +81,37 @@ //! for i in range(0i, 10i) { //! let tx = tx.clone(); //! Thread::spawn(move|| { -//! tx.send(i).unwrap(); +//! tx.send(i); //! }).detach() //! } //! //! for _ in range(0i, 10i) { -//! let j = rx.recv().unwrap(); +//! let j = rx.recv(); //! assert!(0 <= j && j < 10); //! } //! ``` //! //! Propagating panics: //! -//! ``` -//! use std::sync::mpsc::channel; -//! -//! // The call to recv() will return an error because the channel has already -//! // hung up (or been deallocated) +//! ```should_fail +//! // The call to recv() will panic!() because the channel has already hung +//! // up (or been deallocated) //! let (tx, rx) = channel::(); //! drop(tx); -//! assert!(rx.recv().is_err()); +//! rx.recv(); //! ``` //! //! Synchronous channels: //! //! ``` //! use std::thread::Thread; -//! use std::sync::mpsc::sync_channel; //! //! let (tx, rx) = sync_channel::(0); //! Thread::spawn(move|| { //! // This will wait for the parent task to start receiving -//! tx.send(53).unwrap(); +//! tx.send(53); //! }).detach(); -//! rx.recv().unwrap(); +//! rx.recv(); //! ``` //! //! Reading from a channel with a timeout requires to use a Timer together @@ -119,7 +120,6 @@ //! after 10 seconds no matter what: //! //! ```no_run -//! use std::sync::mpsc::channel; //! use std::io::timer::Timer; //! use std::time::Duration; //! @@ -129,8 +129,8 @@ //! //! loop { //! select! { -//! val = rx.recv() => println!("Received {}", val.unwrap()), -//! _ = timeout.recv() => { +//! val = rx.recv() => println!("Received {}", val), +//! () = timeout.recv() => { //! println!("timed out, total time was more than 10 seconds"); //! break; //! } @@ -143,7 +143,6 @@ //! has been inactive for 5 seconds: //! //! ```no_run -//! use std::sync::mpsc::channel; //! use std::io::timer::Timer; //! use std::time::Duration; //! @@ -154,8 +153,8 @@ //! let timeout = timer.oneshot(Duration::seconds(5)); //! //! select! { -//! val = rx.recv() => println!("Received {}", val.unwrap()), -//! _ = timeout.recv() => { +//! val = rx.recv() => println!("Received {}", val), +//! () = timeout.recv() => { //! println!("timed out, no message received in 5 seconds"); //! break; //! } @@ -313,19 +312,38 @@ // And now that you've seen all the races that I found and attempted to fix, // here's the code for you to find some more! -use prelude::v1::*; +use core::prelude::*; -use sync::Arc; -use fmt; -use kinds::marker; -use mem; -use cell::UnsafeCell; +pub use self::TryRecvError::*; +pub use self::TrySendError::*; + +use alloc::arc::Arc; +use core::kinds; +use core::kinds::marker; +use core::mem; +use core::cell::UnsafeCell; pub use self::select::{Select, Handle}; use self::select::StartResult; use self::select::StartResult::*; use self::blocking::SignalToken; +macro_rules! test { + { fn $name:ident() $b:block $(#[$a:meta])*} => ( + mod $name { + #![allow(unused_imports)] + + use super::*; + use comm::*; + use thread::Thread; + use prelude::{Ok, Err, spawn, range, drop, Box, Some, None, Option}; + use prelude::{Vec, Buffer, from_str, Clone}; + + $(#[$a])* #[test] fn f() { $b } + } + ) +} + mod blocking; mod oneshot; mod select; @@ -337,7 +355,7 @@ mod spsc_queue; /// The receiving-half of Rust's channel type. This half can only be owned by /// one task -#[stable] +#[unstable] pub struct Receiver { inner: UnsafeCell>, } @@ -349,14 +367,14 @@ unsafe impl Send for Receiver { } /// An iterator over messages on a receiver, this iterator will block /// whenever `next` is called, waiting for a new message, and `None` will be /// returned when the corresponding channel has hung up. -#[stable] -pub struct Iter<'a, T:'a> { +#[unstable] +pub struct Messages<'a, T:'a> { rx: &'a Receiver } /// The sending-half of Rust's asynchronous channel type. This half can only be /// owned by one task, but it can be cloned to send to other tasks. -#[stable] +#[unstable] pub struct Sender { inner: UnsafeCell>, } @@ -367,50 +385,30 @@ unsafe impl Send for Sender { } /// The sending-half of Rust's synchronous channel type. This half can only be /// owned by one task, but it can be cloned to send to other tasks. -#[stable] +#[unstable = "this type may be renamed, but it will always exist"] pub struct SyncSender { inner: Arc>>, // can't share in an arc _marker: marker::NoSync, } -/// An error returned from the `send` function on channels. -/// -/// A `send` operation can only fail if the receiving end of a channel is -/// disconnected, implying that the data could never be received. The error -/// contains the data being sent as a payload so it can be recovered. -#[derive(PartialEq, Eq)] -#[stable] -pub struct SendError(pub T); - -/// An error returned from the `recv` function on a `Receiver`. -/// -/// The `recv` operation can only fail if the sending half of a channel is -/// disconnected, implying that no further messages will ever be received. -#[derive(PartialEq, Eq, Clone, Copy)] -#[stable] -pub struct RecvError; - /// This enumeration is the list of the possible reasons that try_recv could not /// return data when called. -#[derive(PartialEq, Clone, Copy)] -#[stable] +#[deriving(PartialEq, Clone, Copy, Show)] +#[experimental = "this is likely to be removed in changing try_recv()"] pub enum TryRecvError { /// This channel is currently empty, but the sender(s) have not yet /// disconnected, so data may yet become available. - #[stable] Empty, - /// This channel's sending half has become disconnected, and there will /// never be any more data received on this channel - #[stable] Disconnected, } /// This enumeration is the list of the possible error outcomes for the /// `SyncSender::try_send` method. -#[derive(PartialEq, Clone)] -#[stable] +#[deriving(PartialEq, Clone, Show)] +#[experimental = "this is likely to be removed in changing try_send()"] pub enum TrySendError { /// The data could not be sent on the channel because it would require that /// the callee block to send the data. @@ -418,13 +416,10 @@ pub enum TrySendError { /// If this is a buffered channel, then the buffer is full at this time. If /// this is not a buffered channel, then there is no receiver available to /// acquire the data. - #[stable] Full(T), - /// This channel's receiving half has disconnected, so the data could not be /// sent. The data is returned back to the callee in this case. - #[stable] - Disconnected(T), + RecvDisconnected(T), } enum Flavor { @@ -463,7 +458,6 @@ impl UnsafeFlavor for Receiver { /// # Example /// /// ``` -/// use std::sync::mpsc::channel; /// use std::thread::Thread; /// /// // tx is is the sending half (tx for transmission), and rx is the receiving @@ -473,15 +467,15 @@ impl UnsafeFlavor for Receiver { /// // Spawn off an expensive computation /// Thread::spawn(move|| { /// # fn expensive_computation() {} -/// tx.send(expensive_computation()).unwrap(); +/// tx.send(expensive_computation()); /// }).detach(); /// /// // Do some useful work for awhile /// /// // Let's see what that answer was -/// println!("{}", rx.recv().unwrap()); +/// println!("{}", rx.recv()); /// ``` -#[stable] +#[unstable] pub fn channel() -> (Sender, Receiver) { let a = Arc::new(RacyCell::new(oneshot::Packet::new())); (Sender::new(Flavor::Oneshot(a.clone())), Receiver::new(Flavor::Oneshot(a))) @@ -505,23 +499,23 @@ pub fn channel() -> (Sender, Receiver) { /// # Example /// /// ``` -/// use std::sync::mpsc::sync_channel; /// use std::thread::Thread; /// /// let (tx, rx) = sync_channel(1); /// /// // this returns immediately -/// tx.send(1i).unwrap(); +/// tx.send(1); /// /// Thread::spawn(move|| { /// // this will block until the previous message has been received -/// tx.send(2i).unwrap(); +/// tx.send(2); /// }).detach(); /// -/// assert_eq!(rx.recv().unwrap(), 1i); -/// assert_eq!(rx.recv().unwrap(), 2i); +/// assert_eq!(rx.recv(), 1); +/// assert_eq!(rx.recv(), 2); /// ``` -#[stable] +#[unstable = "this function may be renamed to more accurately reflect the type \ + of channel that is is creating"] pub fn sync_channel(bound: uint) -> (SyncSender, Receiver) { let a = Arc::new(RacyCell::new(sync::Packet::new(bound))); (SyncSender::new(a.clone()), Receiver::new(Flavor::Sync(a))) @@ -538,6 +532,33 @@ impl Sender { } } + /// Sends a value along this channel to be received by the corresponding + /// receiver. + /// + /// Rust channels are infinitely buffered so this method will never block. + /// + /// # Panics + /// + /// This function will panic if the other end of the channel has hung up. + /// This means that if the corresponding receiver has fallen out of scope, + /// this function will trigger a panic message saying that a message is + /// being sent on a closed channel. + /// + /// Note that if this function does *not* panic, it does not mean that the + /// data will be successfully received. All sends are placed into a queue, + /// so it is possible for a send to succeed (the other end is alive), but + /// then the other end could immediately disconnect. + /// + /// The purpose of this functionality is to propagate panics among tasks. + /// If a panic is not desired, then consider using the `send_opt` method + #[experimental = "this function is being considered candidate for removal \ + to adhere to the general guidelines of rust"] + pub fn send(&self, t: T) { + if self.send_opt(t).is_err() { + panic!("sending on a closed channel"); + } + } + /// Attempts to send a value on this channel, returning it back if it could /// not be sent. /// @@ -549,34 +570,37 @@ impl Sender { /// will be received. It is possible for the corresponding receiver to /// hang up immediately after this function returns `Ok`. /// - /// This method will never block the current thread. + /// Like `send`, this method will never block. + /// + /// # Panics + /// + /// This method will never panic, it will return the message back to the + /// caller if the other end is disconnected /// /// # Example /// /// ``` - /// use std::sync::mpsc::channel; - /// /// let (tx, rx) = channel(); /// /// // This send is always successful - /// tx.send(1i).unwrap(); + /// assert_eq!(tx.send_opt(1), Ok(())); /// /// // This send will fail because the receiver is gone /// drop(rx); - /// assert_eq!(tx.send(1i).err().unwrap().0, 1); + /// assert_eq!(tx.send_opt(1), Err(1)); /// ``` - pub fn send(&self, t: T) -> Result<(), SendError> { + #[unstable = "this function may be renamed to send() in the future"] + pub fn send_opt(&self, t: T) -> Result<(), T> { let (new_inner, ret) = match *unsafe { self.inner() } { Flavor::Oneshot(ref p) => { unsafe { let p = p.get(); if !(*p).sent() { - return (*p).send(t).map_err(SendError); + return (*p).send(t); } else { let a = Arc::new(RacyCell::new(stream::Packet::new())); - let rx = Receiver::new(Flavor::Stream(a.clone())); - match (*p).upgrade(rx) { + match (*p).upgrade(Receiver::new(Flavor::Stream(a.clone()))) { oneshot::UpSuccess => { let ret = (*a.get()).send(t); (a, ret) @@ -594,12 +618,8 @@ impl Sender { } } } - Flavor::Stream(ref p) => return unsafe { - (*p.get()).send(t).map_err(SendError) - }, - Flavor::Shared(ref p) => return unsafe { - (*p.get()).send(t).map_err(SendError) - }, + Flavor::Stream(ref p) => return unsafe { (*p.get()).send(t) }, + Flavor::Shared(ref p) => return unsafe { (*p.get()).send(t) }, Flavor::Sync(..) => unreachable!(), }; @@ -607,7 +627,7 @@ impl Sender { let tmp = Sender::new(Flavor::Stream(new_inner)); mem::swap(self.inner_mut(), tmp.inner_mut()); } - ret.map_err(SendError) + return ret; } } @@ -619,8 +639,7 @@ impl Clone for Sender { let a = Arc::new(RacyCell::new(shared::Packet::new())); unsafe { let guard = (*a.get()).postinit_lock(); - let rx = Receiver::new(Flavor::Shared(a.clone())); - match (*p.get()).upgrade(rx) { + match (*p.get()).upgrade(Receiver::new(Flavor::Shared(a.clone()))) { oneshot::UpSuccess | oneshot::UpDisconnected => (a, None, guard), oneshot::UpWoke(task) => (a, Some(task), guard) @@ -631,8 +650,7 @@ impl Clone for Sender { let a = Arc::new(RacyCell::new(shared::Packet::new())); unsafe { let guard = (*a.get()).postinit_lock(); - let rx = Receiver::new(Flavor::Shared(a.clone())); - match (*p.get()).upgrade(rx) { + match (*p.get()).upgrade(Receiver::new(Flavor::Shared(a.clone()))) { stream::UpSuccess | stream::UpDisconnected => (a, None, guard), stream::UpWoke(task) => (a, Some(task), guard), @@ -683,29 +701,59 @@ impl SyncSender { /// available or a receiver is available to hand off the message to. /// /// Note that a successful send does *not* guarantee that the receiver will - /// ever see the data if there is a buffer on this channel. Items may be + /// ever see the data if there is a buffer on this channel. Messages may be /// enqueued in the internal buffer for the receiver to receive at a later /// time. If the buffer size is 0, however, it can be guaranteed that the /// receiver has indeed received the data if this function returns success. /// - /// This function will never panic, but it may return `Err` if the - /// `Receiver` has disconnected and is no longer able to receive - /// information. - #[stable] - pub fn send(&self, t: T) -> Result<(), SendError> { - unsafe { (*self.inner.get()).send(t).map_err(SendError) } + /// # Panics + /// + /// Similarly to `Sender::send`, this function will panic if the + /// corresponding `Receiver` for this channel has disconnected. This + /// behavior is used to propagate panics among tasks. + /// + /// If a panic is not desired, you can achieve the same semantics with the + /// `SyncSender::send_opt` method which will not panic if the receiver + /// disconnects. + #[experimental = "this function is being considered candidate for removal \ + to adhere to the general guidelines of rust"] + pub fn send(&self, t: T) { + if self.send_opt(t).is_err() { + panic!("sending on a closed channel"); + } + } + + /// Send a value on a channel, returning it back if the receiver + /// disconnected + /// + /// This method will *block* to send the value `t` on the channel, but if + /// the value could not be sent due to the receiver disconnecting, the value + /// is returned back to the callee. This function is similar to `try_send`, + /// except that it will block if the channel is currently full. + /// + /// # Panics + /// + /// This function cannot panic. + #[unstable = "this function may be renamed to send() in the future"] + pub fn send_opt(&self, t: T) -> Result<(), T> { + unsafe { (*self.inner.get()).send(t) } } /// Attempts to send a value on this channel without blocking. /// - /// This method differs from `send` by returning immediately if the + /// This method differs from `send_opt` by returning immediately if the /// channel's buffer is full or no receiver is waiting to acquire some - /// data. Compared with `send`, this function has two failure cases + /// data. Compared with `send_opt`, this function has two failure cases /// instead of one (one for disconnection, one for a full buffer). /// /// See `SyncSender::send` for notes about guarantees of whether the /// receiver has received the data or not if this function is successful. - #[stable] + /// + /// # Panics + /// + /// This function cannot panic + #[unstable = "the return type of this function is candidate for \ + modification"] pub fn try_send(&self, t: T) -> Result<(), TrySendError> { unsafe { (*self.inner.get()).try_send(t) } } @@ -735,6 +783,34 @@ impl Receiver { Receiver { inner: UnsafeCell::new(inner) } } + /// Blocks waiting for a value on this receiver + /// + /// This function will block if necessary to wait for a corresponding send + /// on the channel from its paired `Sender` structure. This receiver will + /// be woken up when data is ready, and the data will be returned. + /// + /// # Panics + /// + /// Similar to channels, this method will trigger a task panic if the + /// other end of the channel has hung up (been deallocated). The purpose of + /// this is to propagate panics among tasks. + /// + /// If a panic is not desired, then there are two options: + /// + /// * If blocking is still desired, the `recv_opt` method will return `None` + /// when the other end hangs up + /// + /// * If blocking is not desired, then the `try_recv` method will attempt to + /// peek at a value on this receiver. + #[experimental = "this function is being considered candidate for removal \ + to adhere to the general guidelines of rust"] + pub fn recv(&self) -> T { + match self.recv_opt() { + Ok(t) => t, + Err(()) => panic!("receiving on a closed channel"), + } + } + /// Attempts to return a pending value on this receiver without blocking /// /// This method will never block the caller in order to wait for data to @@ -743,46 +819,42 @@ impl Receiver { /// /// This is useful for a flavor of "optimistic check" before deciding to /// block on a receiver. - #[stable] + /// + /// # Panics + /// + /// This function cannot panic. + #[unstable = "the return type of this function may be altered"] pub fn try_recv(&self) -> Result { loop { let new_port = match *unsafe { self.inner() } { Flavor::Oneshot(ref p) => { match unsafe { (*p.get()).try_recv() } { Ok(t) => return Ok(t), - Err(oneshot::Empty) => return Err(TryRecvError::Empty), - Err(oneshot::Disconnected) => { - return Err(TryRecvError::Disconnected) - } + Err(oneshot::Empty) => return Err(Empty), + Err(oneshot::Disconnected) => return Err(Disconnected), Err(oneshot::Upgraded(rx)) => rx, } } Flavor::Stream(ref p) => { match unsafe { (*p.get()).try_recv() } { Ok(t) => return Ok(t), - Err(stream::Empty) => return Err(TryRecvError::Empty), - Err(stream::Disconnected) => { - return Err(TryRecvError::Disconnected) - } + Err(stream::Empty) => return Err(Empty), + Err(stream::Disconnected) => return Err(Disconnected), Err(stream::Upgraded(rx)) => rx, } } Flavor::Shared(ref p) => { match unsafe { (*p.get()).try_recv() } { Ok(t) => return Ok(t), - Err(shared::Empty) => return Err(TryRecvError::Empty), - Err(shared::Disconnected) => { - return Err(TryRecvError::Disconnected) - } + Err(shared::Empty) => return Err(Empty), + Err(shared::Disconnected) => return Err(Disconnected), } } Flavor::Sync(ref p) => { match unsafe { (*p.get()).try_recv() } { Ok(t) => return Ok(t), - Err(sync::Empty) => return Err(TryRecvError::Empty), - Err(sync::Disconnected) => { - return Err(TryRecvError::Disconnected) - } + Err(sync::Empty) => return Err(Empty), + Err(sync::Disconnected) => return Err(Disconnected), } } }; @@ -793,26 +865,27 @@ impl Receiver { } } - /// Attempt to wait for a value on this receiver, returning an error if the + /// Attempt to wait for a value on this receiver, but does not panic if the /// corresponding channel has hung up. /// - /// This function will always block the current thread if there is no data - /// available and it's possible for more data to be sent. Once a message is - /// sent to the corresponding `Sender`, then this receiver will wake up and - /// return that message. + /// This implementation of iterators for ports will always block if there is + /// not data available on the receiver, but it will not panic in the case + /// that the channel has been deallocated. /// - /// If the corresponding `Sender` has disconnected, or it disconnects while - /// this call is blocking, this call will wake up and return `Err` to - /// indicate that no more messages can ever be received on this channel. - #[stable] - pub fn recv(&self) -> Result { + /// In other words, this function has the same semantics as the `recv` + /// method except for the panic aspect. + /// + /// If the channel has hung up, then `Err` is returned. Otherwise `Ok` of + /// the value found on the receiver is returned. + #[unstable = "this function may be renamed to recv()"] + pub fn recv_opt(&self) -> Result { loop { let new_port = match *unsafe { self.inner() } { Flavor::Oneshot(ref p) => { match unsafe { (*p.get()).recv() } { Ok(t) => return Ok(t), Err(oneshot::Empty) => return unreachable!(), - Err(oneshot::Disconnected) => return Err(RecvError), + Err(oneshot::Disconnected) => return Err(()), Err(oneshot::Upgraded(rx)) => rx, } } @@ -820,7 +893,7 @@ impl Receiver { match unsafe { (*p.get()).recv() } { Ok(t) => return Ok(t), Err(stream::Empty) => return unreachable!(), - Err(stream::Disconnected) => return Err(RecvError), + Err(stream::Disconnected) => return Err(()), Err(stream::Upgraded(rx)) => rx, } } @@ -828,12 +901,10 @@ impl Receiver { match unsafe { (*p.get()).recv() } { Ok(t) => return Ok(t), Err(shared::Empty) => return unreachable!(), - Err(shared::Disconnected) => return Err(RecvError), + Err(shared::Disconnected) => return Err(()), } } - Flavor::Sync(ref p) => return unsafe { - (*p.get()).recv().map_err(|()| RecvError) - } + Flavor::Sync(ref p) => return unsafe { (*p.get()).recv() } }; unsafe { mem::swap(self.inner_mut(), new_port.inner_mut()); @@ -843,9 +914,9 @@ impl Receiver { /// Returns an iterator that will block waiting for messages, but never /// `panic!`. It will return `None` when the channel has hung up. - #[stable] - pub fn iter(&self) -> Iter { - Iter { rx: self } + #[unstable] + pub fn iter<'a>(&'a self) -> Messages<'a, T> { + Messages { rx: self } } } @@ -936,10 +1007,8 @@ impl select::Packet for Receiver { } #[unstable] -impl<'a, T: Send> Iterator for Iter<'a, T> { - type Item = T; - - fn next(&mut self) -> Option { self.rx.recv().ok() } +impl<'a, T: Send> Iterator for Messages<'a, T> { + fn next(&mut self) -> Option { self.rx.recv_opt().ok() } } #[unsafe_destructor] @@ -972,425 +1041,368 @@ impl RacyCell { unsafe impl Send for RacyCell { } -unsafe impl Sync for RacyCell { } // Oh dear - -impl fmt::Show for SendError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - "sending on a closed channel".fmt(f) - } -} - -impl fmt::Show for TrySendError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - TrySendError::Full(..) => { - "sending on a full channel".fmt(f) - } - TrySendError::Disconnected(..) => { - "sending on a closed channel".fmt(f) - } - } - } -} - -impl fmt::Show for RecvError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - "receiving on a closed channel".fmt(f) - } -} +unsafe impl kinds::Sync for RacyCell { } // Oh dear -impl fmt::Show for TryRecvError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - TryRecvError::Empty => { - "receiving on an empty channel".fmt(f) - } - TryRecvError::Disconnected => { - "receiving on a closed channel".fmt(f) - } - } - } -} #[cfg(test)] mod test { - use prelude::v1::*; - - use os; use super::*; - use thread::Thread; + use prelude::{spawn, range, Some, None, from_str, Clone, Str}; + use os; pub fn stress_factor() -> uint { match os::getenv("RUST_TEST_STRESS") { - Some(val) => val.parse().unwrap(), + Some(val) => from_str::(val.as_slice()).unwrap(), None => 1, } } - #[test] - fn smoke() { + test! { fn smoke() { let (tx, rx) = channel::(); - tx.send(1).unwrap(); - assert_eq!(rx.recv().unwrap(), 1); - } + tx.send(1); + assert_eq!(rx.recv(), 1); + } } - #[test] - fn drop_full() { + test! { fn drop_full() { let (tx, _rx) = channel(); - tx.send(box 1i).unwrap(); - } + tx.send(box 1i); + } } - #[test] - fn drop_full_shared() { + test! { fn drop_full_shared() { let (tx, _rx) = channel(); drop(tx.clone()); drop(tx.clone()); - tx.send(box 1i).unwrap(); - } + tx.send(box 1i); + } } - #[test] - fn smoke_shared() { + test! { fn smoke_shared() { let (tx, rx) = channel::(); - tx.send(1).unwrap(); - assert_eq!(rx.recv().unwrap(), 1); + tx.send(1); + assert_eq!(rx.recv(), 1); let tx = tx.clone(); - tx.send(1).unwrap(); - assert_eq!(rx.recv().unwrap(), 1); - } + tx.send(1); + assert_eq!(rx.recv(), 1); + } } - #[test] - fn smoke_threads() { + test! { fn smoke_threads() { let (tx, rx) = channel::(); - let _t = Thread::spawn(move|| { - tx.send(1).unwrap(); + spawn(move|| { + tx.send(1); }); - assert_eq!(rx.recv().unwrap(), 1); - } + assert_eq!(rx.recv(), 1); + } } - #[test] - fn smoke_port_gone() { + test! { fn smoke_port_gone() { let (tx, rx) = channel::(); drop(rx); - assert!(tx.send(1).is_err()); - } + tx.send(1); + } #[should_fail] } - #[test] - fn smoke_shared_port_gone() { + test! { fn smoke_shared_port_gone() { let (tx, rx) = channel::(); drop(rx); - assert!(tx.send(1).is_err()) - } + tx.send(1); + } #[should_fail] } - #[test] - fn smoke_shared_port_gone2() { + test! { fn smoke_shared_port_gone2() { let (tx, rx) = channel::(); drop(rx); let tx2 = tx.clone(); drop(tx); - assert!(tx2.send(1).is_err()); - } + tx2.send(1); + } #[should_fail] } - #[test] - fn port_gone_concurrent() { + test! { fn port_gone_concurrent() { let (tx, rx) = channel::(); - let _t = Thread::spawn(move|| { - rx.recv().unwrap(); + spawn(move|| { + rx.recv(); }); - while tx.send(1).is_ok() {} - } + loop { tx.send(1) } + } #[should_fail] } - #[test] - fn port_gone_concurrent_shared() { + test! { fn port_gone_concurrent_shared() { let (tx, rx) = channel::(); let tx2 = tx.clone(); - let _t = Thread::spawn(move|| { - rx.recv().unwrap(); + spawn(move|| { + rx.recv(); }); - while tx.send(1).is_ok() && tx2.send(1).is_ok() {} - } + loop { + tx.send(1); + tx2.send(1); + } + } #[should_fail] } - #[test] - fn smoke_chan_gone() { + test! { fn smoke_chan_gone() { let (tx, rx) = channel::(); drop(tx); - assert!(rx.recv().is_err()); - } + rx.recv(); + } #[should_fail] } - #[test] - fn smoke_chan_gone_shared() { + test! { fn smoke_chan_gone_shared() { let (tx, rx) = channel::<()>(); let tx2 = tx.clone(); drop(tx); drop(tx2); - assert!(rx.recv().is_err()); - } + rx.recv(); + } #[should_fail] } - #[test] - fn chan_gone_concurrent() { + test! { fn chan_gone_concurrent() { let (tx, rx) = channel::(); - let _t = Thread::spawn(move|| { - tx.send(1).unwrap(); - tx.send(1).unwrap(); + spawn(move|| { + tx.send(1); + tx.send(1); }); - while rx.recv().is_ok() {} - } + loop { rx.recv(); } + } #[should_fail] } - #[test] - fn stress() { + test! { fn stress() { let (tx, rx) = channel::(); - let t = Thread::spawn(move|| { - for _ in range(0u, 10000) { tx.send(1i).unwrap(); } + spawn(move|| { + for _ in range(0u, 10000) { tx.send(1i); } }); for _ in range(0u, 10000) { - assert_eq!(rx.recv().unwrap(), 1); + assert_eq!(rx.recv(), 1); } - t.join().ok().unwrap(); - } + } } - #[test] - fn stress_shared() { + test! { fn stress_shared() { static AMT: uint = 10000; static NTHREADS: uint = 8; let (tx, rx) = channel::(); + let (dtx, drx) = channel::<()>(); - let t = Thread::spawn(move|| { + spawn(move|| { for _ in range(0, AMT * NTHREADS) { - assert_eq!(rx.recv().unwrap(), 1); + assert_eq!(rx.recv(), 1); } match rx.try_recv() { Ok(..) => panic!(), _ => {} } + dtx.send(()); }); for _ in range(0, NTHREADS) { let tx = tx.clone(); - Thread::spawn(move|| { - for _ in range(0, AMT) { tx.send(1).unwrap(); } - }).detach(); + spawn(move|| { + for _ in range(0, AMT) { tx.send(1); } + }); } drop(tx); - t.join().ok().unwrap(); - } + drx.recv(); + } } #[test] fn send_from_outside_runtime() { let (tx1, rx1) = channel::<()>(); let (tx2, rx2) = channel::(); - let t1 = Thread::spawn(move|| { - tx1.send(()).unwrap(); + let (tx3, rx3) = channel::<()>(); + let tx4 = tx3.clone(); + spawn(move|| { + tx1.send(()); for _ in range(0i, 40) { - assert_eq!(rx2.recv().unwrap(), 1); + assert_eq!(rx2.recv(), 1); } + tx3.send(()); }); - rx1.recv().unwrap(); - let t2 = Thread::spawn(move|| { + rx1.recv(); + spawn(move|| { for _ in range(0i, 40) { - tx2.send(1).unwrap(); + tx2.send(1); } + tx4.send(()); }); - t1.join().ok().unwrap(); - t2.join().ok().unwrap(); + rx3.recv(); + rx3.recv(); } #[test] fn recv_from_outside_runtime() { let (tx, rx) = channel::(); - let t = Thread::spawn(move|| { + let (dtx, drx) = channel(); + spawn(move|| { for _ in range(0i, 40) { - assert_eq!(rx.recv().unwrap(), 1); + assert_eq!(rx.recv(), 1); } + dtx.send(()); }); for _ in range(0u, 40) { - tx.send(1).unwrap(); + tx.send(1); } - t.join().ok().unwrap(); + drx.recv(); } #[test] fn no_runtime() { let (tx1, rx1) = channel::(); let (tx2, rx2) = channel::(); - let t1 = Thread::spawn(move|| { - assert_eq!(rx1.recv().unwrap(), 1); - tx2.send(2).unwrap(); + let (tx3, rx3) = channel::<()>(); + let tx4 = tx3.clone(); + spawn(move|| { + assert_eq!(rx1.recv(), 1); + tx2.send(2); + tx4.send(()); }); - let t2 = Thread::spawn(move|| { - tx1.send(1).unwrap(); - assert_eq!(rx2.recv().unwrap(), 2); + spawn(move|| { + tx1.send(1); + assert_eq!(rx2.recv(), 2); + tx3.send(()); }); - t1.join().ok().unwrap(); - t2.join().ok().unwrap(); + rx3.recv(); + rx3.recv(); } - #[test] - fn oneshot_single_thread_close_port_first() { + test! { fn oneshot_single_thread_close_port_first() { // Simple test of closing without sending let (_tx, rx) = channel::(); drop(rx); - } + } } - #[test] - fn oneshot_single_thread_close_chan_first() { + test! { fn oneshot_single_thread_close_chan_first() { // Simple test of closing without sending let (tx, _rx) = channel::(); drop(tx); - } + } } - #[test] - fn oneshot_single_thread_send_port_close() { + test! { fn oneshot_single_thread_send_port_close() { // Testing that the sender cleans up the payload if receiver is closed let (tx, rx) = channel::>(); drop(rx); - assert!(tx.send(box 0).is_err()); - } + tx.send(box 0); + } #[should_fail] } - #[test] - fn oneshot_single_thread_recv_chan_close() { + test! { fn oneshot_single_thread_recv_chan_close() { // Receiving on a closed chan will panic let res = Thread::spawn(move|| { let (tx, rx) = channel::(); drop(tx); - rx.recv().unwrap(); + rx.recv(); }).join(); // What is our res? assert!(res.is_err()); - } + } } - #[test] - fn oneshot_single_thread_send_then_recv() { + test! { fn oneshot_single_thread_send_then_recv() { let (tx, rx) = channel::>(); - tx.send(box 10).unwrap(); - assert!(rx.recv().unwrap() == box 10); - } + tx.send(box 10); + assert!(rx.recv() == box 10); + } } - #[test] - fn oneshot_single_thread_try_send_open() { + test! { fn oneshot_single_thread_try_send_open() { let (tx, rx) = channel::(); - assert!(tx.send(10).is_ok()); - assert!(rx.recv().unwrap() == 10); - } + assert!(tx.send_opt(10).is_ok()); + assert!(rx.recv() == 10); + } } - #[test] - fn oneshot_single_thread_try_send_closed() { + test! { fn oneshot_single_thread_try_send_closed() { let (tx, rx) = channel::(); drop(rx); - assert!(tx.send(10).is_err()); - } + assert!(tx.send_opt(10).is_err()); + } } - #[test] - fn oneshot_single_thread_try_recv_open() { + test! { fn oneshot_single_thread_try_recv_open() { let (tx, rx) = channel::(); - tx.send(10).unwrap(); - assert!(rx.recv() == Ok(10)); - } + tx.send(10); + assert!(rx.recv_opt() == Ok(10)); + } } - #[test] - fn oneshot_single_thread_try_recv_closed() { + test! { fn oneshot_single_thread_try_recv_closed() { let (tx, rx) = channel::(); drop(tx); - assert!(rx.recv().is_err()); - } + assert!(rx.recv_opt() == Err(())); + } } - #[test] - fn oneshot_single_thread_peek_data() { + test! { fn oneshot_single_thread_peek_data() { let (tx, rx) = channel::(); - assert_eq!(rx.try_recv(), Err(TryRecvError::Empty)); - tx.send(10).unwrap(); + assert_eq!(rx.try_recv(), Err(Empty)); + tx.send(10); assert_eq!(rx.try_recv(), Ok(10)); - } + } } - #[test] - fn oneshot_single_thread_peek_close() { + test! { fn oneshot_single_thread_peek_close() { let (tx, rx) = channel::(); drop(tx); - assert_eq!(rx.try_recv(), Err(TryRecvError::Disconnected)); - assert_eq!(rx.try_recv(), Err(TryRecvError::Disconnected)); - } + assert_eq!(rx.try_recv(), Err(Disconnected)); + assert_eq!(rx.try_recv(), Err(Disconnected)); + } } - #[test] - fn oneshot_single_thread_peek_open() { + test! { fn oneshot_single_thread_peek_open() { let (_tx, rx) = channel::(); - assert_eq!(rx.try_recv(), Err(TryRecvError::Empty)); - } + assert_eq!(rx.try_recv(), Err(Empty)); + } } - #[test] - fn oneshot_multi_task_recv_then_send() { + test! { fn oneshot_multi_task_recv_then_send() { let (tx, rx) = channel::>(); - let _t = Thread::spawn(move|| { - assert!(rx.recv().unwrap() == box 10); + spawn(move|| { + assert!(rx.recv() == box 10); }); - tx.send(box 10).unwrap(); - } + tx.send(box 10); + } } - #[test] - fn oneshot_multi_task_recv_then_close() { + test! { fn oneshot_multi_task_recv_then_close() { let (tx, rx) = channel::>(); - let _t = Thread::spawn(move|| { + spawn(move|| { drop(tx); }); let res = Thread::spawn(move|| { - assert!(rx.recv().unwrap() == box 10); + assert!(rx.recv() == box 10); }).join(); assert!(res.is_err()); - } + } } - #[test] - fn oneshot_multi_thread_close_stress() { + test! { fn oneshot_multi_thread_close_stress() { for _ in range(0, stress_factor()) { let (tx, rx) = channel::(); - let _t = Thread::spawn(move|| { + spawn(move|| { drop(rx); }); drop(tx); } - } + } } - #[test] - fn oneshot_multi_thread_send_close_stress() { + test! { fn oneshot_multi_thread_send_close_stress() { for _ in range(0, stress_factor()) { let (tx, rx) = channel::(); - let _t = Thread::spawn(move|| { + spawn(move|| { drop(rx); }); let _ = Thread::spawn(move|| { - tx.send(1).unwrap(); + tx.send(1); }).join(); } - } + } } - #[test] - fn oneshot_multi_thread_recv_close_stress() { + test! { fn oneshot_multi_thread_recv_close_stress() { for _ in range(0, stress_factor()) { let (tx, rx) = channel::(); - Thread::spawn(move|| { + spawn(move|| { let res = Thread::spawn(move|| { - rx.recv().unwrap(); + rx.recv(); }).join(); assert!(res.is_err()); - }).detach(); - let _t = Thread::spawn(move|| { - Thread::spawn(move|| { + }); + spawn(move|| { + spawn(move|| { drop(tx); - }).detach(); + }); }); } - } + } } - #[test] - fn oneshot_multi_thread_send_recv_stress() { + test! { fn oneshot_multi_thread_send_recv_stress() { for _ in range(0, stress_factor()) { let (tx, rx) = channel(); - let _t = Thread::spawn(move|| { - tx.send(box 10i).unwrap(); + spawn(move|| { + tx.send(box 10i); + }); + spawn(move|| { + assert!(rx.recv() == box 10i); }); - assert!(rx.recv().unwrap() == box 10i); } - } + } } - #[test] - fn stream_send_recv_stress() { + test! { fn stream_send_recv_stress() { for _ in range(0, stress_factor()) { let (tx, rx) = channel(); @@ -1400,73 +1412,69 @@ mod test { fn send(tx: Sender>, i: int) { if i == 10 { return } - Thread::spawn(move|| { - tx.send(box i).unwrap(); + spawn(move|| { + tx.send(box i); send(tx, i + 1); - }).detach(); + }); } fn recv(rx: Receiver>, i: int) { if i == 10 { return } - Thread::spawn(move|| { - assert!(rx.recv().unwrap() == box i); + spawn(move|| { + assert!(rx.recv() == box i); recv(rx, i + 1); - }).detach(); + }); } } - } + } } - #[test] - fn recv_a_lot() { + test! { fn recv_a_lot() { // Regression test that we don't run out of stack in scheduler context let (tx, rx) = channel(); - for _ in range(0i, 10000) { tx.send(()).unwrap(); } - for _ in range(0i, 10000) { rx.recv().unwrap(); } - } + for _ in range(0i, 10000) { tx.send(()); } + for _ in range(0i, 10000) { rx.recv(); } + } } - #[test] - fn shared_chan_stress() { + test! { fn shared_chan_stress() { let (tx, rx) = channel(); let total = stress_factor() + 100; for _ in range(0, total) { let tx = tx.clone(); - Thread::spawn(move|| { - tx.send(()).unwrap(); - }).detach(); + spawn(move|| { + tx.send(()); + }); } for _ in range(0, total) { - rx.recv().unwrap(); + rx.recv(); } - } + } } - #[test] - fn test_nested_recv_iter() { + test! { fn test_nested_recv_iter() { let (tx, rx) = channel::(); let (total_tx, total_rx) = channel::(); - let _t = Thread::spawn(move|| { + spawn(move|| { let mut acc = 0; for x in rx.iter() { acc += x; } - total_tx.send(acc).unwrap(); + total_tx.send(acc); }); - tx.send(3).unwrap(); - tx.send(1).unwrap(); - tx.send(2).unwrap(); + tx.send(3); + tx.send(1); + tx.send(2); drop(tx); - assert_eq!(total_rx.recv().unwrap(), 6); - } + assert_eq!(total_rx.recv(), 6); + } } - #[test] - fn test_recv_iter_break() { + test! { fn test_recv_iter_break() { let (tx, rx) = channel::(); let (count_tx, count_rx) = channel(); - let _t = Thread::spawn(move|| { + spawn(move|| { let mut count = 0; for x in rx.iter() { if count >= 3 { @@ -1475,51 +1483,49 @@ mod test { count += x; } } - count_tx.send(count).unwrap(); + count_tx.send(count); }); - tx.send(2).unwrap(); - tx.send(2).unwrap(); - tx.send(2).unwrap(); - let _ = tx.send(2); + tx.send(2); + tx.send(2); + tx.send(2); + let _ = tx.send_opt(2); drop(tx); - assert_eq!(count_rx.recv().unwrap(), 4); - } + assert_eq!(count_rx.recv(), 4); + } } - #[test] - fn try_recv_states() { + test! { fn try_recv_states() { let (tx1, rx1) = channel::(); let (tx2, rx2) = channel::<()>(); let (tx3, rx3) = channel::<()>(); - let _t = Thread::spawn(move|| { - rx2.recv().unwrap(); - tx1.send(1).unwrap(); - tx3.send(()).unwrap(); - rx2.recv().unwrap(); + spawn(move|| { + rx2.recv(); + tx1.send(1); + tx3.send(()); + rx2.recv(); drop(tx1); - tx3.send(()).unwrap(); + tx3.send(()); }); - assert_eq!(rx1.try_recv(), Err(TryRecvError::Empty)); - tx2.send(()).unwrap(); - rx3.recv().unwrap(); + assert_eq!(rx1.try_recv(), Err(Empty)); + tx2.send(()); + rx3.recv(); assert_eq!(rx1.try_recv(), Ok(1)); - assert_eq!(rx1.try_recv(), Err(TryRecvError::Empty)); - tx2.send(()).unwrap(); - rx3.recv().unwrap(); - assert_eq!(rx1.try_recv(), Err(TryRecvError::Disconnected)); - } + assert_eq!(rx1.try_recv(), Err(Empty)); + tx2.send(()); + rx3.recv(); + assert_eq!(rx1.try_recv(), Err(Disconnected)); + } } // This bug used to end up in a livelock inside of the Receiver destructor // because the internal state of the Shared packet was corrupted - #[test] - fn destroy_upgraded_shared_port_when_sender_still_active() { + test! { fn destroy_upgraded_shared_port_when_sender_still_active() { let (tx, rx) = channel(); let (tx2, rx2) = channel(); - let _t = Thread::spawn(move|| { - rx.recv().unwrap(); // wait on a oneshot + spawn(move|| { + rx.recv(); // wait on a oneshot drop(rx); // destroy a shared - tx2.send(()).unwrap(); + tx2.send(()); }); // make sure the other task has gone to sleep for _ in range(0u, 5000) { Thread::yield_now(); } @@ -1527,334 +1533,303 @@ mod test { // upgrade to a shared chan and send a message let t = tx.clone(); drop(tx); - t.send(()).unwrap(); + t.send(()); // wait for the child task to exit before we exit - rx2.recv().unwrap(); - } + rx2.recv(); + }} } #[cfg(test)] mod sync_tests { - use prelude::v1::*; - + use prelude::*; use os; - use thread::Thread; - use super::*; pub fn stress_factor() -> uint { match os::getenv("RUST_TEST_STRESS") { - Some(val) => val.parse().unwrap(), + Some(val) => from_str::(val.as_slice()).unwrap(), None => 1, } } - #[test] - fn smoke() { + test! { fn smoke() { let (tx, rx) = sync_channel::(1); - tx.send(1).unwrap(); - assert_eq!(rx.recv().unwrap(), 1); - } + tx.send(1); + assert_eq!(rx.recv(), 1); + } } - #[test] - fn drop_full() { + test! { fn drop_full() { let (tx, _rx) = sync_channel(1); - tx.send(box 1i).unwrap(); - } + tx.send(box 1i); + } } - #[test] - fn smoke_shared() { + test! { fn smoke_shared() { let (tx, rx) = sync_channel::(1); - tx.send(1).unwrap(); - assert_eq!(rx.recv().unwrap(), 1); + tx.send(1); + assert_eq!(rx.recv(), 1); let tx = tx.clone(); - tx.send(1).unwrap(); - assert_eq!(rx.recv().unwrap(), 1); - } + tx.send(1); + assert_eq!(rx.recv(), 1); + } } - #[test] - fn smoke_threads() { + test! { fn smoke_threads() { let (tx, rx) = sync_channel::(0); - let _t = Thread::spawn(move|| { - tx.send(1).unwrap(); + spawn(move|| { + tx.send(1); }); - assert_eq!(rx.recv().unwrap(), 1); - } + assert_eq!(rx.recv(), 1); + } } - #[test] - fn smoke_port_gone() { + test! { fn smoke_port_gone() { let (tx, rx) = sync_channel::(0); drop(rx); - assert!(tx.send(1).is_err()); - } + tx.send(1); + } #[should_fail] } - #[test] - fn smoke_shared_port_gone2() { + test! { fn smoke_shared_port_gone2() { let (tx, rx) = sync_channel::(0); drop(rx); let tx2 = tx.clone(); drop(tx); - assert!(tx2.send(1).is_err()); - } + tx2.send(1); + } #[should_fail] } - #[test] - fn port_gone_concurrent() { + test! { fn port_gone_concurrent() { let (tx, rx) = sync_channel::(0); - let _t = Thread::spawn(move|| { - rx.recv().unwrap(); + spawn(move|| { + rx.recv(); }); - while tx.send(1).is_ok() {} - } + loop { tx.send(1) } + } #[should_fail] } - #[test] - fn port_gone_concurrent_shared() { + test! { fn port_gone_concurrent_shared() { let (tx, rx) = sync_channel::(0); let tx2 = tx.clone(); - let _t = Thread::spawn(move|| { - rx.recv().unwrap(); + spawn(move|| { + rx.recv(); }); - while tx.send(1).is_ok() && tx2.send(1).is_ok() {} - } + loop { + tx.send(1); + tx2.send(1); + } + } #[should_fail] } - #[test] - fn smoke_chan_gone() { + test! { fn smoke_chan_gone() { let (tx, rx) = sync_channel::(0); drop(tx); - assert!(rx.recv().is_err()); - } + rx.recv(); + } #[should_fail] } - #[test] - fn smoke_chan_gone_shared() { + test! { fn smoke_chan_gone_shared() { let (tx, rx) = sync_channel::<()>(0); let tx2 = tx.clone(); drop(tx); drop(tx2); - assert!(rx.recv().is_err()); - } + rx.recv(); + } #[should_fail] } - #[test] - fn chan_gone_concurrent() { + test! { fn chan_gone_concurrent() { let (tx, rx) = sync_channel::(0); - Thread::spawn(move|| { - tx.send(1).unwrap(); - tx.send(1).unwrap(); - }).detach(); - while rx.recv().is_ok() {} - } + spawn(move|| { + tx.send(1); + tx.send(1); + }); + loop { rx.recv(); } + } #[should_fail] } - #[test] - fn stress() { + test! { fn stress() { let (tx, rx) = sync_channel::(0); - Thread::spawn(move|| { - for _ in range(0u, 10000) { tx.send(1).unwrap(); } - }).detach(); + spawn(move|| { + for _ in range(0u, 10000) { tx.send(1); } + }); for _ in range(0u, 10000) { - assert_eq!(rx.recv().unwrap(), 1); + assert_eq!(rx.recv(), 1); } - } + } } - #[test] - fn stress_shared() { + test! { fn stress_shared() { static AMT: uint = 1000; static NTHREADS: uint = 8; let (tx, rx) = sync_channel::(0); let (dtx, drx) = sync_channel::<()>(0); - Thread::spawn(move|| { + spawn(move|| { for _ in range(0, AMT * NTHREADS) { - assert_eq!(rx.recv().unwrap(), 1); + assert_eq!(rx.recv(), 1); } match rx.try_recv() { Ok(..) => panic!(), _ => {} } - dtx.send(()).unwrap(); - }).detach(); + dtx.send(()); + }); for _ in range(0, NTHREADS) { let tx = tx.clone(); - Thread::spawn(move|| { - for _ in range(0, AMT) { tx.send(1).unwrap(); } - }).detach(); + spawn(move|| { + for _ in range(0, AMT) { tx.send(1); } + }); } drop(tx); - drx.recv().unwrap(); - } + drx.recv(); + } } - #[test] - fn oneshot_single_thread_close_port_first() { + test! { fn oneshot_single_thread_close_port_first() { // Simple test of closing without sending let (_tx, rx) = sync_channel::(0); drop(rx); - } + } } - #[test] - fn oneshot_single_thread_close_chan_first() { + test! { fn oneshot_single_thread_close_chan_first() { // Simple test of closing without sending let (tx, _rx) = sync_channel::(0); drop(tx); - } + } } - #[test] - fn oneshot_single_thread_send_port_close() { + test! { fn oneshot_single_thread_send_port_close() { // Testing that the sender cleans up the payload if receiver is closed let (tx, rx) = sync_channel::>(0); drop(rx); - assert!(tx.send(box 0).is_err()); - } + tx.send(box 0); + } #[should_fail] } - #[test] - fn oneshot_single_thread_recv_chan_close() { + test! { fn oneshot_single_thread_recv_chan_close() { // Receiving on a closed chan will panic let res = Thread::spawn(move|| { let (tx, rx) = sync_channel::(0); drop(tx); - rx.recv().unwrap(); + rx.recv(); }).join(); // What is our res? assert!(res.is_err()); - } + } } - #[test] - fn oneshot_single_thread_send_then_recv() { + test! { fn oneshot_single_thread_send_then_recv() { let (tx, rx) = sync_channel::>(1); - tx.send(box 10).unwrap(); - assert!(rx.recv().unwrap() == box 10); - } + tx.send(box 10); + assert!(rx.recv() == box 10); + } } - #[test] - fn oneshot_single_thread_try_send_open() { + test! { fn oneshot_single_thread_try_send_open() { let (tx, rx) = sync_channel::(1); assert_eq!(tx.try_send(10), Ok(())); - assert!(rx.recv().unwrap() == 10); - } + assert!(rx.recv() == 10); + } } - #[test] - fn oneshot_single_thread_try_send_closed() { + test! { fn oneshot_single_thread_try_send_closed() { let (tx, rx) = sync_channel::(0); drop(rx); - assert_eq!(tx.try_send(10), Err(TrySendError::Disconnected(10))); - } + assert_eq!(tx.try_send(10), Err(RecvDisconnected(10))); + } } - #[test] - fn oneshot_single_thread_try_send_closed2() { + test! { fn oneshot_single_thread_try_send_closed2() { let (tx, _rx) = sync_channel::(0); - assert_eq!(tx.try_send(10), Err(TrySendError::Full(10))); - } + assert_eq!(tx.try_send(10), Err(Full(10))); + } } - #[test] - fn oneshot_single_thread_try_recv_open() { + test! { fn oneshot_single_thread_try_recv_open() { let (tx, rx) = sync_channel::(1); - tx.send(10).unwrap(); - assert!(rx.recv() == Ok(10)); - } + tx.send(10); + assert!(rx.recv_opt() == Ok(10)); + } } - #[test] - fn oneshot_single_thread_try_recv_closed() { + test! { fn oneshot_single_thread_try_recv_closed() { let (tx, rx) = sync_channel::(0); drop(tx); - assert!(rx.recv().is_err()); - } + assert!(rx.recv_opt() == Err(())); + } } - #[test] - fn oneshot_single_thread_peek_data() { + test! { fn oneshot_single_thread_peek_data() { let (tx, rx) = sync_channel::(1); - assert_eq!(rx.try_recv(), Err(TryRecvError::Empty)); - tx.send(10).unwrap(); + assert_eq!(rx.try_recv(), Err(Empty)); + tx.send(10); assert_eq!(rx.try_recv(), Ok(10)); - } + } } - #[test] - fn oneshot_single_thread_peek_close() { + test! { fn oneshot_single_thread_peek_close() { let (tx, rx) = sync_channel::(0); drop(tx); - assert_eq!(rx.try_recv(), Err(TryRecvError::Disconnected)); - assert_eq!(rx.try_recv(), Err(TryRecvError::Disconnected)); - } + assert_eq!(rx.try_recv(), Err(Disconnected)); + assert_eq!(rx.try_recv(), Err(Disconnected)); + } } - #[test] - fn oneshot_single_thread_peek_open() { + test! { fn oneshot_single_thread_peek_open() { let (_tx, rx) = sync_channel::(0); - assert_eq!(rx.try_recv(), Err(TryRecvError::Empty)); - } + assert_eq!(rx.try_recv(), Err(Empty)); + } } - #[test] - fn oneshot_multi_task_recv_then_send() { + test! { fn oneshot_multi_task_recv_then_send() { let (tx, rx) = sync_channel::>(0); - let _t = Thread::spawn(move|| { - assert!(rx.recv().unwrap() == box 10); + spawn(move|| { + assert!(rx.recv() == box 10); }); - tx.send(box 10).unwrap(); - } + tx.send(box 10); + } } - #[test] - fn oneshot_multi_task_recv_then_close() { + test! { fn oneshot_multi_task_recv_then_close() { let (tx, rx) = sync_channel::>(0); - let _t = Thread::spawn(move|| { + spawn(move|| { drop(tx); }); let res = Thread::spawn(move|| { - assert!(rx.recv().unwrap() == box 10); + assert!(rx.recv() == box 10); }).join(); assert!(res.is_err()); - } + } } - #[test] - fn oneshot_multi_thread_close_stress() { + test! { fn oneshot_multi_thread_close_stress() { for _ in range(0, stress_factor()) { let (tx, rx) = sync_channel::(0); - let _t = Thread::spawn(move|| { + spawn(move|| { drop(rx); }); drop(tx); } - } + } } - #[test] - fn oneshot_multi_thread_send_close_stress() { + test! { fn oneshot_multi_thread_send_close_stress() { for _ in range(0, stress_factor()) { let (tx, rx) = sync_channel::(0); - let _t = Thread::spawn(move|| { + spawn(move|| { drop(rx); }); let _ = Thread::spawn(move || { - tx.send(1).unwrap(); + tx.send(1); }).join(); } - } + } } - #[test] - fn oneshot_multi_thread_recv_close_stress() { + test! { fn oneshot_multi_thread_recv_close_stress() { for _ in range(0, stress_factor()) { let (tx, rx) = sync_channel::(0); - let _t = Thread::spawn(move|| { + spawn(move|| { let res = Thread::spawn(move|| { - rx.recv().unwrap(); + rx.recv(); }).join(); assert!(res.is_err()); }); - let _t = Thread::spawn(move|| { - Thread::spawn(move|| { + spawn(move|| { + spawn(move|| { drop(tx); - }).detach(); + }); }); } - } + } } - #[test] - fn oneshot_multi_thread_send_recv_stress() { + test! { fn oneshot_multi_thread_send_recv_stress() { for _ in range(0, stress_factor()) { let (tx, rx) = sync_channel::>(0); - let _t = Thread::spawn(move|| { - tx.send(box 10i).unwrap(); + spawn(move|| { + tx.send(box 10i); + }); + spawn(move|| { + assert!(rx.recv() == box 10i); }); - assert!(rx.recv().unwrap() == box 10i); } - } + } } - #[test] - fn stream_send_recv_stress() { + test! { fn stream_send_recv_stress() { for _ in range(0, stress_factor()) { let (tx, rx) = sync_channel::>(0); @@ -1864,73 +1839,69 @@ mod sync_tests { fn send(tx: SyncSender>, i: int) { if i == 10 { return } - Thread::spawn(move|| { - tx.send(box i).unwrap(); + spawn(move|| { + tx.send(box i); send(tx, i + 1); - }).detach(); + }); } fn recv(rx: Receiver>, i: int) { if i == 10 { return } - Thread::spawn(move|| { - assert!(rx.recv().unwrap() == box i); + spawn(move|| { + assert!(rx.recv() == box i); recv(rx, i + 1); - }).detach(); + }); } } - } + } } - #[test] - fn recv_a_lot() { + test! { fn recv_a_lot() { // Regression test that we don't run out of stack in scheduler context let (tx, rx) = sync_channel(10000); - for _ in range(0u, 10000) { tx.send(()).unwrap(); } - for _ in range(0u, 10000) { rx.recv().unwrap(); } - } + for _ in range(0u, 10000) { tx.send(()); } + for _ in range(0u, 10000) { rx.recv(); } + } } - #[test] - fn shared_chan_stress() { + test! { fn shared_chan_stress() { let (tx, rx) = sync_channel(0); let total = stress_factor() + 100; for _ in range(0, total) { let tx = tx.clone(); - Thread::spawn(move|| { - tx.send(()).unwrap(); - }).detach(); + spawn(move|| { + tx.send(()); + }); } for _ in range(0, total) { - rx.recv().unwrap(); + rx.recv(); } - } + } } - #[test] - fn test_nested_recv_iter() { + test! { fn test_nested_recv_iter() { let (tx, rx) = sync_channel::(0); let (total_tx, total_rx) = sync_channel::(0); - let _t = Thread::spawn(move|| { + spawn(move|| { let mut acc = 0; for x in rx.iter() { acc += x; } - total_tx.send(acc).unwrap(); + total_tx.send(acc); }); - tx.send(3).unwrap(); - tx.send(1).unwrap(); - tx.send(2).unwrap(); + tx.send(3); + tx.send(1); + tx.send(2); drop(tx); - assert_eq!(total_rx.recv().unwrap(), 6); - } + assert_eq!(total_rx.recv(), 6); + } } - #[test] - fn test_recv_iter_break() { + test! { fn test_recv_iter_break() { let (tx, rx) = sync_channel::(0); let (count_tx, count_rx) = sync_channel(0); - let _t = Thread::spawn(move|| { + spawn(move|| { let mut count = 0; for x in rx.iter() { if count >= 3 { @@ -1939,51 +1910,49 @@ mod sync_tests { count += x; } } - count_tx.send(count).unwrap(); + count_tx.send(count); }); - tx.send(2).unwrap(); - tx.send(2).unwrap(); - tx.send(2).unwrap(); + tx.send(2); + tx.send(2); + tx.send(2); let _ = tx.try_send(2); drop(tx); - assert_eq!(count_rx.recv().unwrap(), 4); - } + assert_eq!(count_rx.recv(), 4); + } } - #[test] - fn try_recv_states() { + test! { fn try_recv_states() { let (tx1, rx1) = sync_channel::(1); let (tx2, rx2) = sync_channel::<()>(1); let (tx3, rx3) = sync_channel::<()>(1); - let _t = Thread::spawn(move|| { - rx2.recv().unwrap(); - tx1.send(1).unwrap(); - tx3.send(()).unwrap(); - rx2.recv().unwrap(); + spawn(move|| { + rx2.recv(); + tx1.send(1); + tx3.send(()); + rx2.recv(); drop(tx1); - tx3.send(()).unwrap(); + tx3.send(()); }); - assert_eq!(rx1.try_recv(), Err(TryRecvError::Empty)); - tx2.send(()).unwrap(); - rx3.recv().unwrap(); + assert_eq!(rx1.try_recv(), Err(Empty)); + tx2.send(()); + rx3.recv(); assert_eq!(rx1.try_recv(), Ok(1)); - assert_eq!(rx1.try_recv(), Err(TryRecvError::Empty)); - tx2.send(()).unwrap(); - rx3.recv().unwrap(); - assert_eq!(rx1.try_recv(), Err(TryRecvError::Disconnected)); - } + assert_eq!(rx1.try_recv(), Err(Empty)); + tx2.send(()); + rx3.recv(); + assert_eq!(rx1.try_recv(), Err(Disconnected)); + } } // This bug used to end up in a livelock inside of the Receiver destructor // because the internal state of the Shared packet was corrupted - #[test] - fn destroy_upgraded_shared_port_when_sender_still_active() { + test! { fn destroy_upgraded_shared_port_when_sender_still_active() { let (tx, rx) = sync_channel::<()>(0); let (tx2, rx2) = sync_channel::<()>(0); - let _t = Thread::spawn(move|| { - rx.recv().unwrap(); // wait on a oneshot + spawn(move|| { + rx.recv(); // wait on a oneshot drop(rx); // destroy a shared - tx2.send(()).unwrap(); + tx2.send(()); }); // make sure the other task has gone to sleep for _ in range(0u, 5000) { Thread::yield_now(); } @@ -1991,91 +1960,92 @@ mod sync_tests { // upgrade to a shared chan and send a message let t = tx.clone(); drop(tx); - t.send(()).unwrap(); + t.send(()); // wait for the child task to exit before we exit - rx2.recv().unwrap(); - } + rx2.recv(); + } } - #[test] - fn send1() { + test! { fn send_opt1() { let (tx, rx) = sync_channel::(0); - let _t = Thread::spawn(move|| { rx.recv().unwrap(); }); - assert_eq!(tx.send(1), Ok(())); - } + spawn(move|| { rx.recv(); }); + assert_eq!(tx.send_opt(1), Ok(())); + } } - #[test] - fn send2() { + test! { fn send_opt2() { let (tx, rx) = sync_channel::(0); - let _t = Thread::spawn(move|| { drop(rx); }); - assert!(tx.send(1).is_err()); - } + spawn(move|| { drop(rx); }); + assert_eq!(tx.send_opt(1), Err(1)); + } } - #[test] - fn send3() { + test! { fn send_opt3() { let (tx, rx) = sync_channel::(1); - assert_eq!(tx.send(1), Ok(())); - let _t =Thread::spawn(move|| { drop(rx); }); - assert!(tx.send(1).is_err()); - } + assert_eq!(tx.send_opt(1), Ok(())); + spawn(move|| { drop(rx); }); + assert_eq!(tx.send_opt(1), Err(1)); + } } - #[test] - fn send4() { + test! { fn send_opt4() { let (tx, rx) = sync_channel::(0); let tx2 = tx.clone(); let (done, donerx) = channel(); let done2 = done.clone(); - let _t = Thread::spawn(move|| { - assert!(tx.send(1).is_err()); - done.send(()).unwrap(); + spawn(move|| { + assert_eq!(tx.send_opt(1), Err(1)); + done.send(()); }); - let _t = Thread::spawn(move|| { - assert!(tx2.send(2).is_err()); - done2.send(()).unwrap(); + spawn(move|| { + assert_eq!(tx2.send_opt(2), Err(2)); + done2.send(()); }); drop(rx); - donerx.recv().unwrap(); - donerx.recv().unwrap(); - } + donerx.recv(); + donerx.recv(); + } } - #[test] - fn try_send1() { + test! { fn try_send1() { let (tx, _rx) = sync_channel::(0); - assert_eq!(tx.try_send(1), Err(TrySendError::Full(1))); - } + assert_eq!(tx.try_send(1), Err(Full(1))); + } } - #[test] - fn try_send2() { + test! { fn try_send2() { let (tx, _rx) = sync_channel::(1); assert_eq!(tx.try_send(1), Ok(())); - assert_eq!(tx.try_send(1), Err(TrySendError::Full(1))); - } + assert_eq!(tx.try_send(1), Err(Full(1))); + } } - #[test] - fn try_send3() { + test! { fn try_send3() { let (tx, rx) = sync_channel::(1); assert_eq!(tx.try_send(1), Ok(())); drop(rx); - assert_eq!(tx.try_send(1), Err(TrySendError::Disconnected(1))); - } + assert_eq!(tx.try_send(1), Err(RecvDisconnected(1))); + } } - #[test] - fn issue_15761() { + test! { fn try_send4() { + let (tx, rx) = sync_channel::(0); + spawn(move|| { + for _ in range(0u, 1000) { Thread::yield_now(); } + assert_eq!(tx.try_send(1), Ok(())); + }); + assert_eq!(rx.recv(), 1); + } #[ignore(reason = "flaky on libnative")] } + + test! { fn issue_15761() { fn repro() { let (tx1, rx1) = sync_channel::<()>(3); let (tx2, rx2) = sync_channel::<()>(3); - let _t = Thread::spawn(move|| { - rx1.recv().unwrap(); + spawn(move|| { + rx1.recv(); tx2.try_send(()).unwrap(); }); tx1.try_send(()).unwrap(); - rx2.recv().unwrap(); + rx2.recv(); } for _ in range(0u, 100) { repro() } - } + } } } diff --git a/src/libstd/sync/rwlock.rs b/src/libstd/sync/rwlock.rs index b2367ff8352..bd98b09d779 100644 --- a/src/libstd/sync/rwlock.rs +++ b/src/libstd/sync/rwlock.rs @@ -41,7 +41,7 @@ use sys_common::rwlock as sys; /// ``` /// use std::sync::RWLock; /// -/// let lock = RWLock::new(5i); +/// let lock = RWLock::new(5); /// /// // many reader locks can be held at once /// { -- cgit 1.4.1-3-g733a5 From ee9921aaedb26de3cac4c1c174888528f68bbd3f Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Mon, 5 Jan 2015 19:08:37 -0800 Subject: Revert "Remove i suffix in docs" This reverts commit f031671c6ea79391eeb3e1ad8f06fe0e436103fb. Conflicts: src/libcollections/slice.rs src/libcore/iter.rs src/libstd/sync/mpsc/mod.rs src/libstd/sync/rwlock.rs --- src/liballoc/arc.rs | 52 +- src/liballoc/rc.rs | 54 +- src/libcollections/binary_heap.rs | 22 +- src/libcollections/btree/set.rs | 20 +- src/libcollections/dlist.rs | 10 +- src/libcollections/ring_buf.rs | 72 +- src/libcollections/slice.rs | 790 +++++++++----------- src/libcollections/vec.rs | 58 +- src/libcore/atomic.rs | 18 +- src/libcore/fmt/num.rs | 2 +- src/libcore/iter.rs | 215 +++++- src/libcore/mem.rs | 8 +- src/libcore/num/mod.rs | 2 +- src/libcore/option.rs | 12 +- src/liblog/macros.rs | 4 +- src/librand/lib.rs | 4 +- src/libstd/collections/hash/set.rs | 28 +- src/libstd/macros.rs | 20 +- src/libstd/sync/mpsc/mod.rs | 1413 ++++++++++++++++++------------------ src/libstd/sync/rwlock.rs | 2 +- 20 files changed, 1429 insertions(+), 1377 deletions(-) (limited to 'src/libstd/sync') diff --git a/src/liballoc/arc.rs b/src/liballoc/arc.rs index 1d679f18feb..25f80ad11bd 100644 --- a/src/liballoc/arc.rs +++ b/src/liballoc/arc.rs @@ -35,7 +35,7 @@ //! use std::sync::Arc; //! use std::thread::Thread; //! -//! let five = Arc::new(5); +//! let five = Arc::new(5i); //! //! for i in range(0u, 10) { //! let five = five.clone(); @@ -52,7 +52,7 @@ //! use std::sync::{Arc, Mutex}; //! use std::thread::Thread; //! -//! let five = Arc::new(Mutex::new(5)); +//! let five = Arc::new(Mutex::new(5i)); //! //! for _ in range(0u, 10) { //! let five = five.clone(); @@ -154,7 +154,7 @@ impl Arc { /// ``` /// use std::sync::Arc; /// - /// let five = Arc::new(5); + /// let five = Arc::new(5i); /// ``` #[inline] #[stable] @@ -176,7 +176,7 @@ impl Arc { /// ``` /// use std::sync::Arc; /// - /// let five = Arc::new(5); + /// let five = Arc::new(5i); /// /// let weak_five = five.downgrade(); /// ``` @@ -220,7 +220,7 @@ impl Clone for Arc { /// ``` /// use std::sync::Arc; /// - /// let five = Arc::new(5); + /// let five = Arc::new(5i); /// /// five.clone(); /// ``` @@ -267,7 +267,7 @@ impl Arc { /// ``` /// use std::sync::Arc; /// - /// let mut five = Arc::new(5); + /// let mut five = Arc::new(5i); /// /// let mut_five = five.make_unique(); /// ``` @@ -303,14 +303,14 @@ impl Drop for Arc { /// use std::sync::Arc; /// /// { - /// let five = Arc::new(5); + /// let five = Arc::new(5i); /// /// // stuff /// /// drop(five); // explict drop /// } /// { - /// let five = Arc::new(5); + /// let five = Arc::new(5i); /// /// // stuff /// @@ -369,7 +369,7 @@ impl Weak { /// ``` /// use std::sync::Arc; /// - /// let five = Arc::new(5); + /// let five = Arc::new(5i); /// /// let weak_five = five.downgrade(); /// @@ -405,7 +405,7 @@ impl Clone for Weak { /// ``` /// use std::sync::Arc; /// - /// let weak_five = Arc::new(5).downgrade(); + /// let weak_five = Arc::new(5i).downgrade(); /// /// weak_five.clone(); /// ``` @@ -430,7 +430,7 @@ impl Drop for Weak { /// use std::sync::Arc; /// /// { - /// let five = Arc::new(5); + /// let five = Arc::new(5i); /// let weak_five = five.downgrade(); /// /// // stuff @@ -438,7 +438,7 @@ impl Drop for Weak { /// drop(weak_five); // explict drop /// } /// { - /// let five = Arc::new(5); + /// let five = Arc::new(5i); /// let weak_five = five.downgrade(); /// /// // stuff @@ -472,9 +472,9 @@ impl PartialEq for Arc { /// ``` /// use std::sync::Arc; /// - /// let five = Arc::new(5); + /// let five = Arc::new(5i); /// - /// five == Arc::new(5); + /// five == Arc::new(5i); /// ``` fn eq(&self, other: &Arc) -> bool { *(*self) == *(*other) } @@ -487,9 +487,9 @@ impl PartialEq for Arc { /// ``` /// use std::sync::Arc; /// - /// let five = Arc::new(5); + /// let five = Arc::new(5i); /// - /// five != Arc::new(5); + /// five != Arc::new(5i); /// ``` fn ne(&self, other: &Arc) -> bool { *(*self) != *(*other) } } @@ -504,9 +504,9 @@ impl PartialOrd for Arc { /// ``` /// use std::sync::Arc; /// - /// let five = Arc::new(5); + /// let five = Arc::new(5i); /// - /// five.partial_cmp(&Arc::new(5)); + /// five.partial_cmp(&Arc::new(5i)); /// ``` fn partial_cmp(&self, other: &Arc) -> Option { (**self).partial_cmp(&**other) @@ -521,9 +521,9 @@ impl PartialOrd for Arc { /// ``` /// use std::sync::Arc; /// - /// let five = Arc::new(5); + /// let five = Arc::new(5i); /// - /// five < Arc::new(5); + /// five < Arc::new(5i); /// ``` fn lt(&self, other: &Arc) -> bool { *(*self) < *(*other) } @@ -536,9 +536,9 @@ impl PartialOrd for Arc { /// ``` /// use std::sync::Arc; /// - /// let five = Arc::new(5); + /// let five = Arc::new(5i); /// - /// five <= Arc::new(5); + /// five <= Arc::new(5i); /// ``` fn le(&self, other: &Arc) -> bool { *(*self) <= *(*other) } @@ -551,9 +551,9 @@ impl PartialOrd for Arc { /// ``` /// use std::sync::Arc; /// - /// let five = Arc::new(5); + /// let five = Arc::new(5i); /// - /// five > Arc::new(5); + /// five > Arc::new(5i); /// ``` fn gt(&self, other: &Arc) -> bool { *(*self) > *(*other) } @@ -566,9 +566,9 @@ impl PartialOrd for Arc { /// ``` /// use std::sync::Arc; /// - /// let five = Arc::new(5); + /// let five = Arc::new(5i); /// - /// five >= Arc::new(5); + /// five >= Arc::new(5i); /// ``` fn ge(&self, other: &Arc) -> bool { *(*self) >= *(*other) } } diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index 1621e1934fa..175bba4e71d 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -187,7 +187,7 @@ impl Rc { /// ``` /// use std::rc::Rc; /// - /// let five = Rc::new(5); + /// let five = Rc::new(5i); /// ``` #[stable] pub fn new(value: T) -> Rc { @@ -214,7 +214,7 @@ impl Rc { /// ``` /// use std::rc::Rc; /// - /// let five = Rc::new(5); + /// let five = Rc::new(5i); /// /// let weak_five = five.downgrade(); /// ``` @@ -247,7 +247,7 @@ pub fn strong_count(this: &Rc) -> uint { this.strong() } /// use std::rc; /// use std::rc::Rc; /// -/// let five = Rc::new(5); +/// let five = Rc::new(5i); /// /// rc::is_unique(&five); /// ``` @@ -329,7 +329,7 @@ impl Rc { /// ``` /// use std::rc::Rc; /// - /// let mut five = Rc::new(5); + /// let mut five = Rc::new(5i); /// /// let mut_five = five.make_unique(); /// ``` @@ -378,14 +378,14 @@ impl Drop for Rc { /// use std::rc::Rc; /// /// { - /// let five = Rc::new(5); + /// let five = Rc::new(5i); /// /// // stuff /// /// drop(five); // explict drop /// } /// { - /// let five = Rc::new(5); + /// let five = Rc::new(5i); /// /// // stuff /// @@ -424,7 +424,7 @@ impl Clone for Rc { /// ``` /// use std::rc::Rc; /// - /// let five = Rc::new(5); + /// let five = Rc::new(5i); /// /// five.clone(); /// ``` @@ -465,9 +465,9 @@ impl PartialEq for Rc { /// ``` /// use std::rc::Rc; /// - /// let five = Rc::new(5); + /// let five = Rc::new(5i); /// - /// five == Rc::new(5); + /// five == Rc::new(5i); /// ``` #[inline(always)] fn eq(&self, other: &Rc) -> bool { **self == **other } @@ -481,9 +481,9 @@ impl PartialEq for Rc { /// ``` /// use std::rc::Rc; /// - /// let five = Rc::new(5); + /// let five = Rc::new(5i); /// - /// five != Rc::new(5); + /// five != Rc::new(5i); /// ``` #[inline(always)] fn ne(&self, other: &Rc) -> bool { **self != **other } @@ -503,9 +503,9 @@ impl PartialOrd for Rc { /// ``` /// use std::rc::Rc; /// - /// let five = Rc::new(5); + /// let five = Rc::new(5i); /// - /// five.partial_cmp(&Rc::new(5)); + /// five.partial_cmp(&Rc::new(5i)); /// ``` #[inline(always)] fn partial_cmp(&self, other: &Rc) -> Option { @@ -521,9 +521,9 @@ impl PartialOrd for Rc { /// ``` /// use std::rc::Rc; /// - /// let five = Rc::new(5); + /// let five = Rc::new(5i); /// - /// five < Rc::new(5); + /// five < Rc::new(5i); /// ``` #[inline(always)] fn lt(&self, other: &Rc) -> bool { **self < **other } @@ -537,9 +537,9 @@ impl PartialOrd for Rc { /// ``` /// use std::rc::Rc; /// - /// let five = Rc::new(5); + /// let five = Rc::new(5i); /// - /// five <= Rc::new(5); + /// five <= Rc::new(5i); /// ``` #[inline(always)] fn le(&self, other: &Rc) -> bool { **self <= **other } @@ -553,9 +553,9 @@ impl PartialOrd for Rc { /// ``` /// use std::rc::Rc; /// - /// let five = Rc::new(5); + /// let five = Rc::new(5i); /// - /// five > Rc::new(5); + /// five > Rc::new(5i); /// ``` #[inline(always)] fn gt(&self, other: &Rc) -> bool { **self > **other } @@ -569,9 +569,9 @@ impl PartialOrd for Rc { /// ``` /// use std::rc::Rc; /// - /// let five = Rc::new(5); + /// let five = Rc::new(5i); /// - /// five >= Rc::new(5); + /// five >= Rc::new(5i); /// ``` #[inline(always)] fn ge(&self, other: &Rc) -> bool { **self >= **other } @@ -588,9 +588,9 @@ impl Ord for Rc { /// ``` /// use std::rc::Rc; /// - /// let five = Rc::new(5); + /// let five = Rc::new(5i); /// - /// five.partial_cmp(&Rc::new(5)); + /// five.partial_cmp(&Rc::new(5i)); /// ``` #[inline] fn cmp(&self, other: &Rc) -> Ordering { (**self).cmp(&**other) } @@ -639,7 +639,7 @@ impl Weak { /// ``` /// use std::rc::Rc; /// - /// let five = Rc::new(5); + /// let five = Rc::new(5i); /// /// let weak_five = five.downgrade(); /// @@ -668,7 +668,7 @@ impl Drop for Weak { /// use std::rc::Rc; /// /// { - /// let five = Rc::new(5); + /// let five = Rc::new(5i); /// let weak_five = five.downgrade(); /// /// // stuff @@ -676,7 +676,7 @@ impl Drop for Weak { /// drop(weak_five); // explict drop /// } /// { - /// let five = Rc::new(5); + /// let five = Rc::new(5i); /// let weak_five = five.downgrade(); /// /// // stuff @@ -710,7 +710,7 @@ impl Clone for Weak { /// ``` /// use std::rc::Rc; /// - /// let weak_five = Rc::new(5).downgrade(); + /// let weak_five = Rc::new(5i).downgrade(); /// /// weak_five.clone(); /// ``` diff --git a/src/libcollections/binary_heap.rs b/src/libcollections/binary_heap.rs index d95c666b586..01693391abe 100644 --- a/src/libcollections/binary_heap.rs +++ b/src/libcollections/binary_heap.rs @@ -212,7 +212,7 @@ impl BinaryHeap { /// /// ``` /// use std::collections::BinaryHeap; - /// let heap = BinaryHeap::from_vec(vec![9, 1, 2, 7, 3, 2]); + /// let heap = BinaryHeap::from_vec(vec![9i, 1, 2, 7, 3, 2]); /// ``` pub fn from_vec(vec: Vec) -> BinaryHeap { let mut heap = BinaryHeap { data: vec }; @@ -231,7 +231,7 @@ impl BinaryHeap { /// /// ``` /// use std::collections::BinaryHeap; - /// let heap = BinaryHeap::from_vec(vec![1, 2, 3, 4]); + /// let heap = BinaryHeap::from_vec(vec![1i, 2, 3, 4]); /// /// // Print 1, 2, 3, 4 in arbitrary order /// for x in heap.iter() { @@ -251,7 +251,7 @@ impl BinaryHeap { /// /// ``` /// use std::collections::BinaryHeap; - /// let heap = BinaryHeap::from_vec(vec![1, 2, 3, 4]); + /// let heap = BinaryHeap::from_vec(vec![1i, 2, 3, 4]); /// /// // Print 1, 2, 3, 4 in arbitrary order /// for x in heap.into_iter() { @@ -273,7 +273,7 @@ impl BinaryHeap { /// let mut heap = BinaryHeap::new(); /// assert_eq!(heap.peek(), None); /// - /// heap.push(1); + /// heap.push(1i); /// heap.push(5); /// heap.push(2); /// assert_eq!(heap.peek(), Some(&5)); @@ -356,7 +356,7 @@ impl BinaryHeap { /// /// ``` /// use std::collections::BinaryHeap; - /// let mut heap = BinaryHeap::from_vec(vec![1, 3]); + /// let mut heap = BinaryHeap::from_vec(vec![1i, 3]); /// /// assert_eq!(heap.pop(), Some(3)); /// assert_eq!(heap.pop(), Some(1)); @@ -380,7 +380,7 @@ impl BinaryHeap { /// ``` /// use std::collections::BinaryHeap; /// let mut heap = BinaryHeap::new(); - /// heap.push(3); + /// heap.push(3i); /// heap.push(5); /// heap.push(1); /// @@ -402,7 +402,7 @@ impl BinaryHeap { /// ``` /// use std::collections::BinaryHeap; /// let mut heap = BinaryHeap::new(); - /// heap.push(1); + /// heap.push(1i); /// heap.push(5); /// /// assert_eq!(heap.push_pop(3), 5); @@ -434,7 +434,7 @@ impl BinaryHeap { /// use std::collections::BinaryHeap; /// let mut heap = BinaryHeap::new(); /// - /// assert_eq!(heap.replace(1), None); + /// assert_eq!(heap.replace(1i), None); /// assert_eq!(heap.replace(3), Some(1)); /// assert_eq!(heap.len(), 1); /// assert_eq!(heap.peek(), Some(&3)); @@ -457,7 +457,7 @@ impl BinaryHeap { /// /// ``` /// use std::collections::BinaryHeap; - /// let heap = BinaryHeap::from_vec(vec![1, 2, 3, 4, 5, 6, 7]); + /// let heap = BinaryHeap::from_vec(vec![1i, 2, 3, 4, 5, 6, 7]); /// let vec = heap.into_vec(); /// /// // Will print in some order @@ -475,12 +475,12 @@ impl BinaryHeap { /// ``` /// use std::collections::BinaryHeap; /// - /// let mut heap = BinaryHeap::from_vec(vec![1, 2, 4, 5, 7]); + /// let mut heap = BinaryHeap::from_vec(vec![1i, 2, 4, 5, 7]); /// heap.push(6); /// heap.push(3); /// /// let vec = heap.into_sorted_vec(); - /// assert_eq!(vec, vec![1, 2, 3, 4, 5, 6, 7]); + /// assert_eq!(vec, vec![1i, 2, 3, 4, 5, 6, 7]); /// ``` pub fn into_sorted_vec(mut self) -> Vec { let mut end = self.len(); diff --git a/src/libcollections/btree/set.rs b/src/libcollections/btree/set.rs index 82cef9b3549..98f16332170 100644 --- a/src/libcollections/btree/set.rs +++ b/src/libcollections/btree/set.rs @@ -245,7 +245,7 @@ impl BTreeSet { /// /// let mut v = BTreeSet::new(); /// assert_eq!(v.len(), 0); - /// v.insert(1); + /// v.insert(1i); /// assert_eq!(v.len(), 1); /// ``` #[stable] @@ -260,7 +260,7 @@ impl BTreeSet { /// /// let mut v = BTreeSet::new(); /// assert!(v.is_empty()); - /// v.insert(1); + /// v.insert(1i); /// assert!(!v.is_empty()); /// ``` #[stable] @@ -274,7 +274,7 @@ impl BTreeSet { /// use std::collections::BTreeSet; /// /// let mut v = BTreeSet::new(); - /// v.insert(1); + /// v.insert(1i); /// v.clear(); /// assert!(v.is_empty()); /// ``` @@ -294,7 +294,7 @@ impl BTreeSet { /// ``` /// use std::collections::BTreeSet; /// - /// let set: BTreeSet = [1, 2, 3].iter().map(|&x| x).collect(); + /// let set: BTreeSet = [1i, 2, 3].iter().map(|&x| x).collect(); /// assert_eq!(set.contains(&1), true); /// assert_eq!(set.contains(&4), false); /// ``` @@ -311,7 +311,7 @@ impl BTreeSet { /// ``` /// use std::collections::BTreeSet; /// - /// let a: BTreeSet = [1, 2, 3].iter().map(|&x| x).collect(); + /// let a: BTreeSet = [1i, 2, 3].iter().map(|&x| x).collect(); /// let mut b: BTreeSet = BTreeSet::new(); /// /// assert_eq!(a.is_disjoint(&b), true); @@ -332,7 +332,7 @@ impl BTreeSet { /// ``` /// use std::collections::BTreeSet; /// - /// let sup: BTreeSet = [1, 2, 3].iter().map(|&x| x).collect(); + /// let sup: BTreeSet = [1i, 2, 3].iter().map(|&x| x).collect(); /// let mut set: BTreeSet = BTreeSet::new(); /// /// assert_eq!(set.is_subset(&sup), true); @@ -374,7 +374,7 @@ impl BTreeSet { /// ``` /// use std::collections::BTreeSet; /// - /// let sub: BTreeSet = [1, 2].iter().map(|&x| x).collect(); + /// let sub: BTreeSet = [1i, 2].iter().map(|&x| x).collect(); /// let mut set: BTreeSet = BTreeSet::new(); /// /// assert_eq!(set.is_superset(&sub), false); @@ -401,8 +401,8 @@ impl BTreeSet { /// /// let mut set = BTreeSet::new(); /// - /// assert_eq!(set.insert(2), true); - /// assert_eq!(set.insert(2), false); + /// assert_eq!(set.insert(2i), true); + /// assert_eq!(set.insert(2i), false); /// assert_eq!(set.len(), 1); /// ``` #[stable] @@ -424,7 +424,7 @@ impl BTreeSet { /// /// let mut set = BTreeSet::new(); /// - /// set.insert(2); + /// set.insert(2i); /// assert_eq!(set.remove(&2), true); /// assert_eq!(set.remove(&2), false); /// ``` diff --git a/src/libcollections/dlist.rs b/src/libcollections/dlist.rs index b3c1486eaf3..14d61edca04 100644 --- a/src/libcollections/dlist.rs +++ b/src/libcollections/dlist.rs @@ -232,9 +232,9 @@ impl DList { /// /// let mut a = DList::new(); /// let mut b = DList::new(); - /// a.push_back(1); + /// a.push_back(1i); /// a.push_back(2); - /// b.push_back(3); + /// b.push_back(3i); /// b.push_back(4); /// /// a.append(b); @@ -377,7 +377,7 @@ impl DList { /// use std::collections::DList; /// /// let mut d = DList::new(); - /// d.push_back(1); + /// d.push_back(1i); /// d.push_back(3); /// assert_eq!(3, *d.back().unwrap()); /// ``` @@ -396,7 +396,7 @@ impl DList { /// /// let mut d = DList::new(); /// assert_eq!(d.pop_back(), None); - /// d.push_back(1); + /// d.push_back(1i); /// d.push_back(3); /// assert_eq!(d.pop_back(), Some(3)); /// ``` @@ -553,7 +553,7 @@ impl<'a, A> IterMut<'a, A> { /// } /// { /// let vec: Vec = list.into_iter().collect(); - /// assert_eq!(vec, vec![1, 2, 3, 4]); + /// assert_eq!(vec, vec![1i, 2, 3, 4]); /// } /// ``` #[inline] diff --git a/src/libcollections/ring_buf.rs b/src/libcollections/ring_buf.rs index 0ffede776ea..11775f62b1c 100644 --- a/src/libcollections/ring_buf.rs +++ b/src/libcollections/ring_buf.rs @@ -186,7 +186,7 @@ impl RingBuf { /// use std::collections::RingBuf; /// /// let mut buf = RingBuf::new(); - /// buf.push_back(3); + /// buf.push_back(3i); /// buf.push_back(4); /// buf.push_back(5); /// assert_eq!(buf.get(1).unwrap(), &4); @@ -209,7 +209,7 @@ impl RingBuf { /// use std::collections::RingBuf; /// /// let mut buf = RingBuf::new(); - /// buf.push_back(3); + /// buf.push_back(3i); /// buf.push_back(4); /// buf.push_back(5); /// match buf.get_mut(1) { @@ -243,7 +243,7 @@ impl RingBuf { /// use std::collections::RingBuf; /// /// let mut buf = RingBuf::new(); - /// buf.push_back(3); + /// buf.push_back(3i); /// buf.push_back(4); /// buf.push_back(5); /// buf.swap(0, 2); @@ -495,7 +495,7 @@ impl RingBuf { /// use std::collections::RingBuf; /// /// let mut buf = RingBuf::new(); - /// buf.push_back(5); + /// buf.push_back(5i); /// buf.push_back(3); /// buf.push_back(4); /// let b: &[_] = &[&5, &3, &4]; @@ -518,7 +518,7 @@ impl RingBuf { /// use std::collections::RingBuf; /// /// let mut buf = RingBuf::new(); - /// buf.push_back(5); + /// buf.push_back(5i); /// buf.push_back(3); /// buf.push_back(4); /// for num in buf.iter_mut() { @@ -597,7 +597,7 @@ impl RingBuf { /// /// let mut v = RingBuf::new(); /// assert_eq!(v.len(), 0); - /// v.push_back(1); + /// v.push_back(1i); /// assert_eq!(v.len(), 1); /// ``` #[stable] @@ -612,7 +612,7 @@ impl RingBuf { /// /// let mut v = RingBuf::new(); /// assert!(v.is_empty()); - /// v.push_front(1); + /// v.push_front(1i); /// assert!(!v.is_empty()); /// ``` #[stable] @@ -627,7 +627,7 @@ impl RingBuf { /// use std::collections::RingBuf; /// /// let mut v = RingBuf::new(); - /// v.push_back(1); + /// v.push_back(1i); /// assert_eq!(v.drain().next(), Some(1)); /// assert!(v.is_empty()); /// ``` @@ -647,7 +647,7 @@ impl RingBuf { /// use std::collections::RingBuf; /// /// let mut v = RingBuf::new(); - /// v.push_back(1); + /// v.push_back(1i); /// v.clear(); /// assert!(v.is_empty()); /// ``` @@ -668,9 +668,9 @@ impl RingBuf { /// let mut d = RingBuf::new(); /// assert_eq!(d.front(), None); /// - /// d.push_back(1); - /// d.push_back(2); - /// assert_eq!(d.front(), Some(&1)); + /// d.push_back(1i); + /// d.push_back(2i); + /// assert_eq!(d.front(), Some(&1i)); /// ``` #[stable] pub fn front(&self) -> Option<&T> { @@ -688,13 +688,13 @@ impl RingBuf { /// let mut d = RingBuf::new(); /// assert_eq!(d.front_mut(), None); /// - /// d.push_back(1); - /// d.push_back(2); + /// d.push_back(1i); + /// d.push_back(2i); /// match d.front_mut() { - /// Some(x) => *x = 9, + /// Some(x) => *x = 9i, /// None => (), /// } - /// assert_eq!(d.front(), Some(&9)); + /// assert_eq!(d.front(), Some(&9i)); /// ``` #[stable] pub fn front_mut(&mut self) -> Option<&mut T> { @@ -712,9 +712,9 @@ impl RingBuf { /// let mut d = RingBuf::new(); /// assert_eq!(d.back(), None); /// - /// d.push_back(1); - /// d.push_back(2); - /// assert_eq!(d.back(), Some(&2)); + /// d.push_back(1i); + /// d.push_back(2i); + /// assert_eq!(d.back(), Some(&2i)); /// ``` #[stable] pub fn back(&self) -> Option<&T> { @@ -732,13 +732,13 @@ impl RingBuf { /// let mut d = RingBuf::new(); /// assert_eq!(d.back(), None); /// - /// d.push_back(1); - /// d.push_back(2); + /// d.push_back(1i); + /// d.push_back(2i); /// match d.back_mut() { - /// Some(x) => *x = 9, + /// Some(x) => *x = 9i, /// None => (), /// } - /// assert_eq!(d.back(), Some(&9)); + /// assert_eq!(d.back(), Some(&9i)); /// ``` #[stable] pub fn back_mut(&mut self) -> Option<&mut T> { @@ -755,11 +755,11 @@ impl RingBuf { /// use std::collections::RingBuf; /// /// let mut d = RingBuf::new(); - /// d.push_back(1); - /// d.push_back(2); + /// d.push_back(1i); + /// d.push_back(2i); /// - /// assert_eq!(d.pop_front(), Some(1)); - /// assert_eq!(d.pop_front(), Some(2)); + /// assert_eq!(d.pop_front(), Some(1i)); + /// assert_eq!(d.pop_front(), Some(2i)); /// assert_eq!(d.pop_front(), None); /// ``` #[stable] @@ -781,9 +781,9 @@ impl RingBuf { /// use std::collections::RingBuf; /// /// let mut d = RingBuf::new(); - /// d.push_front(1); - /// d.push_front(2); - /// assert_eq!(d.front(), Some(&2)); + /// d.push_front(1i); + /// d.push_front(2i); + /// assert_eq!(d.front(), Some(&2i)); /// ``` #[stable] pub fn push_front(&mut self, t: T) { @@ -805,7 +805,7 @@ impl RingBuf { /// use std::collections::RingBuf; /// /// let mut buf = RingBuf::new(); - /// buf.push_back(1); + /// buf.push_back(1i); /// buf.push_back(3); /// assert_eq!(3, *buf.back().unwrap()); /// ``` @@ -831,7 +831,7 @@ impl RingBuf { /// /// let mut buf = RingBuf::new(); /// assert_eq!(buf.pop_back(), None); - /// buf.push_back(1); + /// buf.push_back(1i); /// buf.push_back(3); /// assert_eq!(buf.pop_back(), Some(3)); /// ``` @@ -928,7 +928,7 @@ impl RingBuf { /// use std::collections::RingBuf; /// /// let mut buf = RingBuf::new(); - /// buf.push_back(10); + /// buf.push_back(10i); /// buf.push_back(12); /// buf.insert(1,11); /// assert_eq!(Some(&11), buf.get(1)); @@ -1130,9 +1130,9 @@ impl RingBuf { /// use std::collections::RingBuf; /// /// let mut buf = RingBuf::new(); - /// buf.push_back(5); - /// buf.push_back(10); - /// buf.push_back(12); + /// buf.push_back(5i); + /// buf.push_back(10i); + /// buf.push_back(12i); /// buf.push_back(15); /// buf.remove(2); /// assert_eq!(Some(&15), buf.get(2)); diff --git a/src/libcollections/slice.rs b/src/libcollections/slice.rs index 1cb9e9009db..9e5aa7d645b 100644 --- a/src/libcollections/slice.rs +++ b/src/libcollections/slice.rs @@ -15,7 +15,7 @@ //! //! ```rust //! // slicing a Vec -//! let vec = vec!(1, 2, 3); +//! let vec = vec!(1i, 2, 3); //! let int_slice = vec.as_slice(); //! // coercing an array to a slice //! let str_slice: &[&str] = &["one", "two", "three"]; @@ -26,7 +26,7 @@ //! block of memory that a mutable slice points to: //! //! ```rust -//! let x: &mut[int] = &mut [1, 2, 3]; +//! let x: &mut[int] = &mut [1i, 2, 3]; //! x[1] = 7; //! assert_eq!(x[0], 1); //! assert_eq!(x[1], 7); @@ -54,9 +54,9 @@ //! ```rust //! #![feature(slicing_syntax)] //! fn main() { -//! let numbers = [0, 1, 2]; +//! let numbers = [0i, 1i, 2i]; //! let last_numbers = numbers[1..3]; -//! // last_numbers is now &[1, 2] +//! // last_numbers is now &[1i, 2i] //! } //! ``` //! @@ -76,7 +76,7 @@ //! type of the slice is `int`, the element type of the iterator is `&int`. //! //! ```rust -//! let numbers = [0, 1, 2]; +//! let numbers = [0i, 1i, 2i]; //! for &x in numbers.iter() { //! println!("{} is a number!", x); //! } @@ -90,40 +90,38 @@ use alloc::boxed::Box; use core::borrow::{BorrowFrom, BorrowFromMut, ToOwned}; -use core::cmp; -use core::iter::{range_step, MultiplicativeIterator}; +use core::clone::Clone; +use core::cmp::Ordering::{self, Greater, Less}; +use core::cmp::{self, Ord, PartialEq}; +use core::iter::{Iterator, IteratorExt}; +use core::iter::{range, range_step, MultiplicativeIterator}; use core::kinds::Sized; use core::mem::size_of; use core::mem; -use core::ops::{FnMut,SliceMut}; -use core::prelude::{Clone, Greater, Iterator, IteratorExt, Less, None, Option}; -use core::prelude::{Ord, Ordering, PtrExt, Some, range, IteratorCloneExt, Result}; +use core::ops::{FnMut, SliceMut}; +use core::option::Option::{self, Some, None}; +use core::ptr::PtrExt; use core::ptr; +use core::result::Result; use core::slice as core_slice; use self::Direction::*; use vec::Vec; pub use core::slice::{Chunks, AsSlice, Windows}; -pub use core::slice::{Iter, IterMut, PartialEqSliceExt}; +pub use core::slice::{Iter, IterMut}; pub use core::slice::{IntSliceExt, SplitMut, ChunksMut, Split}; pub use core::slice::{SplitN, RSplitN, SplitNMut, RSplitNMut}; pub use core::slice::{bytes, mut_ref_slice, ref_slice}; pub use core::slice::{from_raw_buf, from_raw_mut_buf}; -#[deprecated = "use Iter instead"] -pub type Items<'a, T:'a> = Iter<'a, T>; - -#[deprecated = "use IterMut instead"] -pub type MutItems<'a, T:'a> = IterMut<'a, T>; - //////////////////////////////////////////////////////////////////////////////// // Basic slice extension methods //////////////////////////////////////////////////////////////////////////////// /// Allocating extension methods for slices. #[stable] -pub trait SliceExt for Sized? { +pub trait SliceExt { #[stable] type Item; @@ -136,7 +134,7 @@ pub trait SliceExt for Sized? { /// # Examples /// /// ```rust - /// let mut v = [5, 4, 1, 3, 2]; + /// let mut v = [5i, 4, 1, 3, 2]; /// v.sort_by(|a, b| a.cmp(b)); /// assert!(v == [1, 2, 3, 4, 5]); /// @@ -145,7 +143,7 @@ pub trait SliceExt for Sized? { /// assert!(v == [5, 4, 3, 2, 1]); /// ``` #[stable] - fn sort_by(&mut self, compare: F) where F: FnMut(&T, &T) -> Ordering; + fn sort_by(&mut self, compare: F) where F: FnMut(&Self::Item, &Self::Item) -> Ordering; /// Consumes `src` and moves as many elements as it can into `self` /// from the range [start,end). @@ -162,14 +160,14 @@ pub trait SliceExt for Sized? { /// # Examples /// /// ```rust - /// let mut a = [1, 2, 3, 4, 5]; - /// let b = vec![6, 7, 8]; + /// let mut a = [1i, 2, 3, 4, 5]; + /// let b = vec![6i, 7, 8]; /// let num_moved = a.move_from(b, 0, 3); /// assert_eq!(num_moved, 3); - /// assert!(a == [6, 7, 8, 4, 5]); + /// assert!(a == [6i, 7, 8, 4, 5]); /// ``` #[experimental = "uncertain about this API approach"] - fn move_from(&mut self, src: Vec, start: uint, end: uint) -> uint; + fn move_from(&mut self, src: Vec, start: uint, end: uint) -> uint; /// Returns a subslice spanning the interval [`start`, `end`). /// @@ -178,7 +176,7 @@ pub trait SliceExt for Sized? { /// /// Slicing with `start` equal to `end` yields an empty slice. #[experimental = "will be replaced by slice syntax"] - fn slice(&self, start: uint, end: uint) -> &[T]; + fn slice(&self, start: uint, end: uint) -> &[Self::Item]; /// Returns a subslice from `start` to the end of the slice. /// @@ -186,7 +184,7 @@ pub trait SliceExt for Sized? { /// /// Slicing from `self.len()` yields an empty slice. #[experimental = "will be replaced by slice syntax"] - fn slice_from(&self, start: uint) -> &[T]; + fn slice_from(&self, start: uint) -> &[Self::Item]; /// Returns a subslice from the start of the slice to `end`. /// @@ -194,7 +192,7 @@ pub trait SliceExt for Sized? { /// /// Slicing to `0` yields an empty slice. #[experimental = "will be replaced by slice syntax"] - fn slice_to(&self, end: uint) -> &[T]; + fn slice_to(&self, end: uint) -> &[Self::Item]; /// Divides one slice into two at an index. /// @@ -204,32 +202,32 @@ pub trait SliceExt for Sized? { /// /// Panics if `mid > len`. #[stable] - fn split_at(&self, mid: uint) -> (&[T], &[T]); + fn split_at(&self, mid: uint) -> (&[Self::Item], &[Self::Item]); /// Returns an iterator over the slice #[stable] - fn iter(&self) -> Iter; + fn iter(&self) -> Iter; /// Returns an iterator over subslices separated by elements that match /// `pred`. The matched element is not contained in the subslices. #[stable] - fn split(&self, pred: F) -> Split - where F: FnMut(&T) -> bool; + fn split(&self, pred: F) -> Split + where F: FnMut(&Self::Item) -> bool; /// Returns an iterator over subslices separated by elements that match /// `pred`, limited to splitting at most `n` times. The matched element is /// not contained in the subslices. #[stable] - fn splitn(&self, n: uint, pred: F) -> SplitN - where F: FnMut(&T) -> bool; + fn splitn(&self, n: uint, pred: F) -> SplitN + where F: FnMut(&Self::Item) -> bool; /// Returns an iterator over subslices separated by elements that match /// `pred` limited to splitting at most `n` times. This starts at the end of /// the slice and works backwards. The matched element is not contained in /// the subslices. #[stable] - fn rsplitn(&self, n: uint, pred: F) -> RSplitN - where F: FnMut(&T) -> bool; + fn rsplitn(&self, n: uint, pred: F) -> RSplitN + where F: FnMut(&Self::Item) -> bool; /// Returns an iterator over all contiguous windows of length /// `size`. The windows overlap. If the slice is shorter than @@ -245,13 +243,13 @@ pub trait SliceExt for Sized? { /// `[3,4]`): /// /// ```rust - /// let v = &[1, 2, 3, 4]; + /// let v = &[1i, 2, 3, 4]; /// for win in v.windows(2) { /// println!("{}", win); /// } /// ``` #[stable] - fn windows(&self, size: uint) -> Windows; + fn windows(&self, size: uint) -> Windows; /// Returns an iterator over `size` elements of the slice at a /// time. The chunks do not overlap. If `size` does not divide the @@ -268,49 +266,39 @@ pub trait SliceExt for Sized? { /// `[3,4]`, `[5]`): /// /// ```rust - /// let v = &[1, 2, 3, 4, 5]; + /// let v = &[1i, 2, 3, 4, 5]; /// for win in v.chunks(2) { /// println!("{}", win); /// } /// ``` #[stable] - fn chunks(&self, size: uint) -> Chunks; + fn chunks(&self, size: uint) -> Chunks; /// Returns the element of a slice at the given index, or `None` if the /// index is out of bounds. #[stable] - fn get(&self, index: uint) -> Option<&T>; + fn get(&self, index: uint) -> Option<&Self::Item>; /// Returns the first element of a slice, or `None` if it is empty. #[stable] - fn first(&self) -> Option<&T>; - - /// Deprecated: renamed to `first`. - #[deprecated = "renamed to `first`"] - fn head(&self) -> Option<&T> { self.first() } + fn first(&self) -> Option<&Self::Item>; /// Returns all but the first element of a slice. #[experimental = "likely to be renamed"] - fn tail(&self) -> &[T]; + fn tail(&self) -> &[Self::Item]; /// Returns all but the last element of a slice. #[experimental = "likely to be renamed"] - fn init(&self) -> &[T]; + fn init(&self) -> &[Self::Item]; /// Returns the last element of a slice, or `None` if it is empty. #[stable] - fn last(&self) -> Option<&T>; + fn last(&self) -> Option<&Self::Item>; /// Returns a pointer to the element at the given index, without doing /// bounds checking. #[stable] - unsafe fn get_unchecked(&self, index: uint) -> &T; - - /// Deprecated: renamed to `get_unchecked`. - #[deprecated = "renamed to get_unchecked"] - unsafe fn unsafe_get(&self, index: uint) -> &T { - self.get_unchecked(index) - } + unsafe fn get_unchecked(&self, index: uint) -> &Self::Item; /// Returns an unsafe pointer to the slice's buffer /// @@ -320,7 +308,7 @@ pub trait SliceExt for Sized? { /// Modifying the slice may cause its buffer to be reallocated, which /// would also make any pointers to it invalid. #[stable] - fn as_ptr(&self) -> *const T; + fn as_ptr(&self) -> *const Self::Item; /// Binary search a sorted slice with a comparator function. /// @@ -341,7 +329,7 @@ pub trait SliceExt for Sized? { /// found; the fourth could match any position in `[1,4]`. /// /// ```rust - /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; + /// let s = [0i, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; /// let s = s.as_slice(); /// /// let seek = 13; @@ -356,14 +344,14 @@ pub trait SliceExt for Sized? { /// ``` #[stable] fn binary_search_by(&self, f: F) -> Result where - F: FnMut(&T) -> Ordering; + F: FnMut(&Self::Item) -> Ordering; /// Return the number of elements in the slice /// /// # Example /// /// ``` - /// let a = [1, 2, 3]; + /// let a = [1i, 2, 3]; /// assert_eq!(a.len(), 3); /// ``` #[stable] @@ -374,7 +362,7 @@ pub trait SliceExt for Sized? { /// # Example /// /// ``` - /// let a = [1, 2, 3]; + /// let a = [1i, 2, 3]; /// assert!(!a.is_empty()); /// ``` #[inline] @@ -383,12 +371,12 @@ pub trait SliceExt for Sized? { /// Returns a mutable reference to the element at the given index, /// or `None` if the index is out of bounds #[stable] - fn get_mut(&mut self, index: uint) -> Option<&mut T>; + fn get_mut(&mut self, index: uint) -> Option<&mut Self::Item>; /// Work with `self` as a mut slice. /// Primarily intended for getting a &mut [T] from a [T; N]. #[stable] - fn as_mut_slice(&mut self) -> &mut [T]; + fn as_mut_slice(&mut self) -> &mut [Self::Item]; /// Returns a mutable subslice spanning the interval [`start`, `end`). /// @@ -397,7 +385,7 @@ pub trait SliceExt for Sized? { /// /// Slicing with `start` equal to `end` yields an empty slice. #[experimental = "will be replaced by slice syntax"] - fn slice_mut(&mut self, start: uint, end: uint) -> &mut [T]; + fn slice_mut(&mut self, start: uint, end: uint) -> &mut [Self::Item]; /// Returns a mutable subslice from `start` to the end of the slice. /// @@ -405,7 +393,7 @@ pub trait SliceExt for Sized? { /// /// Slicing from `self.len()` yields an empty slice. #[experimental = "will be replaced by slice syntax"] - fn slice_from_mut(&mut self, start: uint) -> &mut [T]; + fn slice_from_mut(&mut self, start: uint) -> &mut [Self::Item]; /// Returns a mutable subslice from the start of the slice to `end`. /// @@ -413,54 +401,48 @@ pub trait SliceExt for Sized? { /// /// Slicing to `0` yields an empty slice. #[experimental = "will be replaced by slice syntax"] - fn slice_to_mut(&mut self, end: uint) -> &mut [T]; + fn slice_to_mut(&mut self, end: uint) -> &mut [Self::Item]; /// Returns an iterator that allows modifying each value #[stable] - fn iter_mut(&mut self) -> IterMut; + fn iter_mut(&mut self) -> IterMut; /// Returns a mutable pointer to the first element of a slice, or `None` if it is empty #[stable] - fn first_mut(&mut self) -> Option<&mut T>; - - /// Depreated: renamed to `first_mut`. - #[deprecated = "renamed to first_mut"] - fn head_mut(&mut self) -> Option<&mut T> { - self.first_mut() - } + fn first_mut(&mut self) -> Option<&mut Self::Item>; /// Returns all but the first element of a mutable slice #[experimental = "likely to be renamed or removed"] - fn tail_mut(&mut self) -> &mut [T]; + fn tail_mut(&mut self) -> &mut [Self::Item]; /// Returns all but the last element of a mutable slice #[experimental = "likely to be renamed or removed"] - fn init_mut(&mut self) -> &mut [T]; + fn init_mut(&mut self) -> &mut [Self::Item]; /// Returns a mutable pointer to the last item in the slice. #[stable] - fn last_mut(&mut self) -> Option<&mut T>; + fn last_mut(&mut self) -> Option<&mut Self::Item>; /// Returns an iterator over mutable subslices separated by elements that /// match `pred`. The matched element is not contained in the subslices. #[stable] - fn split_mut(&mut self, pred: F) -> SplitMut - where F: FnMut(&T) -> bool; + fn split_mut(&mut self, pred: F) -> SplitMut + where F: FnMut(&Self::Item) -> bool; /// Returns an iterator over subslices separated by elements that match /// `pred`, limited to splitting at most `n` times. The matched element is /// not contained in the subslices. #[stable] - fn splitn_mut(&mut self, n: uint, pred: F) -> SplitNMut - where F: FnMut(&T) -> bool; + fn splitn_mut(&mut self, n: uint, pred: F) -> SplitNMut + where F: FnMut(&Self::Item) -> bool; /// Returns an iterator over subslices separated by elements that match /// `pred` limited to splitting at most `n` times. This starts at the end of /// the slice and works backwards. The matched element is not contained in /// the subslices. #[stable] - fn rsplitn_mut(&mut self, n: uint, pred: F) -> RSplitNMut - where F: FnMut(&T) -> bool; + fn rsplitn_mut(&mut self, n: uint, pred: F) -> RSplitNMut + where F: FnMut(&Self::Item) -> bool; /// Returns an iterator over `chunk_size` elements of the slice at a time. /// The chunks are mutable and do not overlap. If `chunk_size` does @@ -471,7 +453,7 @@ pub trait SliceExt for Sized? { /// /// Panics if `chunk_size` is 0. #[stable] - fn chunks_mut(&mut self, chunk_size: uint) -> ChunksMut; + fn chunks_mut(&mut self, chunk_size: uint) -> ChunksMut; /// Swaps two elements in a slice. /// @@ -507,51 +489,45 @@ pub trait SliceExt for Sized? { /// # Example /// /// ```rust - /// let mut v = [1, 2, 3, 4, 5, 6]; + /// let mut v = [1i, 2, 3, 4, 5, 6]; /// /// // scoped to restrict the lifetime of the borrows /// { /// let (left, right) = v.split_at_mut(0); /// assert!(left == []); - /// assert!(right == [1, 2, 3, 4, 5, 6]); + /// assert!(right == [1i, 2, 3, 4, 5, 6]); /// } /// /// { /// let (left, right) = v.split_at_mut(2); - /// assert!(left == [1, 2]); - /// assert!(right == [3, 4, 5, 6]); + /// assert!(left == [1i, 2]); + /// assert!(right == [3i, 4, 5, 6]); /// } /// /// { /// let (left, right) = v.split_at_mut(6); - /// assert!(left == [1, 2, 3, 4, 5, 6]); + /// assert!(left == [1i, 2, 3, 4, 5, 6]); /// assert!(right == []); /// } /// ``` #[stable] - fn split_at_mut(&mut self, mid: uint) -> (&mut [T], &mut [T]); + fn split_at_mut(&mut self, mid: uint) -> (&mut [Self::Item], &mut [Self::Item]); /// Reverse the order of elements in a slice, in place. /// /// # Example /// /// ```rust - /// let mut v = [1, 2, 3]; + /// let mut v = [1i, 2, 3]; /// v.reverse(); - /// assert!(v == [3, 2, 1]); + /// assert!(v == [3i, 2, 1]); /// ``` #[stable] fn reverse(&mut self); /// Returns an unsafe mutable pointer to the element in index #[stable] - unsafe fn get_unchecked_mut(&mut self, index: uint) -> &mut T; - - /// Deprecated: renamed to `get_unchecked_mut`. - #[deprecated = "renamed to get_unchecked_mut"] - unsafe fn unchecked_mut(&mut self, index: uint) -> &mut T { - self.get_unchecked_mut(index) - } + unsafe fn get_unchecked_mut(&mut self, index: uint) -> &mut Self::Item; /// Return an unsafe mutable pointer to the slice's buffer. /// @@ -562,7 +538,167 @@ pub trait SliceExt for Sized? { /// would also make any pointers to it invalid. #[inline] #[stable] - fn as_mut_ptr(&mut self) -> *mut T; + fn as_mut_ptr(&mut self) -> *mut Self::Item; + + /// Copies `self` into a new `Vec`. + #[stable] + fn to_vec(&self) -> Vec where Self::Item: Clone; + + /// Creates an iterator that yields every possible permutation of the + /// vector in succession. + /// + /// # Examples + /// + /// ```rust + /// let v = [1i, 2, 3]; + /// let mut perms = v.permutations(); + /// + /// for p in perms { + /// println!("{}", p); + /// } + /// ``` + /// + /// Iterating through permutations one by one. + /// + /// ```rust + /// let v = [1i, 2, 3]; + /// let mut perms = v.permutations(); + /// + /// assert_eq!(Some(vec![1i, 2, 3]), perms.next()); + /// assert_eq!(Some(vec![1i, 3, 2]), perms.next()); + /// assert_eq!(Some(vec![3i, 1, 2]), perms.next()); + /// ``` + #[unstable] + fn permutations(&self) -> Permutations where Self::Item: Clone; + + /// Copies as many elements from `src` as it can into `self` (the + /// shorter of `self.len()` and `src.len()`). Returns the number + /// of elements copied. + /// + /// # Example + /// + /// ```rust + /// let mut dst = [0i, 0, 0]; + /// let src = [1i, 2]; + /// + /// assert!(dst.clone_from_slice(&src) == 2); + /// assert!(dst == [1, 2, 0]); + /// + /// let src2 = [3i, 4, 5, 6]; + /// assert!(dst.clone_from_slice(&src2) == 3); + /// assert!(dst == [3i, 4, 5]); + /// ``` + #[experimental] + fn clone_from_slice(&mut self, &[Self::Item]) -> uint where Self::Item: Clone; + + /// Sorts the slice, in place. + /// + /// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`. + /// + /// # Examples + /// + /// ```rust + /// let mut v = [-5i, 4, 1, -3, 2]; + /// + /// v.sort(); + /// assert!(v == [-5i, -3, 1, 2, 4]); + /// ``` + #[stable] + fn sort(&mut self) where Self::Item: Ord; + + /// Binary search a sorted slice for a given element. + /// + /// If the value is found then `Ok` is returned, containing the + /// index of the matching element; if the value is not found then + /// `Err` is returned, containing the index where a matching + /// element could be inserted while maintaining sorted order. + /// + /// # Example + /// + /// Looks up a series of four elements. The first is found, with a + /// uniquely determined position; the second and third are not + /// found; the fourth could match any position in `[1,4]`. + /// + /// ```rust + /// let s = [0i, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; + /// let s = s.as_slice(); + /// + /// assert_eq!(s.binary_search(&13), Ok(9)); + /// assert_eq!(s.binary_search(&4), Err(7)); + /// assert_eq!(s.binary_search(&100), Err(13)); + /// let r = s.binary_search(&1); + /// assert!(match r { Ok(1...4) => true, _ => false, }); + /// ``` + #[stable] + fn binary_search(&self, x: &Self::Item) -> Result where Self::Item: Ord; + + /// Deprecated: use `binary_search` instead. + #[deprecated = "use binary_search instead"] + fn binary_search_elem(&self, x: &Self::Item) -> Result where Self::Item: Ord { + self.binary_search(x) + } + + /// Mutates the slice to the next lexicographic permutation. + /// + /// Returns `true` if successful and `false` if the slice is at the + /// last-ordered permutation. + /// + /// # Example + /// + /// ```rust + /// let v: &mut [_] = &mut [0i, 1, 2]; + /// v.next_permutation(); + /// let b: &mut [_] = &mut [0i, 2, 1]; + /// assert!(v == b); + /// v.next_permutation(); + /// let b: &mut [_] = &mut [1i, 0, 2]; + /// assert!(v == b); + /// ``` + #[unstable = "uncertain if this merits inclusion in std"] + fn next_permutation(&mut self) -> bool where Self::Item: Ord; + + /// Mutates the slice to the previous lexicographic permutation. + /// + /// Returns `true` if successful and `false` if the slice is at the + /// first-ordered permutation. + /// + /// # Example + /// + /// ```rust + /// let v: &mut [_] = &mut [1i, 0, 2]; + /// v.prev_permutation(); + /// let b: &mut [_] = &mut [0i, 2, 1]; + /// assert!(v == b); + /// v.prev_permutation(); + /// let b: &mut [_] = &mut [0i, 1, 2]; + /// assert!(v == b); + /// ``` + #[unstable = "uncertain if this merits inclusion in std"] + fn prev_permutation(&mut self) -> bool where Self::Item: Ord; + + /// Find the first index containing a matching value. + #[experimental] + fn position_elem(&self, t: &Self::Item) -> Option where Self::Item: PartialEq; + + /// Find the last index containing a matching value. + #[experimental] + fn rposition_elem(&self, t: &Self::Item) -> Option where Self::Item: PartialEq; + + /// Return true if the slice contains an element with the given value. + #[stable] + fn contains(&self, x: &Self::Item) -> bool where Self::Item: PartialEq; + + /// Returns true if `needle` is a prefix of the slice. + #[stable] + fn starts_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq; + + /// Returns true if `needle` is a suffix of the slice. + #[stable] + fn ends_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq; + + /// Convert `self` into a vector without clones or allocation. + #[experimental] + fn into_vec(self: Box) -> Vec; } #[stable] @@ -783,229 +919,76 @@ impl SliceExt for [T] { fn as_mut_ptr(&mut self) -> *mut T { core_slice::SliceExt::as_mut_ptr(self) } -} - -//////////////////////////////////////////////////////////////////////////////// -// Extension traits for slices over specifc kinds of data -//////////////////////////////////////////////////////////////////////////////// - -/// Extension methods for boxed slices. -#[experimental = "likely to merge into SliceExt if it survives"] -pub trait BoxedSliceExt { - /// Convert `self` into a vector without clones or allocation. - #[experimental] - fn into_vec(self) -> Vec; -} - -#[experimental = "trait is experimental"] -impl BoxedSliceExt for Box<[T]> { - fn into_vec(mut self) -> Vec { - unsafe { - let xs = Vec::from_raw_parts(self.as_mut_ptr(), self.len(), self.len()); - mem::forget(self); - xs - } - } -} - -/// Allocating extension methods for slices containing `Clone` elements. -#[unstable = "likely to be merged into SliceExt"] -pub trait CloneSliceExt for Sized? { - /// Copies `self` into a new `Vec`. - #[stable] - fn to_vec(&self) -> Vec; - - /// Deprecated: use `iter().cloned().partition(f)` instead. - #[deprecated = "use iter().cloned().partition(f) instead"] - fn partitioned(&self, f: F) -> (Vec, Vec) where F: FnMut(&T) -> bool; - - /// Creates an iterator that yields every possible permutation of the - /// vector in succession. - /// - /// # Examples - /// - /// ```rust - /// let v = [1, 2, 3]; - /// let mut perms = v.permutations(); - /// - /// for p in perms { - /// println!("{}", p); - /// } - /// ``` - /// - /// Iterating through permutations one by one. - /// - /// ```rust - /// let v = [1, 2, 3]; - /// let mut perms = v.permutations(); - /// - /// assert_eq!(Some(vec![1, 2, 3]), perms.next()); - /// assert_eq!(Some(vec![1, 3, 2]), perms.next()); - /// assert_eq!(Some(vec![3, 1, 2]), perms.next()); - /// ``` - #[unstable] - fn permutations(&self) -> Permutations; - - /// Copies as many elements from `src` as it can into `self` (the - /// shorter of `self.len()` and `src.len()`). Returns the number - /// of elements copied. - /// - /// # Example - /// - /// ```rust - /// let mut dst = [0, 0, 0]; - /// let src = [1, 2]; - /// - /// assert!(dst.clone_from_slice(&src) == 2); - /// assert!(dst == [1, 2, 0]); - /// - /// let src2 = [3, 4, 5, 6]; - /// assert!(dst.clone_from_slice(&src2) == 3); - /// assert!(dst == [3, 4, 5]); - /// ``` - #[experimental] - fn clone_from_slice(&mut self, &[T]) -> uint; -} - -#[unstable = "trait is unstable"] -impl CloneSliceExt for [T] { /// Returns a copy of `v`. #[inline] - fn to_vec(&self) -> Vec { + fn to_vec(&self) -> Vec where T: Clone { let mut vector = Vec::with_capacity(self.len()); vector.push_all(self); vector } - - #[inline] - fn partitioned(&self, f: F) -> (Vec, Vec) where F: FnMut(&T) -> bool { - self.iter().cloned().partition(f) - } - /// Returns an iterator over all permutations of a vector. - fn permutations(&self) -> Permutations { + fn permutations(&self) -> Permutations where T: Clone { Permutations{ swaps: ElementSwaps::new(self.len()), v: self.to_vec(), } } - fn clone_from_slice(&mut self, src: &[T]) -> uint { - core_slice::CloneSliceExt::clone_from_slice(self, src) + fn clone_from_slice(&mut self, src: &[T]) -> uint where T: Clone { + core_slice::SliceExt::clone_from_slice(self, src) } -} -/// Allocating extension methods for slices on Ord values. -#[unstable = "likely to merge with SliceExt"] -pub trait OrdSliceExt for Sized? { - /// Sorts the slice, in place. - /// - /// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`. - /// - /// # Examples - /// - /// ```rust - /// let mut v = [-5, 4, 1, -3, 2]; - /// - /// v.sort(); - /// assert!(v == [-5, -3, 1, 2, 4]); - /// ``` - #[stable] - fn sort(&mut self); + #[inline] + fn sort(&mut self) where T: Ord { + self.sort_by(|a, b| a.cmp(b)) + } - /// Binary search a sorted slice for a given element. - /// - /// If the value is found then `Ok` is returned, containing the - /// index of the matching element; if the value is not found then - /// `Err` is returned, containing the index where a matching - /// element could be inserted while maintaining sorted order. - /// - /// # Example - /// - /// Looks up a series of four elements. The first is found, with a - /// uniquely determined position; the second and third are not - /// found; the fourth could match any position in `[1,4]`. - /// - /// ```rust - /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; - /// let s = s.as_slice(); - /// - /// assert_eq!(s.binary_search(&13), Ok(9)); - /// assert_eq!(s.binary_search(&4), Err(7)); - /// assert_eq!(s.binary_search(&100), Err(13)); - /// let r = s.binary_search(&1); - /// assert!(match r { Ok(1...4) => true, _ => false, }); - /// ``` - #[stable] - fn binary_search(&self, x: &T) -> Result; + fn binary_search(&self, x: &T) -> Result where T: Ord { + core_slice::SliceExt::binary_search(self, x) + } - /// Deprecated: use `binary_search` instead. - #[deprecated = "use binary_search instead"] - fn binary_search_elem(&self, x: &T) -> Result { - self.binary_search(x) + fn next_permutation(&mut self) -> bool where T: Ord { + core_slice::SliceExt::next_permutation(self) } - /// Mutates the slice to the next lexicographic permutation. - /// - /// Returns `true` if successful and `false` if the slice is at the - /// last-ordered permutation. - /// - /// # Example - /// - /// ```rust - /// let v: &mut [_] = &mut [0, 1, 2]; - /// v.next_permutation(); - /// let b: &mut [_] = &mut [0, 2, 1]; - /// assert!(v == b); - /// v.next_permutation(); - /// let b: &mut [_] = &mut [1, 0, 2]; - /// assert!(v == b); - /// ``` - #[unstable = "uncertain if this merits inclusion in std"] - fn next_permutation(&mut self) -> bool; + fn prev_permutation(&mut self) -> bool where T: Ord { + core_slice::SliceExt::prev_permutation(self) + } - /// Mutates the slice to the previous lexicographic permutation. - /// - /// Returns `true` if successful and `false` if the slice is at the - /// first-ordered permutation. - /// - /// # Example - /// - /// ```rust - /// let v: &mut [_] = &mut [1, 0, 2]; - /// v.prev_permutation(); - /// let b: &mut [_] = &mut [0, 2, 1]; - /// assert!(v == b); - /// v.prev_permutation(); - /// let b: &mut [_] = &mut [0, 1, 2]; - /// assert!(v == b); - /// ``` - #[unstable = "uncertain if this merits inclusion in std"] - fn prev_permutation(&mut self) -> bool; -} + fn position_elem(&self, t: &T) -> Option where T: PartialEq { + core_slice::SliceExt::position_elem(self, t) + } -#[unstable = "trait is unstable"] -impl OrdSliceExt for [T] { - #[inline] - fn sort(&mut self) { - self.sort_by(|a, b| a.cmp(b)) + fn rposition_elem(&self, t: &T) -> Option where T: PartialEq { + core_slice::SliceExt::rposition_elem(self, t) } - fn binary_search(&self, x: &T) -> Result { - core_slice::OrdSliceExt::binary_search(self, x) + fn contains(&self, x: &T) -> bool where T: PartialEq { + core_slice::SliceExt::contains(self, x) } - fn next_permutation(&mut self) -> bool { - core_slice::OrdSliceExt::next_permutation(self) + fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq { + core_slice::SliceExt::starts_with(self, needle) } - fn prev_permutation(&mut self) -> bool { - core_slice::OrdSliceExt::prev_permutation(self) + fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq { + core_slice::SliceExt::ends_with(self, needle) + } + + fn into_vec(mut self: Box) -> Vec { + unsafe { + let xs = Vec::from_raw_parts(self.as_mut_ptr(), self.len(), self.len()); + mem::forget(self); + xs + } } } +//////////////////////////////////////////////////////////////////////////////// +// Extension traits for slices over specifc kinds of data +//////////////////////////////////////////////////////////////////////////////// #[unstable = "U should be an associated type"] /// An extension trait for concatenating slices pub trait SliceConcatExt { @@ -1013,20 +996,10 @@ pub trait SliceConcatExt { #[stable] fn concat(&self) -> U; - #[deprecated = "renamed to concat"] - fn concat_vec(&self) -> U { - self.concat() - } - /// Flattens a slice of `T` into a single value `U`, placing a /// given seperator between each. #[stable] fn connect(&self, sep: &T) -> U; - - #[deprecated = "renamed to connect"] - fn connect_vec(&self, sep: &T) -> U { - self.connect(sep) - } } impl> SliceConcatExt> for [V] { @@ -1062,7 +1035,7 @@ impl> SliceConcatExt> for [V] { /// The last generated swap is always (0, 1), and it returns the /// sequence to its initial order. #[experimental] -#[deriving(Clone)] +#[derive(Clone)] pub struct ElementSwaps { sdir: Vec, /// If `true`, emit the last swap that returns the sequence to initial @@ -1109,11 +1082,11 @@ impl ToOwned> for [T] { // Iterators //////////////////////////////////////////////////////////////////////////////// -#[deriving(Copy, Clone)] +#[derive(Copy, Clone)] enum Direction { Pos, Neg } /// An `Index` and `Direction` together. -#[deriving(Copy, Clone)] +#[derive(Copy, Clone)] struct SizeDirection { size: uint, dir: Direction, @@ -1189,7 +1162,9 @@ pub struct Permutations { } #[unstable = "trait is unstable"] -impl Iterator> for Permutations { +impl Iterator for Permutations { + type Item = Vec; + #[inline] fn next(&mut self) -> Option> { match self.swaps.next() { @@ -1416,21 +1391,12 @@ fn merge_sort(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Order } } -/// Deprecated, unsafe operations -#[deprecated] -pub mod raw { - pub use core::slice::raw::{buf_as_slice, mut_buf_as_slice}; - pub use core::slice::raw::{shift_ptr, pop_ptr}; -} - #[cfg(test)] mod tests { - use std::boxed::Box; use prelude::{Some, None, range, Vec, ToString, Clone, Greater, Less, Equal}; - use prelude::{SliceExt, Iterator, IteratorExt, DoubleEndedIteratorExt}; - use prelude::{OrdSliceExt, CloneSliceExt, PartialEqSliceExt, AsSlice}; + use prelude::{SliceExt, Iterator, IteratorExt}; + use prelude::AsSlice; use prelude::{RandomAccessIterator, Ord, SliceConcatExt}; - use core::cell::Cell; use core::default::Default; use core::mem; use std::rand::{Rng, thread_rng}; @@ -1444,7 +1410,7 @@ mod tests { #[test] fn test_from_fn() { // Test on-stack from_fn. - let mut v = Vec::from_fn(3u, square); + let mut v = range(0, 3).map(square).collect::>(); { let v = v.as_slice(); assert_eq!(v.len(), 3u); @@ -1454,7 +1420,7 @@ mod tests { } // Test on-heap from_fn. - v = Vec::from_fn(5u, square); + v = range(0, 5).map(square).collect::>(); { let v = v.as_slice(); assert_eq!(v.len(), 5u); @@ -1469,7 +1435,7 @@ mod tests { #[test] fn test_from_elem() { // Test on-stack from_elem. - let mut v = Vec::from_elem(2u, 10u); + let mut v = vec![10u, 10u]; { let v = v.as_slice(); assert_eq!(v.len(), 2u); @@ -1478,7 +1444,7 @@ mod tests { } // Test on-heap from_elem. - v = Vec::from_elem(6u, 20u); + v = vec![20u, 20u, 20u, 20u, 20u, 20u]; { let v = v.as_slice(); assert_eq!(v[0], 20u); @@ -1520,23 +1486,23 @@ mod tests { } #[test] - fn test_head() { + fn test_first() { let mut a = vec![]; - assert_eq!(a.as_slice().head(), None); + assert_eq!(a.as_slice().first(), None); a = vec![11i]; - assert_eq!(a.as_slice().head().unwrap(), &11); + assert_eq!(a.as_slice().first().unwrap(), &11); a = vec![11i, 12]; - assert_eq!(a.as_slice().head().unwrap(), &11); + assert_eq!(a.as_slice().first().unwrap(), &11); } #[test] - fn test_head_mut() { + fn test_first_mut() { let mut a = vec![]; - assert_eq!(a.head_mut(), None); + assert_eq!(a.first_mut(), None); a = vec![11i]; - assert_eq!(*a.head_mut().unwrap(), 11); + assert_eq!(*a.first_mut().unwrap(), 11); a = vec![11i, 12]; - assert_eq!(*a.head_mut().unwrap(), 11); + assert_eq!(*a.first_mut().unwrap(), 11); } #[test] @@ -1740,42 +1706,6 @@ mod tests { assert_eq!(v.as_slice()[1], 2); } - #[test] - fn test_grow() { - // Test on-stack grow(). - let mut v = vec![]; - v.grow(2u, 1i); - { - let v = v.as_slice(); - assert_eq!(v.len(), 2u); - assert_eq!(v[0], 1); - assert_eq!(v[1], 1); - } - - // Test on-heap grow(). - v.grow(3u, 2i); - { - let v = v.as_slice(); - assert_eq!(v.len(), 5u); - assert_eq!(v[0], 1); - assert_eq!(v[1], 1); - assert_eq!(v[2], 2); - assert_eq!(v[3], 2); - assert_eq!(v[4], 2); - } - } - - #[test] - fn test_grow_fn() { - let mut v = vec![]; - v.grow_fn(3u, square); - let v = v.as_slice(); - assert_eq!(v.len(), 3u); - assert_eq!(v[0], 0u); - assert_eq!(v[1], 1u); - assert_eq!(v[2], 4u); - } - #[test] fn test_truncate() { let mut v = vec![box 6i,box 5,box 4]; @@ -2108,22 +2038,6 @@ mod tests { } } - #[test] - fn test_partition() { - assert_eq!((vec![]).partition(|x: &int| *x < 3), (vec![], vec![])); - assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![])); - assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 2), (vec![1], vec![2, 3])); - assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3])); - } - - #[test] - fn test_partitioned() { - assert_eq!(([]).partitioned(|x: &int| *x < 3), (vec![], vec![])); - assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 4), (vec![1, 2, 3], vec![])); - assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 2), (vec![1], vec![2, 3])); - assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 0), (vec![], vec![1, 2, 3])); - } - #[test] fn test_concat() { let v: [Vec; 0] = []; @@ -2141,14 +2055,14 @@ mod tests { #[test] fn test_connect() { let v: [Vec; 0] = []; - assert_eq!(v.connect_vec(&0), vec![]); - assert_eq!([vec![1i], vec![2i, 3]].connect_vec(&0), vec![1, 0, 2, 3]); - assert_eq!([vec![1i], vec![2i], vec![3i]].connect_vec(&0), vec![1, 0, 2, 0, 3]); + assert_eq!(v.connect(&0), vec![]); + assert_eq!([vec![1i], vec![2i, 3]].connect(&0), vec![1, 0, 2, 3]); + assert_eq!([vec![1i], vec![2i], vec![3i]].connect(&0), vec![1, 0, 2, 0, 3]); let v: [&[int]; 2] = [&[1], &[2, 3]]; - assert_eq!(v.connect_vec(&0), vec![1, 0, 2, 3]); + assert_eq!(v.connect(&0), vec![1, 0, 2, 3]); let v: [&[int]; 3] = [&[1], &[2], &[3]]; - assert_eq!(v.connect_vec(&0), vec![1, 0, 2, 0, 3]); + assert_eq!(v.connect(&0), vec![1, 0, 2, 0, 3]); } #[test] @@ -2221,55 +2135,6 @@ mod tests { assert_eq!(v[1], 3); } - - #[test] - #[should_fail] - fn test_from_fn_fail() { - Vec::from_fn(100, |v| { - if v == 50 { panic!() } - box 0i - }); - } - - #[test] - #[should_fail] - fn test_from_elem_fail() { - - struct S { - f: Cell, - boxes: (Box, Rc) - } - - impl Clone for S { - fn clone(&self) -> S { - self.f.set(self.f.get() + 1); - if self.f.get() == 10 { panic!() } - S { - f: self.f.clone(), - boxes: self.boxes.clone(), - } - } - } - - let s = S { - f: Cell::new(0), - boxes: (box 0, Rc::new(0)), - }; - let _ = Vec::from_elem(100, s); - } - - #[test] - #[should_fail] - fn test_grow_fn_fail() { - let mut v = vec![]; - v.grow_fn(100, |i| { - if i == 50 { - panic!() - } - (box 0i, Rc::new(0i)) - }) - } - #[test] #[should_fail] fn test_permute_fail() { @@ -2687,7 +2552,7 @@ mod tests { assert!(values == [2, 3, 5, 6, 7]); } - #[deriving(Clone, PartialEq)] + #[derive(Clone, PartialEq)] struct Foo; #[test] @@ -2858,6 +2723,7 @@ mod bench { use prelude::*; use core::mem; use core::ptr; + use core::iter::repeat; use std::rand::{weak_rng, Rng}; use test::{Bencher, black_box}; @@ -2865,7 +2731,7 @@ mod bench { fn iterator(b: &mut Bencher) { // peculiar numbers to stop LLVM from optimising the summation // out. - let v = Vec::from_fn(100, |i| i ^ (i << 1) ^ (i >> 1)); + let v = range(0u, 100).map(|i| i ^ (i << 1) ^ (i >> 1)).collect::>(); b.iter(|| { let mut sum = 0; @@ -2879,7 +2745,7 @@ mod bench { #[bench] fn mut_iterator(b: &mut Bencher) { - let mut v = Vec::from_elem(100, 0i); + let mut v = repeat(0i).take(100).collect::>(); b.iter(|| { let mut i = 0i; @@ -2893,7 +2759,7 @@ mod bench { #[bench] fn concat(b: &mut Bencher) { let xss: Vec> = - Vec::from_fn(100, |i| range(0u, i).collect()); + range(0, 100u).map(|i| range(0, i).collect()).collect(); b.iter(|| { xss.as_slice().concat(); }); @@ -2902,9 +2768,9 @@ mod bench { #[bench] fn connect(b: &mut Bencher) { let xss: Vec> = - Vec::from_fn(100, |i| range(0u, i).collect()); + range(0, 100u).map(|i| range(0, i).collect()).collect(); b.iter(|| { - xss.as_slice().connect_vec(&0) + xss.as_slice().connect(&0) }); } @@ -2919,7 +2785,7 @@ mod bench { #[bench] fn starts_with_same_vector(b: &mut Bencher) { - let vec: Vec = Vec::from_fn(100, |i| i); + let vec: Vec = range(0, 100).collect(); b.iter(|| { vec.as_slice().starts_with(vec.as_slice()) }) @@ -2935,8 +2801,8 @@ mod bench { #[bench] fn starts_with_diff_one_element_at_end(b: &mut Bencher) { - let vec: Vec = Vec::from_fn(100, |i| i); - let mut match_vec: Vec = Vec::from_fn(99, |i| i); + let vec: Vec = range(0, 100).collect(); + let mut match_vec: Vec = range(0, 99).collect(); match_vec.push(0); b.iter(|| { vec.as_slice().starts_with(match_vec.as_slice()) @@ -2945,7 +2811,7 @@ mod bench { #[bench] fn ends_with_same_vector(b: &mut Bencher) { - let vec: Vec = Vec::from_fn(100, |i| i); + let vec: Vec = range(0, 100).collect(); b.iter(|| { vec.as_slice().ends_with(vec.as_slice()) }) @@ -2961,8 +2827,8 @@ mod bench { #[bench] fn ends_with_diff_one_element_at_beginning(b: &mut Bencher) { - let vec: Vec = Vec::from_fn(100, |i| i); - let mut match_vec: Vec = Vec::from_fn(100, |i| i); + let vec: Vec = range(0, 100).collect(); + let mut match_vec: Vec = range(0, 100).collect(); match_vec.as_mut_slice()[0] = 200; b.iter(|| { vec.as_slice().starts_with(match_vec.as_slice()) @@ -2971,7 +2837,7 @@ mod bench { #[bench] fn contains_last_element(b: &mut Bencher) { - let vec: Vec = Vec::from_fn(100, |i| i); + let vec: Vec = range(0, 100).collect(); b.iter(|| { vec.contains(&99u) }) @@ -2980,7 +2846,7 @@ mod bench { #[bench] fn zero_1kb_from_elem(b: &mut Bencher) { b.iter(|| { - Vec::from_elem(1024, 0u8) + repeat(0u8).take(1024).collect::>() }); } @@ -3028,24 +2894,24 @@ mod bench { fn random_inserts(b: &mut Bencher) { let mut rng = weak_rng(); b.iter(|| { - let mut v = Vec::from_elem(30, (0u, 0u)); - for _ in range(0u, 100) { - let l = v.len(); - v.insert(rng.gen::() % (l + 1), - (1, 1)); - } - }) + let mut v = repeat((0u, 0u)).take(30).collect::>(); + for _ in range(0u, 100) { + let l = v.len(); + v.insert(rng.gen::() % (l + 1), + (1, 1)); + } + }) } #[bench] fn random_removes(b: &mut Bencher) { let mut rng = weak_rng(); b.iter(|| { - let mut v = Vec::from_elem(130, (0u, 0u)); - for _ in range(0u, 100) { - let l = v.len(); - v.remove(rng.gen::() % l); - } - }) + let mut v = repeat((0u, 0u)).take(130).collect::>(); + for _ in range(0u, 100) { + let l = v.len(); + v.remove(rng.gen::() % l); + } + }) } #[bench] @@ -3080,7 +2946,7 @@ mod bench { #[bench] fn sort_sorted(b: &mut Bencher) { - let mut v = Vec::from_fn(10000, |i| i); + let mut v = range(0u, 10000).collect::>(); b.iter(|| { v.sort(); }); @@ -3124,7 +2990,7 @@ mod bench { #[bench] fn sort_big_sorted(b: &mut Bencher) { - let mut v = Vec::from_fn(10000u, |i| (i, i, i, i)); + let mut v = range(0, 10000u).map(|i| (i, i, i, i)).collect::>(); b.iter(|| { v.sort(); }); diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs index 86f5f61b210..99231e7253c 100644 --- a/src/libcollections/vec.rs +++ b/src/libcollections/vec.rs @@ -25,13 +25,13 @@ //! ``` //! let ys: Vec = vec![]; //! -//! let zs = vec![1, 2, 3, 4, 5]; +//! let zs = vec![1i32, 2, 3, 4, 5]; //! ``` //! //! Push: //! //! ``` -//! let mut xs = vec![1, 2]; +//! let mut xs = vec![1i32, 2]; //! //! xs.push(3); //! ``` @@ -39,7 +39,7 @@ //! And pop: //! //! ``` -//! let mut xs = vec![1, 2]; +//! let mut xs = vec![1i32, 2]; //! //! let two = xs.pop(); //! ``` @@ -71,8 +71,8 @@ use core::uint; /// /// ``` /// let mut vec = Vec::new(); -/// vec.push(1); -/// vec.push(2); +/// vec.push(1i); +/// vec.push(2i); /// /// assert_eq!(vec.len(), 2); /// assert_eq!(vec[0], 1); @@ -80,7 +80,7 @@ use core::uint; /// assert_eq!(vec.pop(), Some(2)); /// assert_eq!(vec.len(), 1); /// -/// vec[0] = 7; +/// vec[0] = 7i; /// assert_eq!(vec[0], 7); /// /// vec.push_all(&[1, 2, 3]); @@ -88,13 +88,13 @@ use core::uint; /// for x in vec.iter() { /// println!("{}", x); /// } -/// assert_eq!(vec, vec![7, 1, 2, 3]); +/// assert_eq!(vec, vec![7i, 1, 2, 3]); /// ``` /// /// The `vec!` macro is provided to make initialization more convenient: /// /// ``` -/// let mut vec = vec![1, 2, 3]; +/// let mut vec = vec![1i, 2i, 3i]; /// vec.push(4); /// assert_eq!(vec, vec![1, 2, 3, 4]); /// ``` @@ -104,9 +104,9 @@ use core::uint; /// ``` /// let mut stack = Vec::new(); /// -/// stack.push(1); -/// stack.push(2); -/// stack.push(3); +/// stack.push(1i); +/// stack.push(2i); +/// stack.push(3i); /// /// loop { /// let top = match stack.pop() { @@ -218,7 +218,7 @@ impl Vec { /// use std::mem; /// /// fn main() { - /// let mut v = vec![1, 2, 3]; + /// let mut v = vec![1i, 2, 3]; /// /// // Pull out the various important pieces of information about `v` /// let p = v.as_mut_ptr(); @@ -237,7 +237,7 @@ impl Vec { /// /// // Put everything back together into a Vec /// let rebuilt = Vec::from_raw_parts(p, len, cap); - /// assert_eq!(rebuilt, vec![4, 5, 6]); + /// assert_eq!(rebuilt, vec![4i, 5i, 6i]); /// } /// } /// ``` @@ -392,7 +392,7 @@ impl Vec { /// # Examples /// /// ``` - /// let mut vec = vec![1, 2, 3, 4]; + /// let mut vec = vec![1i, 2, 3, 4]; /// vec.truncate(2); /// assert_eq!(vec, vec![1, 2]); /// ``` @@ -416,7 +416,7 @@ impl Vec { /// ``` /// fn foo(slice: &mut [int]) {} /// - /// let mut vec = vec![1, 2]; + /// let mut vec = vec![1i, 2]; /// foo(vec.as_mut_slice()); /// ``` #[inline] @@ -519,7 +519,7 @@ impl Vec { /// # Examples /// /// ``` - /// let mut vec = vec![1, 2, 3]; + /// let mut vec = vec![1i, 2, 3]; /// vec.insert(1, 4); /// assert_eq!(vec, vec![1, 4, 2, 3]); /// vec.insert(4, 5); @@ -557,7 +557,7 @@ impl Vec { /// # Examples /// /// ``` - /// let mut v = vec![1, 2, 3]; + /// let mut v = vec![1i, 2, 3]; /// assert_eq!(v.remove(1), 2); /// assert_eq!(v, vec![1, 3]); /// ``` @@ -591,7 +591,7 @@ impl Vec { /// # Examples /// /// ``` - /// let mut vec = vec![1, 2, 3, 4]; + /// let mut vec = vec![1i, 2, 3, 4]; /// vec.retain(|&x| x%2 == 0); /// assert_eq!(vec, vec![2, 4]); /// ``` @@ -624,7 +624,7 @@ impl Vec { /// # Examples /// /// ```rust - /// let mut vec = vec!(1, 2); + /// let mut vec = vec!(1i, 2); /// vec.push(3); /// assert_eq!(vec, vec!(1, 2, 3)); /// ``` @@ -662,7 +662,7 @@ impl Vec { /// # Examples /// /// ```rust - /// let mut vec = vec![1, 2, 3]; + /// let mut vec = vec![1i, 2, 3]; /// assert_eq!(vec.pop(), Some(3)); /// assert_eq!(vec, vec![1, 2]); /// ``` @@ -716,7 +716,7 @@ impl Vec { /// # Examples /// /// ``` - /// let mut v = vec![1, 2, 3]; + /// let mut v = vec![1i, 2, 3]; /// /// v.clear(); /// @@ -733,7 +733,7 @@ impl Vec { /// # Examples /// /// ``` - /// let a = vec![1, 2, 3]; + /// let a = vec![1i, 2, 3]; /// assert_eq!(a.len(), 3); /// ``` #[inline] @@ -748,7 +748,7 @@ impl Vec { /// let mut v = Vec::new(); /// assert!(v.is_empty()); /// - /// v.push(1); + /// v.push(1i); /// assert!(!v.is_empty()); /// ``` #[stable] @@ -965,7 +965,7 @@ impl Vec { /// vec.resize(3, "world"); /// assert_eq!(vec, vec!["hello", "world", "world"]); /// - /// let mut vec = vec![1, 2, 3, 4]; + /// let mut vec = vec![1i, 2, 3, 4]; /// vec.resize(2, 0); /// assert_eq!(vec, vec![1, 2]); /// ``` @@ -988,8 +988,8 @@ impl Vec { /// # Examples /// /// ``` - /// let mut vec = vec![1]; - /// vec.push_all(&[2, 3, 4]); + /// let mut vec = vec![1i]; + /// vec.push_all(&[2i, 3, 4]); /// assert_eq!(vec, vec![1, 2, 3, 4]); /// ``` #[inline] @@ -1021,11 +1021,11 @@ impl Vec { /// # Examples /// /// ``` - /// let mut vec = vec![1, 2, 2, 3, 2]; + /// let mut vec = vec![1i, 2, 2, 3, 2]; /// /// vec.dedup(); /// - /// assert_eq!(vec, vec![1, 2, 3, 2]); + /// assert_eq!(vec, vec![1i, 2, 3, 2]); /// ``` #[stable] pub fn dedup(&mut self) { @@ -1378,7 +1378,7 @@ impl AsSlice for Vec { /// ``` /// fn foo(slice: &[int]) {} /// - /// let vec = vec![1, 2]; + /// let vec = vec![1i, 2]; /// foo(vec.as_slice()); /// ``` #[inline] diff --git a/src/libcore/atomic.rs b/src/libcore/atomic.rs index 0f326aac052..15c20253c8b 100644 --- a/src/libcore/atomic.rs +++ b/src/libcore/atomic.rs @@ -765,7 +765,7 @@ impl AtomicPtr { /// ``` /// use std::sync::atomic::AtomicPtr; /// - /// let ptr = &mut 5; + /// let ptr = &mut 5i; /// let atomic_ptr = AtomicPtr::new(ptr); /// ``` #[inline] @@ -787,7 +787,7 @@ impl AtomicPtr { /// ``` /// use std::sync::atomic::{AtomicPtr, Ordering}; /// - /// let ptr = &mut 5; + /// let ptr = &mut 5i; /// let some_ptr = AtomicPtr::new(ptr); /// /// let value = some_ptr.load(Ordering::Relaxed); @@ -809,10 +809,10 @@ impl AtomicPtr { /// ``` /// use std::sync::atomic::{AtomicPtr, Ordering}; /// - /// let ptr = &mut 5; + /// let ptr = &mut 5i; /// let some_ptr = AtomicPtr::new(ptr); /// - /// let other_ptr = &mut 10; + /// let other_ptr = &mut 10i; /// /// some_ptr.store(other_ptr, Ordering::Relaxed); /// ``` @@ -835,10 +835,10 @@ impl AtomicPtr { /// ``` /// use std::sync::atomic::{AtomicPtr, Ordering}; /// - /// let ptr = &mut 5; + /// let ptr = &mut 5i; /// let some_ptr = AtomicPtr::new(ptr); /// - /// let other_ptr = &mut 10; + /// let other_ptr = &mut 10i; /// /// let value = some_ptr.swap(other_ptr, Ordering::Relaxed); /// ``` @@ -860,11 +860,11 @@ impl AtomicPtr { /// ``` /// use std::sync::atomic::{AtomicPtr, Ordering}; /// - /// let ptr = &mut 5; + /// let ptr = &mut 5i; /// let some_ptr = AtomicPtr::new(ptr); /// - /// let other_ptr = &mut 10; - /// let another_ptr = &mut 10; + /// let other_ptr = &mut 10i; + /// let another_ptr = &mut 10i; /// /// let value = some_ptr.compare_and_swap(other_ptr, another_ptr, Ordering::Relaxed); /// ``` diff --git a/src/libcore/fmt/num.rs b/src/libcore/fmt/num.rs index c9646bb3d35..e0724fc2da5 100644 --- a/src/libcore/fmt/num.rs +++ b/src/libcore/fmt/num.rs @@ -145,7 +145,7 @@ pub struct RadixFmt(T, R); /// /// ``` /// use std::fmt::radix; -/// assert_eq!(format!("{}", radix(55, 36)), "1j".to_string()); +/// assert_eq!(format!("{}", radix(55i, 36)), "1j".to_string()); /// ``` #[unstable = "may be renamed or move to a different module"] pub fn radix(x: T, base: u8) -> RadixFmt { diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs index 79c268c8441..9a2245501a8 100644 --- a/src/libcore/iter.rs +++ b/src/libcore/iter.rs @@ -33,7 +33,7 @@ //! translated to the `loop` below. //! //! ```rust -//! let values = vec![1, 2, 3]; +//! let values = vec![1i, 2, 3]; //! //! // "Syntactical sugar" taking advantage of an iterator //! for &x in values.iter() { @@ -176,8 +176,8 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [0]; - /// let b = [1]; + /// let a = [0i]; + /// let b = [1i]; /// let mut it = a.iter().chain(b.iter()); /// assert_eq!(it.next().unwrap(), &0); /// assert_eq!(it.next().unwrap(), &1); @@ -199,10 +199,10 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [0]; - /// let b = [1]; + /// let a = [0i]; + /// let b = [1i]; /// let mut it = a.iter().zip(b.iter()); - /// let (x0, x1) = (0, 1); + /// let (x0, x1) = (0i, 1i); /// assert_eq!(it.next().unwrap(), (&x0, &x1)); /// assert!(it.next().is_none()); /// ``` @@ -220,7 +220,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [1, 2]; + /// let a = [1i, 2]; /// let mut it = a.iter().map(|&x| 2 * x); /// assert_eq!(it.next().unwrap(), 2); /// assert_eq!(it.next().unwrap(), 4); @@ -241,7 +241,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [1, 2]; + /// let a = [1i, 2]; /// let mut it = a.iter().filter(|&x| *x > 1); /// assert_eq!(it.next().unwrap(), &2); /// assert!(it.next().is_none()); @@ -261,7 +261,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [1, 2]; + /// let a = [1i, 2]; /// let mut it = a.iter().filter_map(|&x| if x > 1 {Some(2 * x)} else {None}); /// assert_eq!(it.next().unwrap(), 4); /// assert!(it.next().is_none()); @@ -280,9 +280,9 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [100, 200]; + /// let a = [100i, 200]; /// let mut it = a.iter().enumerate(); - /// let (x100, x200) = (100, 200); + /// let (x100, x200) = (100i, 200i); /// assert_eq!(it.next().unwrap(), (0, &x100)); /// assert_eq!(it.next().unwrap(), (1, &x200)); /// assert!(it.next().is_none()); @@ -299,7 +299,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let xs = [100, 200, 300]; + /// let xs = [100i, 200, 300]; /// let mut it = xs.iter().map(|x| *x).peekable(); /// assert_eq!(*it.peek().unwrap(), 100); /// assert_eq!(it.next().unwrap(), 100); @@ -323,7 +323,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [1, 2, 3, 2, 1]; + /// let a = [1i, 2, 3, 2, 1]; /// let mut it = a.iter().skip_while(|&a| *a < 3); /// assert_eq!(it.next().unwrap(), &3); /// assert_eq!(it.next().unwrap(), &2); @@ -345,7 +345,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [1, 2, 3, 2, 1]; + /// let a = [1i, 2, 3, 2, 1]; /// let mut it = a.iter().take_while(|&a| *a < 3); /// assert_eq!(it.next().unwrap(), &1); /// assert_eq!(it.next().unwrap(), &2); @@ -365,7 +365,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [1, 2, 3, 4, 5]; + /// let a = [1i, 2, 3, 4, 5]; /// let mut it = a.iter().skip(3); /// assert_eq!(it.next().unwrap(), &4); /// assert_eq!(it.next().unwrap(), &5); @@ -383,7 +383,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [1, 2, 3, 4, 5]; + /// let a = [1i, 2, 3, 4, 5]; /// let mut it = a.iter().take(3); /// assert_eq!(it.next().unwrap(), &1); /// assert_eq!(it.next().unwrap(), &2); @@ -404,7 +404,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [1, 2, 3, 4, 5]; + /// let a = [1i, 2, 3, 4, 5]; /// let mut it = a.iter().scan(1, |fac, &x| { /// *fac = *fac * x; /// Some(*fac) @@ -477,9 +477,9 @@ pub trait IteratorExt: Iterator + Sized { /// } /// sum /// } - /// let x = vec![1,2,3,7,8,9]; + /// let x = vec![1i,2,3,7,8,9]; /// assert_eq!(process(x.into_iter()), 6); - /// let x = vec![1,2,3]; + /// let x = vec![1i,2,3]; /// assert_eq!(process(x.into_iter()), 1006); /// ``` #[inline] @@ -540,7 +540,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [1, 2, 3, 4, 5]; + /// let a = [1i, 2, 3, 4, 5]; /// let b: Vec = a.iter().map(|&x| x).collect(); /// assert!(a.as_slice() == b.as_slice()); /// ``` @@ -556,7 +556,7 @@ pub trait IteratorExt: Iterator + Sized { /// do not. /// /// ``` - /// let vec = vec![1, 2, 3, 4]; + /// let vec = vec![1i, 2i, 3i, 4i]; /// let (even, odd): (Vec, Vec) = vec.into_iter().partition(|&n| n % 2 == 0); /// assert_eq!(even, vec![2, 4]); /// assert_eq!(odd, vec![1, 3]); @@ -586,7 +586,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [1, 2, 3, 4, 5]; + /// let a = [1i, 2, 3, 4, 5]; /// assert!(a.iter().fold(0, |a, &b| a + b) == 15); /// ``` #[inline] @@ -606,7 +606,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [1, 2, 3, 4, 5]; + /// let a = [1i, 2, 3, 4, 5]; /// assert!(a.iter().all(|x| *x > 0)); /// assert!(!a.iter().all(|x| *x > 2)); /// ``` @@ -623,7 +623,7 @@ pub trait IteratorExt: Iterator + Sized { /// # Example /// /// ```rust - /// let a = [1, 2, 3, 4, 5]; + /// let a = [1i, 2, 3, 4, 5]; /// let mut it = a.iter(); /// assert!(it.any(|x| *x == 3)); /// assert!(!it.any(|x| *x == 3)); @@ -812,7 +812,7 @@ pub trait IteratorExt: Iterator + Sized { /// ```rust /// use core::num::SignedInt; /// - /// let xs = [-3, 0, 1, 5, -10]; + /// let xs = [-3i, 0, 1, 5, -10]; /// assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10); /// ``` #[inline] @@ -841,7 +841,7 @@ pub trait IteratorExt: Iterator + Sized { /// ```rust /// use core::num::SignedInt; /// - /// let xs = [-3, 0, 1, 5, -10]; + /// let xs = [-3i, 0, 1, 5, -10]; /// assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0); /// ``` #[inline] @@ -1096,7 +1096,7 @@ pub trait AdditiveIterator { /// ```rust /// use std::iter::AdditiveIterator; /// - /// let a: [i32] = [1, 2, 3, 4, 5]; + /// let a = [1i, 2, 3, 4, 5]; /// let mut it = a.iter().map(|&x| x); /// assert!(it.sum() == 15); /// ``` @@ -1171,6 +1171,134 @@ impl_multiplicative! { uint, 1 } impl_multiplicative! { f32, 1.0 } impl_multiplicative! { f64, 1.0 } +<<<<<<< HEAD +======= +/// A trait for iterators over elements which can be compared to one another. +#[unstable = "recently renamed for new extension trait conventions"] +pub trait IteratorOrdExt { + /// Consumes the entire iterator to return the maximum element. + /// + /// # Example + /// + /// ```rust + /// let a = [1i, 2, 3, 4, 5]; + /// assert!(a.iter().max().unwrap() == &5); + /// ``` + fn max(self) -> Option; + + /// Consumes the entire iterator to return the minimum element. + /// + /// # Example + /// + /// ```rust + /// let a = [1i, 2, 3, 4, 5]; + /// assert!(a.iter().min().unwrap() == &1); + /// ``` + fn min(self) -> Option; + + /// `min_max` finds the minimum and maximum elements in the iterator. + /// + /// The return type `MinMaxResult` is an enum of three variants: + /// + /// - `NoElements` if the iterator is empty. + /// - `OneElement(x)` if the iterator has exactly one element. + /// - `MinMax(x, y)` is returned otherwise, where `x <= y`. Two + /// values are equal if and only if there is more than one + /// element in the iterator and all elements are equal. + /// + /// On an iterator of length `n`, `min_max` does `1.5 * n` comparisons, + /// and so is faster than calling `min` and `max` separately which does `2 * n` comparisons. + /// + /// # Example + /// + /// ```rust + /// use std::iter::MinMaxResult::{NoElements, OneElement, MinMax}; + /// + /// let v: [int; 0] = []; + /// assert_eq!(v.iter().min_max(), NoElements); + /// + /// let v = [1i]; + /// assert!(v.iter().min_max() == OneElement(&1)); + /// + /// let v = [1i, 2, 3, 4, 5]; + /// assert!(v.iter().min_max() == MinMax(&1, &5)); + /// + /// let v = [1i, 2, 3, 4, 5, 6]; + /// assert!(v.iter().min_max() == MinMax(&1, &6)); + /// + /// let v = [1i, 1, 1, 1]; + /// assert!(v.iter().min_max() == MinMax(&1, &1)); + /// ``` + fn min_max(self) -> MinMaxResult; +} + +#[unstable = "trait is unstable"] +impl IteratorOrdExt for I where I: Iterator, T: Ord { + #[inline] + fn max(self) -> Option { + self.fold(None, |max, x| { + match max { + None => Some(x), + Some(y) => Some(cmp::max(x, y)) + } + }) + } + + #[inline] + fn min(self) -> Option { + self.fold(None, |min, x| { + match min { + None => Some(x), + Some(y) => Some(cmp::min(x, y)) + } + }) + } + + fn min_max(mut self) -> MinMaxResult { + let (mut min, mut max) = match self.next() { + None => return NoElements, + Some(x) => { + match self.next() { + None => return OneElement(x), + Some(y) => if x < y {(x, y)} else {(y,x)} + } + } + }; + + loop { + // `first` and `second` are the two next elements we want to look at. + // We first compare `first` and `second` (#1). The smaller one is then compared to + // current minimum (#2). The larger one is compared to current maximum (#3). This + // way we do 3 comparisons for 2 elements. + let first = match self.next() { + None => break, + Some(x) => x + }; + let second = match self.next() { + None => { + if first < min { + min = first; + } else if first > max { + max = first; + } + break; + } + Some(x) => x + }; + if first < second { + if first < min {min = first;} + if max < second {max = second;} + } else { + if second < min {min = second;} + if max < first {max = first;} + } + } + + MinMax(min, max) + } +} + +>>>>>>> parent of f031671... Remove i suffix in docs /// `MinMaxResult` is an enum returned by `min_max`. See `IteratorOrdExt::min_max` for more detail. #[derive(Clone, PartialEq, Show)] #[unstable = "unclear whether such a fine-grained result is widely useful"] @@ -1199,10 +1327,10 @@ impl MinMaxResult { /// let r: MinMaxResult = NoElements; /// assert_eq!(r.into_option(), None); /// - /// let r = OneElement(1); + /// let r = OneElement(1i); /// assert_eq!(r.into_option(), Some((1,1))); /// - /// let r = MinMax(1, 2); + /// let r = MinMax(1i,2i); /// assert_eq!(r.into_option(), Some((1,2))); /// ``` #[unstable = "type is unstable"] @@ -1258,6 +1386,35 @@ impl ExactSizeIterator for Cloned where I: ExactSizeIterator + Iterator, {} +<<<<<<< HEAD +======= +#[unstable = "recently renamed for extension trait conventions"] +/// An extension trait for cloneable iterators. +pub trait CloneIteratorExt { + /// Repeats an iterator endlessly + /// + /// # Example + /// + /// ```rust + /// use std::iter::{CloneIteratorExt, count}; + /// + /// let a = count(1i,1i).take(1); + /// let mut cy = a.cycle(); + /// assert_eq!(cy.next(), Some(1)); + /// assert_eq!(cy.next(), Some(1)); + /// ``` + #[stable] + fn cycle(self) -> Cycle; +} + +impl CloneIteratorExt for I where I: Iterator + Clone { + #[inline] + fn cycle(self) -> Cycle { + Cycle{orig: self.clone(), iter: self} + } +} + +>>>>>>> parent of f031671... Remove i suffix in docs /// An iterator that repeats endlessly #[derive(Clone, Copy)] #[must_use = "iterator adaptors are lazy and do nothing unless consumed"] diff --git a/src/libcore/mem.rs b/src/libcore/mem.rs index a8f8802de59..c6056916121 100644 --- a/src/libcore/mem.rs +++ b/src/libcore/mem.rs @@ -187,13 +187,13 @@ pub unsafe fn uninitialized() -> T { /// ``` /// use std::mem; /// -/// let x = &mut 5; -/// let y = &mut 42; +/// let x = &mut 5i; +/// let y = &mut 42i; /// /// mem::swap(x, y); /// -/// assert_eq!(42, *x); -/// assert_eq!(5, *y); +/// assert_eq!(42i, *x); +/// assert_eq!(5i, *y); /// ``` #[inline] #[stable] diff --git a/src/libcore/num/mod.rs b/src/libcore/num/mod.rs index 485d320cf5c..426c858d408 100644 --- a/src/libcore/num/mod.rs +++ b/src/libcore/num/mod.rs @@ -336,7 +336,7 @@ pub trait Int /// ```rust /// use std::num::Int; /// - /// assert_eq!(2.pow(4), 16); + /// assert_eq!(2i.pow(4), 16); /// ``` #[inline] fn pow(self, mut exp: uint) -> Self { diff --git a/src/libcore/option.rs b/src/libcore/option.rs index 3c96011867c..39d0f024d4d 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -470,10 +470,10 @@ impl Option { /// /// ``` /// let x = Some("foo"); - /// assert_eq!(x.ok_or(0), Ok("foo")); + /// assert_eq!(x.ok_or(0i), Ok("foo")); /// /// let x: Option<&str> = None; - /// assert_eq!(x.ok_or(0), Err(0)); + /// assert_eq!(x.ok_or(0i), Err(0i)); /// ``` #[inline] #[experimental] @@ -491,10 +491,10 @@ impl Option { /// /// ``` /// let x = Some("foo"); - /// assert_eq!(x.ok_or_else(|| 0), Ok("foo")); + /// assert_eq!(x.ok_or_else(|| 0i), Ok("foo")); /// /// let x: Option<&str> = None; - /// assert_eq!(x.ok_or_else(|| 0), Err(0)); + /// assert_eq!(x.ok_or_else(|| 0i), Err(0i)); /// ``` #[inline] #[experimental] @@ -728,8 +728,8 @@ impl Option { /// let good_year = good_year_from_input.parse().unwrap_or_default(); /// let bad_year = bad_year_from_input.parse().unwrap_or_default(); /// - /// assert_eq!(1909, good_year); - /// assert_eq!(0, bad_year); + /// assert_eq!(1909i, good_year); + /// assert_eq!(0i, bad_year); /// ``` #[inline] #[stable] diff --git a/src/liblog/macros.rs b/src/liblog/macros.rs index 5c7085b7b6c..5249e971439 100644 --- a/src/liblog/macros.rs +++ b/src/liblog/macros.rs @@ -119,7 +119,7 @@ macro_rules! warn { /// #[macro_use] extern crate log; /// /// fn main() { -/// let ret = 3; +/// let ret = 3i; /// info!("this function is about to return: {}", ret); /// } /// ``` @@ -145,7 +145,7 @@ macro_rules! info { /// #[macro_use] extern crate log; /// /// fn main() { -/// debug!("x = {x}, y = {y}", x=10, y=20); +/// debug!("x = {x}, y = {y}", x=10i, y=20i); /// } /// ``` /// diff --git a/src/librand/lib.rs b/src/librand/lib.rs index 99dd505a9ef..8eae7697376 100644 --- a/src/librand/lib.rs +++ b/src/librand/lib.rs @@ -287,7 +287,7 @@ pub trait Rng : Sized { /// ``` /// use std::rand::{thread_rng, Rng}; /// - /// let choices = [1, 2, 4, 8, 16, 32]; + /// let choices = [1i, 2, 4, 8, 16, 32]; /// let mut rng = thread_rng(); /// println!("{}", rng.choose(&choices)); /// # // replace with slicing syntax when it's stable! @@ -309,7 +309,7 @@ pub trait Rng : Sized { /// use std::rand::{thread_rng, Rng}; /// /// let mut rng = thread_rng(); - /// let mut y = [1, 2, 3]; + /// let mut y = [1i, 2, 3]; /// rng.shuffle(&mut y); /// println!("{}", y.as_slice()); /// rng.shuffle(&mut y); diff --git a/src/libstd/collections/hash/set.rs b/src/libstd/collections/hash/set.rs index 38ea4dad027..211bfe2c10e 100644 --- a/src/libstd/collections/hash/set.rs +++ b/src/libstd/collections/hash/set.rs @@ -166,7 +166,7 @@ impl, S, H: Hasher> HashSet { /// /// let h = SipHasher::new(); /// let mut set = HashSet::with_capacity_and_hasher(10u, h); - /// set.insert(1); + /// set.insert(1i); /// ``` #[inline] #[unstable = "hasher stuff is unclear"] @@ -285,8 +285,8 @@ impl, S, H: Hasher> HashSet { /// /// ``` /// use std::collections::HashSet; - /// let a: HashSet = [1, 2, 3].iter().map(|&x| x).collect(); - /// let b: HashSet = [4, 2, 3, 4].iter().map(|&x| x).collect(); + /// let a: HashSet = [1i, 2, 3].iter().map(|&x| x).collect(); + /// let b: HashSet = [4i, 2, 3, 4].iter().map(|&x| x).collect(); /// /// // Can be seen as `a - b`. /// for x in a.difference(&b) { @@ -294,12 +294,12 @@ impl, S, H: Hasher> HashSet { /// } /// /// let diff: HashSet = a.difference(&b).map(|&x| x).collect(); - /// assert_eq!(diff, [1].iter().map(|&x| x).collect()); + /// assert_eq!(diff, [1i].iter().map(|&x| x).collect()); /// /// // Note that difference is not symmetric, /// // and `b - a` means something else: /// let diff: HashSet = b.difference(&a).map(|&x| x).collect(); - /// assert_eq!(diff, [4].iter().map(|&x| x).collect()); + /// assert_eq!(diff, [4i].iter().map(|&x| x).collect()); /// ``` #[stable] pub fn difference<'a>(&'a self, other: &'a HashSet) -> Difference<'a, T, H> { @@ -315,8 +315,8 @@ impl, S, H: Hasher> HashSet { /// /// ``` /// use std::collections::HashSet; - /// let a: HashSet = [1, 2, 3].iter().map(|&x| x).collect(); - /// let b: HashSet = [4, 2, 3, 4].iter().map(|&x| x).collect(); + /// let a: HashSet = [1i, 2, 3].iter().map(|&x| x).collect(); + /// let b: HashSet = [4i, 2, 3, 4].iter().map(|&x| x).collect(); /// /// // Print 1, 4 in arbitrary order. /// for x in a.symmetric_difference(&b) { @@ -327,7 +327,7 @@ impl, S, H: Hasher> HashSet { /// let diff2: HashSet = b.symmetric_difference(&a).map(|&x| x).collect(); /// /// assert_eq!(diff1, diff2); - /// assert_eq!(diff1, [1, 4].iter().map(|&x| x).collect()); + /// assert_eq!(diff1, [1i, 4].iter().map(|&x| x).collect()); /// ``` #[stable] pub fn symmetric_difference<'a>(&'a self, other: &'a HashSet) @@ -341,8 +341,8 @@ impl, S, H: Hasher> HashSet { /// /// ``` /// use std::collections::HashSet; - /// let a: HashSet = [1, 2, 3].iter().map(|&x| x).collect(); - /// let b: HashSet = [4, 2, 3, 4].iter().map(|&x| x).collect(); + /// let a: HashSet = [1i, 2, 3].iter().map(|&x| x).collect(); + /// let b: HashSet = [4i, 2, 3, 4].iter().map(|&x| x).collect(); /// /// // Print 2, 3 in arbitrary order. /// for x in a.intersection(&b) { @@ -350,7 +350,7 @@ impl, S, H: Hasher> HashSet { /// } /// /// let diff: HashSet = a.intersection(&b).map(|&x| x).collect(); - /// assert_eq!(diff, [2, 3].iter().map(|&x| x).collect()); + /// assert_eq!(diff, [2i, 3].iter().map(|&x| x).collect()); /// ``` #[stable] pub fn intersection<'a>(&'a self, other: &'a HashSet) -> Intersection<'a, T, H> { @@ -366,8 +366,8 @@ impl, S, H: Hasher> HashSet { /// /// ``` /// use std::collections::HashSet; - /// let a: HashSet = [1, 2, 3].iter().map(|&x| x).collect(); - /// let b: HashSet = [4, 2, 3, 4].iter().map(|&x| x).collect(); + /// let a: HashSet = [1i, 2, 3].iter().map(|&x| x).collect(); + /// let b: HashSet = [4i, 2, 3, 4].iter().map(|&x| x).collect(); /// /// // Print 1, 2, 3, 4 in arbitrary order. /// for x in a.union(&b) { @@ -375,7 +375,7 @@ impl, S, H: Hasher> HashSet { /// } /// /// let diff: HashSet = a.union(&b).map(|&x| x).collect(); - /// assert_eq!(diff, [1, 2, 3, 4].iter().map(|&x| x).collect()); + /// assert_eq!(diff, [1i, 2, 3, 4].iter().map(|&x| x).collect()); /// ``` #[stable] pub fn union<'a>(&'a self, other: &'a HashSet) -> Union<'a, T, H> { diff --git a/src/libstd/macros.rs b/src/libstd/macros.rs index 22cbf16e2b0..d96441e09a8 100644 --- a/src/libstd/macros.rs +++ b/src/libstd/macros.rs @@ -32,7 +32,7 @@ /// # #![allow(unreachable_code)] /// panic!(); /// panic!("this is a terrible mistake!"); -/// panic!(4); // panic with the value of 4 to be collected elsewhere +/// panic!(4i); // panic with the value of 4 to be collected elsewhere /// panic!("this is a {} {message}", "fancy", message = "message"); /// ``` #[macro_export] @@ -73,7 +73,7 @@ macro_rules! panic { /// // assert with a custom message /// # let x = true; /// assert!(x, "x wasn't true!"); -/// # let a = 3; let b = 27; +/// # let a = 3i; let b = 27i; /// assert!(a + b == 30, "a = {}, b = {}", a, b); /// ``` #[macro_export] @@ -98,8 +98,8 @@ macro_rules! assert { /// # Example /// /// ``` -/// let a = 3; -/// let b = 1 + 2; +/// let a = 3i; +/// let b = 1i + 2i; /// assert_eq!(a, b); /// ``` #[macro_export] @@ -140,7 +140,7 @@ macro_rules! assert_eq { /// // assert with a custom message /// # let x = true; /// debug_assert!(x, "x wasn't true!"); -/// # let a = 3; let b = 27; +/// # let a = 3i; let b = 27i; /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b); /// ``` #[macro_export] @@ -161,8 +161,8 @@ macro_rules! debug_assert { /// # Example /// /// ``` -/// let a = 3; -/// let b = 1 + 2; +/// let a = 3i; +/// let b = 1i + 2i; /// debug_assert_eq!(a, b); /// ``` #[macro_export] @@ -237,7 +237,7 @@ macro_rules! unimplemented { /// ``` /// format!("test"); /// format!("hello {}", "world!"); -/// format!("x = {}, y = {y}", 10, y = 30); +/// format!("x = {}, y = {y}", 10i, y = 30i); /// ``` #[macro_export] #[stable] @@ -301,7 +301,7 @@ macro_rules! try { /// let (tx1, rx1) = channel(); /// let (tx2, rx2) = channel(); /// # fn long_running_task() {} -/// # fn calculate_the_answer() -> int { 42 } +/// # fn calculate_the_answer() -> int { 42i } /// /// Thread::spawn(move|| { long_running_task(); tx1.send(()) }).detach(); /// Thread::spawn(move|| { tx2.send(calculate_the_answer()) }).detach(); @@ -470,7 +470,7 @@ pub mod builtin { /// # Example /// /// ``` - /// let s = concat!("test", 10, 'b', true); + /// let s = concat!("test", 10i, 'b', true); /// assert_eq!(s, "test10btrue"); /// ``` #[macro_export] diff --git a/src/libstd/sync/mpsc/mod.rs b/src/libstd/sync/mpsc/mod.rs index bcfd61582a3..7c18b8a43fa 100644 --- a/src/libstd/sync/mpsc/mod.rs +++ b/src/libstd/sync/mpsc/mod.rs @@ -8,12 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! Communication primitives for concurrent tasks -//! -//! Rust makes it very difficult to share data among tasks to prevent race -//! conditions and to improve parallelism, but there is often a need for -//! communication between concurrent tasks. The primitives defined in this -//! module are the building blocks for synchronization in rust. +//! Multi-producer, single-consumer communication primitives threads //! //! This module provides message-based communication over channels, concretely //! defined among three types: @@ -23,12 +18,10 @@ //! * `Receiver` //! //! A `Sender` or `SyncSender` is used to send data to a `Receiver`. Both -//! senders are clone-able such that many tasks can send simultaneously to one -//! receiver. These channels are *task blocking*, not *thread blocking*. This -//! means that if one task is blocked on a channel, other tasks can continue to -//! make progress. +//! senders are clone-able (multi-producer) such that many threads can send +//! simultaneously to one receiver (single-consumer). //! -//! Rust channels come in one of two flavors: +//! These channels come in two flavors: //! //! 1. An asynchronous, infinitely buffered channel. The `channel()` function //! will return a `(Sender, Receiver)` tuple where all sends will be @@ -43,36 +36,39 @@ //! "rendezvous" channel where each sender atomically hands off a message to //! a receiver. //! -//! ## Panic Propagation +//! ## Disconnection //! -//! In addition to being a core primitive for communicating in rust, channels -//! are the points at which panics are propagated among tasks. Whenever the one -//! half of channel is closed, the other half will have its next operation -//! `panic!`. The purpose of this is to allow propagation of panics among tasks -//! that are linked to one another via channels. +//! The send and receive operations on channels will all return a `Result` +//! indicating whether the operation succeeded or not. An unsuccessful operation +//! is normally indicative of the other half of a channel having "hung up" by +//! being dropped in its corresponding thread. //! -//! There are methods on both of senders and receivers to perform their -//! respective operations without panicking, however. +//! Once half of a channel has been deallocated, most operations can no longer +//! continue to make progress, so `Err` will be returned. Many applications will +//! continue to `unwrap()` the results returned from this module, instigating a +//! propagation of failure among threads if one unexpectedly dies. //! -//! # Example +//! # Examples //! //! Simple usage: //! //! ``` //! use std::thread::Thread; +//! use std::sync::mpsc::channel; //! //! // Create a simple streaming channel //! let (tx, rx) = channel(); //! Thread::spawn(move|| { -//! tx.send(10); +//! tx.send(10i).unwrap(); //! }).detach(); -//! assert_eq!(rx.recv(), 10); +//! assert_eq!(rx.recv().unwrap(), 10i); //! ``` //! //! Shared usage: //! //! ``` //! use std::thread::Thread; +//! use std::sync::mpsc::channel; //! //! // Create a shared channel that can be sent along from many threads //! // where tx is the sending half (tx for transmission), and rx is the receiving @@ -81,37 +77,40 @@ //! for i in range(0i, 10i) { //! let tx = tx.clone(); //! Thread::spawn(move|| { -//! tx.send(i); +//! tx.send(i).unwrap(); //! }).detach() //! } //! //! for _ in range(0i, 10i) { -//! let j = rx.recv(); +//! let j = rx.recv().unwrap(); //! assert!(0 <= j && j < 10); //! } //! ``` //! //! Propagating panics: //! -//! ```should_fail -//! // The call to recv() will panic!() because the channel has already hung -//! // up (or been deallocated) +//! ``` +//! use std::sync::mpsc::channel; +//! +//! // The call to recv() will return an error because the channel has already +//! // hung up (or been deallocated) //! let (tx, rx) = channel::(); //! drop(tx); -//! rx.recv(); +//! assert!(rx.recv().is_err()); //! ``` //! //! Synchronous channels: //! //! ``` //! use std::thread::Thread; +//! use std::sync::mpsc::sync_channel; //! //! let (tx, rx) = sync_channel::(0); //! Thread::spawn(move|| { //! // This will wait for the parent task to start receiving -//! tx.send(53); +//! tx.send(53).unwrap(); //! }).detach(); -//! rx.recv(); +//! rx.recv().unwrap(); //! ``` //! //! Reading from a channel with a timeout requires to use a Timer together @@ -120,6 +119,7 @@ //! after 10 seconds no matter what: //! //! ```no_run +//! use std::sync::mpsc::channel; //! use std::io::timer::Timer; //! use std::time::Duration; //! @@ -129,8 +129,8 @@ //! //! loop { //! select! { -//! val = rx.recv() => println!("Received {}", val), -//! () = timeout.recv() => { +//! val = rx.recv() => println!("Received {}", val.unwrap()), +//! _ = timeout.recv() => { //! println!("timed out, total time was more than 10 seconds"); //! break; //! } @@ -143,6 +143,7 @@ //! has been inactive for 5 seconds: //! //! ```no_run +//! use std::sync::mpsc::channel; //! use std::io::timer::Timer; //! use std::time::Duration; //! @@ -153,8 +154,8 @@ //! let timeout = timer.oneshot(Duration::seconds(5)); //! //! select! { -//! val = rx.recv() => println!("Received {}", val), -//! () = timeout.recv() => { +//! val = rx.recv() => println!("Received {}", val.unwrap()), +//! _ = timeout.recv() => { //! println!("timed out, no message received in 5 seconds"); //! break; //! } @@ -314,38 +315,19 @@ // And now that you've seen all the races that I found and attempted to fix, // here's the code for you to find some more! -use core::prelude::*; +use prelude::v1::*; -pub use self::TryRecvError::*; -pub use self::TrySendError::*; - -use alloc::arc::Arc; -use core::kinds; -use core::kinds::marker; -use core::mem; -use core::cell::UnsafeCell; +use sync::Arc; +use fmt; +use kinds::marker; +use mem; +use cell::UnsafeCell; pub use self::select::{Select, Handle}; use self::select::StartResult; use self::select::StartResult::*; use self::blocking::SignalToken; -macro_rules! test { - { fn $name:ident() $b:block $(#[$a:meta])*} => ( - mod $name { - #![allow(unused_imports)] - - use super::*; - use comm::*; - use thread::Thread; - use prelude::{Ok, Err, spawn, range, drop, Box, Some, None, Option}; - use prelude::{Vec, Buffer, from_str, Clone}; - - $(#[$a])* #[test] fn f() { $b } - } - ) -} - mod blocking; mod oneshot; mod select; @@ -357,7 +339,7 @@ mod spsc_queue; /// The receiving-half of Rust's channel type. This half can only be owned by /// one task -#[unstable] +#[stable] pub struct Receiver { inner: UnsafeCell>, } @@ -369,14 +351,14 @@ unsafe impl Send for Receiver { } /// An iterator over messages on a receiver, this iterator will block /// whenever `next` is called, waiting for a new message, and `None` will be /// returned when the corresponding channel has hung up. -#[unstable] -pub struct Messages<'a, T:'a> { +#[stable] +pub struct Iter<'a, T:'a> { rx: &'a Receiver } /// The sending-half of Rust's asynchronous channel type. This half can only be /// owned by one task, but it can be cloned to send to other tasks. -#[unstable] +#[stable] pub struct Sender { inner: UnsafeCell>, } @@ -387,30 +369,50 @@ unsafe impl Send for Sender { } /// The sending-half of Rust's synchronous channel type. This half can only be /// owned by one task, but it can be cloned to send to other tasks. -#[unstable = "this type may be renamed, but it will always exist"] +#[stable] pub struct SyncSender { inner: Arc>>, // can't share in an arc _marker: marker::NoSync, } +/// An error returned from the `send` function on channels. +/// +/// A `send` operation can only fail if the receiving end of a channel is +/// disconnected, implying that the data could never be received. The error +/// contains the data being sent as a payload so it can be recovered. +#[derive(PartialEq, Eq)] +#[stable] +pub struct SendError(pub T); + +/// An error returned from the `recv` function on a `Receiver`. +/// +/// The `recv` operation can only fail if the sending half of a channel is +/// disconnected, implying that no further messages will ever be received. +#[derive(PartialEq, Eq, Clone, Copy)] +#[stable] +pub struct RecvError; + /// This enumeration is the list of the possible reasons that try_recv could not /// return data when called. -#[deriving(PartialEq, Clone, Copy, Show)] -#[experimental = "this is likely to be removed in changing try_recv()"] +#[derive(PartialEq, Clone, Copy)] +#[stable] pub enum TryRecvError { /// This channel is currently empty, but the sender(s) have not yet /// disconnected, so data may yet become available. + #[stable] Empty, + /// This channel's sending half has become disconnected, and there will /// never be any more data received on this channel + #[stable] Disconnected, } /// This enumeration is the list of the possible error outcomes for the /// `SyncSender::try_send` method. -#[deriving(PartialEq, Clone, Show)] -#[experimental = "this is likely to be removed in changing try_send()"] +#[derive(PartialEq, Clone)] +#[stable] pub enum TrySendError { /// The data could not be sent on the channel because it would require that /// the callee block to send the data. @@ -418,10 +420,13 @@ pub enum TrySendError { /// If this is a buffered channel, then the buffer is full at this time. If /// this is not a buffered channel, then there is no receiver available to /// acquire the data. + #[stable] Full(T), + /// This channel's receiving half has disconnected, so the data could not be /// sent. The data is returned back to the callee in this case. - RecvDisconnected(T), + #[stable] + Disconnected(T), } enum Flavor { @@ -460,6 +465,7 @@ impl UnsafeFlavor for Receiver { /// # Example /// /// ``` +/// use std::sync::mpsc::channel; /// use std::thread::Thread; /// /// // tx is is the sending half (tx for transmission), and rx is the receiving @@ -469,15 +475,15 @@ impl UnsafeFlavor for Receiver { /// // Spawn off an expensive computation /// Thread::spawn(move|| { /// # fn expensive_computation() {} -/// tx.send(expensive_computation()); +/// tx.send(expensive_computation()).unwrap(); /// }).detach(); /// /// // Do some useful work for awhile /// /// // Let's see what that answer was -/// println!("{}", rx.recv()); +/// println!("{}", rx.recv().unwrap()); /// ``` -#[unstable] +#[stable] pub fn channel() -> (Sender, Receiver) { let a = Arc::new(RacyCell::new(oneshot::Packet::new())); (Sender::new(Flavor::Oneshot(a.clone())), Receiver::new(Flavor::Oneshot(a))) @@ -501,23 +507,23 @@ pub fn channel() -> (Sender, Receiver) { /// # Example /// /// ``` +/// use std::sync::mpsc::sync_channel; /// use std::thread::Thread; /// /// let (tx, rx) = sync_channel(1); /// /// // this returns immediately -/// tx.send(1); +/// tx.send(1i).unwrap(); /// /// Thread::spawn(move|| { /// // this will block until the previous message has been received -/// tx.send(2); +/// tx.send(2i).unwrap(); /// }).detach(); /// -/// assert_eq!(rx.recv(), 1); -/// assert_eq!(rx.recv(), 2); +/// assert_eq!(rx.recv().unwrap(), 1i); +/// assert_eq!(rx.recv().unwrap(), 2i); /// ``` -#[unstable = "this function may be renamed to more accurately reflect the type \ - of channel that is is creating"] +#[stable] pub fn sync_channel(bound: uint) -> (SyncSender, Receiver) { let a = Arc::new(RacyCell::new(sync::Packet::new(bound))); (SyncSender::new(a.clone()), Receiver::new(Flavor::Sync(a))) @@ -534,33 +540,6 @@ impl Sender { } } - /// Sends a value along this channel to be received by the corresponding - /// receiver. - /// - /// Rust channels are infinitely buffered so this method will never block. - /// - /// # Panics - /// - /// This function will panic if the other end of the channel has hung up. - /// This means that if the corresponding receiver has fallen out of scope, - /// this function will trigger a panic message saying that a message is - /// being sent on a closed channel. - /// - /// Note that if this function does *not* panic, it does not mean that the - /// data will be successfully received. All sends are placed into a queue, - /// so it is possible for a send to succeed (the other end is alive), but - /// then the other end could immediately disconnect. - /// - /// The purpose of this functionality is to propagate panics among tasks. - /// If a panic is not desired, then consider using the `send_opt` method - #[experimental = "this function is being considered candidate for removal \ - to adhere to the general guidelines of rust"] - pub fn send(&self, t: T) { - if self.send_opt(t).is_err() { - panic!("sending on a closed channel"); - } - } - /// Attempts to send a value on this channel, returning it back if it could /// not be sent. /// @@ -572,24 +551,21 @@ impl Sender { /// will be received. It is possible for the corresponding receiver to /// hang up immediately after this function returns `Ok`. /// - /// Like `send`, this method will never block. - /// - /// # Panics - /// - /// This method will never panic, it will return the message back to the - /// caller if the other end is disconnected + /// This method will never block the current thread. /// /// # Example /// /// ``` + /// use std::sync::mpsc::channel; + /// /// let (tx, rx) = channel(); /// /// // This send is always successful - /// assert_eq!(tx.send_opt(1), Ok(())); + /// tx.send(1i).unwrap(); /// /// // This send will fail because the receiver is gone /// drop(rx); - /// assert_eq!(tx.send_opt(1), Err(1)); + /// assert_eq!(tx.send(1i).err().unwrap().0, 1); /// ``` #[stable] pub fn send(&self, t: T) -> Result<(), SendError> { @@ -598,11 +574,12 @@ impl Sender { unsafe { let p = p.get(); if !(*p).sent() { - return (*p).send(t); + return (*p).send(t).map_err(SendError); } else { let a = Arc::new(RacyCell::new(stream::Packet::new())); - match (*p).upgrade(Receiver::new(Flavor::Stream(a.clone()))) { + let rx = Receiver::new(Flavor::Stream(a.clone())); + match (*p).upgrade(rx) { oneshot::UpSuccess => { let ret = (*a.get()).send(t); (a, ret) @@ -613,15 +590,19 @@ impl Sender { // asleep (we're looking at it), so the receiver // can't go away. (*a.get()).send(t).ok().unwrap(); - token.signal(); + token.signal(); (a, Ok(())) } } } } } - Flavor::Stream(ref p) => return unsafe { (*p.get()).send(t) }, - Flavor::Shared(ref p) => return unsafe { (*p.get()).send(t) }, + Flavor::Stream(ref p) => return unsafe { + (*p.get()).send(t).map_err(SendError) + }, + Flavor::Shared(ref p) => return unsafe { + (*p.get()).send(t).map_err(SendError) + }, Flavor::Sync(..) => unreachable!(), }; @@ -629,7 +610,7 @@ impl Sender { let tmp = Sender::new(Flavor::Stream(new_inner)); mem::swap(self.inner_mut(), tmp.inner_mut()); } - return ret; + ret.map_err(SendError) } } @@ -641,7 +622,8 @@ impl Clone for Sender { let a = Arc::new(RacyCell::new(shared::Packet::new())); unsafe { let guard = (*a.get()).postinit_lock(); - match (*p.get()).upgrade(Receiver::new(Flavor::Shared(a.clone()))) { + let rx = Receiver::new(Flavor::Shared(a.clone())); + match (*p.get()).upgrade(rx) { oneshot::UpSuccess | oneshot::UpDisconnected => (a, None, guard), oneshot::UpWoke(task) => (a, Some(task), guard) @@ -652,7 +634,8 @@ impl Clone for Sender { let a = Arc::new(RacyCell::new(shared::Packet::new())); unsafe { let guard = (*a.get()).postinit_lock(); - match (*p.get()).upgrade(Receiver::new(Flavor::Shared(a.clone()))) { + let rx = Receiver::new(Flavor::Shared(a.clone())); + match (*p.get()).upgrade(rx) { stream::UpSuccess | stream::UpDisconnected => (a, None, guard), stream::UpWoke(task) => (a, Some(task), guard), @@ -704,59 +687,29 @@ impl SyncSender { /// available or a receiver is available to hand off the message to. /// /// Note that a successful send does *not* guarantee that the receiver will - /// ever see the data if there is a buffer on this channel. Messages may be + /// ever see the data if there is a buffer on this channel. Items may be /// enqueued in the internal buffer for the receiver to receive at a later /// time. If the buffer size is 0, however, it can be guaranteed that the /// receiver has indeed received the data if this function returns success. /// - /// # Panics - /// - /// Similarly to `Sender::send`, this function will panic if the - /// corresponding `Receiver` for this channel has disconnected. This - /// behavior is used to propagate panics among tasks. - /// - /// If a panic is not desired, you can achieve the same semantics with the - /// `SyncSender::send_opt` method which will not panic if the receiver - /// disconnects. - #[experimental = "this function is being considered candidate for removal \ - to adhere to the general guidelines of rust"] - pub fn send(&self, t: T) { - if self.send_opt(t).is_err() { - panic!("sending on a closed channel"); - } - } - - /// Send a value on a channel, returning it back if the receiver - /// disconnected - /// - /// This method will *block* to send the value `t` on the channel, but if - /// the value could not be sent due to the receiver disconnecting, the value - /// is returned back to the callee. This function is similar to `try_send`, - /// except that it will block if the channel is currently full. - /// - /// # Panics - /// - /// This function cannot panic. - #[unstable = "this function may be renamed to send() in the future"] - pub fn send_opt(&self, t: T) -> Result<(), T> { - unsafe { (*self.inner.get()).send(t) } + /// This function will never panic, but it may return `Err` if the + /// `Receiver` has disconnected and is no longer able to receive + /// information. + #[stable] + pub fn send(&self, t: T) -> Result<(), SendError> { + unsafe { (*self.inner.get()).send(t).map_err(SendError) } } /// Attempts to send a value on this channel without blocking. /// - /// This method differs from `send_opt` by returning immediately if the + /// This method differs from `send` by returning immediately if the /// channel's buffer is full or no receiver is waiting to acquire some - /// data. Compared with `send_opt`, this function has two failure cases + /// data. Compared with `send`, this function has two failure cases /// instead of one (one for disconnection, one for a full buffer). /// /// See `SyncSender::send` for notes about guarantees of whether the /// receiver has received the data or not if this function is successful. - /// - /// # Panics - /// - /// This function cannot panic - #[unstable = "the return type of this function is candidate for \ - modification"] + #[stable] pub fn try_send(&self, t: T) -> Result<(), TrySendError> { unsafe { (*self.inner.get()).try_send(t) } } @@ -787,34 +740,6 @@ impl Receiver { Receiver { inner: UnsafeCell::new(inner) } } - /// Blocks waiting for a value on this receiver - /// - /// This function will block if necessary to wait for a corresponding send - /// on the channel from its paired `Sender` structure. This receiver will - /// be woken up when data is ready, and the data will be returned. - /// - /// # Panics - /// - /// Similar to channels, this method will trigger a task panic if the - /// other end of the channel has hung up (been deallocated). The purpose of - /// this is to propagate panics among tasks. - /// - /// If a panic is not desired, then there are two options: - /// - /// * If blocking is still desired, the `recv_opt` method will return `None` - /// when the other end hangs up - /// - /// * If blocking is not desired, then the `try_recv` method will attempt to - /// peek at a value on this receiver. - #[experimental = "this function is being considered candidate for removal \ - to adhere to the general guidelines of rust"] - pub fn recv(&self) -> T { - match self.recv_opt() { - Ok(t) => t, - Err(()) => panic!("receiving on a closed channel"), - } - } - /// Attempts to return a pending value on this receiver without blocking /// /// This method will never block the caller in order to wait for data to @@ -823,42 +748,46 @@ impl Receiver { /// /// This is useful for a flavor of "optimistic check" before deciding to /// block on a receiver. - /// - /// # Panics - /// - /// This function cannot panic. - #[unstable = "the return type of this function may be altered"] + #[stable] pub fn try_recv(&self) -> Result { loop { let new_port = match *unsafe { self.inner() } { Flavor::Oneshot(ref p) => { match unsafe { (*p.get()).try_recv() } { Ok(t) => return Ok(t), - Err(oneshot::Empty) => return Err(Empty), - Err(oneshot::Disconnected) => return Err(Disconnected), + Err(oneshot::Empty) => return Err(TryRecvError::Empty), + Err(oneshot::Disconnected) => { + return Err(TryRecvError::Disconnected) + } Err(oneshot::Upgraded(rx)) => rx, } } Flavor::Stream(ref p) => { match unsafe { (*p.get()).try_recv() } { Ok(t) => return Ok(t), - Err(stream::Empty) => return Err(Empty), - Err(stream::Disconnected) => return Err(Disconnected), + Err(stream::Empty) => return Err(TryRecvError::Empty), + Err(stream::Disconnected) => { + return Err(TryRecvError::Disconnected) + } Err(stream::Upgraded(rx)) => rx, } } Flavor::Shared(ref p) => { match unsafe { (*p.get()).try_recv() } { Ok(t) => return Ok(t), - Err(shared::Empty) => return Err(Empty), - Err(shared::Disconnected) => return Err(Disconnected), + Err(shared::Empty) => return Err(TryRecvError::Empty), + Err(shared::Disconnected) => { + return Err(TryRecvError::Disconnected) + } } } Flavor::Sync(ref p) => { match unsafe { (*p.get()).try_recv() } { Ok(t) => return Ok(t), - Err(sync::Empty) => return Err(Empty), - Err(sync::Disconnected) => return Err(Disconnected), + Err(sync::Empty) => return Err(TryRecvError::Empty), + Err(sync::Disconnected) => { + return Err(TryRecvError::Disconnected) + } } } }; @@ -869,27 +798,26 @@ impl Receiver { } } - /// Attempt to wait for a value on this receiver, but does not panic if the + /// Attempt to wait for a value on this receiver, returning an error if the /// corresponding channel has hung up. /// - /// This implementation of iterators for ports will always block if there is - /// not data available on the receiver, but it will not panic in the case - /// that the channel has been deallocated. + /// This function will always block the current thread if there is no data + /// available and it's possible for more data to be sent. Once a message is + /// sent to the corresponding `Sender`, then this receiver will wake up and + /// return that message. /// - /// In other words, this function has the same semantics as the `recv` - /// method except for the panic aspect. - /// - /// If the channel has hung up, then `Err` is returned. Otherwise `Ok` of - /// the value found on the receiver is returned. - #[unstable = "this function may be renamed to recv()"] - pub fn recv_opt(&self) -> Result { + /// If the corresponding `Sender` has disconnected, or it disconnects while + /// this call is blocking, this call will wake up and return `Err` to + /// indicate that no more messages can ever be received on this channel. + #[stable] + pub fn recv(&self) -> Result { loop { let new_port = match *unsafe { self.inner() } { Flavor::Oneshot(ref p) => { match unsafe { (*p.get()).recv() } { Ok(t) => return Ok(t), Err(oneshot::Empty) => return unreachable!(), - Err(oneshot::Disconnected) => return Err(()), + Err(oneshot::Disconnected) => return Err(RecvError), Err(oneshot::Upgraded(rx)) => rx, } } @@ -897,7 +825,7 @@ impl Receiver { match unsafe { (*p.get()).recv() } { Ok(t) => return Ok(t), Err(stream::Empty) => return unreachable!(), - Err(stream::Disconnected) => return Err(()), + Err(stream::Disconnected) => return Err(RecvError), Err(stream::Upgraded(rx)) => rx, } } @@ -905,10 +833,12 @@ impl Receiver { match unsafe { (*p.get()).recv() } { Ok(t) => return Ok(t), Err(shared::Empty) => return unreachable!(), - Err(shared::Disconnected) => return Err(()), + Err(shared::Disconnected) => return Err(RecvError), } } - Flavor::Sync(ref p) => return unsafe { (*p.get()).recv() } + Flavor::Sync(ref p) => return unsafe { + (*p.get()).recv().map_err(|()| RecvError) + } }; unsafe { mem::swap(self.inner_mut(), new_port.inner_mut()); @@ -918,9 +848,9 @@ impl Receiver { /// Returns an iterator that will block waiting for messages, but never /// `panic!`. It will return `None` when the channel has hung up. - #[unstable] - pub fn iter<'a>(&'a self) -> Messages<'a, T> { - Messages { rx: self } + #[stable] + pub fn iter(&self) -> Iter { + Iter { rx: self } } } @@ -1048,368 +978,425 @@ impl RacyCell { unsafe impl Send for RacyCell { } -unsafe impl kinds::Sync for RacyCell { } // Oh dear +unsafe impl Sync for RacyCell { } // Oh dear + +impl fmt::Show for SendError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + "sending on a closed channel".fmt(f) + } +} + +impl fmt::Show for TrySendError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + TrySendError::Full(..) => { + "sending on a full channel".fmt(f) + } + TrySendError::Disconnected(..) => { + "sending on a closed channel".fmt(f) + } + } + } +} + +impl fmt::Show for RecvError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + "receiving on a closed channel".fmt(f) + } +} +impl fmt::Show for TryRecvError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + TryRecvError::Empty => { + "receiving on an empty channel".fmt(f) + } + TryRecvError::Disconnected => { + "receiving on a closed channel".fmt(f) + } + } + } +} #[cfg(test)] mod test { - use super::*; - use prelude::{spawn, range, Some, None, from_str, Clone, Str}; + use prelude::v1::*; + use os; + use super::*; + use thread::Thread; pub fn stress_factor() -> uint { match os::getenv("RUST_TEST_STRESS") { - Some(val) => from_str::(val.as_slice()).unwrap(), + Some(val) => val.parse().unwrap(), None => 1, } } - test! { fn smoke() { + #[test] + fn smoke() { let (tx, rx) = channel::(); - tx.send(1); - assert_eq!(rx.recv(), 1); - } } + tx.send(1).unwrap(); + assert_eq!(rx.recv().unwrap(), 1); + } - test! { fn drop_full() { + #[test] + fn drop_full() { let (tx, _rx) = channel(); - tx.send(box 1i); - } } + tx.send(box 1i).unwrap(); + } - test! { fn drop_full_shared() { + #[test] + fn drop_full_shared() { let (tx, _rx) = channel(); drop(tx.clone()); drop(tx.clone()); - tx.send(box 1i); - } } + tx.send(box 1i).unwrap(); + } - test! { fn smoke_shared() { + #[test] + fn smoke_shared() { let (tx, rx) = channel::(); - tx.send(1); - assert_eq!(rx.recv(), 1); + tx.send(1).unwrap(); + assert_eq!(rx.recv().unwrap(), 1); let tx = tx.clone(); - tx.send(1); - assert_eq!(rx.recv(), 1); - } } + tx.send(1).unwrap(); + assert_eq!(rx.recv().unwrap(), 1); + } - test! { fn smoke_threads() { + #[test] + fn smoke_threads() { let (tx, rx) = channel::(); - spawn(move|| { - tx.send(1); + let _t = Thread::spawn(move|| { + tx.send(1).unwrap(); }); - assert_eq!(rx.recv(), 1); - } } + assert_eq!(rx.recv().unwrap(), 1); + } - test! { fn smoke_port_gone() { + #[test] + fn smoke_port_gone() { let (tx, rx) = channel::(); drop(rx); - tx.send(1); - } #[should_fail] } + assert!(tx.send(1).is_err()); + } - test! { fn smoke_shared_port_gone() { + #[test] + fn smoke_shared_port_gone() { let (tx, rx) = channel::(); drop(rx); - tx.send(1); - } #[should_fail] } + assert!(tx.send(1).is_err()) + } - test! { fn smoke_shared_port_gone2() { + #[test] + fn smoke_shared_port_gone2() { let (tx, rx) = channel::(); drop(rx); let tx2 = tx.clone(); drop(tx); - tx2.send(1); - } #[should_fail] } + assert!(tx2.send(1).is_err()); + } - test! { fn port_gone_concurrent() { + #[test] + fn port_gone_concurrent() { let (tx, rx) = channel::(); - spawn(move|| { - rx.recv(); + let _t = Thread::spawn(move|| { + rx.recv().unwrap(); }); - loop { tx.send(1) } - } #[should_fail] } + while tx.send(1).is_ok() {} + } - test! { fn port_gone_concurrent_shared() { + #[test] + fn port_gone_concurrent_shared() { let (tx, rx) = channel::(); let tx2 = tx.clone(); - spawn(move|| { - rx.recv(); + let _t = Thread::spawn(move|| { + rx.recv().unwrap(); }); - loop { - tx.send(1); - tx2.send(1); - } - } #[should_fail] } + while tx.send(1).is_ok() && tx2.send(1).is_ok() {} + } - test! { fn smoke_chan_gone() { + #[test] + fn smoke_chan_gone() { let (tx, rx) = channel::(); drop(tx); - rx.recv(); - } #[should_fail] } + assert!(rx.recv().is_err()); + } - test! { fn smoke_chan_gone_shared() { + #[test] + fn smoke_chan_gone_shared() { let (tx, rx) = channel::<()>(); let tx2 = tx.clone(); drop(tx); drop(tx2); - rx.recv(); - } #[should_fail] } + assert!(rx.recv().is_err()); + } - test! { fn chan_gone_concurrent() { + #[test] + fn chan_gone_concurrent() { let (tx, rx) = channel::(); - spawn(move|| { - tx.send(1); - tx.send(1); + let _t = Thread::spawn(move|| { + tx.send(1).unwrap(); + tx.send(1).unwrap(); }); - loop { rx.recv(); } - } #[should_fail] } + while rx.recv().is_ok() {} + } - test! { fn stress() { + #[test] + fn stress() { let (tx, rx) = channel::(); - spawn(move|| { - for _ in range(0u, 10000) { tx.send(1i); } + let t = Thread::spawn(move|| { + for _ in range(0u, 10000) { tx.send(1i).unwrap(); } }); for _ in range(0u, 10000) { - assert_eq!(rx.recv(), 1); + assert_eq!(rx.recv().unwrap(), 1); } - } } + t.join().ok().unwrap(); + } - test! { fn stress_shared() { + #[test] + fn stress_shared() { static AMT: uint = 10000; static NTHREADS: uint = 8; let (tx, rx) = channel::(); - let (dtx, drx) = channel::<()>(); - spawn(move|| { + let t = Thread::spawn(move|| { for _ in range(0, AMT * NTHREADS) { - assert_eq!(rx.recv(), 1); + assert_eq!(rx.recv().unwrap(), 1); } match rx.try_recv() { Ok(..) => panic!(), _ => {} } - dtx.send(()); }); for _ in range(0, NTHREADS) { let tx = tx.clone(); - spawn(move|| { - for _ in range(0, AMT) { tx.send(1); } - }); + Thread::spawn(move|| { + for _ in range(0, AMT) { tx.send(1).unwrap(); } + }).detach(); } drop(tx); - drx.recv(); - } } + t.join().ok().unwrap(); + } #[test] fn send_from_outside_runtime() { let (tx1, rx1) = channel::<()>(); let (tx2, rx2) = channel::(); - let (tx3, rx3) = channel::<()>(); - let tx4 = tx3.clone(); - spawn(move|| { - tx1.send(()); + let t1 = Thread::spawn(move|| { + tx1.send(()).unwrap(); for _ in range(0i, 40) { - assert_eq!(rx2.recv(), 1); + assert_eq!(rx2.recv().unwrap(), 1); } - tx3.send(()); }); - rx1.recv(); - spawn(move|| { + rx1.recv().unwrap(); + let t2 = Thread::spawn(move|| { for _ in range(0i, 40) { - tx2.send(1); + tx2.send(1).unwrap(); } - tx4.send(()); }); - rx3.recv(); - rx3.recv(); + t1.join().ok().unwrap(); + t2.join().ok().unwrap(); } #[test] fn recv_from_outside_runtime() { let (tx, rx) = channel::(); - let (dtx, drx) = channel(); - spawn(move|| { + let t = Thread::spawn(move|| { for _ in range(0i, 40) { - assert_eq!(rx.recv(), 1); + assert_eq!(rx.recv().unwrap(), 1); } - dtx.send(()); }); for _ in range(0u, 40) { - tx.send(1); + tx.send(1).unwrap(); } - drx.recv(); + t.join().ok().unwrap(); } #[test] fn no_runtime() { let (tx1, rx1) = channel::(); let (tx2, rx2) = channel::(); - let (tx3, rx3) = channel::<()>(); - let tx4 = tx3.clone(); - spawn(move|| { - assert_eq!(rx1.recv(), 1); - tx2.send(2); - tx4.send(()); + let t1 = Thread::spawn(move|| { + assert_eq!(rx1.recv().unwrap(), 1); + tx2.send(2).unwrap(); }); - spawn(move|| { - tx1.send(1); - assert_eq!(rx2.recv(), 2); - tx3.send(()); + let t2 = Thread::spawn(move|| { + tx1.send(1).unwrap(); + assert_eq!(rx2.recv().unwrap(), 2); }); - rx3.recv(); - rx3.recv(); + t1.join().ok().unwrap(); + t2.join().ok().unwrap(); } - test! { fn oneshot_single_thread_close_port_first() { + #[test] + fn oneshot_single_thread_close_port_first() { // Simple test of closing without sending let (_tx, rx) = channel::(); drop(rx); - } } + } - test! { fn oneshot_single_thread_close_chan_first() { + #[test] + fn oneshot_single_thread_close_chan_first() { // Simple test of closing without sending let (tx, _rx) = channel::(); drop(tx); - } } + } - test! { fn oneshot_single_thread_send_port_close() { + #[test] + fn oneshot_single_thread_send_port_close() { // Testing that the sender cleans up the payload if receiver is closed let (tx, rx) = channel::>(); drop(rx); - tx.send(box 0); - } #[should_fail] } + assert!(tx.send(box 0).is_err()); + } - test! { fn oneshot_single_thread_recv_chan_close() { + #[test] + fn oneshot_single_thread_recv_chan_close() { // Receiving on a closed chan will panic let res = Thread::spawn(move|| { let (tx, rx) = channel::(); drop(tx); - rx.recv(); + rx.recv().unwrap(); }).join(); // What is our res? assert!(res.is_err()); - } } + } - test! { fn oneshot_single_thread_send_then_recv() { + #[test] + fn oneshot_single_thread_send_then_recv() { let (tx, rx) = channel::>(); - tx.send(box 10); - assert!(rx.recv() == box 10); - } } + tx.send(box 10).unwrap(); + assert!(rx.recv().unwrap() == box 10); + } - test! { fn oneshot_single_thread_try_send_open() { + #[test] + fn oneshot_single_thread_try_send_open() { let (tx, rx) = channel::(); - assert!(tx.send_opt(10).is_ok()); - assert!(rx.recv() == 10); - } } + assert!(tx.send(10).is_ok()); + assert!(rx.recv().unwrap() == 10); + } - test! { fn oneshot_single_thread_try_send_closed() { + #[test] + fn oneshot_single_thread_try_send_closed() { let (tx, rx) = channel::(); drop(rx); - assert!(tx.send_opt(10).is_err()); - } } + assert!(tx.send(10).is_err()); + } - test! { fn oneshot_single_thread_try_recv_open() { + #[test] + fn oneshot_single_thread_try_recv_open() { let (tx, rx) = channel::(); - tx.send(10); - assert!(rx.recv_opt() == Ok(10)); - } } + tx.send(10).unwrap(); + assert!(rx.recv() == Ok(10)); + } - test! { fn oneshot_single_thread_try_recv_closed() { + #[test] + fn oneshot_single_thread_try_recv_closed() { let (tx, rx) = channel::(); drop(tx); - assert!(rx.recv_opt() == Err(())); - } } + assert!(rx.recv().is_err()); + } - test! { fn oneshot_single_thread_peek_data() { + #[test] + fn oneshot_single_thread_peek_data() { let (tx, rx) = channel::(); - assert_eq!(rx.try_recv(), Err(Empty)); - tx.send(10); + assert_eq!(rx.try_recv(), Err(TryRecvError::Empty)); + tx.send(10).unwrap(); assert_eq!(rx.try_recv(), Ok(10)); - } } + } - test! { fn oneshot_single_thread_peek_close() { + #[test] + fn oneshot_single_thread_peek_close() { let (tx, rx) = channel::(); drop(tx); - assert_eq!(rx.try_recv(), Err(Disconnected)); - assert_eq!(rx.try_recv(), Err(Disconnected)); - } } + assert_eq!(rx.try_recv(), Err(TryRecvError::Disconnected)); + assert_eq!(rx.try_recv(), Err(TryRecvError::Disconnected)); + } - test! { fn oneshot_single_thread_peek_open() { + #[test] + fn oneshot_single_thread_peek_open() { let (_tx, rx) = channel::(); - assert_eq!(rx.try_recv(), Err(Empty)); - } } + assert_eq!(rx.try_recv(), Err(TryRecvError::Empty)); + } - test! { fn oneshot_multi_task_recv_then_send() { + #[test] + fn oneshot_multi_task_recv_then_send() { let (tx, rx) = channel::>(); - spawn(move|| { - assert!(rx.recv() == box 10); + let _t = Thread::spawn(move|| { + assert!(rx.recv().unwrap() == box 10); }); - tx.send(box 10); - } } + tx.send(box 10).unwrap(); + } - test! { fn oneshot_multi_task_recv_then_close() { + #[test] + fn oneshot_multi_task_recv_then_close() { let (tx, rx) = channel::>(); - spawn(move|| { + let _t = Thread::spawn(move|| { drop(tx); }); let res = Thread::spawn(move|| { - assert!(rx.recv() == box 10); + assert!(rx.recv().unwrap() == box 10); }).join(); assert!(res.is_err()); - } } + } - test! { fn oneshot_multi_thread_close_stress() { + #[test] + fn oneshot_multi_thread_close_stress() { for _ in range(0, stress_factor()) { let (tx, rx) = channel::(); - spawn(move|| { + let _t = Thread::spawn(move|| { drop(rx); }); drop(tx); } - } } + } - test! { fn oneshot_multi_thread_send_close_stress() { + #[test] + fn oneshot_multi_thread_send_close_stress() { for _ in range(0, stress_factor()) { let (tx, rx) = channel::(); - spawn(move|| { + let _t = Thread::spawn(move|| { drop(rx); }); let _ = Thread::spawn(move|| { - tx.send(1); + tx.send(1).unwrap(); }).join(); } - } } + } - test! { fn oneshot_multi_thread_recv_close_stress() { + #[test] + fn oneshot_multi_thread_recv_close_stress() { for _ in range(0, stress_factor()) { let (tx, rx) = channel::(); - spawn(move|| { + Thread::spawn(move|| { let res = Thread::spawn(move|| { - rx.recv(); + rx.recv().unwrap(); }).join(); assert!(res.is_err()); - }); - spawn(move|| { - spawn(move|| { + }).detach(); + let _t = Thread::spawn(move|| { + Thread::spawn(move|| { drop(tx); - }); + }).detach(); }); } - } } + } - test! { fn oneshot_multi_thread_send_recv_stress() { + #[test] + fn oneshot_multi_thread_send_recv_stress() { for _ in range(0, stress_factor()) { let (tx, rx) = channel(); - spawn(move|| { - tx.send(box 10i); - }); - spawn(move|| { - assert!(rx.recv() == box 10i); + let _t = Thread::spawn(move|| { + tx.send(box 10i).unwrap(); }); + assert!(rx.recv().unwrap() == box 10i); } - } } + } - test! { fn stream_send_recv_stress() { + #[test] + fn stream_send_recv_stress() { for _ in range(0, stress_factor()) { let (tx, rx) = channel(); @@ -1419,69 +1406,73 @@ mod test { fn send(tx: Sender>, i: int) { if i == 10 { return } - spawn(move|| { - tx.send(box i); + Thread::spawn(move|| { + tx.send(box i).unwrap(); send(tx, i + 1); - }); + }).detach(); } fn recv(rx: Receiver>, i: int) { if i == 10 { return } - spawn(move|| { - assert!(rx.recv() == box i); + Thread::spawn(move|| { + assert!(rx.recv().unwrap() == box i); recv(rx, i + 1); - }); + }).detach(); } } - } } + } - test! { fn recv_a_lot() { + #[test] + fn recv_a_lot() { // Regression test that we don't run out of stack in scheduler context let (tx, rx) = channel(); - for _ in range(0i, 10000) { tx.send(()); } - for _ in range(0i, 10000) { rx.recv(); } - } } + for _ in range(0i, 10000) { tx.send(()).unwrap(); } + for _ in range(0i, 10000) { rx.recv().unwrap(); } + } - test! { fn shared_chan_stress() { + #[test] + fn shared_chan_stress() { let (tx, rx) = channel(); let total = stress_factor() + 100; for _ in range(0, total) { let tx = tx.clone(); - spawn(move|| { - tx.send(()); - }); + Thread::spawn(move|| { + tx.send(()).unwrap(); + }).detach(); } for _ in range(0, total) { - rx.recv(); + rx.recv().unwrap(); } - } } + } - test! { fn test_nested_recv_iter() { + #[test] + fn test_nested_recv_iter() { let (tx, rx) = channel::(); let (total_tx, total_rx) = channel::(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut acc = 0; for x in rx.iter() { acc += x; } - total_tx.send(acc); + total_tx.send(acc).unwrap(); }); - tx.send(3); - tx.send(1); - tx.send(2); + tx.send(3).unwrap(); + tx.send(1).unwrap(); + tx.send(2).unwrap(); drop(tx); - assert_eq!(total_rx.recv(), 6); - } } + assert_eq!(total_rx.recv().unwrap(), 6); + } - test! { fn test_recv_iter_break() { + #[test] + fn test_recv_iter_break() { let (tx, rx) = channel::(); let (count_tx, count_rx) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut count = 0; for x in rx.iter() { if count >= 3 { @@ -1490,49 +1481,51 @@ mod test { count += x; } } - count_tx.send(count); + count_tx.send(count).unwrap(); }); - tx.send(2); - tx.send(2); - tx.send(2); - let _ = tx.send_opt(2); + tx.send(2).unwrap(); + tx.send(2).unwrap(); + tx.send(2).unwrap(); + let _ = tx.send(2); drop(tx); - assert_eq!(count_rx.recv(), 4); - } } + assert_eq!(count_rx.recv().unwrap(), 4); + } - test! { fn try_recv_states() { + #[test] + fn try_recv_states() { let (tx1, rx1) = channel::(); let (tx2, rx2) = channel::<()>(); let (tx3, rx3) = channel::<()>(); - spawn(move|| { - rx2.recv(); - tx1.send(1); - tx3.send(()); - rx2.recv(); + let _t = Thread::spawn(move|| { + rx2.recv().unwrap(); + tx1.send(1).unwrap(); + tx3.send(()).unwrap(); + rx2.recv().unwrap(); drop(tx1); - tx3.send(()); + tx3.send(()).unwrap(); }); - assert_eq!(rx1.try_recv(), Err(Empty)); - tx2.send(()); - rx3.recv(); + assert_eq!(rx1.try_recv(), Err(TryRecvError::Empty)); + tx2.send(()).unwrap(); + rx3.recv().unwrap(); assert_eq!(rx1.try_recv(), Ok(1)); - assert_eq!(rx1.try_recv(), Err(Empty)); - tx2.send(()); - rx3.recv(); - assert_eq!(rx1.try_recv(), Err(Disconnected)); - } } + assert_eq!(rx1.try_recv(), Err(TryRecvError::Empty)); + tx2.send(()).unwrap(); + rx3.recv().unwrap(); + assert_eq!(rx1.try_recv(), Err(TryRecvError::Disconnected)); + } // This bug used to end up in a livelock inside of the Receiver destructor // because the internal state of the Shared packet was corrupted - test! { fn destroy_upgraded_shared_port_when_sender_still_active() { + #[test] + fn destroy_upgraded_shared_port_when_sender_still_active() { let (tx, rx) = channel(); let (tx2, rx2) = channel(); - spawn(move|| { - rx.recv(); // wait on a oneshot + let _t = Thread::spawn(move|| { + rx.recv().unwrap(); // wait on a oneshot drop(rx); // destroy a shared - tx2.send(()); + tx2.send(()).unwrap(); }); // make sure the other task has gone to sleep for _ in range(0u, 5000) { Thread::yield_now(); } @@ -1540,303 +1533,334 @@ mod test { // upgrade to a shared chan and send a message let t = tx.clone(); drop(tx); - t.send(()); + t.send(()).unwrap(); // wait for the child task to exit before we exit - rx2.recv(); - }} + rx2.recv().unwrap(); + } } #[cfg(test)] mod sync_tests { - use prelude::*; + use prelude::v1::*; + use os; + use thread::Thread; + use super::*; pub fn stress_factor() -> uint { match os::getenv("RUST_TEST_STRESS") { - Some(val) => from_str::(val.as_slice()).unwrap(), + Some(val) => val.parse().unwrap(), None => 1, } } - test! { fn smoke() { + #[test] + fn smoke() { let (tx, rx) = sync_channel::(1); - tx.send(1); - assert_eq!(rx.recv(), 1); - } } + tx.send(1).unwrap(); + assert_eq!(rx.recv().unwrap(), 1); + } - test! { fn drop_full() { + #[test] + fn drop_full() { let (tx, _rx) = sync_channel(1); - tx.send(box 1i); - } } + tx.send(box 1i).unwrap(); + } - test! { fn smoke_shared() { + #[test] + fn smoke_shared() { let (tx, rx) = sync_channel::(1); - tx.send(1); - assert_eq!(rx.recv(), 1); + tx.send(1).unwrap(); + assert_eq!(rx.recv().unwrap(), 1); let tx = tx.clone(); - tx.send(1); - assert_eq!(rx.recv(), 1); - } } + tx.send(1).unwrap(); + assert_eq!(rx.recv().unwrap(), 1); + } - test! { fn smoke_threads() { + #[test] + fn smoke_threads() { let (tx, rx) = sync_channel::(0); - spawn(move|| { - tx.send(1); + let _t = Thread::spawn(move|| { + tx.send(1).unwrap(); }); - assert_eq!(rx.recv(), 1); - } } + assert_eq!(rx.recv().unwrap(), 1); + } - test! { fn smoke_port_gone() { + #[test] + fn smoke_port_gone() { let (tx, rx) = sync_channel::(0); drop(rx); - tx.send(1); - } #[should_fail] } + assert!(tx.send(1).is_err()); + } - test! { fn smoke_shared_port_gone2() { + #[test] + fn smoke_shared_port_gone2() { let (tx, rx) = sync_channel::(0); drop(rx); let tx2 = tx.clone(); drop(tx); - tx2.send(1); - } #[should_fail] } + assert!(tx2.send(1).is_err()); + } - test! { fn port_gone_concurrent() { + #[test] + fn port_gone_concurrent() { let (tx, rx) = sync_channel::(0); - spawn(move|| { - rx.recv(); + let _t = Thread::spawn(move|| { + rx.recv().unwrap(); }); - loop { tx.send(1) } - } #[should_fail] } + while tx.send(1).is_ok() {} + } - test! { fn port_gone_concurrent_shared() { + #[test] + fn port_gone_concurrent_shared() { let (tx, rx) = sync_channel::(0); let tx2 = tx.clone(); - spawn(move|| { - rx.recv(); + let _t = Thread::spawn(move|| { + rx.recv().unwrap(); }); - loop { - tx.send(1); - tx2.send(1); - } - } #[should_fail] } + while tx.send(1).is_ok() && tx2.send(1).is_ok() {} + } - test! { fn smoke_chan_gone() { + #[test] + fn smoke_chan_gone() { let (tx, rx) = sync_channel::(0); drop(tx); - rx.recv(); - } #[should_fail] } + assert!(rx.recv().is_err()); + } - test! { fn smoke_chan_gone_shared() { + #[test] + fn smoke_chan_gone_shared() { let (tx, rx) = sync_channel::<()>(0); let tx2 = tx.clone(); drop(tx); drop(tx2); - rx.recv(); - } #[should_fail] } + assert!(rx.recv().is_err()); + } - test! { fn chan_gone_concurrent() { + #[test] + fn chan_gone_concurrent() { let (tx, rx) = sync_channel::(0); - spawn(move|| { - tx.send(1); - tx.send(1); - }); - loop { rx.recv(); } - } #[should_fail] } + Thread::spawn(move|| { + tx.send(1).unwrap(); + tx.send(1).unwrap(); + }).detach(); + while rx.recv().is_ok() {} + } - test! { fn stress() { + #[test] + fn stress() { let (tx, rx) = sync_channel::(0); - spawn(move|| { - for _ in range(0u, 10000) { tx.send(1); } - }); + Thread::spawn(move|| { + for _ in range(0u, 10000) { tx.send(1).unwrap(); } + }).detach(); for _ in range(0u, 10000) { - assert_eq!(rx.recv(), 1); + assert_eq!(rx.recv().unwrap(), 1); } - } } + } - test! { fn stress_shared() { + #[test] + fn stress_shared() { static AMT: uint = 1000; static NTHREADS: uint = 8; let (tx, rx) = sync_channel::(0); let (dtx, drx) = sync_channel::<()>(0); - spawn(move|| { + Thread::spawn(move|| { for _ in range(0, AMT * NTHREADS) { - assert_eq!(rx.recv(), 1); + assert_eq!(rx.recv().unwrap(), 1); } match rx.try_recv() { Ok(..) => panic!(), _ => {} } - dtx.send(()); - }); + dtx.send(()).unwrap(); + }).detach(); for _ in range(0, NTHREADS) { let tx = tx.clone(); - spawn(move|| { - for _ in range(0, AMT) { tx.send(1); } - }); + Thread::spawn(move|| { + for _ in range(0, AMT) { tx.send(1).unwrap(); } + }).detach(); } drop(tx); - drx.recv(); - } } + drx.recv().unwrap(); + } - test! { fn oneshot_single_thread_close_port_first() { + #[test] + fn oneshot_single_thread_close_port_first() { // Simple test of closing without sending let (_tx, rx) = sync_channel::(0); drop(rx); - } } + } - test! { fn oneshot_single_thread_close_chan_first() { + #[test] + fn oneshot_single_thread_close_chan_first() { // Simple test of closing without sending let (tx, _rx) = sync_channel::(0); drop(tx); - } } + } - test! { fn oneshot_single_thread_send_port_close() { + #[test] + fn oneshot_single_thread_send_port_close() { // Testing that the sender cleans up the payload if receiver is closed let (tx, rx) = sync_channel::>(0); drop(rx); - tx.send(box 0); - } #[should_fail] } + assert!(tx.send(box 0).is_err()); + } - test! { fn oneshot_single_thread_recv_chan_close() { + #[test] + fn oneshot_single_thread_recv_chan_close() { // Receiving on a closed chan will panic let res = Thread::spawn(move|| { let (tx, rx) = sync_channel::(0); drop(tx); - rx.recv(); + rx.recv().unwrap(); }).join(); // What is our res? assert!(res.is_err()); - } } + } - test! { fn oneshot_single_thread_send_then_recv() { + #[test] + fn oneshot_single_thread_send_then_recv() { let (tx, rx) = sync_channel::>(1); - tx.send(box 10); - assert!(rx.recv() == box 10); - } } + tx.send(box 10).unwrap(); + assert!(rx.recv().unwrap() == box 10); + } - test! { fn oneshot_single_thread_try_send_open() { + #[test] + fn oneshot_single_thread_try_send_open() { let (tx, rx) = sync_channel::(1); assert_eq!(tx.try_send(10), Ok(())); - assert!(rx.recv() == 10); - } } + assert!(rx.recv().unwrap() == 10); + } - test! { fn oneshot_single_thread_try_send_closed() { + #[test] + fn oneshot_single_thread_try_send_closed() { let (tx, rx) = sync_channel::(0); drop(rx); - assert_eq!(tx.try_send(10), Err(RecvDisconnected(10))); - } } + assert_eq!(tx.try_send(10), Err(TrySendError::Disconnected(10))); + } - test! { fn oneshot_single_thread_try_send_closed2() { + #[test] + fn oneshot_single_thread_try_send_closed2() { let (tx, _rx) = sync_channel::(0); - assert_eq!(tx.try_send(10), Err(Full(10))); - } } + assert_eq!(tx.try_send(10), Err(TrySendError::Full(10))); + } - test! { fn oneshot_single_thread_try_recv_open() { + #[test] + fn oneshot_single_thread_try_recv_open() { let (tx, rx) = sync_channel::(1); - tx.send(10); - assert!(rx.recv_opt() == Ok(10)); - } } + tx.send(10).unwrap(); + assert!(rx.recv() == Ok(10)); + } - test! { fn oneshot_single_thread_try_recv_closed() { + #[test] + fn oneshot_single_thread_try_recv_closed() { let (tx, rx) = sync_channel::(0); drop(tx); - assert!(rx.recv_opt() == Err(())); - } } + assert!(rx.recv().is_err()); + } - test! { fn oneshot_single_thread_peek_data() { + #[test] + fn oneshot_single_thread_peek_data() { let (tx, rx) = sync_channel::(1); - assert_eq!(rx.try_recv(), Err(Empty)); - tx.send(10); + assert_eq!(rx.try_recv(), Err(TryRecvError::Empty)); + tx.send(10).unwrap(); assert_eq!(rx.try_recv(), Ok(10)); - } } + } - test! { fn oneshot_single_thread_peek_close() { + #[test] + fn oneshot_single_thread_peek_close() { let (tx, rx) = sync_channel::(0); drop(tx); - assert_eq!(rx.try_recv(), Err(Disconnected)); - assert_eq!(rx.try_recv(), Err(Disconnected)); - } } + assert_eq!(rx.try_recv(), Err(TryRecvError::Disconnected)); + assert_eq!(rx.try_recv(), Err(TryRecvError::Disconnected)); + } - test! { fn oneshot_single_thread_peek_open() { + #[test] + fn oneshot_single_thread_peek_open() { let (_tx, rx) = sync_channel::(0); - assert_eq!(rx.try_recv(), Err(Empty)); - } } + assert_eq!(rx.try_recv(), Err(TryRecvError::Empty)); + } - test! { fn oneshot_multi_task_recv_then_send() { + #[test] + fn oneshot_multi_task_recv_then_send() { let (tx, rx) = sync_channel::>(0); - spawn(move|| { - assert!(rx.recv() == box 10); + let _t = Thread::spawn(move|| { + assert!(rx.recv().unwrap() == box 10); }); - tx.send(box 10); - } } + tx.send(box 10).unwrap(); + } - test! { fn oneshot_multi_task_recv_then_close() { + #[test] + fn oneshot_multi_task_recv_then_close() { let (tx, rx) = sync_channel::>(0); - spawn(move|| { + let _t = Thread::spawn(move|| { drop(tx); }); let res = Thread::spawn(move|| { - assert!(rx.recv() == box 10); + assert!(rx.recv().unwrap() == box 10); }).join(); assert!(res.is_err()); - } } + } - test! { fn oneshot_multi_thread_close_stress() { + #[test] + fn oneshot_multi_thread_close_stress() { for _ in range(0, stress_factor()) { let (tx, rx) = sync_channel::(0); - spawn(move|| { + let _t = Thread::spawn(move|| { drop(rx); }); drop(tx); } - } } + } - test! { fn oneshot_multi_thread_send_close_stress() { + #[test] + fn oneshot_multi_thread_send_close_stress() { for _ in range(0, stress_factor()) { let (tx, rx) = sync_channel::(0); - spawn(move|| { + let _t = Thread::spawn(move|| { drop(rx); }); let _ = Thread::spawn(move || { - tx.send(1); + tx.send(1).unwrap(); }).join(); } - } } + } - test! { fn oneshot_multi_thread_recv_close_stress() { + #[test] + fn oneshot_multi_thread_recv_close_stress() { for _ in range(0, stress_factor()) { let (tx, rx) = sync_channel::(0); - spawn(move|| { + let _t = Thread::spawn(move|| { let res = Thread::spawn(move|| { - rx.recv(); + rx.recv().unwrap(); }).join(); assert!(res.is_err()); }); - spawn(move|| { - spawn(move|| { + let _t = Thread::spawn(move|| { + Thread::spawn(move|| { drop(tx); - }); + }).detach(); }); } - } } + } - test! { fn oneshot_multi_thread_send_recv_stress() { + #[test] + fn oneshot_multi_thread_send_recv_stress() { for _ in range(0, stress_factor()) { let (tx, rx) = sync_channel::>(0); - spawn(move|| { - tx.send(box 10i); - }); - spawn(move|| { - assert!(rx.recv() == box 10i); + let _t = Thread::spawn(move|| { + tx.send(box 10i).unwrap(); }); + assert!(rx.recv().unwrap() == box 10i); } - } } + } - test! { fn stream_send_recv_stress() { + #[test] + fn stream_send_recv_stress() { for _ in range(0, stress_factor()) { let (tx, rx) = sync_channel::>(0); @@ -1846,69 +1870,73 @@ mod sync_tests { fn send(tx: SyncSender>, i: int) { if i == 10 { return } - spawn(move|| { - tx.send(box i); + Thread::spawn(move|| { + tx.send(box i).unwrap(); send(tx, i + 1); - }); + }).detach(); } fn recv(rx: Receiver>, i: int) { if i == 10 { return } - spawn(move|| { - assert!(rx.recv() == box i); + Thread::spawn(move|| { + assert!(rx.recv().unwrap() == box i); recv(rx, i + 1); - }); + }).detach(); } } - } } + } - test! { fn recv_a_lot() { + #[test] + fn recv_a_lot() { // Regression test that we don't run out of stack in scheduler context let (tx, rx) = sync_channel(10000); - for _ in range(0u, 10000) { tx.send(()); } - for _ in range(0u, 10000) { rx.recv(); } - } } + for _ in range(0u, 10000) { tx.send(()).unwrap(); } + for _ in range(0u, 10000) { rx.recv().unwrap(); } + } - test! { fn shared_chan_stress() { + #[test] + fn shared_chan_stress() { let (tx, rx) = sync_channel(0); let total = stress_factor() + 100; for _ in range(0, total) { let tx = tx.clone(); - spawn(move|| { - tx.send(()); - }); + Thread::spawn(move|| { + tx.send(()).unwrap(); + }).detach(); } for _ in range(0, total) { - rx.recv(); + rx.recv().unwrap(); } - } } + } - test! { fn test_nested_recv_iter() { + #[test] + fn test_nested_recv_iter() { let (tx, rx) = sync_channel::(0); let (total_tx, total_rx) = sync_channel::(0); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut acc = 0; for x in rx.iter() { acc += x; } - total_tx.send(acc); + total_tx.send(acc).unwrap(); }); - tx.send(3); - tx.send(1); - tx.send(2); + tx.send(3).unwrap(); + tx.send(1).unwrap(); + tx.send(2).unwrap(); drop(tx); - assert_eq!(total_rx.recv(), 6); - } } + assert_eq!(total_rx.recv().unwrap(), 6); + } - test! { fn test_recv_iter_break() { + #[test] + fn test_recv_iter_break() { let (tx, rx) = sync_channel::(0); let (count_tx, count_rx) = sync_channel(0); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut count = 0; for x in rx.iter() { if count >= 3 { @@ -1917,49 +1945,51 @@ mod sync_tests { count += x; } } - count_tx.send(count); + count_tx.send(count).unwrap(); }); - tx.send(2); - tx.send(2); - tx.send(2); + tx.send(2).unwrap(); + tx.send(2).unwrap(); + tx.send(2).unwrap(); let _ = tx.try_send(2); drop(tx); - assert_eq!(count_rx.recv(), 4); - } } + assert_eq!(count_rx.recv().unwrap(), 4); + } - test! { fn try_recv_states() { + #[test] + fn try_recv_states() { let (tx1, rx1) = sync_channel::(1); let (tx2, rx2) = sync_channel::<()>(1); let (tx3, rx3) = sync_channel::<()>(1); - spawn(move|| { - rx2.recv(); - tx1.send(1); - tx3.send(()); - rx2.recv(); + let _t = Thread::spawn(move|| { + rx2.recv().unwrap(); + tx1.send(1).unwrap(); + tx3.send(()).unwrap(); + rx2.recv().unwrap(); drop(tx1); - tx3.send(()); + tx3.send(()).unwrap(); }); - assert_eq!(rx1.try_recv(), Err(Empty)); - tx2.send(()); - rx3.recv(); + assert_eq!(rx1.try_recv(), Err(TryRecvError::Empty)); + tx2.send(()).unwrap(); + rx3.recv().unwrap(); assert_eq!(rx1.try_recv(), Ok(1)); - assert_eq!(rx1.try_recv(), Err(Empty)); - tx2.send(()); - rx3.recv(); - assert_eq!(rx1.try_recv(), Err(Disconnected)); - } } + assert_eq!(rx1.try_recv(), Err(TryRecvError::Empty)); + tx2.send(()).unwrap(); + rx3.recv().unwrap(); + assert_eq!(rx1.try_recv(), Err(TryRecvError::Disconnected)); + } // This bug used to end up in a livelock inside of the Receiver destructor // because the internal state of the Shared packet was corrupted - test! { fn destroy_upgraded_shared_port_when_sender_still_active() { + #[test] + fn destroy_upgraded_shared_port_when_sender_still_active() { let (tx, rx) = sync_channel::<()>(0); let (tx2, rx2) = sync_channel::<()>(0); - spawn(move|| { - rx.recv(); // wait on a oneshot + let _t = Thread::spawn(move|| { + rx.recv().unwrap(); // wait on a oneshot drop(rx); // destroy a shared - tx2.send(()); + tx2.send(()).unwrap(); }); // make sure the other task has gone to sleep for _ in range(0u, 5000) { Thread::yield_now(); } @@ -1967,92 +1997,91 @@ mod sync_tests { // upgrade to a shared chan and send a message let t = tx.clone(); drop(tx); - t.send(()); + t.send(()).unwrap(); // wait for the child task to exit before we exit - rx2.recv(); - } } + rx2.recv().unwrap(); + } - test! { fn send_opt1() { + #[test] + fn send1() { let (tx, rx) = sync_channel::(0); - spawn(move|| { rx.recv(); }); - assert_eq!(tx.send_opt(1), Ok(())); - } } + let _t = Thread::spawn(move|| { rx.recv().unwrap(); }); + assert_eq!(tx.send(1), Ok(())); + } - test! { fn send_opt2() { + #[test] + fn send2() { let (tx, rx) = sync_channel::(0); - spawn(move|| { drop(rx); }); - assert_eq!(tx.send_opt(1), Err(1)); - } } + let _t = Thread::spawn(move|| { drop(rx); }); + assert!(tx.send(1).is_err()); + } - test! { fn send_opt3() { + #[test] + fn send3() { let (tx, rx) = sync_channel::(1); - assert_eq!(tx.send_opt(1), Ok(())); - spawn(move|| { drop(rx); }); - assert_eq!(tx.send_opt(1), Err(1)); - } } + assert_eq!(tx.send(1), Ok(())); + let _t =Thread::spawn(move|| { drop(rx); }); + assert!(tx.send(1).is_err()); + } - test! { fn send_opt4() { + #[test] + fn send4() { let (tx, rx) = sync_channel::(0); let tx2 = tx.clone(); let (done, donerx) = channel(); let done2 = done.clone(); - spawn(move|| { - assert_eq!(tx.send_opt(1), Err(1)); - done.send(()); + let _t = Thread::spawn(move|| { + assert!(tx.send(1).is_err()); + done.send(()).unwrap(); }); - spawn(move|| { - assert_eq!(tx2.send_opt(2), Err(2)); - done2.send(()); + let _t = Thread::spawn(move|| { + assert!(tx2.send(2).is_err()); + done2.send(()).unwrap(); }); drop(rx); - donerx.recv(); - donerx.recv(); - } } + donerx.recv().unwrap(); + donerx.recv().unwrap(); + } - test! { fn try_send1() { + #[test] + fn try_send1() { let (tx, _rx) = sync_channel::(0); - assert_eq!(tx.try_send(1), Err(Full(1))); - } } + assert_eq!(tx.try_send(1), Err(TrySendError::Full(1))); + } - test! { fn try_send2() { + #[test] + fn try_send2() { let (tx, _rx) = sync_channel::(1); assert_eq!(tx.try_send(1), Ok(())); - assert_eq!(tx.try_send(1), Err(Full(1))); - } } + assert_eq!(tx.try_send(1), Err(TrySendError::Full(1))); + } - test! { fn try_send3() { + #[test] + fn try_send3() { let (tx, rx) = sync_channel::(1); assert_eq!(tx.try_send(1), Ok(())); drop(rx); - assert_eq!(tx.try_send(1), Err(RecvDisconnected(1))); - } } - - test! { fn try_send4() { - let (tx, rx) = sync_channel::(0); - spawn(move|| { - for _ in range(0u, 1000) { Thread::yield_now(); } - assert_eq!(tx.try_send(1), Ok(())); - }); - assert_eq!(rx.recv(), 1); - } #[ignore(reason = "flaky on libnative")] } + assert_eq!(tx.try_send(1), Err(TrySendError::Disconnected(1))); + } - test! { fn issue_15761() { + #[test] + fn issue_15761() { fn repro() { let (tx1, rx1) = sync_channel::<()>(3); let (tx2, rx2) = sync_channel::<()>(3); - spawn(move|| { - rx1.recv(); + let _t = Thread::spawn(move|| { + rx1.recv().unwrap(); tx2.try_send(()).unwrap(); }); tx1.try_send(()).unwrap(); - rx2.recv(); + rx2.recv().unwrap(); } for _ in range(0u, 100) { repro() } - } } + } } diff --git a/src/libstd/sync/rwlock.rs b/src/libstd/sync/rwlock.rs index e21aa3ef7e9..4afd5bb63f4 100644 --- a/src/libstd/sync/rwlock.rs +++ b/src/libstd/sync/rwlock.rs @@ -41,7 +41,7 @@ use sys_common::rwlock as sys; /// ``` /// use std::sync::RwLock; /// -/// let lock = RwLock::new(5); +/// let lock = RwLock::new(5i); /// /// // many reader locks can be held at once /// { -- cgit 1.4.1-3-g733a5