diff --git a/src/compiletest/compiletest.rs b/src/compiletest/compiletest.rs index bdbfbfd7c89d6..ad1264828cb96 100644 --- a/src/compiletest/compiletest.rs +++ b/src/compiletest/compiletest.rs @@ -22,8 +22,8 @@ extern crate regex; use std::os; use std::io; use std::io::fs; -use std::str::FromStr; -use std::thunk::{Thunk}; +use std::str::{FromStr, from_str}; +use std::thunk::Thunk; use getopts::{optopt, optflag, reqopt}; use common::Config; use common::{Pretty, DebugInfoGdb, DebugInfoLldb, Codegen}; diff --git a/src/doc/guide-ffi.md b/src/doc/guide-ffi.md index 3a87271ede7d8..b8808eaf57d93 100644 --- a/src/doc/guide-ffi.md +++ b/src/doc/guide-ffi.md @@ -450,6 +450,8 @@ them. ~~~no_run extern crate libc; + +use std::c_str::ToCStr; use std::ptr; #[link(name = "readline")] diff --git a/src/doc/guide.md b/src/doc/guide.md index 22cbd18a86520..26a39b5140550 100644 --- a/src/doc/guide.md +++ b/src/doc/guide.md @@ -1100,13 +1100,21 @@ enum Ordering { ``` An `Ordering` can only be _one_ of `Less`, `Equal`, or `Greater` at any given -time. Here's an example: +time. + +Because `Ordering` is provided by the standard library, we can use the `use` +keyword to use it in our code. We'll learn more about `use` later, but it's +used to bring names into scope. + +Here's an example of how to use `Ordering`: ```{rust} +use std::cmp::Ordering; + fn cmp(a: int, b: int) -> Ordering { - if a < b { Less } - else if a > b { Greater } - else { Equal } + if a < b { Ordering::Less } + else if a > b { Ordering::Greater } + else { Ordering::Equal } } fn main() { @@ -1115,28 +1123,35 @@ fn main() { let ordering = cmp(x, y); // ordering: Ordering - if ordering == Less { + if ordering == Ordering::Less { println!("less"); - } else if ordering == Greater { + } else if ordering == Ordering::Greater { println!("greater"); - } else if ordering == Equal { + } else if ordering == Ordering::Equal { println!("equal"); } } ``` -`cmp` is a function that compares two things, and returns an `Ordering`. We -return either `Less`, `Greater`, or `Equal`, depending on if the two values -are greater, less, or equal. +There's a symbol here we haven't seen before: the double colon (`::`). +This is used to indicate a namesapce. In this case, `Ordering` lives in +the `cmp` submodule of the `std` module. We'll talk more about modules +later in the guide. For now, all you need to know is that you can `use` +things from the standard library if you need them. -The `ordering` variable has the type `Ordering`, and so contains one of the -three values. We can then do a bunch of `if`/`else` comparisons to check -which one it is. +Okay, let's talk about the actual code in the example. `cmp` is a function that +compares two things, and returns an `Ordering`. We return either +`Ordering::Less`, `Ordering::Greater`, or `Ordering::Equal`, depending on if +the two values are greater, less, or equal. Note that each variant of the +`enum` is namespaced under the `enum` itself: it's `Ordering::Greater` not +`Greater`. -However, repeated `if`/`else` comparisons get quite tedious. Rust has a feature -that not only makes them nicer to read, but also makes sure that you never -miss a case. Before we get to that, though, let's talk about another kind of -enum: one with values. +The `ordering` variable has the type `Ordering`, and so contains one of the +three values. We can then do a bunch of `if`/`else` comparisons to check which +one it is. However, repeated `if`/`else` comparisons get quite tedious. Rust +has a feature that not only makes them nicer to read, but also makes sure that +you never miss a case. Before we get to that, though, let's talk about another +kind of enum: one with values. This enum has two variants, one of which has a value: @@ -1169,18 +1184,19 @@ enum StringResult { ErrorReason(String), } ``` -Where a `StringResult` is either a `StringOK`, with the result of a computation, or an -`ErrorReason` with a `String` explaining what caused the computation to fail. These kinds of -`enum`s are actually very useful and are even part of the standard library. +Where a `StringResult` is either a `StringResult::StringOK`, with the result of +a computation, or an `StringResult::ErrorReason` with a `String` explaining +what caused the computation to fail. These kinds of `enum`s are actually very +useful and are even part of the standard library. -Enum variants are namespaced under the enum names. For example, here is an example of using -our `StringResult`: +Here is an example of using our `StringResult`: ```rust -# enum StringResult { -# StringOK(String), -# ErrorReason(String), -# } +enum StringResult { + StringOK(String), + ErrorReason(String), +} + fn respond(greeting: &str) -> StringResult { if greeting == "Hello" { StringResult::StringOK("Good morning!".to_string()) @@ -1190,10 +1206,7 @@ fn respond(greeting: &str) -> StringResult { } ``` -Notice that we need both the enum name and the variant name: `StringResult::StringOK`, but -we didn't need to with `Ordering` – we just said `Greater` rather than `Ordering::Greater`. -There's a reason: the Rust prelude imports the variants of `Ordering` as well as the enum -itself. We can use the `use` keyword to do something similar with `StringResult`: +That's a lot of typing! We can use the `use` keyword to make it shorter: ```rust use StringResult::StringOK; @@ -1215,12 +1228,11 @@ fn respond(greeting: &str) -> StringResult { } ``` -We'll learn more about `use` later, but it's used to bring names into scope. `use` declarations -must come before anything else, which looks a little strange in this example, since we `use` -the variants before we define them. Anyway, in the body of `respond`, we can just say `StringOK` -now, rather than the full `StringResult::StringOK`. Importing variants can be convenient, but can -also cause name conflicts, so do this with caution. It's considered good style to rarely import -variants for this reason. +`use` declarations must come before anything else, which looks a little strange in this example, +since we `use` the variants before we define them. Anyway, in the body of `respond`, we can just +say `StringOK` now, rather than the full `StringResult::StringOK`. Importing variants can be +convenient, but can also cause name conflicts, so do this with caution. It's considered good style +to rarely import variants for this reason. As you can see, `enum`s with values are quite a powerful tool for data representation, and can be even more useful when they're generic across types. Before we get to generics, @@ -1274,10 +1286,12 @@ for every possible value of `x`, and so our program will compile successfully. section on enums? ```{rust} +use std::cmp::Ordering; + fn cmp(a: int, b: int) -> Ordering { - if a < b { Less } - else if a > b { Greater } - else { Equal } + if a < b { Ordering::Less } + else if a > b { Ordering::Greater } + else { Ordering::Equal } } fn main() { @@ -1286,11 +1300,11 @@ fn main() { let ordering = cmp(x, y); - if ordering == Less { + if ordering == Ordering::Less { println!("less"); - } else if ordering == Greater { + } else if ordering == Ordering::Greater { println!("greater"); - } else if ordering == Equal { + } else if ordering == Ordering::Equal { println!("equal"); } } @@ -1299,10 +1313,12 @@ fn main() { We can re-write this as a `match`: ```{rust} +use std::cmp::Ordering; + fn cmp(a: int, b: int) -> Ordering { - if a < b { Less } - else if a > b { Greater } - else { Equal } + if a < b { Ordering::Less } + else if a > b { Ordering::Greater } + else { Ordering::Equal } } fn main() { @@ -1310,9 +1326,9 @@ fn main() { let y = 10i; match cmp(x, y) { - Less => println!("less"), - Greater => println!("greater"), - Equal => println!("equal"), + Ordering::Less => println!("less"), + Ordering::Greater => println!("greater"), + Ordering::Equal => println!("equal"), } } ``` @@ -1359,10 +1375,12 @@ side of a `let` binding or directly where an expression is used. We could also implement the previous line like this: ```{rust} +use std::cmp::Ordering; + fn cmp(a: int, b: int) -> Ordering { - if a < b { Less } - else if a > b { Greater } - else { Equal } + if a < b { Ordering::Less } + else if a > b { Ordering::Greater } + else { Ordering::Equal } } fn main() { @@ -1370,9 +1388,9 @@ fn main() { let y = 10i; println!("{}", match cmp(x, y) { - Less => "less", - Greater => "greater", - Equal => "equal", + Ordering::Less => "less", + Ordering::Greater => "greater", + Ordering::Equal => "equal", }); } ``` @@ -2137,6 +2155,7 @@ guess to the secret number: ```{rust,ignore} use std::io; use std::rand; +use std::cmp::Ordering; fn main() { println!("Guess the number!"); @@ -2155,16 +2174,16 @@ fn main() { println!("You guessed: {}", input); match cmp(input, secret_number) { - Less => println!("Too small!"), - Greater => println!("Too big!"), - Equal => println!("You win!"), + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => println!("You win!"), } } fn cmp(a: int, b: int) -> Ordering { - if a < b { Less } - else if a > b { Greater } - else { Equal } + if a < b { Ordering::Less } + else if a > b { Ordering::Greater } + else { Ordering::Equal } } ``` @@ -2191,6 +2210,7 @@ we wrote the `cmp` function! Let's change it to take `uint`s: ```{rust,ignore} use std::io; use std::rand; +use std::cmp::Ordering; fn main() { println!("Guess the number!"); @@ -2209,16 +2229,16 @@ fn main() { println!("You guessed: {}", input); match cmp(input, secret_number) { - Less => println!("Too small!"), - Greater => println!("Too big!"), - Equal => println!("You win!"), + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => println!("You win!"), } } fn cmp(a: uint, b: uint) -> Ordering { - if a < b { Less } - else if a > b { Greater } - else { Equal } + if a < b { Ordering::Less } + else if a > b { Ordering::Greater } + else { Ordering::Equal } } ``` @@ -2288,6 +2308,8 @@ Anyway, with us now converting our input to a number, our code looks like this: ```{rust,ignore} use std::io; use std::rand; +use std::str::from_str; +use std::cmp::Ordering; fn main() { println!("Guess the number!"); @@ -2306,16 +2328,16 @@ fn main() { println!("You guessed: {}", input_num); match cmp(input_num, secret_number) { - Less => println!("Too small!"), - Greater => println!("Too big!"), - Equal => println!("You win!"), + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => println!("You win!"), } } fn cmp(a: uint, b: uint) -> Ordering { - if a < b { Less } - else if a > b { Greater } - else { Equal } + if a < b { Ordering::Less } + else if a > b { Ordering::Greater } + else { Ordering::Equal } } ``` @@ -2337,6 +2359,8 @@ to do that. Try this code: ```{rust,no_run} use std::io; use std::rand; +use std::str::from_str; +use std::cmp::Ordering; fn main() { println!("Guess the number!"); @@ -2364,16 +2388,16 @@ fn main() { println!("You guessed: {}", num); match cmp(num, secret_number) { - Less => println!("Too small!"), - Greater => println!("Too big!"), - Equal => println!("You win!"), + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => println!("You win!"), } } fn cmp(a: uint, b: uint) -> Ordering { - if a < b { Less } - else if a > b { Greater } - else { Equal } + if a < b { Ordering::Less } + else if a > b { Ordering::Greater } + else { Ordering::Equal } } ``` @@ -2403,6 +2427,8 @@ code looks like this: ```{rust,no_run} use std::io; use std::rand; +use std::str::from_str; +use std::cmp::Ordering; fn main() { println!("Guess the number!"); @@ -2430,16 +2456,16 @@ fn main() { println!("You guessed: {}", num); match cmp(num, secret_number) { - Less => println!("Too small!"), - Greater => println!("Too big!"), - Equal => println!("You win!"), + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => println!("You win!"), } } fn cmp(a: uint, b: uint) -> Ordering { - if a < b { Less } - else if a > b { Greater } - else { Equal } + if a < b { Ordering::Less } + else if a > b { Ordering::Greater } + else { Ordering::Equal } } ``` @@ -2476,6 +2502,8 @@ Let's add that in: ```{rust,no_run} use std::io; use std::rand; +use std::str::from_str; +use std::cmp::Ordering; fn main() { println!("Guess the number!"); @@ -2505,17 +2533,17 @@ fn main() { println!("You guessed: {}", num); match cmp(num, secret_number) { - Less => println!("Too small!"), - Greater => println!("Too big!"), - Equal => println!("You win!"), + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => println!("You win!"), } } } fn cmp(a: uint, b: uint) -> Ordering { - if a < b { Less } - else if a > b { Greater } - else { Equal } + if a < b { Ordering::Less } + else if a > b { Ordering::Greater } + else { Ordering::Equal } } ``` @@ -2551,6 +2579,8 @@ suboptimal to say the least. First, let's actually quit when you win the game: ```{rust,no_run} use std::io; use std::rand; +use std::str::from_str; +use std::cmp::Ordering; fn main() { println!("Guess the number!"); @@ -2580,9 +2610,9 @@ fn main() { println!("You guessed: {}", num); match cmp(num, secret_number) { - Less => println!("Too small!"), - Greater => println!("Too big!"), - Equal => { + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => { println!("You win!"); return; }, @@ -2591,9 +2621,9 @@ fn main() { } fn cmp(a: uint, b: uint) -> Ordering { - if a < b { Less } - else if a > b { Greater } - else { Equal } + if a < b { Ordering::Less } + else if a > b { Ordering::Greater } + else { Ordering::Equal } } ``` @@ -2606,6 +2636,8 @@ we don't want to quit, we just want to ignore it. Change that `return` to ```{rust,no_run} use std::io; use std::rand; +use std::str::from_str; +use std::cmp::Ordering; fn main() { println!("Guess the number!"); @@ -2635,9 +2667,9 @@ fn main() { println!("You guessed: {}", num); match cmp(num, secret_number) { - Less => println!("Too small!"), - Greater => println!("Too big!"), - Equal => { + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => { println!("You win!"); return; }, @@ -2646,9 +2678,9 @@ fn main() { } fn cmp(a: uint, b: uint) -> Ordering { - if a < b { Less } - else if a > b { Greater } - else { Equal } + if a < b { Ordering::Less } + else if a > b { Ordering::Greater } + else { Ordering::Equal } } ``` @@ -2684,6 +2716,8 @@ It was good for testing, but it kind of ruins the game. Here's our final source: ```{rust,no_run} use std::io; use std::rand; +use std::str::from_str; +use std::cmp::Ordering; fn main() { println!("Guess the number!"); @@ -2711,9 +2745,9 @@ fn main() { println!("You guessed: {}", num); match cmp(num, secret_number) { - Less => println!("Too small!"), - Greater => println!("Too big!"), - Equal => { + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => { println!("You win!"); return; }, @@ -2722,9 +2756,9 @@ fn main() { } fn cmp(a: uint, b: uint) -> Ordering { - if a < b { Less } - else if a > b { Greater } - else { Equal } + if a < b { Ordering::Less } + else if a > b { Ordering::Greater } + else { Ordering::Equal } } ``` diff --git a/src/doc/reference.md b/src/doc/reference.md index b71994c9836a1..e510685bb1869 100644 --- a/src/doc/reference.md +++ b/src/doc/reference.md @@ -3174,6 +3174,7 @@ then the expression completes. Some examples of call expressions: ``` +# use std::str::from_str; # fn add(x: int, y: int) -> int { 0 } let x: int = add(1, 2); diff --git a/src/etc/licenseck.py b/src/etc/licenseck.py index 7669df36b041d..9ac0acc38a73e 100644 --- a/src/etc/licenseck.py +++ b/src/etc/licenseck.py @@ -38,8 +38,8 @@ "rt/isaac/randport.cpp", # public domain "rt/isaac/rand.h", # public domain "rt/isaac/standard.h", # public domain - "libstd/comm/mpsc_queue.rs", # BSD - "libstd/comm/spsc_queue.rs", # BSD + "libstd/sync/mpsc/mpsc_queue.rs", # BSD + "libstd/sync/mpsc/spsc_queue.rs", # BSD "test/bench/shootout-binarytrees.rs", # BSD "test/bench/shootout-chameneos-redux.rs", # BSD "test/bench/shootout-fannkuch-redux.rs", # BSD diff --git a/src/liballoc/arc.rs b/src/liballoc/arc.rs index 3e235caab18ad..b8c7bc74132e4 100644 --- a/src/liballoc/arc.rs +++ b/src/liballoc/arc.rs @@ -592,7 +592,7 @@ impl Default for Arc { #[allow(experimental)] mod tests { use std::clone::Clone; - use std::comm::channel; + use std::sync::mpsc::channel; use std::mem::drop; use std::ops::Drop; use std::option::Option; @@ -628,11 +628,11 @@ mod tests { let (tx, rx) = channel(); task::spawn(move || { - let arc_v: Arc> = rx.recv(); + let arc_v: Arc> = rx.recv().unwrap(); assert_eq!((*arc_v)[3], 4); }); - tx.send(arc_v.clone()); + tx.send(arc_v.clone()).unwrap(); assert_eq!((*arc_v)[2], 3); assert_eq!((*arc_v)[4], 5); diff --git a/src/libcollections/binary_heap.rs b/src/libcollections/binary_heap.rs index a2f38bb667447..dfddf045fc8e4 100644 --- a/src/libcollections/binary_heap.rs +++ b/src/libcollections/binary_heap.rs @@ -26,6 +26,7 @@ //! [dir_graph]: http://en.wikipedia.org/wiki/Directed_graph //! //! ``` +//! use std::cmp::Ordering; //! use std::collections::BinaryHeap; //! use std::uint; //! @@ -151,6 +152,7 @@ use core::prelude::*; use core::default::Default; +use core::iter::FromIterator; use core::mem::{zeroed, replace, swap}; use core::ptr; diff --git a/src/libcollections/bit.rs b/src/libcollections/bit.rs index 430d7210bf69b..fe3267b6c35d9 100644 --- a/src/libcollections/bit.rs +++ b/src/libcollections/bit.rs @@ -82,16 +82,19 @@ use core::prelude::*; +use core::cmp::Ordering; use core::cmp; use core::default::Default; use core::fmt; -use core::iter::{Cloned, Chain, Enumerate, Repeat, Skip, Take}; -use core::iter; +use core::hash; +use core::iter::RandomAccessIterator; +use core::iter::{Chain, Enumerate, Repeat, Skip, Take, repeat, Cloned}; +use core::iter::{mod, FromIterator}; use core::num::Int; +use core::ops::Index; use core::slice::{Iter, IterMut}; use core::{u8, u32, uint}; -use core::hash; use Vec; type Blocks<'a> = Cloned>; @@ -2449,7 +2452,7 @@ mod tests { #[cfg(test)] mod bitv_bench { - use std::prelude::*; + use std::prelude::v1::*; use std::rand; use std::rand::Rng; use std::u32; @@ -2944,7 +2947,7 @@ mod bitv_set_test { #[cfg(test)] mod bitv_set_bench { - use std::prelude::*; + use std::prelude::v1::*; use std::rand; use std::rand::Rng; use std::u32; diff --git a/src/libcollections/btree/map.rs b/src/libcollections/btree/map.rs index 65c644da3d892..0030e612f6eb7 100644 --- a/src/libcollections/btree/map.rs +++ b/src/libcollections/btree/map.rs @@ -19,21 +19,23 @@ pub use self::Entry::*; use core::prelude::*; -use self::StackOp::*; -use super::node::{mod, Node, Found, GoDown}; -use super::node::{Traversal, MutTraversal, MoveTraversal}; -use super::node::TraversalItem::{mod, Elem, Edge}; -use super::node::ForceResult::{Leaf, Internal}; use core::borrow::BorrowFrom; -use std::hash::{Writer, Hash}; +use core::cmp::Ordering; use core::default::Default; -use core::{iter, fmt, mem}; use core::fmt::Show; -use core::iter::Map; +use core::hash::{Writer, Hash}; +use core::iter::{Map, FromIterator}; +use core::ops::{Index, IndexMut}; +use core::{iter, fmt, mem}; use ring_buf::RingBuf; use self::Continuation::{Continue, Finished}; +use self::StackOp::*; +use super::node::ForceResult::{Leaf, Internal}; +use super::node::TraversalItem::{mod, Elem, Edge}; +use super::node::{Traversal, MutTraversal, MoveTraversal}; +use super::node::{mod, Node, Found, GoDown}; // FIXME(conventions): implement bounded iterators @@ -495,6 +497,7 @@ mod stack { use core::prelude::*; use core::kinds::marker; use core::mem; + use core::ops::{Deref, DerefMut}; use super::BTreeMap; use super::super::node::{mod, Node, Fit, Split, Internal, Leaf}; use super::super::node::handle; diff --git a/src/libcollections/btree/node.rs b/src/libcollections/btree/node.rs index 2c3c546fdb7ff..828c1ae89b44e 100644 --- a/src/libcollections/btree/node.rs +++ b/src/libcollections/btree/node.rs @@ -18,9 +18,11 @@ pub use self::TraversalItem::*; use core::prelude::*; -use core::{slice, mem, ptr, cmp, num, raw}; -use core::iter::Zip; use core::borrow::BorrowFrom; +use core::cmp::Ordering::{Greater, Less, Equal}; +use core::iter::Zip; +use core::ops::{Deref, DerefMut}; +use core::{slice, mem, ptr, cmp, num, raw}; use alloc::heap; /// Represents the result of an Insertion: either the item fit, or the node had to split diff --git a/src/libcollections/btree/set.rs b/src/libcollections/btree/set.rs index 2935692ed1580..e24b203efed6d 100644 --- a/src/libcollections/btree/set.rs +++ b/src/libcollections/btree/set.rs @@ -13,13 +13,16 @@ use core::prelude::*; -use btree_map::{BTreeMap, Keys}; -use std::hash::Hash; use core::borrow::BorrowFrom; +use core::cmp::Ordering::{mod, Less, Greater, Equal}; use core::default::Default; -use core::fmt; -use core::iter::{Peekable, Map}; use core::fmt::Show; +use core::fmt; +use core::hash::Hash; +use core::iter::{Peekable, Map, FromIterator}; +use core::ops::{BitOr, BitAnd, BitXor, Sub}; + +use btree_map::{BTreeMap, Keys}; // FIXME(conventions): implement bounded iterators diff --git a/src/libcollections/dlist.rs b/src/libcollections/dlist.rs index f20b37cb60f26..53fefcc830542 100644 --- a/src/libcollections/dlist.rs +++ b/src/libcollections/dlist.rs @@ -22,12 +22,13 @@ use core::prelude::*; use alloc::boxed::Box; +use core::cmp::Ordering; use core::default::Default; use core::fmt; -use core::iter; +use core::hash::{Writer, Hash}; +use core::iter::{mod, FromIterator}; use core::mem; use core::ptr; -use std::hash::{Writer, Hash}; /// A doubly-linked list. pub struct DList { diff --git a/src/libcollections/enum_set.rs b/src/libcollections/enum_set.rs index fd04ce94247b7..fae3228b064da 100644 --- a/src/libcollections/enum_set.rs +++ b/src/libcollections/enum_set.rs @@ -16,6 +16,8 @@ use core::prelude::*; use core::fmt; use core::num::Int; +use core::iter::FromIterator; +use core::ops::{Sub, BitOr, BitAnd, BitXor}; // FIXME(contentions): implement union family of methods? (general design may be wrong here) diff --git a/src/libcollections/ring_buf.rs b/src/libcollections/ring_buf.rs index 2715ff0678af7..66f7b9e9c4ccd 100644 --- a/src/libcollections/ring_buf.rs +++ b/src/libcollections/ring_buf.rs @@ -14,14 +14,16 @@ use core::prelude::*; +use core::cmp::Ordering; use core::default::Default; use core::fmt; -use core::iter; -use core::raw::Slice as RawSlice; -use core::ptr; +use core::iter::{mod, FromIterator, RandomAccessIterator}; use core::kinds::marker; use core::mem; use core::num::{Int, UnsignedInt}; +use core::ops::{Index, IndexMut}; +use core::ptr; +use core::raw::Slice as RawSlice; use std::hash::{Writer, Hash}; use std::cmp; diff --git a/src/libcollections/slice.rs b/src/libcollections/slice.rs index d6d94f57acf45..a183250fed075 100644 --- a/src/libcollections/slice.rs +++ b/src/libcollections/slice.rs @@ -89,14 +89,15 @@ use alloc::boxed::Box; use core::borrow::{BorrowFrom, BorrowFromMut, ToOwned}; +use core::cmp::Ordering::{mod, Greater, Less}; 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; -use core::prelude::{Clone, Greater, Iterator, IteratorExt, Less, None, Option}; -use core::prelude::{Ord, Ordering, RawPtr, Some, range}; +use core::prelude::{Clone, Iterator, IteratorExt, None, Option}; +use core::prelude::{Ord, RawPtr, Some, range}; use core::ptr; use core::slice as core_slice; use self::Direction::*; diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index 9460b9a896646..26ff3e8679446 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -15,12 +15,14 @@ use core::prelude::*; use core::borrow::{Cow, IntoCow}; +use core::cmp::Equiv; use core::default::Default; use core::fmt; use core::hash; +use core::iter::FromIterator; use core::mem; +use core::ops::{mod, Deref, Add}; use core::ptr; -use core::ops; use core::raw::Slice as RawSlice; use unicode::str as unicode_str; use unicode::str::Utf16Item; diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs index bf69980b49c8f..e5c2ef9300ead 100644 --- a/src/libcollections/vec.rs +++ b/src/libcollections/vec.rs @@ -50,14 +50,16 @@ use alloc::boxed::Box; use alloc::heap::{EMPTY, allocate, reallocate, deallocate}; use core::borrow::{Cow, IntoCow}; use core::cmp::max; +use core::cmp::{Equiv, Ordering}; use core::default::Default; use core::fmt; use core::hash::{mod, Hash}; -use core::iter::repeat; +use core::iter::{repeat, FromIterator}; use core::kinds::marker::{ContravariantLifetime, InvariantType}; use core::mem; use core::nonzero::NonZero; use core::num::{Int, UnsignedInt}; +use core::ops::{Index, IndexMut, Deref, Add}; use core::ops; use core::ptr; use core::raw::Slice as RawSlice; diff --git a/src/libcollections/vec_map.rs b/src/libcollections/vec_map.rs index 5ebcc736624f6..063366c8d9c49 100644 --- a/src/libcollections/vec_map.rs +++ b/src/libcollections/vec_map.rs @@ -15,12 +15,14 @@ use core::prelude::*; +use core::cmp::Ordering; use core::default::Default; use core::fmt; use core::hash::{Hash, Writer}; +use core::iter::{Enumerate, FilterMap, Map, FromIterator}; use core::iter; -use core::iter::{Enumerate, FilterMap, Map}; use core::mem::replace; +use core::ops::{Index, IndexMut}; use {vec, slice}; use vec::Vec; diff --git a/src/libcore/cmp.rs b/src/libcore/cmp.rs index ca523db214b0c..4d72fb8ac9209 100644 --- a/src/libcore/cmp.rs +++ b/src/libcore/cmp.rs @@ -112,11 +112,12 @@ impl Ordering { /// # Example /// /// ```rust + /// use std::cmp::Ordering::{Less, Equal, Greater}; + /// /// assert_eq!(Less.reverse(), Greater); /// assert_eq!(Equal.reverse(), Equal); /// assert_eq!(Greater.reverse(), Less); /// - /// /// let mut data: &mut [_] = &mut [2u, 10, 5, 8]; /// /// // sort the array from largest to smallest. @@ -157,6 +158,8 @@ pub trait Ord for Sized?: Eq + PartialOrd { /// the expression `self other` if true. For example: /// /// ``` + /// use std::cmp::Ordering::{Less, Equal, Greater}; + /// /// assert_eq!( 5u.cmp(&10), Less); // because 5 < 10 /// assert_eq!(10u.cmp(&5), Greater); // because 10 > 5 /// assert_eq!( 5u.cmp(&5), Equal); // because 5 == 5 diff --git a/src/libcore/ops.rs b/src/libcore/ops.rs index 0cd8c1d69d1a1..a2ef8d484a75a 100644 --- a/src/libcore/ops.rs +++ b/src/libcore/ops.rs @@ -25,6 +25,8 @@ //! demonstrates adding and subtracting two `Point`s. //! //! ```rust +//! use std::ops::{Add, Sub}; +//! //! #[deriving(Show)] //! struct Point { //! x: int, @@ -68,13 +70,13 @@ use option::Option::{mod, Some, None}; /// struct HasDrop; /// /// impl Drop for HasDrop { -/// fn drop(&mut self) { -/// println!("Dropping!"); -/// } +/// fn drop(&mut self) { +/// println!("Dropping!"); +/// } /// } /// /// fn main() { -/// let _x = HasDrop; +/// let _x = HasDrop; /// } /// ``` #[lang="drop"] @@ -91,6 +93,8 @@ pub trait Drop { /// calling `add`, and therefore, `main` prints `Adding!`. /// /// ```rust +/// use std::ops::Add; +/// /// #[deriving(Copy)] /// struct Foo; /// @@ -130,6 +134,8 @@ add_impl! { uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64 } /// calling `sub`, and therefore, `main` prints `Subtracting!`. /// /// ```rust +/// use std::ops::Sub; +/// /// #[deriving(Copy)] /// struct Foo; /// @@ -169,6 +175,8 @@ sub_impl! { uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64 } /// calling `mul`, and therefore, `main` prints `Multiplying!`. /// /// ```rust +/// use std::ops::Mul; +/// /// #[deriving(Copy)] /// struct Foo; /// @@ -208,6 +216,8 @@ mul_impl! { uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64 } /// calling `div`, and therefore, `main` prints `Dividing!`. /// /// ``` +/// use std::ops::Div; +/// /// #[deriving(Copy)] /// struct Foo; /// @@ -247,6 +257,8 @@ div_impl! { uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64 } /// calling `rem`, and therefore, `main` prints `Remainder-ing!`. /// /// ``` +/// use std::ops::Rem; +/// /// #[deriving(Copy)] /// struct Foo; /// @@ -300,6 +312,8 @@ rem_float_impl! { f64, fmod } /// `neg`, and therefore, `main` prints `Negating!`. /// /// ``` +/// use std::ops::Neg; +/// /// #[deriving(Copy)] /// struct Foo; /// @@ -352,6 +366,8 @@ macro_rules! neg_uint_impl { /// `neg`, and therefore, `main` prints `Negating!`. /// /// ``` +/// use std::ops::Neg; +/// /// struct Foo; /// /// impl Copy for Foo {} @@ -411,6 +427,8 @@ neg_uint_impl! { u64, i64 } /// `not`, and therefore, `main` prints `Not-ing!`. /// /// ``` +/// use std::ops::Not; +/// /// #[deriving(Copy)] /// struct Foo; /// @@ -453,6 +471,8 @@ macro_rules! not_impl { /// `not`, and therefore, `main` prints `Not-ing!`. /// /// ``` +/// use std::ops::Not; +/// /// struct Foo; /// /// impl Copy for Foo {} @@ -495,6 +515,8 @@ not_impl! { bool uint u8 u16 u32 u64 int i8 i16 i32 i64 } /// calling `bitand`, and therefore, `main` prints `Bitwise And-ing!`. /// /// ``` +/// use std::ops::BitAnd; +/// /// #[deriving(Copy)] /// struct Foo; /// @@ -534,6 +556,8 @@ bitand_impl! { bool uint u8 u16 u32 u64 int i8 i16 i32 i64 } /// calling `bitor`, and therefore, `main` prints `Bitwise Or-ing!`. /// /// ``` +/// use std::ops::BitOr; +/// /// #[deriving(Copy)] /// struct Foo; /// @@ -573,6 +597,8 @@ bitor_impl! { bool uint u8 u16 u32 u64 int i8 i16 i32 i64 } /// calling `bitxor`, and therefore, `main` prints `Bitwise Xor-ing!`. /// /// ``` +/// use std::ops::BitXor; +/// /// #[deriving(Copy)] /// struct Foo; /// @@ -612,6 +638,8 @@ bitxor_impl! { bool uint u8 u16 u32 u64 int i8 i16 i32 i64 } /// calling `shl`, and therefore, `main` prints `Shifting left!`. /// /// ``` +/// use std::ops::Shl; +/// /// #[deriving(Copy)] /// struct Foo; /// @@ -653,6 +681,8 @@ shl_impl! { uint u8 u16 u32 u64 int i8 i16 i32 i64 } /// calling `shr`, and therefore, `main` prints `Shifting right!`. /// /// ``` +/// use std::ops::Shr; +/// /// #[deriving(Copy)] /// struct Foo; /// @@ -693,6 +723,8 @@ shr_impl! { uint u8 u16 u32 u64 int i8 i16 i32 i64 } /// calling `index`, and therefore, `main` prints `Indexing!`. /// /// ``` +/// use std::ops::Index; +/// /// #[deriving(Copy)] /// struct Foo; /// @@ -722,6 +754,8 @@ pub trait Index for Sized? { /// calling `index_mut`, and therefore, `main` prints `Indexing!`. /// /// ``` +/// use std::ops::IndexMut; +/// /// #[deriving(Copy)] /// struct Foo; /// @@ -751,6 +785,8 @@ pub trait IndexMut for Sized? { /// calling `slice_to`, and therefore, `main` prints `Slicing!`. /// /// ```ignore +/// use std::ops::Slice; +/// /// #[deriving(Copy)] /// struct Foo; /// @@ -798,6 +834,8 @@ pub trait Slice for Sized? { /// calling `slice_from_mut`, and therefore, `main` prints `Slicing!`. /// /// ```ignore +/// use std::ops::SliceMut; +/// /// #[deriving(Copy)] /// struct Foo; /// @@ -918,6 +956,8 @@ impl Iterator for RangeFrom { /// struct. /// /// ``` +/// use std::ops::Deref; +/// /// struct DerefExample { /// value: T /// } @@ -956,6 +996,8 @@ impl<'a, Sized? T> Deref for &'a mut T { /// struct. /// /// ``` +/// use std::ops::{Deref, DerefMut}; +/// /// struct DerefMutExample { /// value: T /// } diff --git a/src/libcore/option.rs b/src/libcore/option.rs index d831a57893bd7..ac0a6a78baed2 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -723,6 +723,8 @@ impl Option { /// `None` on error. /// /// ``` + /// use std::str::from_str; + /// /// let good_year_from_input = "1909"; /// let bad_year_from_input = "190blarg"; /// let good_year = good_year_from_input.parse().unwrap_or_default(); diff --git a/src/libcore/prelude.rs b/src/libcore/prelude.rs index f6abc8da79c0c..1fc377cda0a0f 100644 --- a/src/libcore/prelude.rs +++ b/src/libcore/prelude.rs @@ -30,39 +30,24 @@ // Reexported core operators pub use kinds::{Copy, Send, Sized, Sync}; -pub use ops::{Add, Sub, Mul, Div, Rem, Neg, Not}; -pub use ops::{BitAnd, BitOr, BitXor}; -pub use ops::{Drop, Deref, DerefMut}; -pub use ops::{Shl, Shr}; -pub use ops::{Index, IndexMut}; -pub use ops::{Slice, SliceMut}; -pub use ops::{Fn, FnMut, FnOnce}; +pub use ops::{Drop, Fn, FnMut, FnOnce}; // Reexported functions pub use iter::range; pub use mem::drop; -pub use str::from_str; // Reexported types and traits pub use char::Char; pub use clone::Clone; pub use cmp::{PartialEq, PartialOrd, Eq, Ord}; -pub use cmp::{Ordering, Equiv}; -pub use cmp::Ordering::{Less, Equal, Greater}; -pub use iter::{FromIterator, Extend, IteratorExt}; -pub use iter::{Iterator, DoubleEndedIterator, DoubleEndedIteratorExt, RandomAccessIterator}; +pub use iter::{Extend, IteratorExt}; +pub use iter::{Iterator, DoubleEndedIterator, DoubleEndedIteratorExt}; pub use iter::{IteratorCloneExt, CloneIteratorExt}; -pub use iter::{IteratorOrdExt, MutableDoubleEndedIterator, ExactSizeIterator}; -pub use num::{ToPrimitive, FromPrimitive}; -pub use option::Option; -pub use option::Option::{Some, None}; +pub use iter::{IteratorOrdExt, ExactSizeIterator}; +pub use option::Option::{mod, Some, None}; pub use ptr::RawPtr; -pub use result::Result; -pub use result::Result::{Ok, Err}; +pub use result::Result::{mod, Ok, Err}; pub use str::{Str, StrExt}; -pub use tuple::{Tuple1, Tuple2, Tuple3, Tuple4}; -pub use tuple::{Tuple5, Tuple6, Tuple7, Tuple8}; -pub use tuple::{Tuple9, Tuple10, Tuple11, Tuple12}; pub use slice::{PartialEqSliceExt, OrdSliceExt}; pub use slice::{AsSlice, SliceExt}; diff --git a/src/libcore/result.rs b/src/libcore/result.rs index 8014b4dc89d70..c738f61e20a25 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -449,6 +449,7 @@ impl Result { /// /// ``` /// use std::io::IoResult; + /// use std::str::from_str; /// /// let mut buffer = &mut b"1\n2\n3\n4\n"; /// diff --git a/src/libcore/tuple.rs b/src/libcore/tuple.rs index a92914c99e35b..270c5c59058b6 100644 --- a/src/libcore/tuple.rs +++ b/src/libcore/tuple.rs @@ -32,35 +32,6 @@ //! * `PartialOrd` //! * `Ord` //! * `Default` -//! -//! # Examples -//! -//! Using methods: -//! -//! ``` -//! #[allow(deprecated)] -//! # fn main() { -//! let pair = ("pi", 3.14f64); -//! assert_eq!(pair.val0(), "pi"); -//! assert_eq!(pair.val1(), 3.14f64); -//! # } -//! ``` -//! -//! Using traits implemented for tuples: -//! -//! ``` -//! use std::default::Default; -//! -//! let a = (1i, 2i); -//! let b = (3i, 4i); -//! assert!(a != b); -//! -//! let c = b.clone(); -//! assert!(b == c); -//! -//! let d : (u32, f32) = Default::default(); -//! assert_eq!(d, (0u32, 0.0f32)); -//! ``` #![stable] diff --git a/src/libcoretest/cmp.rs b/src/libcoretest/cmp.rs index 716300f652d67..992c99f1f9fe0 100644 --- a/src/libcoretest/cmp.rs +++ b/src/libcoretest/cmp.rs @@ -8,7 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::cmp::{ partial_min, partial_max }; +use core::cmp::{partial_min, partial_max}; +use core::cmp::Ordering::{Less, Greater, Equal}; #[test] fn test_int_totalord() { diff --git a/src/libcoretest/num/int_macros.rs b/src/libcoretest/num/int_macros.rs index 55e0f10c8655c..e409dc61510f6 100644 --- a/src/libcoretest/num/int_macros.rs +++ b/src/libcoretest/num/int_macros.rs @@ -17,6 +17,7 @@ mod tests { use core::int; use core::num::{FromStrRadix, Int, SignedInt}; use core::str::from_str; + use core::ops::{Shl, Shr, Not, BitXor, BitAnd, BitOr}; use num; #[test] diff --git a/src/libcoretest/num/mod.rs b/src/libcoretest/num/mod.rs index acc593d7be9c0..82e91c5b7120a 100644 --- a/src/libcoretest/num/mod.rs +++ b/src/libcoretest/num/mod.rs @@ -13,6 +13,7 @@ use core::fmt::Show; use core::num::{NumCast, cast}; use core::ops::{Add, Sub, Mul, Div, Rem}; use core::kinds::Copy; +use std::str::from_str; mod int_macros; mod i8; @@ -54,6 +55,7 @@ mod test { use core::option::Option::{Some, None}; use core::num::Float; use core::num::from_str_radix; + use core::str::from_str; #[test] fn from_str_issue7588() { diff --git a/src/libcoretest/num/uint_macros.rs b/src/libcoretest/num/uint_macros.rs index b21ac11e6a0b5..2311c19d5573a 100644 --- a/src/libcoretest/num/uint_macros.rs +++ b/src/libcoretest/num/uint_macros.rs @@ -16,6 +16,7 @@ mod tests { use core::$T_i::*; use core::num::Int; use num; + use core::ops::{BitOr, BitAnd, BitXor, Shl, Shr, Not}; #[test] fn test_overflows() { diff --git a/src/libcoretest/str.rs b/src/libcoretest/str.rs index 63d6e14a4a6b8..fc02f46724fb8 100644 --- a/src/libcoretest/str.rs +++ b/src/libcoretest/str.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::str::from_str; + #[test] fn test_bool_from_str() { assert_eq!(from_str::("true"), Some(true)); diff --git a/src/libcoretest/tuple.rs b/src/libcoretest/tuple.rs index f7b714757f8da..c3bc38a6614b8 100644 --- a/src/libcoretest/tuple.rs +++ b/src/libcoretest/tuple.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::cmp::Ordering::{Equal, Less, Greater}; + #[test] fn test_clone() { let a = (1i, "2"); diff --git a/src/libgraphviz/lib.rs b/src/libgraphviz/lib.rs index ce3df1090bd58..9574549a26094 100644 --- a/src/libgraphviz/lib.rs +++ b/src/libgraphviz/lib.rs @@ -47,6 +47,7 @@ //! which is cyclic. //! //! ```rust +//! use std::borrow::IntoCow; //! use graphviz as dot; //! //! type Nd = int; @@ -146,6 +147,7 @@ //! entity `&sube`). //! //! ```rust +//! use std::borrow::IntoCow; //! use graphviz as dot; //! //! type Nd = uint; @@ -201,6 +203,7 @@ //! Hasse-diagram for the subsets of the set `{x, y}`. //! //! ```rust +//! use std::borrow::IntoCow; //! use graphviz as dot; //! //! type Nd<'a> = (uint, &'a str); @@ -273,6 +276,7 @@ pub use self::LabelText::*; +use std::borrow::IntoCow; use std::io; use std::str::CowString; use std::vec::CowVec; @@ -586,6 +590,7 @@ mod tests { use super::{Nodes, Edges, GraphWalk, render}; use std::io::IoResult; use std::str; + use std::borrow::IntoCow; /// each node is an index in a vector in the graph. type Node = uint; diff --git a/src/libgraphviz/maybe_owned_vec.rs b/src/libgraphviz/maybe_owned_vec.rs index ddda2b38c223a..573f0926e2915 100644 --- a/src/libgraphviz/maybe_owned_vec.rs +++ b/src/libgraphviz/maybe_owned_vec.rs @@ -12,8 +12,10 @@ pub use self::MaybeOwnedVector::*; +use std::cmp::{Equiv, Ordering}; use std::default::Default; use std::fmt; +use std::iter::FromIterator; use std::path::BytesContainer; use std::slice; @@ -125,7 +127,7 @@ impl<'a,T> FromIterator for MaybeOwnedVector<'a,T> { fn from_iter>(iterator: I) -> MaybeOwnedVector<'a,T> { // If we are building from scratch, might as well build the // most flexible variant. - Growable(FromIterator::from_iter(iterator)) + Growable(iterator.collect()) } } diff --git a/src/librand/chacha.rs b/src/librand/chacha.rs index 6fc92e1e94fcb..c8d7b91042442 100644 --- a/src/librand/chacha.rs +++ b/src/librand/chacha.rs @@ -206,7 +206,7 @@ impl Rand for ChaChaRng { #[cfg(test)] mod test { - use std::prelude::*; + use std::prelude::v1::*; use core::iter::order; use {Rng, SeedableRng}; diff --git a/src/librand/distributions/exponential.rs b/src/librand/distributions/exponential.rs index 431a530726a08..da34b96505d68 100644 --- a/src/librand/distributions/exponential.rs +++ b/src/librand/distributions/exponential.rs @@ -94,7 +94,7 @@ impl IndependentSample for Exp { #[cfg(test)] mod test { - use std::prelude::*; + use std::prelude::v1::*; use distributions::{Sample, IndependentSample}; use super::Exp; @@ -124,7 +124,7 @@ mod test { mod bench { extern crate test; - use std::prelude::*; + use std::prelude::v1::*; use self::test::Bencher; use std::mem::size_of; diff --git a/src/librand/distributions/gamma.rs b/src/librand/distributions/gamma.rs index d33d838766f22..21565224e5723 100644 --- a/src/librand/distributions/gamma.rs +++ b/src/librand/distributions/gamma.rs @@ -323,7 +323,7 @@ impl IndependentSample for StudentT { #[cfg(test)] mod test { - use std::prelude::*; + use std::prelude::v1::*; use distributions::{Sample, IndependentSample}; use super::{ChiSquared, StudentT, FisherF}; @@ -385,7 +385,7 @@ mod test { #[cfg(test)] mod bench { extern crate test; - use std::prelude::*; + use std::prelude::v1::*; use self::test::Bencher; use std::mem::size_of; use distributions::IndependentSample; diff --git a/src/librand/distributions/mod.rs b/src/librand/distributions/mod.rs index 58125c67fdae9..d48c7b9aaa4d5 100644 --- a/src/librand/distributions/mod.rs +++ b/src/librand/distributions/mod.rs @@ -258,7 +258,7 @@ fn ziggurat( #[cfg(test)] mod tests { - use std::prelude::*; + use std::prelude::v1::*; use {Rng, Rand}; use super::{RandSample, WeightedChoice, Weighted, Sample, IndependentSample}; diff --git a/src/librand/distributions/normal.rs b/src/librand/distributions/normal.rs index 16413af626739..140f34f67f5bc 100644 --- a/src/librand/distributions/normal.rs +++ b/src/librand/distributions/normal.rs @@ -160,7 +160,7 @@ impl IndependentSample for LogNormal { #[cfg(test)] mod tests { - use std::prelude::*; + use std::prelude::v1::*; use distributions::{Sample, IndependentSample}; use super::{Normal, LogNormal}; @@ -200,7 +200,7 @@ mod tests { #[cfg(test)] mod bench { extern crate test; - use std::prelude::*; + use std::prelude::v1::*; use self::test::Bencher; use std::mem::size_of; use distributions::{Sample}; diff --git a/src/librand/distributions/range.rs b/src/librand/distributions/range.rs index 6301623bbdc18..f23ad6a753b6a 100644 --- a/src/librand/distributions/range.rs +++ b/src/librand/distributions/range.rs @@ -164,7 +164,7 @@ float_impl! { f64 } #[cfg(test)] mod tests { use std::num::Int; - use std::prelude::*; + use std::prelude::v1::*; use distributions::{Sample, IndependentSample}; use super::Range; diff --git a/src/librand/isaac.rs b/src/librand/isaac.rs index 3cb1f51a6a801..d7ae91593a136 100644 --- a/src/librand/isaac.rs +++ b/src/librand/isaac.rs @@ -487,7 +487,7 @@ impl Rand for Isaac64Rng { #[cfg(test)] mod test { - use std::prelude::*; + use std::prelude::v1::*; use core::iter::order; use {Rng, SeedableRng}; diff --git a/src/librand/rand_impls.rs b/src/librand/rand_impls.rs index 3b38fde3884f1..937723aa5f591 100644 --- a/src/librand/rand_impls.rs +++ b/src/librand/rand_impls.rs @@ -214,7 +214,7 @@ impl Rand for Option { #[cfg(test)] mod tests { - use std::prelude::*; + use std::prelude::v1::*; use std::rand::{Rng, task_rng, Open01, Closed01}; struct ConstantRng(u64); diff --git a/src/librand/reseeding.rs b/src/librand/reseeding.rs index 94a11c040e497..46371d427e63f 100644 --- a/src/librand/reseeding.rs +++ b/src/librand/reseeding.rs @@ -149,7 +149,7 @@ impl Default for ReseedWithDefault { #[cfg(test)] mod test { - use std::prelude::*; + use std::prelude::v1::*; use core::iter::order; use super::{ReseedingRng, ReseedWithDefault}; diff --git a/src/libregex/re.rs b/src/libregex/re.rs index 4383192edafb0..1b6dcb3a8e226 100644 --- a/src/libregex/re.rs +++ b/src/libregex/re.rs @@ -11,6 +11,7 @@ pub use self::NamesIter::*; pub use self::Regex::*; +use std::borrow::IntoCow; use std::collections::HashMap; use std::fmt; use std::str::CowString; diff --git a/src/libregex/vm.rs b/src/libregex/vm.rs index 990d5a159f60d..0cdafb73b6ef7 100644 --- a/src/libregex/vm.rs +++ b/src/libregex/vm.rs @@ -37,6 +37,7 @@ pub use self::MatchKind::*; pub use self::StepState::*; use std::cmp; +use std::cmp::Ordering::{mod, Less, Equal, Greater}; use std::mem; use std::slice::SliceExt; use compile::{ diff --git a/src/librustc/lint/builtin.rs b/src/librustc/lint/builtin.rs index 9ce344586fd99..602de8cd90df5 100644 --- a/src/librustc/lint/builtin.rs +++ b/src/librustc/lint/builtin.rs @@ -36,10 +36,11 @@ use util::ppaux::{ty_to_string}; use util::nodemap::{FnvHashMap, NodeSet}; use lint::{Context, LintPass, LintArray}; -use std::{cmp, slice}; use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::num::SignedInt; +use std::{cmp, slice}; use std::{i8, i16, i32, i64, u8, u16, u32, u64, f32, f64}; + use syntax::{abi, ast, ast_map}; use syntax::ast_util::is_shift_binop; use syntax::attr::{mod, AttrMetaMethods}; diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index 4447af809e4b2..567c3f5e752b1 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -32,13 +32,15 @@ use middle::ty::{ImplContainer, TraitContainer}; use middle::ty::{mod, Ty}; use middle::astencode::vtable_decoder_helpers; +use std::collections::HashMap; use std::hash::Hash; use std::hash; use std::io::extensions::u64_from_be_bytes; use std::io; -use std::collections::hash_map::HashMap; +use std::num::FromPrimitive; use std::rc::Rc; use std::str; + use rbml::reader; use rbml; use serialize::Decodable; diff --git a/src/librustc/metadata/tydecode.rs b/src/librustc/metadata/tydecode.rs index 9b008f36a9646..e0a69f58d379e 100644 --- a/src/librustc/metadata/tydecode.rs +++ b/src/librustc/metadata/tydecode.rs @@ -25,7 +25,6 @@ use middle::ty::{mod, AsPredicate, Ty}; use std::rc::Rc; use std::str; -use std::string::String; use syntax::abi; use syntax::ast; use syntax::parse::token; diff --git a/src/librustc/middle/cfg/graphviz.rs b/src/librustc/middle/cfg/graphviz.rs index 13bd22a67c410..06fef66c1e003 100644 --- a/src/librustc/middle/cfg/graphviz.rs +++ b/src/librustc/middle/cfg/graphviz.rs @@ -11,7 +11,9 @@ /// This module provides linkage between rustc::middle::graph and /// libgraphviz traits. -/// For clarity, rename the graphviz crate locally to dot. +use std::borrow::IntoCow; + +// For clarity, rename the graphviz crate locally to dot. use graphviz as dot; use syntax::ast; diff --git a/src/librustc/middle/check_match.rs b/src/librustc/middle/check_match.rs index da1bd09ceffdd..234f830bc6621 100644 --- a/src/librustc/middle/check_match.rs +++ b/src/librustc/middle/check_match.rs @@ -24,8 +24,7 @@ use middle::pat_util::*; use middle::ty::*; use middle::ty; use std::fmt; -use std::iter::AdditiveIterator; -use std::iter::range_inclusive; +use std::iter::{range_inclusive, AdditiveIterator, FromIterator}; use std::num::Float; use std::slice; use syntax::ast::{mod, DUMMY_NODE_ID, NodeId, Pat}; diff --git a/src/librustc/middle/const_eval.rs b/src/librustc/middle/const_eval.rs index 5b89912dd03fc..9fc5cb0335313 100644 --- a/src/librustc/middle/const_eval.rs +++ b/src/librustc/middle/const_eval.rs @@ -27,8 +27,8 @@ use syntax::ptr::P; use syntax::visit::{mod, Visitor}; use syntax::{ast_map, ast_util, codemap}; -use std::rc::Rc; use std::collections::hash_map::Entry::Vacant; +use std::rc::Rc; // // This pass classifies expressions by their constant-ness. diff --git a/src/librustc/middle/infer/region_inference/mod.rs b/src/librustc/middle/infer/region_inference/mod.rs index 97fab3bc9395a..99c6f732c3645 100644 --- a/src/librustc/middle/infer/region_inference/mod.rs +++ b/src/librustc/middle/infer/region_inference/mod.rs @@ -33,6 +33,7 @@ use util::nodemap::{FnvHashMap, FnvHashSet}; use util::ppaux::Repr; use std::cell::{Cell, RefCell}; +use std::cmp::Ordering::{mod, Less, Greater, Equal}; use std::u32; use syntax::ast; diff --git a/src/librustc/middle/lang_items.rs b/src/librustc/middle/lang_items.rs index 90e3e2bb34aba..6d2db05689431 100644 --- a/src/librustc/middle/lang_items.rs +++ b/src/librustc/middle/lang_items.rs @@ -36,6 +36,7 @@ use syntax::visit::Visitor; use syntax::visit; use std::iter::Enumerate; +use std::num::FromPrimitive; use std::slice; // The actual lang items defined come at the end of this file in one handy table. diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index 398e52cf0430b..02ca72fffa122 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -70,7 +70,7 @@ use util::nodemap::{FnvHashMap, FnvHashSet}; use arena::TypedArena; use std::borrow::BorrowFrom; use std::cell::{Cell, RefCell}; -use std::cmp; +use std::cmp::{mod, Ordering}; use std::fmt::{mod, Show}; use std::hash::{Hash, sip, Writer}; use std::mem; diff --git a/src/librustc/session/config.rs b/src/librustc/session/config.rs index 5f3fbf897dc16..7ccb68f2a75f6 100644 --- a/src/librustc/session/config.rs +++ b/src/librustc/session/config.rs @@ -394,6 +394,7 @@ macro_rules! cgoptions { mod cgsetters { use super::{CodegenOptions, Passes, SomePasses, AllPasses}; + use std::str::from_str; $( pub fn $opt(cg: &mut CodegenOptions, v: Option<&str>) -> bool { diff --git a/src/librustc_borrowck/borrowck/gather_loans/move_error.rs b/src/librustc_borrowck/borrowck/gather_loans/move_error.rs index 73b345a70af46..8d3aa397f3061 100644 --- a/src/librustc_borrowck/borrowck/gather_loans/move_error.rs +++ b/src/librustc_borrowck/borrowck/gather_loans/move_error.rs @@ -33,7 +33,7 @@ impl<'tcx> MoveErrorCollector<'tcx> { } pub fn report_potential_errors<'a>(&self, bccx: &BorrowckCtxt<'a, 'tcx>) { - report_move_errors(bccx, self.errors.borrow().deref()) + report_move_errors(bccx, &*self.errors.borrow()) } } diff --git a/src/librustc_borrowck/graphviz.rs b/src/librustc_borrowck/graphviz.rs index e2813c8e9882a..ac6b962d64704 100644 --- a/src/librustc_borrowck/graphviz.rs +++ b/src/librustc_borrowck/graphviz.rs @@ -24,6 +24,7 @@ use rustc::middle::cfg::{CFGIndex}; use rustc::middle::dataflow::{DataFlowOperator, DataFlowContext, EntryOrExit}; use rustc::middle::dataflow; use std::rc::Rc; +use std::borrow::IntoCow; #[deriving(Show, Copy)] pub enum Variant { diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs index e2791aff14e49..8b716a8431d88 100644 --- a/src/librustc_driver/lib.rs +++ b/src/librustc_driver/lib.rs @@ -54,9 +54,11 @@ use rustc::metadata; use rustc::DIAGNOSTICS; use std::any::AnyRefExt; +use std::cmp::Ordering::Equal; use std::io; use std::iter::repeat; use std::os; +use std::sync::mpsc::channel; use std::thread; use rustc::session::early_error; diff --git a/src/librustc_llvm/archive_ro.rs b/src/librustc_llvm/archive_ro.rs index 6c3778787e2e2..53992d4567a34 100644 --- a/src/librustc_llvm/archive_ro.rs +++ b/src/librustc_llvm/archive_ro.rs @@ -13,8 +13,9 @@ use libc; use ArchiveRef; -use std::raw; +use std::c_str::ToCStr; use std::mem; +use std::raw; pub struct ArchiveRO { ptr: ArchiveRef, diff --git a/src/librustc_resolve/check_unused.rs b/src/librustc_resolve/check_unused.rs index 78527315199ca..b3d0d30726c5d 100644 --- a/src/librustc_resolve/check_unused.rs +++ b/src/librustc_resolve/check_unused.rs @@ -17,6 +17,8 @@ // `use` directives. // +use std::ops::{Deref, DerefMut}; + use Resolver; use Namespace::{TypeNS, ValueNS}; diff --git a/src/librustc_resolve/record_exports.rs b/src/librustc_resolve/record_exports.rs index 80659152f9fc7..c6618f10e0e79 100644 --- a/src/librustc_resolve/record_exports.rs +++ b/src/librustc_resolve/record_exports.rs @@ -25,6 +25,7 @@ use rustc::middle::def::Export; use syntax::ast; use syntax::parse::token; +use std::ops::{Deref, DerefMut}; use std::rc::Rc; struct ExportRecorder<'a, 'b:'a, 'tcx:'b> { diff --git a/src/librustc_trans/back/lto.rs b/src/librustc_trans/back/lto.rs index 1271330897e73..7cf4bafe032e0 100644 --- a/src/librustc_trans/back/lto.rs +++ b/src/librustc_trans/back/lto.rs @@ -20,6 +20,7 @@ use rustc::util::common::time; use libc; use flate; +use std::c_str::ToCStr; use std::iter; use std::mem; use std::num::Int; diff --git a/src/librustc_trans/back/write.rs b/src/librustc_trans/back/write.rs index 513b955da3f58..55e6dfaebcd51 100644 --- a/src/librustc_trans/back/write.rs +++ b/src/librustc_trans/back/write.rs @@ -30,6 +30,7 @@ use std::ptr; use std::str; use std::mem; use std::sync::{Arc, Mutex}; +use std::sync::mpsc::channel; use std::thread; use libc::{c_uint, c_int, c_void}; @@ -928,13 +929,13 @@ fn run_work_multithreaded(sess: &Session, } } - tx.take().unwrap().send(()); + tx.take().unwrap().send(()).unwrap(); }).detach(); } let mut panicked = false; for rx in futures.into_iter() { - match rx.recv_opt() { + match rx.recv() { Ok(()) => {}, Err(_) => { panicked = true; diff --git a/src/librustc_trans/save/mod.rs b/src/librustc_trans/save/mod.rs index f491bc84b62c4..e105a1f6a95f3 100644 --- a/src/librustc_trans/save/mod.rs +++ b/src/librustc_trans/save/mod.rs @@ -1203,8 +1203,7 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { let glob_map = &self.analysis.glob_map; let glob_map = glob_map.as_ref().unwrap(); if glob_map.contains_key(&id) { - let names = glob_map.index(&id); - for n in names.iter() { + for n in glob_map[id].iter() { if name_string.len() > 0 { name_string.push_str(", "); } diff --git a/src/librustc_trans/trans/builder.rs b/src/librustc_trans/trans/builder.rs index 1b9c9d221b909..e7d4128eb4e48 100644 --- a/src/librustc_trans/trans/builder.rs +++ b/src/librustc_trans/trans/builder.rs @@ -20,7 +20,7 @@ use trans::machine::llalign_of_pref; use trans::type_::Type; use util::nodemap::FnvHashMap; use libc::{c_uint, c_char}; -use std::string::String; +use std::c_str::ToCStr; use syntax::codemap::Span; pub struct Builder<'a, 'tcx: 'a> { diff --git a/src/librustc_trans/trans/foreign.rs b/src/librustc_trans/trans/foreign.rs index 1bad476863fdb..f94e1af314968 100644 --- a/src/librustc_trans/trans/foreign.rs +++ b/src/librustc_trans/trans/foreign.rs @@ -25,6 +25,7 @@ use trans::type_of; use middle::ty::{mod, Ty}; use middle::subst::{Subst, Substs}; use std::cmp; +use std::c_str::ToCStr; use libc::c_uint; use syntax::abi::{Cdecl, Aapcs, C, Win64, Abi}; use syntax::abi::{RustIntrinsic, Rust, RustCall, Stdcall, Fastcall, System}; diff --git a/src/librustdoc/flock.rs b/src/librustdoc/flock.rs index a89b20c949b40..0f0dbf6a24dff 100644 --- a/src/librustdoc/flock.rs +++ b/src/librustdoc/flock.rs @@ -18,10 +18,10 @@ pub use self::imp::Lock; - #[cfg(unix)] mod imp { use libc; + use std::c_str::ToCStr; #[cfg(target_os = "linux")] mod os { diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs index bff670f9ea954..aed8cdfb8b2c5 100644 --- a/src/librustdoc/html/markdown.rs +++ b/src/librustdoc/html/markdown.rs @@ -29,11 +29,12 @@ use libc; use std::ascii::AsciiExt; +use std::c_str::ToCStr; use std::cell::{RefCell, Cell}; +use std::collections::HashMap; use std::fmt; use std::slice; use std::str; -use std::collections::HashMap; use html::toc::TocBuilder; use html::highlight; diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 304dbe201e8fd..ebdd43b1775bd 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -35,6 +35,7 @@ pub use self::ExternalLocation::*; use std::cell::RefCell; +use std::cmp::Ordering::{mod, Less, Greater, Equal}; use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::collections::{HashMap, HashSet}; use std::default::Default; diff --git a/src/librustdoc/stability_summary.rs b/src/librustdoc/stability_summary.rs index 2e3adf8e76787..058a7acd4550b 100644 --- a/src/librustdoc/stability_summary.rs +++ b/src/librustdoc/stability_summary.rs @@ -13,8 +13,9 @@ //! hierarchy, with item counts for every stability level per module. A parent //! module's count includes its children's. -use std::ops::Add; +use std::cmp::Ordering; use std::num::Zero; +use std::ops::Add; use syntax::attr::{Deprecated, Experimental, Unstable, Stable, Frozen, Locked}; use syntax::ast::Public; diff --git a/src/librustdoc/test.rs b/src/librustdoc/test.rs index b55097c0c5a1b..a50bfbde0fea2 100644 --- a/src/librustdoc/test.rs +++ b/src/librustdoc/test.rs @@ -9,14 +9,14 @@ // except according to those terms. use std::cell::RefCell; +use std::sync::mpsc::channel; use std::dynamic_lib::DynamicLibrary; use std::io::{Command, TempDir}; use std::io; use std::os; use std::str; -use std::string::String; -use std::thunk::Thunk; use std::thread::Thread; +use std::thunk::Thunk; use std::collections::{HashSet, HashMap}; use testing; diff --git a/src/libstd/ascii.rs b/src/libstd/ascii.rs index 7bd955a905bbd..db01c091dc018 100644 --- a/src/libstd/ascii.rs +++ b/src/libstd/ascii.rs @@ -315,8 +315,8 @@ static ASCII_UPPERCASE_MAP: [u8, ..256] = [ #[cfg(test)] mod tests { + use prelude::v1::*; use super::*; - use prelude::*; use char::from_u32; #[test] diff --git a/src/libstd/bitflags.rs b/src/libstd/bitflags.rs index 5dd76047779a0..4ec329de600e1 100644 --- a/src/libstd/bitflags.rs +++ b/src/libstd/bitflags.rs @@ -205,7 +205,7 @@ macro_rules! bitflags { } } - impl BitOr<$BitFlags, $BitFlags> for $BitFlags { + impl ::std::ops::BitOr<$BitFlags, $BitFlags> for $BitFlags { /// Returns the union of the two sets of flags. #[inline] fn bitor(self, other: $BitFlags) -> $BitFlags { @@ -213,7 +213,7 @@ macro_rules! bitflags { } } - impl BitXor<$BitFlags, $BitFlags> for $BitFlags { + impl ::std::ops::BitXor<$BitFlags, $BitFlags> for $BitFlags { /// Returns the left flags, but with all the right flags toggled. #[inline] fn bitxor(self, other: $BitFlags) -> $BitFlags { @@ -221,7 +221,7 @@ macro_rules! bitflags { } } - impl BitAnd<$BitFlags, $BitFlags> for $BitFlags { + impl ::std::ops::BitAnd<$BitFlags, $BitFlags> for $BitFlags { /// Returns the intersection between the two sets of flags. #[inline] fn bitand(self, other: $BitFlags) -> $BitFlags { @@ -229,7 +229,7 @@ macro_rules! bitflags { } } - impl Sub<$BitFlags, $BitFlags> for $BitFlags { + impl ::std::ops::Sub<$BitFlags, $BitFlags> for $BitFlags { /// Returns the set difference of the two sets of flags. #[inline] fn sub(self, other: $BitFlags) -> $BitFlags { @@ -239,7 +239,7 @@ macro_rules! bitflags { // NOTE(stage0): Remove impl after a snapshot #[cfg(stage0)] - impl Not<$BitFlags> for $BitFlags { + impl ::std::ops::Not<$BitFlags> for $BitFlags { /// Returns the complement of this set of flags. #[inline] fn not(&self) -> $BitFlags { @@ -248,7 +248,7 @@ macro_rules! bitflags { } #[cfg(not(stage0))] // NOTE(stage0): Remove cfg after a snapshot - impl Not<$BitFlags> for $BitFlags { + impl ::std::ops::Not<$BitFlags> for $BitFlags { /// Returns the complement of this set of flags. #[inline] fn not(self) -> $BitFlags { @@ -273,7 +273,6 @@ macro_rules! bitflags { mod tests { use hash; use option::Option::{Some, None}; - use ops::{BitOr, BitAnd, BitXor, Sub, Not}; bitflags! { #[doc = "> The first principle is that you must not fool yourself — and"] diff --git a/src/libstd/c_str.rs b/src/libstd/c_str.rs index ffe19203769d4..d096903f9c47d 100644 --- a/src/libstd/c_str.rs +++ b/src/libstd/c_str.rs @@ -45,6 +45,8 @@ //! ```rust //! extern crate libc; //! +//! use std::c_str::ToCStr; +//! //! extern { //! fn puts(s: *const libc::c_char); //! } @@ -70,6 +72,7 @@ use core::prelude::*; use libc; +use cmp::Ordering; use fmt; use hash; use mem; @@ -155,6 +158,8 @@ impl CString { /// one). /// /// ```rust + /// use std::c_str::ToCStr; + /// /// let foo = "some string"; /// /// // right @@ -170,6 +175,8 @@ impl CString { /// ```rust /// extern crate libc; /// + /// use std::c_str::ToCStr; + /// /// fn main() { /// let c_str = "foo bar".to_c_str(); /// unsafe { @@ -189,6 +196,8 @@ impl CString { /// one). /// /// ```rust + /// use std::c_str::ToCStr; + /// /// let foo = "some string"; /// /// // right @@ -309,6 +318,8 @@ pub trait ToCStr for Sized? { /// ```rust /// extern crate libc; /// + /// use std::c_str::ToCStr; + /// /// fn main() { /// let s = "PATH".with_c_str(|path| unsafe { /// libc::getenv(path) @@ -537,7 +548,7 @@ pub unsafe fn from_c_multistring(buf: *const libc::c_char, #[cfg(test)] mod tests { use super::*; - use prelude::*; + use prelude::v1::*; use ptr; use thread::Thread; use libc; @@ -610,7 +621,7 @@ mod tests { #[test] fn test_unwrap() { let c_str = "hello".to_c_str(); - unsafe { libc::free(c_str.unwrap() as *mut libc::c_void) } + unsafe { libc::free(c_str.into_inner() as *mut libc::c_void) } } #[test] @@ -729,9 +740,10 @@ mod tests { mod bench { extern crate test; + use prelude::v1::*; use self::test::Bencher; use libc; - use prelude::*; + use c_str::ToCStr; #[inline] fn check(s: &str, c_str: *const libc::c_char) { diff --git a/src/libstd/c_vec.rs b/src/libstd/c_vec.rs index f4338815f759b..a80659ed937e5 100644 --- a/src/libstd/c_vec.rs +++ b/src/libstd/c_vec.rs @@ -172,7 +172,7 @@ impl AsSlice for CVec { #[cfg(test)] mod tests { - use prelude::*; + use prelude::v1::*; use super::CVec; use libc; @@ -228,7 +228,7 @@ mod tests { let cv = CVec::new_with_dtor(1 as *mut int, 0, move|:| panic!("Don't run this destructor!")); - let p = cv.unwrap(); + let p = cv.into_inner(); assert_eq!(p, 1 as *mut int); } } diff --git a/src/libstd/collections/hash/bench.rs b/src/libstd/collections/hash/bench.rs index 87aebb24f987b..28689767cb0e3 100644 --- a/src/libstd/collections/hash/bench.rs +++ b/src/libstd/collections/hash/bench.rs @@ -11,7 +11,7 @@ #![cfg(test)] extern crate test; -use prelude::*; +use prelude::v1::*; use self::test::Bencher; use iter::{range_inclusive}; diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs index d749cd77cef2d..8585b4ecf52ad 100644 --- a/src/libstd/collections/hash/map.rs +++ b/src/libstd/collections/hash/map.rs @@ -87,7 +87,7 @@ impl DefaultResizePolicy { #[test] fn test_resize_policy() { - use prelude::*; + use prelude::v1::*; let rp = DefaultResizePolicy; for n in range(0u, 1000) { assert!(rp.min_capacity(rp.usable_capacity(n)) <= n); @@ -1473,8 +1473,9 @@ impl, V, S, H: Hasher + Default> Extend<(K, V)> for HashMap for KindaIntLike { fn equiv(&self, other: &int) -> bool { let KindaIntLike(this) = *self; @@ -1811,7 +1813,7 @@ mod test_map { } #[test] - #[allow(experimental)] + #[allow(deprecated)] fn test_pop_equiv() { let mut m = HashMap::new(); m.insert(1i, 2i); diff --git a/src/libstd/collections/hash/set.rs b/src/libstd/collections/hash/set.rs index 6d83d5510b357..e00116344c848 100644 --- a/src/libstd/collections/hash/set.rs +++ b/src/libstd/collections/hash/set.rs @@ -844,7 +844,7 @@ impl<'a, T, S, H> Iterator<&'a T> for Union<'a, T, H> #[cfg(test)] mod test_set { - use prelude::*; + use prelude::v1::*; use super::HashSet; diff --git a/src/libstd/dynamic_lib.rs b/src/libstd/dynamic_lib.rs index 368abe7cb1244..ecfe2d15ae1c2 100644 --- a/src/libstd/dynamic_lib.rs +++ b/src/libstd/dynamic_lib.rs @@ -15,7 +15,9 @@ #![experimental] #![allow(missing_docs)] -use prelude::*; +use prelude::v1::*; + +use c_str::ToCStr; use mem; use os; use str; @@ -146,7 +148,7 @@ impl DynamicLibrary { #[cfg(all(test, not(target_os = "ios")))] mod test { use super::*; - use prelude::*; + use prelude::v1::*; use libc; use mem; @@ -202,8 +204,8 @@ mod test { pub mod dl { use self::Rtld::*; - use prelude::*; - use c_str::CString; + use prelude::v1::*; + use c_str::{CString, ToCStr}; use libc; use ptr; diff --git a/src/libstd/error.rs b/src/libstd/error.rs index cd7d9aacc9010..956185c6443de 100644 --- a/src/libstd/error.rs +++ b/src/libstd/error.rs @@ -78,7 +78,7 @@ //! } //! ``` -use prelude::*; +use prelude::v1::*; use str::Utf8Error; diff --git a/src/libstd/failure.rs b/src/libstd/failure.rs index 7010eae6dba0d..3d98b6ec40e49 100644 --- a/src/libstd/failure.rs +++ b/src/libstd/failure.rs @@ -10,7 +10,7 @@ #![experimental] -use prelude::*; +use prelude::v1::*; use any::{Any, AnyRefExt}; use cell::RefCell; diff --git a/src/libstd/io/buffered.rs b/src/libstd/io/buffered.rs index c26450310a9b2..1679d2e552f22 100644 --- a/src/libstd/io/buffered.rs +++ b/src/libstd/io/buffered.rs @@ -410,7 +410,7 @@ impl Writer for BufferedStream { mod test { extern crate test; use io; - use prelude::*; + use prelude::v1::*; use super::*; use super::super::{IoResult, EndOfFile}; use super::super::mem::MemReader; @@ -533,7 +533,7 @@ mod test { w.write(&[0, 1]).unwrap(); let a: &[_] = &[]; assert_eq!(a, w.get_ref()[]); - let w = w.unwrap(); + let w = w.into_inner(); let a: &[_] = &[0, 1]; assert_eq!(a, w[]); } diff --git a/src/libstd/io/comm_adapters.rs b/src/libstd/io/comm_adapters.rs index 3a18b0dc1b525..7b8513ce423b2 100644 --- a/src/libstd/io/comm_adapters.rs +++ b/src/libstd/io/comm_adapters.rs @@ -10,7 +10,7 @@ use clone::Clone; use cmp; -use comm::{Sender, Receiver}; +use sync::mpsc::{Sender, Receiver}; use io; use option::Option::{None, Some}; use result::Result::{Ok, Err}; @@ -23,6 +23,7 @@ use vec::Vec; /// # Example /// /// ``` +/// use std::sync::mpsc::channel; /// use std::io::ChanReader; /// /// let (tx, rx) = channel(); @@ -58,11 +59,11 @@ impl Buffer for ChanReader { fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]> { if self.pos >= self.buf.len() { self.pos = 0; - match self.rx.recv_opt() { + match self.rx.recv() { Ok(bytes) => { self.buf = bytes; }, - Err(()) => { + Err(..) => { self.closed = true; self.buf = Vec::new(); } @@ -114,6 +115,7 @@ impl Reader for ChanReader { /// /// ``` /// # #![allow(unused_must_use)] +/// use std::sync::mpsc::channel; /// use std::io::ChanWriter; /// /// let (tx, rx) = channel(); @@ -141,7 +143,7 @@ impl Clone for ChanWriter { impl Writer for ChanWriter { fn write(&mut self, buf: &[u8]) -> IoResult<()> { - self.tx.send_opt(buf.to_vec()).map_err(|_| { + self.tx.send(buf.to_vec()).map_err(|_| { io::IoError { kind: io::BrokenPipe, desc: "Pipe closed", @@ -154,7 +156,9 @@ impl Writer for ChanWriter { #[cfg(test)] mod test { - use prelude::*; + use prelude::v1::*; + + use sync::mpsc::channel; use super::*; use io; use thread::Thread; @@ -163,11 +167,11 @@ mod test { fn test_rx_reader() { let (tx, rx) = channel(); Thread::spawn(move|| { - tx.send(vec![1u8, 2u8]); - tx.send(vec![]); - tx.send(vec![3u8, 4u8]); - tx.send(vec![5u8, 6u8]); - tx.send(vec![7u8, 8u8]); + tx.send(vec![1u8, 2u8]).unwrap(); + tx.send(vec![]).unwrap(); + tx.send(vec![3u8, 4u8]).unwrap(); + tx.send(vec![5u8, 6u8]).unwrap(); + tx.send(vec![7u8, 8u8]).unwrap(); }).detach(); let mut reader = ChanReader::new(rx); @@ -205,12 +209,12 @@ mod test { fn test_rx_buffer() { let (tx, rx) = channel(); Thread::spawn(move|| { - tx.send(b"he".to_vec()); - tx.send(b"llo wo".to_vec()); - tx.send(b"".to_vec()); - tx.send(b"rld\nhow ".to_vec()); - tx.send(b"are you?".to_vec()); - tx.send(b"".to_vec()); + tx.send(b"he".to_vec()).unwrap(); + tx.send(b"llo wo".to_vec()).unwrap(); + tx.send(b"".to_vec()).unwrap(); + tx.send(b"rld\nhow ".to_vec()).unwrap(); + tx.send(b"are you?".to_vec()).unwrap(); + tx.send(b"".to_vec()).unwrap(); }).detach(); let mut reader = ChanReader::new(rx); @@ -230,7 +234,7 @@ mod test { writer.write_be_u32(42).unwrap(); let wanted = vec![0u8, 0u8, 0u8, 42u8]; - let got = match Thread::spawn(move|| { rx.recv() }).join() { + let got = match Thread::spawn(move|| { rx.recv().unwrap() }).join() { Ok(got) => got, Err(_) => panic!(), }; diff --git a/src/libstd/io/extensions.rs b/src/libstd/io/extensions.rs index c1f1a5b786985..dfea9678277e5 100644 --- a/src/libstd/io/extensions.rs +++ b/src/libstd/io/extensions.rs @@ -175,7 +175,7 @@ pub fn u64_from_be_bytes(data: &[u8], start: uint, size: uint) -> u64 { #[cfg(test)] mod test { - use prelude::*; + use prelude::v1::*; use io; use io::{MemReader, BytesReader}; @@ -507,7 +507,7 @@ mod test { mod bench { extern crate test; - use prelude::*; + use prelude::v1::*; use self::test::Bencher; // why is this a macro? wouldn't an inlined function work just as well? diff --git a/src/libstd/io/fs.rs b/src/libstd/io/fs.rs index 4e736908c3720..20920e6056171 100644 --- a/src/libstd/io/fs.rs +++ b/src/libstd/io/fs.rs @@ -818,7 +818,7 @@ fn access_string(access: FileAccess) -> &'static str { #[allow(unused_variables)] #[allow(unused_mut)] mod test { - use prelude::*; + use prelude::v1::*; use io::{SeekSet, SeekCur, SeekEnd, Read, Open, ReadWrite, FileType}; use io; use str; diff --git a/src/libstd/io/mem.rs b/src/libstd/io/mem.rs index 01151059530f0..71c42273c2219 100644 --- a/src/libstd/io/mem.rs +++ b/src/libstd/io/mem.rs @@ -399,10 +399,11 @@ impl<'a> Buffer for BufReader<'a> { #[cfg(test)] mod test { extern crate "test" as test_crate; + use prelude::v1::*; + use super::*; - use io::*; - use prelude::*; use io; + use io::{SeekSet, SeekCur, SeekEnd}; use self::test_crate::Bencher; #[test] diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index b6f8bb25b6531..0f8b3de48041a 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -233,7 +233,7 @@ use fmt; use int; use iter::{Iterator, IteratorExt}; use mem::transmute; -use ops::{BitOr, BitXor, BitAnd, Sub, Not, FnOnce}; +use ops::FnOnce; use option::Option; use option::Option::{Some, None}; use os; @@ -1960,7 +1960,7 @@ impl fmt::Show for FilePermission { mod tests { use self::BadReaderBehavior::*; use super::{IoResult, Reader, MemReader, NoProgress, InvalidInput}; - use prelude::*; + use prelude::v1::*; use uint; #[deriving(Clone, PartialEq, Show)] diff --git a/src/libstd/io/net/addrinfo.rs b/src/libstd/io/net/addrinfo.rs index 69ba64d856e7f..18993aaa9d0f3 100644 --- a/src/libstd/io/net/addrinfo.rs +++ b/src/libstd/io/net/addrinfo.rs @@ -105,7 +105,7 @@ fn lookup(hostname: Option<&str>, servname: Option<&str>, hint: Option) // permission without help of apk #[cfg(all(test, not(target_os = "android")))] mod test { - use prelude::*; + use prelude::v1::*; use super::*; use io::net::ip::*; diff --git a/src/libstd/io/net/ip.rs b/src/libstd/io/net/ip.rs index add986387daf7..ce6bac0f8c423 100644 --- a/src/libstd/io/net/ip.rs +++ b/src/libstd/io/net/ip.rs @@ -544,7 +544,7 @@ impl<'a> ToSocketAddr for &'a str { #[cfg(test)] mod test { - use prelude::*; + use prelude::v1::*; use super::*; use str::FromStr; diff --git a/src/libstd/io/net/pipe.rs b/src/libstd/io/net/pipe.rs index 4afc72cde711e..68f3a8e183635 100644 --- a/src/libstd/io/net/pipe.rs +++ b/src/libstd/io/net/pipe.rs @@ -20,14 +20,14 @@ #![allow(missing_docs)] -use prelude::*; +use prelude::v1::*; +use c_str::ToCStr; use io::{Listener, Acceptor, IoResult, TimedOut, standard_error}; -use time::Duration; - -use sys::pipe::UnixStream as UnixStreamImp; -use sys::pipe::UnixListener as UnixListenerImp; use sys::pipe::UnixAcceptor as UnixAcceptorImp; +use sys::pipe::UnixListener as UnixListenerImp; +use sys::pipe::UnixStream as UnixStreamImp; +use time::Duration; use sys_common; @@ -264,13 +264,17 @@ impl sys_common::AsInner for UnixAcceptor { } #[cfg(test)] -#[allow(experimental)] mod tests { - use super::*; - use io::*; - use io::test::*; - use prelude::*; + use prelude::v1::*; + use io::fs::PathExtensions; + use io::{EndOfFile, TimedOut, ShortWrite, IoError, ConnectionReset}; + use io::{NotConnected, BrokenPipe, FileNotFound, InvalidInput, OtherIoError}; + use io::{PermissionDenied, Acceptor, Listener}; + use io::test::*; + use super::*; + use sync::mpsc::channel; + use thread::Thread; use time::Duration; pub fn smalltest(server: F, client: G) @@ -282,7 +286,7 @@ mod tests { let mut acceptor = UnixListener::bind(&path1).listen(); - spawn(move|| { + let _t = Thread::spawn(move|| { match UnixStream::connect(&path2) { Ok(c) => client(c), Err(e) => panic!("failed connect: {}", e), @@ -377,7 +381,7 @@ mod tests { Err(e) => panic!("failed listen: {}", e), }; - spawn(move|| { + let _t = Thread::spawn(move|| { for _ in range(0u, times) { let mut stream = UnixStream::connect(&path2); match stream.write(&[100]) { @@ -411,7 +415,7 @@ mod tests { let addr = next_test_unix(); let mut acceptor = UnixListener::bind(&addr).listen(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut s = UnixStream::connect(&addr); let mut buf = [0, 0]; debug!("client reading"); @@ -427,20 +431,20 @@ mod tests { let (tx1, rx1) = channel(); let (tx2, rx2) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut s2 = s2; - rx1.recv(); + rx1.recv().unwrap(); debug!("writer writing"); s2.write(&[1]).unwrap(); debug!("writer done"); - tx2.send(()); + tx2.send(()).unwrap(); }); - tx1.send(()); + tx1.send(()).unwrap(); let mut buf = [0, 0]; debug!("reader reading"); assert_eq!(s1.read(&mut buf), Ok(1)); debug!("reader done"); - rx2.recv(); + rx2.recv().unwrap(); } #[test] @@ -450,30 +454,30 @@ mod tests { let (tx1, rx) = channel(); let tx2 = tx1.clone(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut s = UnixStream::connect(&addr); s.write(&[1]).unwrap(); - rx.recv(); + rx.recv().unwrap(); s.write(&[2]).unwrap(); - rx.recv(); + rx.recv().unwrap(); }); let mut s1 = acceptor.accept().unwrap(); let s2 = s1.clone(); let (done, rx) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut s2 = s2; let mut buf = [0, 0]; s2.read(&mut buf).unwrap(); - tx2.send(()); - done.send(()); + tx2.send(()).unwrap(); + done.send(()).unwrap(); }); let mut buf = [0, 0]; s1.read(&mut buf).unwrap(); - tx1.send(()); + tx1.send(()).unwrap(); - rx.recv(); + rx.recv().unwrap(); } #[test] @@ -481,7 +485,7 @@ mod tests { let addr = next_test_unix(); let mut acceptor = UnixListener::bind(&addr).listen(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut s = UnixStream::connect(&addr); let buf = &mut [0, 1]; s.read(buf).unwrap(); @@ -492,14 +496,14 @@ mod tests { let s2 = s1.clone(); let (tx, rx) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut s2 = s2; s2.write(&[1]).unwrap(); - tx.send(()); + tx.send(()).unwrap(); }); s1.write(&[2]).unwrap(); - rx.recv(); + rx.recv().unwrap(); } #[cfg(not(windows))] @@ -539,10 +543,10 @@ mod tests { // continue to receive any pending connections. let (tx, rx) = channel(); let addr2 = addr.clone(); - spawn(move|| { - tx.send(UnixStream::connect(&addr2).unwrap()); + let _t = Thread::spawn(move|| { + tx.send(UnixStream::connect(&addr2).unwrap()).unwrap(); }); - let l = rx.recv(); + let l = rx.recv().unwrap(); for i in range(0u, 1001) { match a.accept() { Ok(..) => break, @@ -557,7 +561,7 @@ mod tests { // Unset the timeout and make sure that this always blocks. a.set_timeout(None); let addr2 = addr.clone(); - spawn(move|| { + let _t = Thread::spawn(move|| { drop(UnixStream::connect(&addr2).unwrap()); }); a.accept().unwrap(); @@ -595,11 +599,11 @@ mod tests { let addr = next_test_unix(); let a = UnixListener::bind(&addr).listen().unwrap(); let (_tx, rx) = channel::<()>(); - spawn(move|| { + Thread::spawn(move|| { let mut a = a; let _s = a.accept().unwrap(); - let _ = rx.recv_opt(); - }); + let _ = rx.recv(); + }).detach(); let mut b = [0]; let mut s = UnixStream::connect(&addr).unwrap(); @@ -632,25 +636,25 @@ mod tests { let addr = next_test_unix(); let a = UnixListener::bind(&addr).listen().unwrap(); let (_tx, rx) = channel::<()>(); - spawn(move|| { + Thread::spawn(move|| { let mut a = a; let _s = a.accept().unwrap(); - let _ = rx.recv_opt(); - }); + let _ = rx.recv(); + }).detach(); let mut s = UnixStream::connect(&addr).unwrap(); let s2 = s.clone(); let (tx, rx) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut s2 = s2; assert!(s2.read(&mut [0]).is_err()); - tx.send(()); + tx.send(()).unwrap(); }); // this should wake up the child task s.close_read().unwrap(); // this test will never finish if the child doesn't wake up - rx.recv(); + rx.recv().unwrap(); } #[test] @@ -658,12 +662,12 @@ mod tests { let addr = next_test_unix(); let mut a = UnixListener::bind(&addr).listen().unwrap(); let (tx, rx) = channel::<()>(); - spawn(move|| { + Thread::spawn(move|| { let mut s = UnixStream::connect(&addr).unwrap(); - rx.recv(); + rx.recv().unwrap(); assert!(s.write(&[0]).is_ok()); - let _ = rx.recv_opt(); - }); + let _ = rx.recv(); + }).detach(); let mut s = a.accept().unwrap(); s.set_timeout(Some(20)); @@ -686,7 +690,7 @@ mod tests { assert_eq!(s.write(&[0]).err().unwrap().kind, TimedOut); } - tx.send(()); + tx.send(()).unwrap(); s.set_timeout(None); assert_eq!(s.read(&mut [0, 0]), Ok(1)); } @@ -696,9 +700,9 @@ mod tests { let addr = next_test_unix(); let mut a = UnixListener::bind(&addr).listen().unwrap(); let (tx, rx) = channel::<()>(); - spawn(move|| { + Thread::spawn(move|| { let mut s = UnixStream::connect(&addr).unwrap(); - rx.recv(); + rx.recv().unwrap(); let mut amt = 0; while amt < 100 * 128 * 1024 { match s.read(&mut [0, ..128 * 1024]) { @@ -706,15 +710,15 @@ mod tests { Err(e) => panic!("{}", e), } } - let _ = rx.recv_opt(); - }); + let _ = rx.recv(); + }).detach(); let mut s = a.accept().unwrap(); s.set_read_timeout(Some(20)); assert_eq!(s.read(&mut [0]).err().unwrap().kind, TimedOut); assert_eq!(s.read(&mut [0]).err().unwrap().kind, TimedOut); - tx.send(()); + tx.send(()).unwrap(); for _ in range(0u, 100) { assert!(s.write(&[0, ..128 * 1024]).is_ok()); } @@ -725,12 +729,12 @@ mod tests { let addr = next_test_unix(); let mut a = UnixListener::bind(&addr).listen().unwrap(); let (tx, rx) = channel::<()>(); - spawn(move|| { + Thread::spawn(move|| { let mut s = UnixStream::connect(&addr).unwrap(); - rx.recv(); + rx.recv().unwrap(); assert!(s.write(&[0]).is_ok()); - let _ = rx.recv_opt(); - }); + let _ = rx.recv(); + }).detach(); let mut s = a.accept().unwrap(); s.set_write_timeout(Some(20)); @@ -743,7 +747,7 @@ mod tests { if i == 1000 { panic!("should have filled up?!"); } } - tx.send(()); + tx.send(()).unwrap(); assert!(s.read(&mut [0]).is_ok()); } @@ -752,27 +756,27 @@ mod tests { let addr = next_test_unix(); let mut a = UnixListener::bind(&addr).listen().unwrap(); let (tx, rx) = channel::<()>(); - spawn(move|| { + Thread::spawn(move|| { let mut s = UnixStream::connect(&addr).unwrap(); - rx.recv(); + rx.recv().unwrap(); assert!(s.write(&[0]).is_ok()); - let _ = rx.recv_opt(); - }); + let _ = rx.recv(); + }).detach(); let mut s = a.accept().unwrap(); let s2 = s.clone(); let (tx2, rx2) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut s2 = s2; assert!(s2.read(&mut [0]).is_ok()); - tx2.send(()); + tx2.send(()).unwrap(); }); s.set_read_timeout(Some(20)); assert_eq!(s.read(&mut [0]).err().unwrap().kind, TimedOut); - tx.send(()); + tx.send(()).unwrap(); - rx2.recv(); + rx2.recv().unwrap(); } #[cfg(not(windows))] @@ -784,10 +788,10 @@ mod tests { let mut a2 = a.clone(); let addr2 = addr.clone(); - spawn(move|| { + let _t = Thread::spawn(move|| { let _ = UnixStream::connect(&addr2); }); - spawn(move|| { + let _t = Thread::spawn(move|| { let _ = UnixStream::connect(&addr); }); @@ -807,19 +811,25 @@ mod tests { let (tx, rx) = channel(); let tx2 = tx.clone(); - spawn(move|| { let mut a = a; tx.send(a.accept()) }); - spawn(move|| { let mut a = a2; tx2.send(a.accept()) }); + let _t = Thread::spawn(move|| { + let mut a = a; + tx.send(a.accept()).unwrap() + }); + let _t = Thread::spawn(move|| { + let mut a = a2; + tx2.send(a.accept()).unwrap() + }); let addr2 = addr.clone(); - spawn(move|| { + let _t = Thread::spawn(move|| { let _ = UnixStream::connect(&addr2); }); - spawn(move|| { + let _t = Thread::spawn(move|| { let _ = UnixStream::connect(&addr); }); - assert!(rx.recv().is_ok()); - assert!(rx.recv().is_ok()); + assert!(rx.recv().unwrap().is_ok()); + assert!(rx.recv().unwrap().is_ok()); } #[test] @@ -840,12 +850,12 @@ mod tests { let mut a2 = a.clone(); let (tx, rx) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut a = a; - tx.send(a.accept()); + tx.send(a.accept()).unwrap(); }); a2.close_accept().unwrap(); - assert_eq!(rx.recv().err().unwrap().kind, EndOfFile); + assert_eq!(rx.recv().unwrap().err().unwrap().kind, EndOfFile); } } diff --git a/src/libstd/io/net/tcp.rs b/src/libstd/io/net/tcp.rs index 6adb5387f2ef5..57ffcfaad30a7 100644 --- a/src/libstd/io/net/tcp.rs +++ b/src/libstd/io/net/tcp.rs @@ -141,7 +141,7 @@ impl TcpStream { /// let mut stream = TcpStream::connect("127.0.0.1:34254").unwrap(); /// let stream2 = stream.clone(); /// - /// Thread::spawn(move|| { + /// let _t = Thread::spawn(move|| { /// // close this stream after one second /// timer::sleep(Duration::seconds(1)); /// let mut stream = stream2; @@ -282,10 +282,10 @@ impl sys_common::AsInner for TcpStream { /// use std::io::{Acceptor, Listener}; /// use std::thread::Thread; /// -/// let listener = TcpListener::bind("127.0.0.1:80"); +/// let listener = TcpListener::bind("127.0.0.1:80").unwrap(); /// /// // bind the listener to the specified address -/// let mut acceptor = listener.listen(); +/// let mut acceptor = listener.listen().unwrap(); /// /// fn handle_client(mut stream: TcpStream) { /// // ... @@ -423,7 +423,7 @@ impl TcpAcceptor { /// let mut a = TcpListener::bind("127.0.0.1:8482").listen().unwrap(); /// let a2 = a.clone(); /// - /// Thread::spawn(move|| { + /// let _t = Thread::spawn(move|| { /// let mut a2 = a2; /// for socket in a2.incoming() { /// match socket { @@ -482,11 +482,17 @@ impl sys_common::AsInner for TcpAcceptor { #[cfg(test)] #[allow(experimental)] mod test { + use prelude::v1::*; + + use sync::mpsc::channel; + use thread::Thread; use io::net::tcp::*; use io::net::ip::*; - use io::*; use io::test::*; - use prelude::*; + use io::{EndOfFile, TimedOut, ShortWrite, IoError}; + use io::{ConnectionRefused, BrokenPipe, ConnectionAborted}; + use io::{ConnectionReset, NotConnected, PermissionDenied, OtherIoError}; + use io::{Acceptor, Listener}; // FIXME #11530 this fails on android because tests are run as root #[cfg_attr(any(windows, target_os = "android"), ignore)] @@ -512,7 +518,7 @@ mod test { let listener = TcpListener::bind(socket_addr); let mut acceptor = listener.listen(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut stream = TcpStream::connect(("localhost", socket_addr.port)); stream.write(&[144]).unwrap(); }); @@ -528,7 +534,7 @@ mod test { let addr = next_test_ip4(); let mut acceptor = TcpListener::bind(addr).listen(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut stream = TcpStream::connect(("localhost", addr.port)); stream.write(&[64]).unwrap(); }); @@ -544,7 +550,7 @@ mod test { let addr = next_test_ip4(); let mut acceptor = TcpListener::bind(addr).listen(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut stream = TcpStream::connect(("127.0.0.1", addr.port)); stream.write(&[44]).unwrap(); }); @@ -560,7 +566,7 @@ mod test { let addr = next_test_ip6(); let mut acceptor = TcpListener::bind(addr).listen(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut stream = TcpStream::connect(("::1", addr.port)); stream.write(&[66]).unwrap(); }); @@ -576,7 +582,7 @@ mod test { let addr = next_test_ip4(); let mut acceptor = TcpListener::bind(addr).listen(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut stream = TcpStream::connect(addr); stream.write(&[99]).unwrap(); }); @@ -592,7 +598,7 @@ mod test { let addr = next_test_ip6(); let mut acceptor = TcpListener::bind(addr).listen(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut stream = TcpStream::connect(addr); stream.write(&[99]).unwrap(); }); @@ -608,7 +614,7 @@ mod test { let addr = next_test_ip4(); let mut acceptor = TcpListener::bind(addr).listen(); - spawn(move|| { + let _t = Thread::spawn(move|| { let _stream = TcpStream::connect(addr); // Close }); @@ -624,7 +630,7 @@ mod test { let addr = next_test_ip6(); let mut acceptor = TcpListener::bind(addr).listen(); - spawn(move|| { + let _t = Thread::spawn(move|| { let _stream = TcpStream::connect(addr); // Close }); @@ -640,7 +646,7 @@ mod test { let addr = next_test_ip4(); let mut acceptor = TcpListener::bind(addr).listen(); - spawn(move|| { + let _t = Thread::spawn(move|| { let _stream = TcpStream::connect(addr); // Close }); @@ -664,7 +670,7 @@ mod test { let addr = next_test_ip6(); let mut acceptor = TcpListener::bind(addr).listen(); - spawn(move|| { + let _t = Thread::spawn(move|| { let _stream = TcpStream::connect(addr); // Close }); @@ -689,13 +695,13 @@ mod test { let mut acceptor = TcpListener::bind(addr).listen(); let (tx, rx) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { drop(TcpStream::connect(addr)); - tx.send(()); + tx.send(()).unwrap(); }); let mut stream = acceptor.accept(); - rx.recv(); + rx.recv().unwrap(); let buf = [0]; match stream.write(&buf) { Ok(..) => {} @@ -714,13 +720,13 @@ mod test { let mut acceptor = TcpListener::bind(addr).listen(); let (tx, rx) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { drop(TcpStream::connect(addr)); - tx.send(()); + tx.send(()).unwrap(); }); let mut stream = acceptor.accept(); - rx.recv(); + rx.recv().unwrap(); let buf = [0]; match stream.write(&buf) { Ok(..) => {} @@ -739,7 +745,7 @@ mod test { let max = 10u; let mut acceptor = TcpListener::bind(addr).listen(); - spawn(move|| { + let _t = Thread::spawn(move|| { for _ in range(0, max) { let mut stream = TcpStream::connect(addr); stream.write(&[99]).unwrap(); @@ -759,7 +765,7 @@ mod test { let max = 10u; let mut acceptor = TcpListener::bind(addr).listen(); - spawn(move|| { + let _t = Thread::spawn(move|| { for _ in range(0, max) { let mut stream = TcpStream::connect(addr); stream.write(&[99]).unwrap(); @@ -779,11 +785,11 @@ mod test { static MAX: int = 10; let acceptor = TcpListener::bind(addr).listen(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut acceptor = acceptor; for (i, stream) in acceptor.incoming().enumerate().take(MAX as uint) { // Start another task to handle the connection - spawn(move|| { + let _t = Thread::spawn(move|| { let mut stream = stream; let mut buf = [0]; stream.read(&mut buf).unwrap(); @@ -798,7 +804,7 @@ mod test { fn connect(i: int, addr: SocketAddr) { if i == MAX { return } - spawn(move|| { + let _t = Thread::spawn(move|| { debug!("connecting"); let mut stream = TcpStream::connect(addr); // Connect again before writing @@ -815,11 +821,11 @@ mod test { static MAX: int = 10; let acceptor = TcpListener::bind(addr).listen(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut acceptor = acceptor; for (i, stream) in acceptor.incoming().enumerate().take(MAX as uint) { // Start another task to handle the connection - spawn(move|| { + let _t = Thread::spawn(move|| { let mut stream = stream; let mut buf = [0]; stream.read(&mut buf).unwrap(); @@ -834,7 +840,7 @@ mod test { fn connect(i: int, addr: SocketAddr) { if i == MAX { return } - spawn(move|| { + let _t = Thread::spawn(move|| { debug!("connecting"); let mut stream = TcpStream::connect(addr); // Connect again before writing @@ -851,11 +857,11 @@ mod test { let addr = next_test_ip4(); let acceptor = TcpListener::bind(addr).listen(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut acceptor = acceptor; for stream in acceptor.incoming().take(MAX as uint) { // Start another task to handle the connection - spawn(move|| { + let _t = Thread::spawn(move|| { let mut stream = stream; let mut buf = [0]; stream.read(&mut buf).unwrap(); @@ -870,7 +876,7 @@ mod test { fn connect(i: int, addr: SocketAddr) { if i == MAX { return } - spawn(move|| { + let _t = Thread::spawn(move|| { debug!("connecting"); let mut stream = TcpStream::connect(addr); // Connect again before writing @@ -887,11 +893,11 @@ mod test { let addr = next_test_ip6(); let acceptor = TcpListener::bind(addr).listen(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut acceptor = acceptor; for stream in acceptor.incoming().take(MAX as uint) { // Start another task to handle the connection - spawn(move|| { + let _t = Thread::spawn(move|| { let mut stream = stream; let mut buf = [0]; stream.read(&mut buf).unwrap(); @@ -906,7 +912,7 @@ mod test { fn connect(i: int, addr: SocketAddr) { if i == MAX { return } - spawn(move|| { + let _t = Thread::spawn(move|| { debug!("connecting"); let mut stream = TcpStream::connect(addr); // Connect again before writing @@ -929,7 +935,7 @@ mod test { pub fn peer_name(addr: SocketAddr) { let acceptor = TcpListener::bind(addr).listen(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut acceptor = acceptor; acceptor.accept().unwrap(); }); @@ -964,22 +970,22 @@ mod test { fn partial_read() { let addr = next_test_ip4(); let (tx, rx) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut srv = TcpListener::bind(addr).listen().unwrap(); - tx.send(()); + tx.send(()).unwrap(); let mut cl = srv.accept().unwrap(); cl.write(&[10]).unwrap(); let mut b = [0]; cl.read(&mut b).unwrap(); - tx.send(()); + tx.send(()).unwrap(); }); - rx.recv(); + rx.recv().unwrap(); let mut c = TcpStream::connect(addr).unwrap(); let mut b = [0, ..10]; assert_eq!(c.read(&mut b), Ok(1)); c.write(&[1]).unwrap(); - rx.recv(); + rx.recv().unwrap(); } #[test] @@ -1001,20 +1007,20 @@ mod test { let addr = next_test_ip4(); let (tx, rx) = channel(); - spawn(move|| { - rx.recv(); + let _t = Thread::spawn(move|| { + rx.recv().unwrap(); let _stream = TcpStream::connect(addr).unwrap(); // Close - rx.recv(); + rx.recv().unwrap(); }); { let mut acceptor = TcpListener::bind(addr).listen(); - tx.send(()); + tx.send(()).unwrap(); { let _stream = acceptor.accept().unwrap(); // Close client - tx.send(()); + tx.send(()).unwrap(); } // Close listener } @@ -1026,7 +1032,7 @@ mod test { let addr = next_test_ip4(); let mut acceptor = TcpListener::bind(addr).listen(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut s = TcpStream::connect(addr); let mut buf = [0, 0]; assert_eq!(s.read(&mut buf), Ok(1)); @@ -1039,16 +1045,16 @@ mod test { let (tx1, rx1) = channel(); let (tx2, rx2) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut s2 = s2; - rx1.recv(); + rx1.recv().unwrap(); s2.write(&[1]).unwrap(); - tx2.send(()); + tx2.send(()).unwrap(); }); - tx1.send(()); + tx1.send(()).unwrap(); let mut buf = [0, 0]; assert_eq!(s1.read(&mut buf), Ok(1)); - rx2.recv(); + rx2.recv().unwrap(); } #[test] @@ -1058,30 +1064,30 @@ mod test { let (tx1, rx) = channel(); let tx2 = tx1.clone(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut s = TcpStream::connect(addr); s.write(&[1]).unwrap(); - rx.recv(); + rx.recv().unwrap(); s.write(&[2]).unwrap(); - rx.recv(); + rx.recv().unwrap(); }); let mut s1 = acceptor.accept().unwrap(); let s2 = s1.clone(); let (done, rx) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut s2 = s2; let mut buf = [0, 0]; s2.read(&mut buf).unwrap(); - tx2.send(()); - done.send(()); + tx2.send(()).unwrap(); + done.send(()).unwrap(); }); let mut buf = [0, 0]; s1.read(&mut buf).unwrap(); - tx1.send(()); + tx1.send(()).unwrap(); - rx.recv(); + rx.recv().unwrap(); } #[test] @@ -1089,7 +1095,7 @@ mod test { let addr = next_test_ip4(); let mut acceptor = TcpListener::bind(addr).listen(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut s = TcpStream::connect(addr); let mut buf = [0, 1]; s.read(&mut buf).unwrap(); @@ -1100,21 +1106,21 @@ mod test { let s2 = s1.clone(); let (done, rx) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut s2 = s2; s2.write(&[1]).unwrap(); - done.send(()); + done.send(()).unwrap(); }); s1.write(&[2]).unwrap(); - rx.recv(); + rx.recv().unwrap(); } #[test] fn shutdown_smoke() { let addr = next_test_ip4(); let a = TcpListener::bind(addr).unwrap().listen(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut a = a; let mut c = a.accept().unwrap(); assert_eq!(c.read_to_end(), Ok(vec!())); @@ -1148,10 +1154,10 @@ mod test { // flakiness. if !cfg!(target_os = "freebsd") { let (tx, rx) = channel(); - spawn(move|| { - tx.send(TcpStream::connect(addr).unwrap()); + let _t = Thread::spawn(move|| { + tx.send(TcpStream::connect(addr).unwrap()).unwrap(); }); - let _l = rx.recv(); + let _l = rx.recv().unwrap(); for i in range(0i, 1001) { match a.accept() { Ok(..) => break, @@ -1165,7 +1171,7 @@ mod test { // Unset the timeout and make sure that this always blocks. a.set_timeout(None); - spawn(move|| { + let _t = Thread::spawn(move|| { drop(TcpStream::connect(addr).unwrap()); }); a.accept().unwrap(); @@ -1176,11 +1182,11 @@ mod test { let addr = next_test_ip4(); let a = TcpListener::bind(addr).listen().unwrap(); let (_tx, rx) = channel::<()>(); - spawn(move|| { + Thread::spawn(move|| { let mut a = a; let _s = a.accept().unwrap(); - let _ = rx.recv_opt(); - }); + let _ = rx.recv().unwrap(); + }).detach(); let mut b = [0]; let mut s = TcpStream::connect(addr).unwrap(); @@ -1213,25 +1219,25 @@ mod test { let addr = next_test_ip4(); let a = TcpListener::bind(addr).listen().unwrap(); let (_tx, rx) = channel::<()>(); - spawn(move|| { + Thread::spawn(move|| { let mut a = a; let _s = a.accept().unwrap(); - let _ = rx.recv_opt(); - }); + let _ = rx.recv().unwrap(); + }).detach(); let mut s = TcpStream::connect(addr).unwrap(); let s2 = s.clone(); let (tx, rx) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut s2 = s2; assert!(s2.read(&mut [0]).is_err()); - tx.send(()); + tx.send(()).unwrap(); }); // this should wake up the child task s.close_read().unwrap(); // this test will never finish if the child doesn't wake up - rx.recv(); + rx.recv().unwrap(); } #[test] @@ -1239,12 +1245,12 @@ mod test { let addr = next_test_ip6(); let mut a = TcpListener::bind(addr).listen().unwrap(); let (tx, rx) = channel::<()>(); - spawn(move|| { + Thread::spawn(move|| { let mut s = TcpStream::connect(addr).unwrap(); - rx.recv(); + rx.recv().unwrap(); assert!(s.write(&[0]).is_ok()); - let _ = rx.recv_opt(); - }); + let _ = rx.recv(); + }).detach(); let mut s = a.accept().unwrap(); s.set_timeout(Some(20)); @@ -1262,7 +1268,7 @@ mod test { } assert_eq!(s.write(&[0]).err().unwrap().kind, TimedOut); - tx.send(()); + tx.send(()).unwrap(); s.set_timeout(None); assert_eq!(s.read(&mut [0, 0]), Ok(1)); } @@ -1272,9 +1278,9 @@ mod test { let addr = next_test_ip6(); let mut a = TcpListener::bind(addr).listen().unwrap(); let (tx, rx) = channel::<()>(); - spawn(move|| { + Thread::spawn(move|| { let mut s = TcpStream::connect(addr).unwrap(); - rx.recv(); + rx.recv().unwrap(); let mut amt = 0; while amt < 100 * 128 * 1024 { match s.read(&mut [0, ..128 * 1024]) { @@ -1282,15 +1288,15 @@ mod test { Err(e) => panic!("{}", e), } } - let _ = rx.recv_opt(); - }); + let _ = rx.recv(); + }).detach(); let mut s = a.accept().unwrap(); s.set_read_timeout(Some(20)); assert_eq!(s.read(&mut [0]).err().unwrap().kind, TimedOut); assert_eq!(s.read(&mut [0]).err().unwrap().kind, TimedOut); - tx.send(()); + tx.send(()).unwrap(); for _ in range(0i, 100) { assert!(s.write(&[0, ..128 * 1024]).is_ok()); } @@ -1301,12 +1307,12 @@ mod test { let addr = next_test_ip6(); let mut a = TcpListener::bind(addr).listen().unwrap(); let (tx, rx) = channel::<()>(); - spawn(move|| { + Thread::spawn(move|| { let mut s = TcpStream::connect(addr).unwrap(); - rx.recv(); + rx.recv().unwrap(); assert!(s.write(&[0]).is_ok()); - let _ = rx.recv_opt(); - }); + let _ = rx.recv(); + }).detach(); let mut s = a.accept().unwrap(); s.set_write_timeout(Some(20)); @@ -1320,7 +1326,7 @@ mod test { } assert_eq!(s.write(&[0]).err().unwrap().kind, TimedOut); - tx.send(()); + tx.send(()).unwrap(); assert!(s.read(&mut [0]).is_ok()); } @@ -1329,27 +1335,27 @@ mod test { let addr = next_test_ip6(); let mut a = TcpListener::bind(addr).listen().unwrap(); let (tx, rx) = channel::<()>(); - spawn(move|| { + Thread::spawn(move|| { let mut s = TcpStream::connect(addr).unwrap(); - rx.recv(); + rx.recv().unwrap(); assert_eq!(s.write(&[0]), Ok(())); - let _ = rx.recv_opt(); - }); + let _ = rx.recv(); + }).detach(); let mut s = a.accept().unwrap(); let s2 = s.clone(); let (tx2, rx2) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut s2 = s2; assert_eq!(s2.read(&mut [0]), Ok(1)); - tx2.send(()); + tx2.send(()).unwrap(); }); s.set_read_timeout(Some(20)); assert_eq!(s.read(&mut [0]).err().unwrap().kind, TimedOut); - tx.send(()); + tx.send(()).unwrap(); - rx2.recv(); + rx2.recv().unwrap(); } #[test] @@ -1362,21 +1368,21 @@ mod test { let (tx, rx) = channel(); let (txdone, rxdone) = channel(); let txdone2 = txdone.clone(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut tcp = TcpStream::connect(addr).unwrap(); - rx.recv(); + rx.recv().unwrap(); tcp.write_u8(0).unwrap(); - txdone2.send(()); + txdone2.send(()).unwrap(); }); // Spawn off a reading clone let tcp = accept.accept().unwrap(); let tcp2 = tcp.clone(); let txdone3 = txdone.clone(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut tcp2 = tcp2; tcp2.read_u8().unwrap(); - txdone3.send(()); + txdone3.send(()).unwrap(); }); // Try to ensure that the reading clone is indeed reading @@ -1387,9 +1393,9 @@ mod test { // clone the handle again while it's reading, then let it finish the // read. let _ = tcp.clone(); - tx.send(()); - rxdone.recv(); - rxdone.recv(); + tx.send(()).unwrap(); + rxdone.recv().unwrap(); + rxdone.recv().unwrap(); } #[test] @@ -1399,10 +1405,10 @@ mod test { let mut a = l.listen().unwrap(); let mut a2 = a.clone(); - spawn(move|| { + let _t = Thread::spawn(move|| { let _ = TcpStream::connect(addr); }); - spawn(move|| { + let _t = Thread::spawn(move|| { let _ = TcpStream::connect(addr); }); @@ -1420,18 +1426,24 @@ mod test { let (tx, rx) = channel(); let tx2 = tx.clone(); - spawn(move|| { let mut a = a; tx.send(a.accept()) }); - spawn(move|| { let mut a = a2; tx2.send(a.accept()) }); + let _t = Thread::spawn(move|| { + let mut a = a; + tx.send(a.accept()).unwrap(); + }); + let _t = Thread::spawn(move|| { + let mut a = a2; + tx2.send(a.accept()).unwrap(); + }); - spawn(move|| { + let _t = Thread::spawn(move|| { let _ = TcpStream::connect(addr); }); - spawn(move|| { + let _t = Thread::spawn(move|| { let _ = TcpStream::connect(addr); }); - assert!(rx.recv().is_ok()); - assert!(rx.recv().is_ok()); + assert!(rx.recv().unwrap().is_ok()); + assert!(rx.recv().unwrap().is_ok()); } #[test] @@ -1452,12 +1464,12 @@ mod test { let mut a2 = a.clone(); let (tx, rx) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut a = a; - tx.send(a.accept()); + tx.send(a.accept()).unwrap(); }); a2.close_accept().unwrap(); - assert_eq!(rx.recv().err().unwrap().kind, EndOfFile); + assert_eq!(rx.recv().unwrap().err().unwrap().kind, EndOfFile); } } diff --git a/src/libstd/io/net/udp.rs b/src/libstd/io/net/udp.rs index a36703172c3ca..d6c379cc9f760 100644 --- a/src/libstd/io/net/udp.rs +++ b/src/libstd/io/net/udp.rs @@ -248,11 +248,14 @@ impl Writer for UdpStream { #[cfg(test)] #[allow(experimental)] mod test { - use super::*; + use prelude::v1::*; + + use sync::mpsc::channel; use io::net::ip::*; - use io::*; use io::test::*; - use prelude::*; + use io::{IoError, TimedOut, PermissionDenied, ShortWrite}; + use super::*; + use thread::Thread; // FIXME #11530 this fails on android because tests are run as root #[cfg_attr(any(windows, target_os = "android"), ignore)] @@ -272,20 +275,20 @@ mod test { let (tx1, rx1) = channel(); let (tx2, rx2) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { match UdpSocket::bind(client_ip) { Ok(ref mut client) => { - rx1.recv(); + rx1.recv().unwrap(); client.send_to(&[99], server_ip).unwrap() } Err(..) => panic!() } - tx2.send(()); + tx2.send(()).unwrap(); }); match UdpSocket::bind(server_ip) { Ok(ref mut server) => { - tx1.send(()); + tx1.send(()).unwrap(); let mut buf = [0]; match server.recv_from(&mut buf) { Ok((nread, src)) => { @@ -298,7 +301,7 @@ mod test { } Err(..) => panic!() } - rx2.recv(); + rx2.recv().unwrap(); } #[test] @@ -307,10 +310,10 @@ mod test { let client_ip = next_test_ip6(); let (tx, rx) = channel::<()>(); - spawn(move|| { + let _t = Thread::spawn(move|| { match UdpSocket::bind(client_ip) { Ok(ref mut client) => { - rx.recv(); + rx.recv().unwrap(); client.send_to(&[99], server_ip).unwrap() } Err(..) => panic!() @@ -319,7 +322,7 @@ mod test { match UdpSocket::bind(server_ip) { Ok(ref mut server) => { - tx.send(()); + tx.send(()).unwrap(); let mut buf = [0]; match server.recv_from(&mut buf) { Ok((nread, src)) => { @@ -343,7 +346,7 @@ mod test { let (tx1, rx1) = channel(); let (tx2, rx2) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { let send_as = |ip, val: &[u8]| { match UdpSocket::bind(ip) { Ok(client) => { @@ -354,17 +357,17 @@ mod test { Err(..) => panic!() } }; - rx1.recv(); + rx1.recv().unwrap(); send_as(dummy_ip, &[98]); send_as(client_ip, &[99]); - tx2.send(()); + tx2.send(()).unwrap(); }); match UdpSocket::bind(server_ip) { Ok(server) => { let server = box server; let mut stream = server.connect(client_ip); - tx1.send(()); + tx1.send(()).unwrap(); let mut buf = [0]; match stream.read(&mut buf) { Ok(nread) => { @@ -376,7 +379,7 @@ mod test { } Err(..) => panic!() } - rx2.recv(); + rx2.recv().unwrap(); } #[test] @@ -387,24 +390,24 @@ mod test { let (tx1, rx1) = channel(); let (tx2, rx2) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { match UdpSocket::bind(client_ip) { Ok(client) => { let client = box client; let mut stream = client.connect(server_ip); - rx1.recv(); + rx1.recv().unwrap(); stream.write(&[99]).unwrap(); } Err(..) => panic!() } - tx2.send(()); + tx2.send(()).unwrap(); }); match UdpSocket::bind(server_ip) { Ok(server) => { let server = box server; let mut stream = server.connect(client_ip); - tx1.send(()); + tx1.send(()).unwrap(); let mut buf = [0]; match stream.read(&mut buf) { Ok(nread) => { @@ -416,7 +419,7 @@ mod test { } Err(..) => panic!() } - rx2.recv(); + rx2.recv().unwrap(); } pub fn socket_name(addr: SocketAddr) { @@ -449,7 +452,7 @@ mod test { let mut sock1 = UdpSocket::bind(addr1).unwrap(); let sock2 = UdpSocket::bind(addr2).unwrap(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut sock2 = sock2; let mut buf = [0, 0]; assert_eq!(sock2.recv_from(&mut buf), Ok((1, addr1))); @@ -461,16 +464,16 @@ mod test { let (tx1, rx1) = channel(); let (tx2, rx2) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut sock3 = sock3; - rx1.recv(); + rx1.recv().unwrap(); sock3.send_to(&[1], addr2).unwrap(); - tx2.send(()); + tx2.send(()).unwrap(); }); - tx1.send(()); + tx1.send(()).unwrap(); let mut buf = [0, 0]; assert_eq!(sock1.recv_from(&mut buf), Ok((1, addr2))); - rx2.recv(); + rx2.recv().unwrap(); } #[test] @@ -482,29 +485,29 @@ mod test { let (tx1, rx) = channel(); let tx2 = tx1.clone(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut sock2 = sock2; sock2.send_to(&[1], addr1).unwrap(); - rx.recv(); + rx.recv().unwrap(); sock2.send_to(&[2], addr1).unwrap(); - rx.recv(); + rx.recv().unwrap(); }); let sock3 = sock1.clone(); let (done, rx) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut sock3 = sock3; let mut buf = [0, 0]; sock3.recv_from(&mut buf).unwrap(); - tx2.send(()); - done.send(()); + tx2.send(()).unwrap(); + done.send(()).unwrap(); }); let mut buf = [0, 0]; sock1.recv_from(&mut buf).unwrap(); - tx1.send(()); + tx1.send(()).unwrap(); - rx.recv(); + rx.recv().unwrap(); } #[test] @@ -517,38 +520,38 @@ mod test { let (tx, rx) = channel(); let (serv_tx, serv_rx) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut sock2 = sock2; let mut buf = [0, 1]; - rx.recv(); + rx.recv().unwrap(); match sock2.recv_from(&mut buf) { Ok(..) => {} Err(e) => panic!("failed receive: {}", e), } - serv_tx.send(()); + serv_tx.send(()).unwrap(); }); let sock3 = sock1.clone(); let (done, rx) = channel(); let tx2 = tx.clone(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut sock3 = sock3; match sock3.send_to(&[1], addr2) { - Ok(..) => { let _ = tx2.send_opt(()); } + Ok(..) => { let _ = tx2.send(()); } Err(..) => {} } - done.send(()); + done.send(()).unwrap(); }); match sock1.send_to(&[2], addr2) { - Ok(..) => { let _ = tx.send_opt(()); } + Ok(..) => { let _ = tx.send(()); } Err(..) => {} } drop(tx); - rx.recv(); - serv_rx.recv(); + rx.recv().unwrap(); + serv_rx.recv().unwrap(); } #[cfg(not(windows))] // FIXME #17553 @@ -561,14 +564,14 @@ mod test { let (tx, rx) = channel(); let (tx2, rx2) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut a = a2; assert_eq!(a.recv_from(&mut [0]), Ok((1, addr1))); assert_eq!(a.send_to(&[0], addr1), Ok(())); - rx.recv(); + rx.recv().unwrap(); assert_eq!(a.send_to(&[0], addr1), Ok(())); - tx2.send(()); + tx2.send(()).unwrap(); }); // Make sure that reads time out, but writes can continue @@ -583,11 +586,11 @@ mod test { // Clearing the timeout should allow for receiving a.set_timeout(None); - tx.send(()); + tx.send(()).unwrap(); assert_eq!(a2.recv_from(&mut [0]), Ok((1, addr2))); // Make sure the child didn't die - rx2.recv(); + rx2.recv().unwrap(); } #[test] diff --git a/src/libstd/io/pipe.rs b/src/libstd/io/pipe.rs index 73a893c4f2dcd..ee3766582838a 100644 --- a/src/libstd/io/pipe.rs +++ b/src/libstd/io/pipe.rs @@ -15,7 +15,7 @@ #![allow(missing_docs)] -use prelude::*; +use prelude::v1::*; use io::IoResult; use libc; @@ -112,7 +112,10 @@ impl Writer for PipeStream { #[cfg(test)] mod test { - use prelude::*; + use prelude::v1::*; + + use sync::mpsc::channel; + use thread::Thread; #[test] fn partial_read() { @@ -123,14 +126,14 @@ mod test { let out = PipeStream::open(writer); let mut input = PipeStream::open(reader); let (tx, rx) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut out = out; out.write(&[10]).unwrap(); - rx.recv(); // don't close the pipe until the other read has finished + rx.recv().unwrap(); // don't close the pipe until the other read has finished }); let mut buf = [0, ..10]; input.read(&mut buf).unwrap(); - tx.send(()); + tx.send(()).unwrap(); } } diff --git a/src/libstd/io/process.rs b/src/libstd/io/process.rs index 93aa627ffba13..1e008287a3167 100644 --- a/src/libstd/io/process.rs +++ b/src/libstd/io/process.rs @@ -16,25 +16,25 @@ pub use self::StdioContainer::*; pub use self::ProcessExit::*; -use prelude::*; +use prelude::v1::*; +use c_str::{CString, ToCStr}; +use collections::HashMap; use fmt; -use os; +use hash::Hash; +use io::pipe::{PipeStream, PipePair}; use io::{IoResult, IoError}; use io; use libc; -use c_str::CString; -use collections::HashMap; -use hash::Hash; -#[cfg(windows)] -use std::hash::sip::SipState; -use io::pipe::{PipeStream, PipePair}; +use os; use path::BytesContainer; -use thread::Thread; - -use sys; +use sync::mpsc::{channel, Receiver}; use sys::fs::FileDesc; use sys::process::Process as ProcessImp; +use sys; +use thread::Thread; + +#[cfg(windows)] use std::hash::sip::SipState; /// Signal a process to exit, without forcibly killing it. Corresponds to /// SIGTERM on unix platforms. @@ -693,10 +693,10 @@ impl Process { Some(stream) => { Thread::spawn(move |:| { let mut stream = stream; - tx.send(stream.read_to_end()) + tx.send(stream.read_to_end()).unwrap(); }).detach(); } - None => tx.send(Ok(Vec::new())) + None => tx.send(Ok(Vec::new())).unwrap() } rx } @@ -707,8 +707,8 @@ impl Process { Ok(ProcessOutput { status: status, - output: stdout.recv().ok().unwrap_or(Vec::new()), - error: stderr.recv().ok().unwrap_or(Vec::new()), + output: stdout.recv().unwrap().unwrap_or(Vec::new()), + error: stderr.recv().unwrap().unwrap_or(Vec::new()), }) } @@ -741,16 +741,19 @@ impl Drop for Process { #[cfg(test)] mod tests { - #![allow(unused_imports)] + use prelude::v1::*; - use super::*; - use io::timer::*; - use io::*; - use prelude::*; use io::fs::PathExtensions; - use time::Duration; - use str; + use io::process; + use io::timer::*; + use io::{Truncate, Write, TimedOut, timer, FileNotFound}; use rt::running_on_valgrind; + use str; + use super::{CreatePipe}; + use super::{InheritFd, Process, PleaseExitSignal, Command, ProcessOutput}; + use sync::mpsc::channel; + use thread::Thread; + use time::Duration; // FIXME(#10380) these tests should not all be ignored on android. @@ -1154,22 +1157,22 @@ mod tests { fn wait_timeout2() { let (tx, rx) = channel(); let tx2 = tx.clone(); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut p = sleeper(); p.set_timeout(Some(10)); assert_eq!(p.wait().err().unwrap().kind, TimedOut); p.signal_kill().unwrap(); - tx.send(()); + tx.send(()).unwrap(); }); - spawn(move|| { + let _t = Thread::spawn(move|| { let mut p = sleeper(); p.set_timeout(Some(10)); assert_eq!(p.wait().err().unwrap().kind, TimedOut); p.signal_kill().unwrap(); - tx2.send(()); + tx2.send(()).unwrap(); }); - rx.recv(); - rx.recv(); + rx.recv().unwrap(); + rx.recv().unwrap(); } #[test] diff --git a/src/libstd/io/result.rs b/src/libstd/io/result.rs index 32965d23971ed..c1474650f1eb4 100644 --- a/src/libstd/io/result.rs +++ b/src/libstd/io/result.rs @@ -78,7 +78,7 @@ impl> Acceptor for IoResult { #[cfg(test)] mod test { - use prelude::*; + use prelude::v1::*; use super::super::mem::*; use io; diff --git a/src/libstd/io/stdio.rs b/src/libstd/io/stdio.rs index 6bd721599f341..74b0930a14500 100644 --- a/src/libstd/io/stdio.rs +++ b/src/libstd/io/stdio.rs @@ -540,8 +540,11 @@ impl Writer for StdWriter { #[cfg(test)] mod tests { + use prelude::v1::*; + use super::*; - use prelude::*; + use sync::mpsc::channel; + use thread::Thread; #[test] fn smoke() { @@ -557,7 +560,7 @@ mod tests { let (tx, rx) = channel(); let (mut r, w) = (ChanReader::new(rx), ChanWriter::new(tx)); - spawn(move|| { + let _t = Thread::spawn(move|| { set_stdout(box w); println!("hello!"); }); @@ -570,7 +573,7 @@ mod tests { let (tx, rx) = channel(); let (mut r, w) = (ChanReader::new(rx), ChanWriter::new(tx)); - spawn(move|| { + let _t = Thread::spawn(move || -> () { set_stderr(box w); panic!("my special message"); }); diff --git a/src/libstd/io/test.rs b/src/libstd/io/test.rs index af56735021e86..9c6033f37c93c 100644 --- a/src/libstd/io/test.rs +++ b/src/libstd/io/test.rs @@ -12,9 +12,10 @@ #![macro_escape] +use prelude::v1::*; + use libc; use os; -use prelude::*; use std::io::net::ip::*; use sync::atomic::{AtomicUint, INIT_ATOMIC_UINT, Relaxed}; diff --git a/src/libstd/io/timer.rs b/src/libstd/io/timer.rs index 953effe4345ce..e073f76af825c 100644 --- a/src/libstd/io/timer.rs +++ b/src/libstd/io/timer.rs @@ -15,7 +15,7 @@ // FIXME: These functions take Durations but only pass ms to the backend impls. -use comm::{Receiver, Sender, channel}; +use sync::mpsc::{Receiver, Sender, channel}; use time::Duration; use io::IoResult; use sys::timer::Callback; @@ -40,11 +40,11 @@ use sys::timer::Timer as TimerImp; /// /// let timeout = timer.oneshot(Duration::milliseconds(10)); /// // do some work -/// timeout.recv(); // wait for the timeout to expire +/// timeout.recv().unwrap(); // wait for the timeout to expire /// /// let periodic = timer.periodic(Duration::milliseconds(10)); /// loop { -/// periodic.recv(); +/// periodic.recv().unwrap(); /// // this loop is only executed once every 10ms /// } /// # } @@ -126,7 +126,7 @@ impl Timer { /// for _ in range(0u, 100) { /* do work */ } /// /// // blocks until 10 ms after the `oneshot` call - /// ten_milliseconds.recv(); + /// ten_milliseconds.recv().unwrap(); /// ``` /// /// ```rust @@ -136,7 +136,7 @@ impl Timer { /// // Incorrect, method chaining-style: /// let mut five_ms = Timer::new().unwrap().oneshot(Duration::milliseconds(5)); /// // The timer object was destroyed, so this will always fail: - /// // five_ms.recv() + /// // five_ms.recv().unwrap() /// ``` /// /// When provided a zero or negative `duration`, the message will @@ -147,7 +147,7 @@ impl Timer { if in_ms_u64(duration) != 0 { self.inner.oneshot(in_ms_u64(duration), box TimerCallback { tx: tx }); } else { - tx.send(()); + tx.send(()).unwrap(); } return rx } @@ -178,13 +178,13 @@ impl Timer { /// for _ in range(0u, 100) { /* do work */ } /// /// // blocks until 10 ms after the `periodic` call - /// ten_milliseconds.recv(); + /// ten_milliseconds.recv().unwrap(); /// /// for _ in range(0u, 100) { /* do work */ } /// /// // blocks until 20 ms after the `periodic` call (*not* 10ms after the /// // previous `recv`) - /// ten_milliseconds.recv(); + /// ten_milliseconds.recv().unwrap(); /// ``` /// /// ```rust @@ -194,7 +194,7 @@ impl Timer { /// // Incorrect, method chaining-style. /// let mut five_ms = Timer::new().unwrap().periodic(Duration::milliseconds(5)); /// // The timer object was destroyed, so this will always fail: - /// // five_ms.recv() + /// // five_ms.recv().unwrap() /// ``` /// /// When provided a zero or negative `duration`, the messages will @@ -213,7 +213,7 @@ impl Timer { impl Callback for TimerCallback { fn call(&mut self) { - let _ = self.tx.send_opt(()); + let _ = self.tx.send(()); } } @@ -225,9 +225,8 @@ fn in_ms_u64(d: Duration) -> u64 { #[cfg(test)] mod test { - use prelude::*; - use super::Timer; + use thread::Thread; use time::Duration; #[test] @@ -239,7 +238,7 @@ mod test { #[test] fn test_io_timer_sleep_oneshot() { let mut timer = Timer::new().unwrap(); - timer.oneshot(Duration::milliseconds(1)).recv(); + timer.oneshot(Duration::milliseconds(1)).recv().unwrap(); } #[test] @@ -253,8 +252,8 @@ mod test { let mut timer = Timer::new().unwrap(); let rx1 = timer.oneshot(Duration::milliseconds(10000)); let rx = timer.oneshot(Duration::milliseconds(1)); - rx.recv(); - assert_eq!(rx1.recv_opt(), Err(())); + rx.recv().unwrap(); + assert!(rx1.recv().is_err()); } #[test] @@ -263,16 +262,16 @@ mod test { let rx = timer.oneshot(Duration::milliseconds(100000000)); timer.sleep(Duration::milliseconds(1)); // this should invalidate rx - assert_eq!(rx.recv_opt(), Err(())); + assert!(rx.recv().is_err()); } #[test] fn test_io_timer_sleep_periodic() { let mut timer = Timer::new().unwrap(); let rx = timer.periodic(Duration::milliseconds(1)); - rx.recv(); - rx.recv(); - rx.recv(); + rx.recv().unwrap(); + rx.recv().unwrap(); + rx.recv().unwrap(); } #[test] @@ -291,12 +290,12 @@ mod test { let mut timer = Timer::new().unwrap(); let rx = timer.oneshot(Duration::milliseconds(1)); - rx.recv(); - assert!(rx.recv_opt().is_err()); + rx.recv().unwrap(); + assert!(rx.recv().is_err()); let rx = timer.oneshot(Duration::milliseconds(1)); - rx.recv(); - assert!(rx.recv_opt().is_err()); + rx.recv().unwrap(); + assert!(rx.recv().is_err()); } #[test] @@ -305,20 +304,20 @@ mod test { let orx = timer.oneshot(Duration::milliseconds(100)); let prx = timer.periodic(Duration::milliseconds(100)); timer.sleep(Duration::milliseconds(1)); - assert_eq!(orx.recv_opt(), Err(())); - assert_eq!(prx.recv_opt(), Err(())); - timer.oneshot(Duration::milliseconds(1)).recv(); + assert!(orx.recv().is_err()); + assert!(prx.recv().is_err()); + timer.oneshot(Duration::milliseconds(1)).recv().unwrap(); } #[test] fn period() { let mut timer = Timer::new().unwrap(); let rx = timer.periodic(Duration::milliseconds(1)); - rx.recv(); - rx.recv(); + rx.recv().unwrap(); + rx.recv().unwrap(); let rx2 = timer.periodic(Duration::milliseconds(1)); - rx2.recv(); - rx2.recv(); + rx2.recv().unwrap(); + rx2.recv().unwrap(); } #[test] @@ -357,9 +356,9 @@ mod test { let mut timer = Timer::new().unwrap(); let timer_rx = timer.periodic(Duration::milliseconds(1000)); - spawn(move|| { - let _ = timer_rx.recv_opt(); - }); + Thread::spawn(move|| { + let _ = timer_rx.recv(); + }).detach(); // when we drop the TimerWatcher we're going to destroy the channel, // which must wake up the task on the other end @@ -371,9 +370,9 @@ mod test { let mut timer = Timer::new().unwrap(); let timer_rx = timer.periodic(Duration::milliseconds(1000)); - spawn(move|| { - let _ = timer_rx.recv_opt(); - }); + Thread::spawn(move|| { + let _ = timer_rx.recv(); + }).detach(); timer.oneshot(Duration::milliseconds(1)); } @@ -384,9 +383,9 @@ mod test { let mut timer = Timer::new().unwrap(); let timer_rx = timer.periodic(Duration::milliseconds(1000)); - spawn(move|| { - let _ = timer_rx.recv_opt(); - }); + Thread::spawn(move|| { + let _ = timer_rx.recv(); + }).detach(); timer.sleep(Duration::milliseconds(1)); } @@ -397,7 +396,7 @@ mod test { let mut timer = Timer::new().unwrap(); timer.oneshot(Duration::milliseconds(1000)) }; - assert_eq!(rx.recv_opt(), Err(())); + assert!(rx.recv().is_err()); } #[test] @@ -406,7 +405,7 @@ mod test { let mut timer = Timer::new().unwrap(); timer.periodic(Duration::milliseconds(1000)) }; - assert_eq!(rx.recv_opt(), Err(())); + assert!(rx.recv().is_err()); } #[test] @@ -445,34 +444,34 @@ mod test { fn oneshot_zero() { let mut timer = Timer::new().unwrap(); let rx = timer.oneshot(Duration::milliseconds(0)); - rx.recv(); + rx.recv().unwrap(); } #[test] fn oneshot_negative() { let mut timer = Timer::new().unwrap(); let rx = timer.oneshot(Duration::milliseconds(-1000000)); - rx.recv(); + rx.recv().unwrap(); } #[test] fn periodic_zero() { let mut timer = Timer::new().unwrap(); let rx = timer.periodic(Duration::milliseconds(0)); - rx.recv(); - rx.recv(); - rx.recv(); - rx.recv(); + rx.recv().unwrap(); + rx.recv().unwrap(); + rx.recv().unwrap(); + rx.recv().unwrap(); } #[test] fn periodic_negative() { let mut timer = Timer::new().unwrap(); let rx = timer.periodic(Duration::milliseconds(-1000000)); - rx.recv(); - rx.recv(); - rx.recv(); - rx.recv(); + rx.recv().unwrap(); + rx.recv().unwrap(); + rx.recv().unwrap(); + rx.recv().unwrap(); } } diff --git a/src/libstd/io/util.rs b/src/libstd/io/util.rs index 18fabcbd1a2a4..b22090e0f163a 100644 --- a/src/libstd/io/util.rs +++ b/src/libstd/io/util.rs @@ -10,7 +10,7 @@ //! Utility implementations of Reader and Writer -use prelude::*; +use prelude::v1::*; use cmp; use io; use slice::bytes::MutableByteVector; @@ -280,7 +280,7 @@ mod test { use io; use boxed::Box; use super::*; - use prelude::*; + use prelude::v1::*; #[test] fn test_limit_reader_unlimited() { @@ -384,7 +384,7 @@ mod test { let mut r = TeeReader::new(MemReader::new(vec!(0, 1, 2)), Vec::new()); assert_eq!(vec!(0, 1, 2), r.read_to_end().unwrap()); - let (_, w) = r.unwrap(); + let (_, w) = r.into_inner(); assert_eq!(vec!(0, 1, 2), w); } diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index 8274baeacfad8..aa1a0add0681a 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -226,7 +226,6 @@ pub mod hash; pub mod task; pub mod thread; pub mod sync; -pub mod comm; #[cfg(unix)] #[path = "sys/unix/mod.rs"] mod sys; @@ -254,7 +253,7 @@ mod std { pub use cmp; pub use hash; - pub use comm; // used for select!() + pub use sync; // used for select!() pub use error; // used for try!() pub use fmt; // used for any formatting strings pub use io; // used for println!() @@ -264,6 +263,7 @@ mod std { pub use cell; // used for tls! pub use thread_local; // used for thread_local! pub use kinds; // used for tls! + pub use ops; // used for bitflags! // The test runner calls ::std::os::args() but really wants realstd #[cfg(test)] pub use realstd::os as os; diff --git a/src/libstd/macros.rs b/src/libstd/macros.rs index edb6218c5cc0b..51a0853687ebe 100644 --- a/src/libstd/macros.rs +++ b/src/libstd/macros.rs @@ -474,6 +474,7 @@ macro_rules! vec { /// /// ``` /// use std::thread::Thread; +/// use std::sync::mpsc::channel; /// /// let (tx1, rx1) = channel(); /// let (tx2, rx2) = channel(); @@ -484,21 +485,21 @@ macro_rules! vec { /// Thread::spawn(move|| { tx2.send(calculate_the_answer()) }).detach(); /// /// select! ( -/// () = rx1.recv() => println!("the long running task finished first"), +/// _ = rx1.recv() => println!("the long running task finished first"), /// answer = rx2.recv() => { -/// println!("the answer was: {}", answer); +/// println!("the answer was: {}", answer.unwrap()); /// } /// ) /// ``` /// -/// For more information about select, see the `std::comm::Select` structure. +/// For more information about select, see the `std::sync::mpsc::Select` structure. #[macro_export] #[experimental] macro_rules! select { ( $($name:pat = $rx:ident.$meth:ident() => $code:expr),+ ) => ({ - use std::comm::Select; + use std::sync::mpsc::Select; let sel = Select::new(); $( let mut $rx = sel.handle(&$rx); )+ unsafe { diff --git a/src/libstd/num/f32.rs b/src/libstd/num/f32.rs index 1f76382ce8a41..f2a0419e39196 100644 --- a/src/libstd/num/f32.rs +++ b/src/libstd/num/f32.rs @@ -15,7 +15,7 @@ #![allow(unsigned_negation)] #![doc(primitive = "f32")] -use prelude::*; +use prelude::v1::*; use intrinsics; use libc::c_int; @@ -496,23 +496,25 @@ mod tests { #[test] fn test_real_consts() { - let pi: f32 = Float::pi(); - let two_pi: f32 = Float::two_pi(); - let frac_pi_2: f32 = Float::frac_pi_2(); - let frac_pi_3: f32 = Float::frac_pi_3(); - let frac_pi_4: f32 = Float::frac_pi_4(); - let frac_pi_6: f32 = Float::frac_pi_6(); - let frac_pi_8: f32 = Float::frac_pi_8(); - let frac_1_pi: f32 = Float::frac_1_pi(); - let frac_2_pi: f32 = Float::frac_2_pi(); - let frac_2_sqrtpi: f32 = Float::frac_2_sqrtpi(); - let sqrt2: f32 = Float::sqrt2(); - let frac_1_sqrt2: f32 = Float::frac_1_sqrt2(); - let e: f32 = Float::e(); - let log2_e: f32 = Float::log2_e(); - let log10_e: f32 = Float::log10_e(); - let ln_2: f32 = Float::ln_2(); - let ln_10: f32 = Float::ln_10(); + use super::consts; + + let pi: f32 = consts::PI; + let two_pi: f32 = consts::PI_2; + let frac_pi_2: f32 = consts::FRAC_PI_2; + let frac_pi_3: f32 = consts::FRAC_PI_3; + let frac_pi_4: f32 = consts::FRAC_PI_4; + let frac_pi_6: f32 = consts::FRAC_PI_6; + let frac_pi_8: f32 = consts::FRAC_PI_8; + let frac_1_pi: f32 = consts::FRAC_1_PI; + let frac_2_pi: f32 = consts::FRAC_2_PI; + let frac_2_sqrtpi: f32 = consts::FRAC_2_SQRTPI; + let sqrt2: f32 = consts::SQRT2; + let frac_1_sqrt2: f32 = consts::FRAC_1_SQRT2; + let e: f32 = consts::E; + let log2_e: f32 = consts::LOG2_E; + let log10_e: f32 = consts::LOG10_E; + let ln_2: f32 = consts::LN_2; + let ln_10: f32 = consts::LN_10; assert_approx_eq!(two_pi, 2f32 * pi); assert_approx_eq!(frac_pi_2, pi / 2f32); diff --git a/src/libstd/num/f64.rs b/src/libstd/num/f64.rs index 221ecf62c058d..105a8a23bd104 100644 --- a/src/libstd/num/f64.rs +++ b/src/libstd/num/f64.rs @@ -14,7 +14,7 @@ #![allow(missing_docs)] #![doc(primitive = "f64")] -use prelude::*; +use prelude::v1::*; use intrinsics; use libc::c_int; @@ -499,23 +499,24 @@ mod tests { #[test] fn test_real_consts() { - let pi: f64 = Float::pi(); - let two_pi: f64 = Float::two_pi(); - let frac_pi_2: f64 = Float::frac_pi_2(); - let frac_pi_3: f64 = Float::frac_pi_3(); - let frac_pi_4: f64 = Float::frac_pi_4(); - let frac_pi_6: f64 = Float::frac_pi_6(); - let frac_pi_8: f64 = Float::frac_pi_8(); - let frac_1_pi: f64 = Float::frac_1_pi(); - let frac_2_pi: f64 = Float::frac_2_pi(); - let frac_2_sqrtpi: f64 = Float::frac_2_sqrtpi(); - let sqrt2: f64 = Float::sqrt2(); - let frac_1_sqrt2: f64 = Float::frac_1_sqrt2(); - let e: f64 = Float::e(); - let log2_e: f64 = Float::log2_e(); - let log10_e: f64 = Float::log10_e(); - let ln_2: f64 = Float::ln_2(); - let ln_10: f64 = Float::ln_10(); + use super::consts; + let pi: f64 = consts::PI; + let two_pi: f64 = consts::PI_2; + let frac_pi_2: f64 = consts::FRAC_PI_2; + let frac_pi_3: f64 = consts::FRAC_PI_3; + let frac_pi_4: f64 = consts::FRAC_PI_4; + let frac_pi_6: f64 = consts::FRAC_PI_6; + let frac_pi_8: f64 = consts::FRAC_PI_8; + let frac_1_pi: f64 = consts::FRAC_1_PI; + let frac_2_pi: f64 = consts::FRAC_2_PI; + let frac_2_sqrtpi: f64 = consts::FRAC_2_SQRTPI; + let sqrt2: f64 = consts::SQRT2; + let frac_1_sqrt2: f64 = consts::FRAC_1_SQRT2; + let e: f64 = consts::E; + let log2_e: f64 = consts::LOG2_E; + let log10_e: f64 = consts::LOG10_E; + let ln_2: f64 = consts::LN_2; + let ln_10: f64 = consts::LN_10; assert_approx_eq!(two_pi, 2.0 * pi); assert_approx_eq!(frac_pi_2, pi / 2f64); diff --git a/src/libstd/num/mod.rs b/src/libstd/num/mod.rs index 7c8763979bb36..01aa21c692bf5 100644 --- a/src/libstd/num/mod.rs +++ b/src/libstd/num/mod.rs @@ -147,7 +147,7 @@ pub fn test_num(ten: T, two: T) where #[cfg(test)] mod tests { - use prelude::*; + use prelude::v1::*; use super::*; use i8; use i16; @@ -800,7 +800,7 @@ mod bench { extern crate test; use self::test::Bencher; use num::Int; - use prelude::*; + use prelude::v1::*; #[bench] fn bench_pow_function(b: &mut Bencher) { diff --git a/src/libstd/num/uint_macros.rs b/src/libstd/num/uint_macros.rs index c42b7eebfdd1c..61fd754018eba 100644 --- a/src/libstd/num/uint_macros.rs +++ b/src/libstd/num/uint_macros.rs @@ -49,8 +49,9 @@ pub fn to_str_bytes(n: $T, radix: uint, f: F) -> U where #[cfg(test)] mod tests { - use prelude::*; + use prelude::v1::*; use num::FromStrRadix; + use str::from_str; #[test] pub fn test_from_str() { diff --git a/src/libstd/os.rs b/src/libstd/os.rs index ceb9a4102f635..754b13886af7e 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -1424,8 +1424,9 @@ mod arch_consts { #[cfg(test)] mod tests { - use prelude::*; - use option; + use prelude::v1::*; + + use iter::repeat; use os::{env, getcwd, getenv, make_absolute}; use os::{split_paths, join_paths, setenv, unsetenv}; use os; @@ -1454,7 +1455,7 @@ mod tests { fn test_setenv() { let n = make_rand_name(); setenv(n.as_slice(), "VALUE"); - assert_eq!(getenv(n.as_slice()), option::Option::Some("VALUE".to_string())); + assert_eq!(getenv(n.as_slice()), Some("VALUE".to_string())); } #[test] @@ -1462,7 +1463,7 @@ mod tests { let n = make_rand_name(); setenv(n.as_slice(), "VALUE"); unsetenv(n.as_slice()); - assert_eq!(getenv(n.as_slice()), option::Option::None); + assert_eq!(getenv(n.as_slice()), None); } #[test] @@ -1471,9 +1472,9 @@ mod tests { let n = make_rand_name(); setenv(n.as_slice(), "1"); setenv(n.as_slice(), "2"); - assert_eq!(getenv(n.as_slice()), option::Option::Some("2".to_string())); + assert_eq!(getenv(n.as_slice()), Some("2".to_string())); setenv(n.as_slice(), ""); - assert_eq!(getenv(n.as_slice()), option::Option::Some("".to_string())); + assert_eq!(getenv(n.as_slice()), Some("".to_string())); } // Windows GetEnvironmentVariable requires some extra work to make sure @@ -1490,7 +1491,7 @@ mod tests { let n = make_rand_name(); setenv(n.as_slice(), s.as_slice()); debug!("{}", s.clone()); - assert_eq!(getenv(n.as_slice()), option::Option::Some(s)); + assert_eq!(getenv(n.as_slice()), Some(s)); } #[test] @@ -1527,14 +1528,14 @@ mod tests { // MingW seems to set some funky environment variables like // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned // from env() but not visible from getenv(). - assert!(v2.is_none() || v2 == option::Option::Some(v)); + assert!(v2.is_none() || v2 == Some(v)); } } #[test] fn test_env_set_get_huge() { let n = make_rand_name(); - let s = "x".repeat(10000).to_string(); + let s = repeat("x").take(10000).collect::(); setenv(n.as_slice(), s.as_slice()); assert_eq!(getenv(n.as_slice()), Some(s)); unsetenv(n.as_slice()); @@ -1656,8 +1657,8 @@ mod tests { path.push("mmap_file.tmp"); let size = MemoryMap::granularity() * 2; let mut file = File::open_mode(&path, Open, ReadWrite).unwrap(); - file.seek(size as i64, SeekSet); - file.write_u8(0); + file.seek(size as i64, SeekSet).unwrap(); + file.write_u8(0).unwrap(); let chunk = MemoryMap::new(size / 2, &[ MapOption::MapReadable, diff --git a/src/libstd/path/mod.rs b/src/libstd/path/mod.rs index 30f3f56bc1c10..024dc56073d04 100644 --- a/src/libstd/path/mod.rs +++ b/src/libstd/path/mod.rs @@ -931,7 +931,9 @@ fn contains_nul(v: &T) -> bool { #[cfg(test)] mod tests { - use prelude::*; + use prelude::v1::*; + use c_str::ToCStr; + use path::{WindowsPath, PosixPath}; #[test] fn test_cstring() { diff --git a/src/libstd/path/posix.rs b/src/libstd/path/posix.rs index d941665f0482f..5c415239c5e2f 100644 --- a/src/libstd/path/posix.rs +++ b/src/libstd/path/posix.rs @@ -447,10 +447,7 @@ static dot_dot_static: &'static [u8] = b".."; #[cfg(test)] mod tests { - use super::*; - use prelude::Option::{mod, Some, None}; - use prelude::{Vec, Clone, AsSlice, SliceExt, CloneSliceExt, IteratorExt}; - use prelude::{DoubleEndedIteratorExt, Str, StrExt, ToString, GenericPath}; + use prelude::v1::*; use str; macro_rules! t { @@ -1239,7 +1236,7 @@ mod bench { extern crate test; use self::test::Bencher; use super::*; - use prelude::*; + use prelude::v1::*; #[bench] fn join_home_dir(b: &mut Bencher) { diff --git a/src/libstd/path/windows.rs b/src/libstd/path/windows.rs index ea381bc0577d6..9117827ffc2b4 100644 --- a/src/libstd/path/windows.rs +++ b/src/libstd/path/windows.rs @@ -1119,12 +1119,13 @@ fn prefix_len(p: Option) -> uint { #[cfg(test)] mod tests { - use super::*; - use prelude::Option::{mod, Some, None}; - use prelude::{Vec, Clone, AsSlice, SliceExt, CloneSliceExt, IteratorExt}; - use prelude::{DoubleEndedIteratorExt, Str, ToString, GenericPath}; + use prelude::v1::Option::{mod, Some, None}; + use prelude::v1::{Vec, Clone, AsSlice, SliceExt, CloneSliceExt, IteratorExt}; + use prelude::v1::{DoubleEndedIteratorExt, Str, ToString, GenericPath}; + use super::PathPrefix::*; use super::parse_prefix; + use super::*; macro_rules! t { (s: $path:expr, $exp:expr) => ( diff --git a/src/libstd/prelude.rs b/src/libstd/prelude.rs deleted file mode 100644 index d1540f98a2355..0000000000000 --- a/src/libstd/prelude.rs +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The Rust prelude -//! -//! Because `std` is required by most serious Rust software, it is -//! imported at the topmost level of every crate by default, as if the -//! first line of each crate was -//! -//! ```ignore -//! extern crate std; -//! ``` -//! -//! This means that the contents of std can be accessed from any context -//! with the `std::` path prefix, as in `use std::vec`, `use std::task::spawn`, -//! etc. -//! -//! Additionally, `std` contains a `prelude` module that reexports many of the -//! most common traits, types and functions. The contents of the prelude are -//! imported into every *module* by default. Implicitly, all modules behave as if -//! they contained the following prologue: -//! -//! ```ignore -//! use std::prelude::*; -//! ``` -//! -//! The prelude is primarily concerned with exporting *traits* that are so -//! pervasive that it would be obnoxious to import for every use, particularly -//! those that define methods on primitive types. It does include a few -//! particularly useful standalone functions, like `from_str`, `range`, and -//! `drop`, `spawn`, and `channel`. - -#![experimental] - -// Reexported core operators -#[doc(no_inline)] pub use kinds::{Copy, Send, Sized, Sync}; -#[doc(no_inline)] pub use ops::{Add, Sub, Mul, Div, Rem, Neg, Not}; -#[doc(no_inline)] pub use ops::{BitAnd, BitOr, BitXor}; -#[doc(no_inline)] pub use ops::{Drop, Deref, DerefMut}; -#[doc(no_inline)] pub use ops::{Shl, Shr}; -#[doc(no_inline)] pub use ops::{Index, IndexMut}; -#[doc(no_inline)] pub use ops::{Slice, SliceMut}; -#[doc(no_inline)] pub use ops::{Fn, FnMut, FnOnce}; - -// Reexported functions -#[doc(no_inline)] pub use iter::range; -#[doc(no_inline)] pub use mem::drop; -#[doc(no_inline)] pub use str::from_str; - -// Reexported types and traits - -#[doc(no_inline)] pub use borrow::IntoCow; -#[doc(no_inline)] pub use c_str::ToCStr; -#[doc(no_inline)] pub use char::{Char, UnicodeChar}; -#[doc(no_inline)] pub use clone::Clone; -#[doc(no_inline)] pub use cmp::{PartialEq, PartialOrd, Eq, Ord}; -#[doc(no_inline)] pub use cmp::{Ordering, Equiv}; -#[doc(no_inline)] pub use cmp::Ordering::{Less, Equal, Greater}; -#[doc(no_inline)] pub use iter::{FromIterator, Extend, ExactSizeIterator}; -#[doc(no_inline)] pub use iter::{Iterator, IteratorExt, DoubleEndedIterator}; -#[doc(no_inline)] pub use iter::{DoubleEndedIteratorExt, CloneIteratorExt}; -#[doc(no_inline)] pub use iter::{RandomAccessIterator, IteratorCloneExt}; -#[doc(no_inline)] pub use iter::{IteratorOrdExt, MutableDoubleEndedIterator}; -#[doc(no_inline)] pub use num::{ToPrimitive, FromPrimitive}; -#[doc(no_inline)] pub use boxed::Box; -#[doc(no_inline)] pub use option::Option; -#[doc(no_inline)] pub use option::Option::{Some, None}; -#[doc(no_inline)] pub use path::{GenericPath, Path, PosixPath, WindowsPath}; -#[doc(no_inline)] pub use ptr::{RawPtr, RawMutPtr}; -#[doc(no_inline)] pub use result::Result; -#[doc(no_inline)] pub use result::Result::{Ok, Err}; -#[doc(no_inline)] pub use io::{Buffer, Writer, Reader, Seek, BufferPrelude}; -#[doc(no_inline)] pub use core::prelude::{Tuple1, Tuple2, Tuple3, Tuple4}; -#[doc(no_inline)] pub use core::prelude::{Tuple5, Tuple6, Tuple7, Tuple8}; -#[doc(no_inline)] pub use core::prelude::{Tuple9, Tuple10, Tuple11, Tuple12}; -#[doc(no_inline)] pub use str::{Str, StrVector}; -#[doc(no_inline)] pub use str::StrExt; -#[doc(no_inline)] pub use slice::AsSlice; -#[doc(no_inline)] pub use slice::{VectorVector, PartialEqSliceExt}; -#[doc(no_inline)] pub use slice::{CloneSliceExt, OrdSliceExt, SliceExt}; -#[doc(no_inline)] pub use slice::{BoxedSliceExt}; -#[doc(no_inline)] pub use string::{IntoString, String, ToString}; -#[doc(no_inline)] pub use vec::Vec; - -// Reexported runtime types -#[doc(no_inline)] pub use comm::{sync_channel, channel}; -#[doc(no_inline)] pub use comm::{SyncSender, Sender, Receiver}; -#[doc(no_inline)] pub use task::spawn; diff --git a/src/libstd/prelude/mod.rs b/src/libstd/prelude/mod.rs new file mode 100644 index 0000000000000..da945b4c9fa08 --- /dev/null +++ b/src/libstd/prelude/mod.rs @@ -0,0 +1,42 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The Rust prelude +//! +//! Because `std` is required by most serious Rust software, it is +//! imported at the topmost level of every crate by default, as if the +//! first line of each crate was +//! +//! ```ignore +//! extern crate std; +//! ``` +//! +//! This means that the contents of std can be accessed from any context +//! with the `std::` path prefix, as in `use std::vec`, `use std::task::spawn`, +//! etc. +//! +//! Additionally, `std` contains a `prelude` module that reexports many of the +//! most common traits, types and functions. The contents of the prelude are +//! imported into every *module* by default. Implicitly, all modules behave as if +//! they contained the following prologue: +//! +//! ```ignore +//! use std::prelude::v1::*; +//! ``` +//! +//! The prelude is primarily concerned with exporting *traits* that are so +//! pervasive that it would be obnoxious to import for every use, particularly +//! those that define methods on primitive types. + +#[cfg(stage0)] +pub use self::v1::*; + +#[stable] +pub mod v1; diff --git a/src/libstd/prelude/v1.rs b/src/libstd/prelude/v1.rs new file mode 100644 index 0000000000000..8c4189c37e75c --- /dev/null +++ b/src/libstd/prelude/v1.rs @@ -0,0 +1,50 @@ +// Copyright 2013 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The first version of the prelude of the standard library. + +#![stable] + +// Reexported core operators +#[stable] #[doc(no_inline)] pub use kinds::{Copy, Send, Sized, Sync}; +#[stable] #[doc(no_inline)] pub use ops::{Drop, Fn, FnMut, FnOnce}; + +// Reexported functions +#[stable] #[doc(no_inline)] pub use mem::drop; + +// Reexported types and traits + +#[stable] #[doc(no_inline)] pub use boxed::Box; +#[stable] #[doc(no_inline)] pub use char::{Char, UnicodeChar}; +#[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::DoubleEndedIteratorExt; +#[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::{mod, Some, None}; +#[stable] #[doc(no_inline)] pub use ptr::{RawPtr, RawMutPtr}; +#[stable] #[doc(no_inline)] pub use result::Result::{mod, Ok, Err}; +#[stable] #[doc(no_inline)] pub use slice::AsSlice; +#[stable] #[doc(no_inline)] pub use slice::{BoxedSliceExt, SliceExt}; +#[stable] #[doc(no_inline)] pub use slice::{CloneSliceExt, OrdSliceExt}; +#[stable] #[doc(no_inline)] pub use slice::{VectorVector, PartialEqSliceExt}; +#[stable] #[doc(no_inline)] pub use str::{Str, StrVector, StrExt}; +#[stable] #[doc(no_inline)] pub use string::{String, ToString}; +#[stable] #[doc(no_inline)] pub use vec::Vec; + +// NB: remove when path reform lands +#[doc(no_inline)] pub use path::{Path, GenericPath}; +// NB: remove when I/O reform lands +#[doc(no_inline)] pub use io::{Buffer, Writer, Reader, Seek, BufferPrelude}; +// NB: remove when range syntax lands +#[doc(no_inline)] pub use iter::range; diff --git a/src/libstd/rand/mod.rs b/src/libstd/rand/mod.rs index c590c0f575ee6..4371fe7e59a01 100644 --- a/src/libstd/rand/mod.rs +++ b/src/libstd/rand/mod.rs @@ -419,7 +419,7 @@ pub fn sample, R: Rng>(rng: &mut R, #[cfg(test)] mod test { - use prelude::*; + use prelude::v1::*; use super::{Rng, task_rng, random, SeedableRng, StdRng, sample}; use iter::order; @@ -615,7 +615,7 @@ static RAND_BENCH_N: u64 = 100; #[cfg(test)] mod bench { extern crate test; - use prelude::*; + use prelude::v1::*; use self::test::Bencher; use super::{XorShiftRng, StdRng, IsaacRng, Isaac64Rng, Rng, RAND_BENCH_N}; diff --git a/src/libstd/rand/os.rs b/src/libstd/rand/os.rs index 68c99b1275855..0a7b9d07636ad 100644 --- a/src/libstd/rand/os.rs +++ b/src/libstd/rand/os.rs @@ -335,10 +335,11 @@ mod imp { #[cfg(test)] mod test { - use prelude::*; + use prelude::v1::*; - use super::OsRng; + use sync::mpsc::channel; use rand::Rng; + use super::OsRng; use thread::Thread; #[test] @@ -362,7 +363,7 @@ mod test { Thread::spawn(move|| { // wait until all the tasks are ready to go. - rx.recv(); + rx.recv().unwrap(); // deschedule to attempt to interleave things as much // as possible (XXX: is this a good test?) @@ -383,7 +384,7 @@ mod test { // start all the tasks for tx in txs.iter() { - tx.send(()) + tx.send(()).unwrap(); } } } diff --git a/src/libstd/rand/reader.rs b/src/libstd/rand/reader.rs index 7298b2ef0acc7..642ab3d1e8674 100644 --- a/src/libstd/rand/reader.rs +++ b/src/libstd/rand/reader.rs @@ -74,7 +74,7 @@ impl Rng for ReaderRng { #[cfg(test)] mod test { - use prelude::*; + use prelude::v1::*; use super::ReaderRng; use io::MemReader; diff --git a/src/libstd/rt/args.rs b/src/libstd/rt/args.rs index b1f268597c7ad..1fedf9652a000 100644 --- a/src/libstd/rt/args.rs +++ b/src/libstd/rt/args.rs @@ -44,7 +44,7 @@ pub fn clone() -> Option>> { imp::clone() } target_os = "freebsd", target_os = "dragonfly"))] mod imp { - use prelude::*; + use prelude::v1::*; use mem; use slice; @@ -107,7 +107,7 @@ mod imp { #[cfg(test)] mod tests { - use prelude::*; + use prelude::v1::*; use finally::Finally; use super::*; diff --git a/src/libstd/rt/backtrace.rs b/src/libstd/rt/backtrace.rs index 775e9bb526f7c..d4101bb215219 100644 --- a/src/libstd/rt/backtrace.rs +++ b/src/libstd/rt/backtrace.rs @@ -12,7 +12,7 @@ #![allow(non_camel_case_types)] -use prelude::*; +use prelude::v1::*; use os; use sync::atomic; @@ -39,7 +39,7 @@ pub fn log_enabled() -> bool { #[cfg(test)] mod test { - use prelude::*; + use prelude::v1::*; use sys_common; macro_rules! t { ($a:expr, $b:expr) => ({ let mut m = Vec::new(); diff --git a/src/libstd/rt/exclusive.rs b/src/libstd/rt/exclusive.rs index 88bdb29caecad..eb6b365544457 100644 --- a/src/libstd/rt/exclusive.rs +++ b/src/libstd/rt/exclusive.rs @@ -83,7 +83,7 @@ impl<'a, T: Send> DerefMut for ExclusiveGuard<'a, T> { #[cfg(test)] mod tests { - use prelude::*; + use prelude::v1::*; use sync::Arc; use super::Exclusive; use task; diff --git a/src/libstd/rt/mod.rs b/src/libstd/rt/mod.rs index d64336569c6e9..eb446edbbd8d8 100644 --- a/src/libstd/rt/mod.rs +++ b/src/libstd/rt/mod.rs @@ -23,14 +23,10 @@ #![allow(dead_code)] -use os; -use thunk::Thunk; use kinds::Send; -use thread::Thread; use ops::FnOnce; use sys; -use sys_common; -use sys_common::thread_info::{mod, NewThread}; +use thunk::Thunk; // Reexport some of our utilities which are expected by other crates. pub use self::util::{default_sched_threads, min_stack, running_on_valgrind}; @@ -65,9 +61,14 @@ const OS_DEFAULT_STACK_ESTIMATE: uint = 2 * (1 << 20); #[cfg(not(test))] #[lang = "start"] fn lang_start(main: *const u8, argc: int, argv: *const *const u8) -> int { + use prelude::v1::*; + use mem; - use prelude::*; + use os; use rt; + use sys_common::thread_info::{mod, NewThread}; + use sys_common; + use thread::Thread; let something_around_the_top_of_the_stack = 1; let addr = &something_around_the_top_of_the_stack as *const int; diff --git a/src/libstd/rt/task.rs b/src/libstd/rt/task.rs index 98940a2b381c7..a8d5216e20281 100644 --- a/src/libstd/rt/task.rs +++ b/src/libstd/rt/task.rs @@ -496,7 +496,7 @@ impl Death { #[cfg(test)] mod test { use super::*; - use prelude::*; + use prelude::v1::*; use task; use rt::unwind; diff --git a/src/libstd/rt/unwind.rs b/src/libstd/rt/unwind.rs index 261a8335173d0..8c35eb5828426 100644 --- a/src/libstd/rt/unwind.rs +++ b/src/libstd/rt/unwind.rs @@ -57,7 +57,7 @@ //! //! Currently Rust uses unwind runtime provided by libgcc. -use prelude::*; +use prelude::v1::*; use any::Any; use cell::Cell; diff --git a/src/libstd/rt/util.rs b/src/libstd/rt/util.rs index 26dadfd9fb1db..d6c0e4a5aea55 100644 --- a/src/libstd/rt/util.rs +++ b/src/libstd/rt/util.rs @@ -10,13 +10,12 @@ // // ignore-lexer-test FIXME #15677 -use prelude::*; +use prelude::v1::*; use cmp; use fmt; use intrinsics; -use libc::uintptr_t; -use libc; +use libc::{mod, uintptr_t}; use os; use slice; use str; diff --git a/src/libstd/sync/atomic.rs b/src/libstd/sync/atomic.rs index 26778ef70b3ca..5d45836af80ed 100644 --- a/src/libstd/sync/atomic.rs +++ b/src/libstd/sync/atomic.rs @@ -180,7 +180,7 @@ impl Drop for AtomicOption { #[cfg(test)] mod test { - use prelude::*; + use prelude::v1::*; use super::*; #[test] diff --git a/src/libstd/sync/barrier.rs b/src/libstd/sync/barrier.rs index 6cdb199819aff..55d50af3b8365 100644 --- a/src/libstd/sync/barrier.rs +++ b/src/libstd/sync/barrier.rs @@ -89,10 +89,11 @@ impl Barrier { #[cfg(test)] mod tests { - use prelude::*; + use prelude::v1::*; use sync::{Arc, Barrier}; - use comm::Empty; + use sync::mpsc::{channel, TryRecvError}; + use thread::Thread; #[test] fn test_barrier() { @@ -102,23 +103,23 @@ mod tests { for _ in range(0u, 9) { let c = barrier.clone(); let tx = tx.clone(); - spawn(move|| { + Thread::spawn(move|| { c.wait(); - tx.send(true); - }); + tx.send(true).unwrap(); + }).detach(); } // At this point, all spawned tasks should be blocked, // so we shouldn't get anything from the port assert!(match rx.try_recv() { - Err(Empty) => true, + Err(TryRecvError::Empty) => true, _ => false, }); barrier.wait(); // Now, the barrier is cleared and we should get data. for _ in range(0u, 9) { - rx.recv(); + rx.recv().unwrap(); } } } diff --git a/src/libstd/sync/condvar.rs b/src/libstd/sync/condvar.rs index f1940bfd829b7..28960c1574e92 100644 --- a/src/libstd/sync/condvar.rs +++ b/src/libstd/sync/condvar.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use prelude::*; +use prelude::v1::*; use sync::atomic::{mod, AtomicUint}; use sync::{mutex, StaticMutexGuard}; @@ -262,11 +262,13 @@ impl StaticCondvar { #[cfg(test)] mod tests { - use prelude::*; + use prelude::v1::*; - use time::Duration; use super::{StaticCondvar, CONDVAR_INIT}; + use sync::mpsc::channel; use sync::{StaticMutex, MUTEX_INIT, Condvar, Mutex, Arc}; + use thread::Thread; + use time::Duration; #[test] fn smoke() { @@ -289,7 +291,7 @@ mod tests { static M: StaticMutex = MUTEX_INIT; let g = M.lock(); - spawn(move|| { + let _t = Thread::spawn(move|| { let _g = M.lock(); C.notify_one(); }); @@ -307,30 +309,30 @@ mod tests { for _ in range(0, N) { let data = data.clone(); let tx = tx.clone(); - spawn(move|| { + Thread::spawn(move|| { let &(ref lock, ref cond) = &*data; let mut cnt = lock.lock(); *cnt += 1; if *cnt == N { - tx.send(()); + tx.send(()).unwrap(); } while *cnt != 0 { cond.wait(&cnt); } - tx.send(()); - }); + tx.send(()).unwrap(); + }).detach(); } drop(tx); let &(ref lock, ref cond) = &*data; - rx.recv(); + rx.recv().unwrap(); let mut cnt = lock.lock(); *cnt = 0; cond.notify_all(); drop(cnt); for _ in range(0, N) { - rx.recv(); + rx.recv().unwrap(); } } @@ -341,7 +343,7 @@ mod tests { let g = M.lock(); assert!(!C.wait_timeout(&g, Duration::nanoseconds(1000))); - spawn(move|| { + let _t = Thread::spawn(move|| { let _g = M.lock(); C.notify_one(); }); @@ -358,7 +360,7 @@ mod tests { static C: StaticCondvar = CONDVAR_INIT; let g = M1.lock(); - spawn(move|| { + let _t = Thread::spawn(move|| { let _g = M1.lock(); C.notify_one(); }); diff --git a/src/libstd/sync/future.rs b/src/libstd/sync/future.rs index 51899a87a325d..e3620617d5735 100644 --- a/src/libstd/sync/future.rs +++ b/src/libstd/sync/future.rs @@ -28,7 +28,7 @@ use core::prelude::*; use core::mem::replace; use self::FutureState::*; -use comm::{Receiver, channel}; +use sync::mpsc::{Receiver, channel}; use thunk::{Thunk}; use thread::Thread; @@ -122,8 +122,8 @@ impl Future { * waiting for the result to be received on the port. */ - Future::from_fn(move|:| { - rx.recv() + Future::from_fn(move |:| { + rx.recv().unwrap() }) } @@ -141,7 +141,7 @@ impl Future { Thread::spawn(move |:| { // Don't panic if the other end has hung up - let _ = tx.send_opt(blk()); + let _ = tx.send(blk()); }).detach(); Future::from_receiver(rx) @@ -150,9 +150,10 @@ impl Future { #[cfg(test)] mod test { - use prelude::*; + use prelude::v1::*; + use sync::mpsc::channel; use sync::Future; - use task; + use thread::Thread; #[test] fn test_from_value() { @@ -163,7 +164,7 @@ mod test { #[test] fn test_from_receiver() { let (tx, rx) = channel(); - tx.send("whale".to_string()); + tx.send("whale".to_string()).unwrap(); let mut f = Future::from_receiver(rx); assert_eq!(f.get(), "whale"); } @@ -183,7 +184,7 @@ mod test { #[test] fn test_interface_unwrap() { let f = Future::from_value("fail".to_string()); - assert_eq!(f.unwrap(), "fail"); + assert_eq!(f.into_inner(), "fail"); } #[test] @@ -210,10 +211,10 @@ mod test { let expected = "schlorf"; let (tx, rx) = channel(); let f = Future::spawn(move|| { expected }); - task::spawn(move|| { + let _t = Thread::spawn(move|| { let mut f = f; - tx.send(f.get()); + tx.send(f.get()).unwrap(); }); - assert_eq!(rx.recv(), expected); + assert_eq!(rx.recv().unwrap(), expected); } } diff --git a/src/libstd/sync/mod.rs b/src/libstd/sync/mod.rs index 7605a6a96a005..2b7311e4e982b 100644 --- a/src/libstd/sync/mod.rs +++ b/src/libstd/sync/mod.rs @@ -32,6 +32,8 @@ pub use self::future::Future; pub use self::task_pool::TaskPool; pub mod atomic; +pub mod mpsc; + mod barrier; mod condvar; mod future; diff --git a/src/libstd/comm/blocking.rs b/src/libstd/sync/mpsc/blocking.rs similarity index 100% rename from src/libstd/comm/blocking.rs rename to src/libstd/sync/mpsc/blocking.rs diff --git a/src/libstd/comm/mod.rs b/src/libstd/sync/mpsc/mod.rs similarity index 62% rename from src/libstd/comm/mod.rs rename to src/libstd/sync/mpsc/mod.rs index c85bea87218ff..e2294906229dc 100644 --- a/src/libstd/comm/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). These channels are //! -//! 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(10i); +//! tx.send(10i).unwrap(); //! }).detach(); -//! assert_eq!(rx.recv(), 10i); +//! 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; //! } @@ -312,38 +313,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 self::Flavor::*; - -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::*; - - $(#[$a])* #[test] fn f() { $b } - } - ) -} - mod blocking; mod oneshot; mod select; @@ -355,7 +337,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>, } @@ -367,14 +349,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>, } @@ -385,30 +367,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. +#[deriving(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. +#[deriving(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()"] +#[deriving(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()"] +#[deriving(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. @@ -416,10 +418,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 { @@ -458,6 +463,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 @@ -467,18 +473,18 @@ 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(Oneshot(a.clone())), Receiver::new(Oneshot(a))) + (Sender::new(Flavor::Oneshot(a.clone())), Receiver::new(Flavor::Oneshot(a))) } /// Creates a new synchronous, bounded channel. @@ -499,26 +505,26 @@ 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); +/// tx.send(1i).unwrap(); /// /// Thread::spawn(move|| { /// // this will block until the previous message has been received -/// tx.send(2i); +/// tx.send(2i).unwrap(); /// }).detach(); /// -/// assert_eq!(rx.recv(), 1i); -/// assert_eq!(rx.recv(), 2i); +/// 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(Sync(a))) + (SyncSender::new(a.clone()), Receiver::new(Flavor::Sync(a))) } //////////////////////////////////////////////////////////////////////////////// @@ -532,33 +538,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. /// @@ -570,37 +549,34 @@ 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(1i), Ok(())); + /// tx.send(1i).unwrap(); /// /// // This send will fail because the receiver is gone /// drop(rx); - /// assert_eq!(tx.send_opt(1i), Err(1)); + /// assert_eq!(tx.send(1i).err().unwrap().0, 1); /// ``` - #[unstable = "this function may be renamed to send() in the future"] - pub fn send_opt(&self, t: T) -> Result<(), T> { + pub fn send(&self, t: T) -> Result<(), SendError> { let (new_inner, ret) = match *unsafe { self.inner() } { - Oneshot(ref p) => { + Flavor::Oneshot(ref p) => { 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(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) @@ -618,16 +594,20 @@ impl Sender { } } } - Stream(ref p) => return unsafe { (*p.get()).send(t) }, - Shared(ref p) => return unsafe { (*p.get()).send(t) }, - Sync(..) => unreachable!(), + 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!(), }; unsafe { - let tmp = Sender::new(Stream(new_inner)); + let tmp = Sender::new(Flavor::Stream(new_inner)); mem::swap(self.inner_mut(), tmp.inner_mut()); } - return ret; + ret.map_err(SendError) } } @@ -635,42 +615,44 @@ impl Sender { impl Clone for Sender { fn clone(&self) -> Sender { let (packet, sleeper, guard) = match *unsafe { self.inner() } { - Oneshot(ref p) => { + Flavor::Oneshot(ref p) => { let a = Arc::new(RacyCell::new(shared::Packet::new())); unsafe { let guard = (*a.get()).postinit_lock(); - match (*p.get()).upgrade(Receiver::new(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) } } } - Stream(ref p) => { + Flavor::Stream(ref p) => { let a = Arc::new(RacyCell::new(shared::Packet::new())); unsafe { let guard = (*a.get()).postinit_lock(); - match (*p.get()).upgrade(Receiver::new(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), } } } - Shared(ref p) => { + Flavor::Shared(ref p) => { unsafe { (*p.get()).clone_chan(); } - return Sender::new(Shared(p.clone())); + return Sender::new(Flavor::Shared(p.clone())); } - Sync(..) => unreachable!(), + Flavor::Sync(..) => unreachable!(), }; unsafe { (*packet.get()).inherit_blocker(sleeper, guard); - let tmp = Sender::new(Shared(packet.clone())); + let tmp = Sender::new(Flavor::Shared(packet.clone())); mem::swap(self.inner_mut(), tmp.inner_mut()); } - Sender::new(Shared(packet)) + Sender::new(Flavor::Shared(packet)) } } @@ -678,10 +660,10 @@ impl Clone for Sender { impl Drop for Sender { fn drop(&mut self) { match *unsafe { self.inner_mut() } { - Oneshot(ref mut p) => unsafe { (*p.get()).drop_chan(); }, - Stream(ref mut p) => unsafe { (*p.get()).drop_chan(); }, - Shared(ref mut p) => unsafe { (*p.get()).drop_chan(); }, - Sync(..) => unreachable!(), + Flavor::Oneshot(ref mut p) => unsafe { (*p.get()).drop_chan(); }, + Flavor::Stream(ref mut p) => unsafe { (*p.get()).drop_chan(); }, + Flavor::Shared(ref mut p) => unsafe { (*p.get()).drop_chan(); }, + Flavor::Sync(..) => unreachable!(), } } } @@ -701,59 +683,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) } } @@ -783,34 +735,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 @@ -819,42 +743,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() } { - Oneshot(ref p) => { + 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, } } - Stream(ref p) => { + 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, } } - Shared(ref p) => { + 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) + } } } - Sync(ref p) => { + 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) + } } } }; @@ -865,46 +793,47 @@ 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() } { - Oneshot(ref p) => { + 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, } } - Stream(ref p) => { + Flavor::Stream(ref p) => { 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, } } - Shared(ref p) => { + Flavor::Shared(ref p) => { 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), } } - 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()); @@ -914,9 +843,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 } } } @@ -924,22 +853,22 @@ impl select::Packet for Receiver { fn can_recv(&self) -> bool { loop { let new_port = match *unsafe { self.inner() } { - Oneshot(ref p) => { + Flavor::Oneshot(ref p) => { match unsafe { (*p.get()).can_recv() } { Ok(ret) => return ret, Err(upgrade) => upgrade, } } - Stream(ref p) => { + Flavor::Stream(ref p) => { match unsafe { (*p.get()).can_recv() } { Ok(ret) => return ret, Err(upgrade) => upgrade, } } - Shared(ref p) => { + Flavor::Shared(ref p) => { return unsafe { (*p.get()).can_recv() }; } - Sync(ref p) => { + Flavor::Sync(ref p) => { return unsafe { (*p.get()).can_recv() }; } }; @@ -953,24 +882,24 @@ impl select::Packet for Receiver { fn start_selection(&self, mut token: SignalToken) -> StartResult { loop { let (t, new_port) = match *unsafe { self.inner() } { - Oneshot(ref p) => { + Flavor::Oneshot(ref p) => { match unsafe { (*p.get()).start_selection(token) } { oneshot::SelSuccess => return Installed, oneshot::SelCanceled => return Abort, oneshot::SelUpgraded(t, rx) => (t, rx), } } - Stream(ref p) => { + Flavor::Stream(ref p) => { match unsafe { (*p.get()).start_selection(token) } { stream::SelSuccess => return Installed, stream::SelCanceled => return Abort, stream::SelUpgraded(t, rx) => (t, rx), } } - Shared(ref p) => { + Flavor::Shared(ref p) => { return unsafe { (*p.get()).start_selection(token) }; } - Sync(ref p) => { + Flavor::Sync(ref p) => { return unsafe { (*p.get()).start_selection(token) }; } }; @@ -985,14 +914,14 @@ impl select::Packet for Receiver { let mut was_upgrade = false; loop { let result = match *unsafe { self.inner() } { - Oneshot(ref p) => unsafe { (*p.get()).abort_selection() }, - Stream(ref p) => unsafe { + Flavor::Oneshot(ref p) => unsafe { (*p.get()).abort_selection() }, + Flavor::Stream(ref p) => unsafe { (*p.get()).abort_selection(was_upgrade) }, - Shared(ref p) => return unsafe { + Flavor::Shared(ref p) => return unsafe { (*p.get()).abort_selection(was_upgrade) }, - Sync(ref p) => return unsafe { + Flavor::Sync(ref p) => return unsafe { (*p.get()).abort_selection() }, }; @@ -1007,18 +936,18 @@ impl select::Packet for Receiver { } #[unstable] -impl<'a, T: Send> Iterator for Messages<'a, T> { - fn next(&mut self) -> Option { self.rx.recv_opt().ok() } +impl<'a, T: Send> Iterator for Iter<'a, T> { + fn next(&mut self) -> Option { self.rx.recv().ok() } } #[unsafe_destructor] impl Drop for Receiver { fn drop(&mut self) { match *unsafe { self.inner_mut() } { - Oneshot(ref mut p) => unsafe { (*p.get()).drop_port(); }, - Stream(ref mut p) => unsafe { (*p.get()).drop_port(); }, - Shared(ref mut p) => unsafe { (*p.get()).drop_port(); }, - Sync(ref mut p) => unsafe { (*p.get()).drop_port(); }, + Flavor::Oneshot(ref mut p) => unsafe { (*p.get()).drop_port(); }, + Flavor::Stream(ref mut p) => unsafe { (*p.get()).drop_port(); }, + Flavor::Shared(ref mut p) => unsafe { (*p.get()).drop_port(); }, + Flavor::Sync(ref mut p) => unsafe { (*p.get()).drop_port(); }, } } } @@ -1041,368 +970,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::*; + 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(); @@ -1412,69 +1398,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 { @@ -1483,49 +1473,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(); } @@ -1533,303 +1525,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); @@ -1839,69 +1862,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 { @@ -1910,49 +1937,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(); } @@ -1960,92 +1989,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/comm/mpsc_queue.rs b/src/libstd/sync/mpsc/mpsc_queue.rs similarity index 96% rename from src/libstd/comm/mpsc_queue.rs rename to src/libstd/sync/mpsc/mpsc_queue.rs index cddef23666434..8945233dac9cd 100644 --- a/src/libstd/comm/mpsc_queue.rs +++ b/src/libstd/sync/mpsc/mpsc_queue.rs @@ -153,11 +153,12 @@ impl Drop for Queue { #[cfg(test)] mod tests { - use prelude::*; - - use alloc::arc::Arc; + use prelude::v1::*; + use sync::mpsc::channel; use super::{Queue, Data, Empty, Inconsistent}; + use sync::Arc; + use thread::Thread; #[test] fn test_full() { @@ -181,12 +182,12 @@ mod tests { for _ in range(0, nthreads) { let tx = tx.clone(); let q = q.clone(); - spawn(move|| { + Thread::spawn(move|| { for i in range(0, nmsgs) { q.push(i); } - tx.send(()); - }); + tx.send(()).unwrap(); + }).detach(); } let mut i = 0u; @@ -198,7 +199,7 @@ mod tests { } drop(tx); for _ in range(0, nthreads) { - rx.recv(); + rx.recv().unwrap(); } } } diff --git a/src/libstd/comm/oneshot.rs b/src/libstd/sync/mpsc/oneshot.rs similarity index 99% rename from src/libstd/comm/oneshot.rs rename to src/libstd/sync/mpsc/oneshot.rs index 9c5a651884530..5f599752a46fc 100644 --- a/src/libstd/comm/oneshot.rs +++ b/src/libstd/sync/mpsc/oneshot.rs @@ -39,8 +39,8 @@ use self::MyUpgrade::*; use core::prelude::*; -use comm::Receiver; -use comm::blocking::{mod, SignalToken}; +use sync::mpsc::Receiver; +use sync::mpsc::blocking::{mod, SignalToken}; use core::mem; use sync::atomic; diff --git a/src/libstd/comm/select.rs b/src/libstd/sync/mpsc/select.rs similarity index 77% rename from src/libstd/comm/select.rs rename to src/libstd/sync/mpsc/select.rs index 690b5861c2239..fc1e0b34977e4 100644 --- a/src/libstd/comm/select.rs +++ b/src/libstd/sync/mpsc/select.rs @@ -27,18 +27,20 @@ //! # Example //! //! ```rust +//! use std::sync::mpsc::channel; +//! //! let (tx1, rx1) = channel(); //! let (tx2, rx2) = channel(); //! -//! tx1.send(1i); -//! tx2.send(2i); +//! tx1.send(1i).unwrap(); +//! tx2.send(2i).unwrap(); //! //! select! { //! val = rx1.recv() => { -//! assert_eq!(val, 1i); +//! assert_eq!(val.unwrap(), 1i); //! }, //! val = rx2.recv() => { -//! assert_eq!(val, 2i); +//! assert_eq!(val.unwrap(), 2i); //! } //! } //! ``` @@ -59,8 +61,8 @@ use core::kinds::marker; use core::mem; use core::uint; -use comm::Receiver; -use comm::blocking::{mod, SignalToken}; +use sync::mpsc::{Receiver, RecvError}; +use sync::mpsc::blocking::{mod, SignalToken}; /// The "receiver set" of the select interface. This structure is used to manage /// a set of receivers which are being selected over. @@ -245,13 +247,10 @@ impl<'rx, T: Send> Handle<'rx, T> { #[inline] pub fn id(&self) -> uint { self.id } - /// Receive a value on the underlying receiver. Has the same semantics as - /// `Receiver.recv` - pub fn recv(&mut self) -> T { self.rx.recv() } /// Block to receive a value on the underlying receiver, returning `Some` on /// success or `None` if the channel disconnects. This function has the same - /// semantics as `Receiver.recv_opt` - pub fn recv_opt(&mut self) -> Result { self.rx.recv_opt() } + /// semantics as `Receiver.recv` + pub fn recv(&mut self) -> Result { self.rx.recv() } /// Adds this handle to the receiver set that the handle was created from. This /// method can be called multiple times, but it has no effect if `add` was @@ -335,9 +334,11 @@ impl Iterator<*mut Handle<'static, ()>> for Packets { #[cfg(test)] #[allow(unused_imports)] mod test { - use prelude::*; + use prelude::v1::*; + use thread::Thread; use super::*; + use sync::mpsc::*; // Don't use the libstd version so we can pull in the right Select structure // (std::comm points at the wrong one) @@ -345,7 +346,6 @@ mod test { ( $($name:pat = $rx:ident.$meth:ident() => $code:expr),+ ) => ({ - use comm::Select; let sel = Select::new(); $( let mut $rx = sel.handle(&$rx); )+ unsafe { @@ -357,365 +357,391 @@ mod test { }) } - test! { fn smoke() { + #[test] + fn smoke() { let (tx1, rx1) = channel::(); let (tx2, rx2) = channel::(); - tx1.send(1); + tx1.send(1).unwrap(); select! { - foo = rx1.recv() => { assert_eq!(foo, 1); }, + foo = rx1.recv() => { assert_eq!(foo.unwrap(), 1); }, _bar = rx2.recv() => { panic!() } } - tx2.send(2); + tx2.send(2).unwrap(); select! { _foo = rx1.recv() => { panic!() }, - bar = rx2.recv() => { assert_eq!(bar, 2) } + bar = rx2.recv() => { assert_eq!(bar.unwrap(), 2) } } drop(tx1); select! { - foo = rx1.recv_opt() => { assert_eq!(foo, Err(())); }, + foo = rx1.recv() => { assert!(foo.is_err()); }, _bar = rx2.recv() => { panic!() } } drop(tx2); select! { - bar = rx2.recv_opt() => { assert_eq!(bar, Err(())); } + bar = rx2.recv() => { assert!(bar.is_err()); } } - } } + } - test! { fn smoke2() { + #[test] + fn smoke2() { let (_tx1, rx1) = channel::(); let (_tx2, rx2) = channel::(); let (_tx3, rx3) = channel::(); let (_tx4, rx4) = channel::(); let (tx5, rx5) = channel::(); - tx5.send(4); + tx5.send(4).unwrap(); select! { _foo = rx1.recv() => { panic!("1") }, _foo = rx2.recv() => { panic!("2") }, _foo = rx3.recv() => { panic!("3") }, _foo = rx4.recv() => { panic!("4") }, - foo = rx5.recv() => { assert_eq!(foo, 4); } + foo = rx5.recv() => { assert_eq!(foo.unwrap(), 4); } } - } } + } - test! { fn closed() { + #[test] + fn closed() { let (_tx1, rx1) = channel::(); let (tx2, rx2) = channel::(); drop(tx2); select! { - _a1 = rx1.recv_opt() => { panic!() }, - a2 = rx2.recv_opt() => { assert_eq!(a2, Err(())); } + _a1 = rx1.recv() => { panic!() }, + a2 = rx2.recv() => { assert!(a2.is_err()); } } - } } + } - test! { fn unblocks() { + #[test] + fn unblocks() { let (tx1, rx1) = channel::(); let (_tx2, rx2) = channel::(); let (tx3, rx3) = channel::(); - spawn(move|| { + let _t = Thread::spawn(move|| { for _ in range(0u, 20) { Thread::yield_now(); } - tx1.send(1); - rx3.recv(); + tx1.send(1).unwrap(); + rx3.recv().unwrap(); for _ in range(0u, 20) { Thread::yield_now(); } }); select! { - a = rx1.recv() => { assert_eq!(a, 1); }, + a = rx1.recv() => { assert_eq!(a.unwrap(), 1); }, _b = rx2.recv() => { panic!() } } - tx3.send(1); + tx3.send(1).unwrap(); select! { - a = rx1.recv_opt() => { assert_eq!(a, Err(())); }, + a = rx1.recv() => { assert!(a.is_err()) }, _b = rx2.recv() => { panic!() } } - } } + } - test! { fn both_ready() { + #[test] + fn both_ready() { let (tx1, rx1) = channel::(); let (tx2, rx2) = channel::(); let (tx3, rx3) = channel::<()>(); - spawn(move|| { + let _t = Thread::spawn(move|| { for _ in range(0u, 20) { Thread::yield_now(); } - tx1.send(1); - tx2.send(2); - rx3.recv(); + tx1.send(1).unwrap(); + tx2.send(2).unwrap(); + rx3.recv().unwrap(); }); select! { - a = rx1.recv() => { assert_eq!(a, 1); }, - a = rx2.recv() => { assert_eq!(a, 2); } + a = rx1.recv() => { assert_eq!(a.unwrap(), 1); }, + a = rx2.recv() => { assert_eq!(a.unwrap(), 2); } } select! { - a = rx1.recv() => { assert_eq!(a, 1); }, - a = rx2.recv() => { assert_eq!(a, 2); } + a = rx1.recv() => { assert_eq!(a.unwrap(), 1); }, + a = rx2.recv() => { assert_eq!(a.unwrap(), 2); } } - assert_eq!(rx1.try_recv(), Err(Empty)); - assert_eq!(rx2.try_recv(), Err(Empty)); - tx3.send(()); - } } + assert_eq!(rx1.try_recv(), Err(TryRecvError::Empty)); + assert_eq!(rx2.try_recv(), Err(TryRecvError::Empty)); + tx3.send(()).unwrap(); + } - test! { fn stress() { + #[test] + fn stress() { static AMT: int = 10000; let (tx1, rx1) = channel::(); let (tx2, rx2) = channel::(); let (tx3, rx3) = channel::<()>(); - spawn(move|| { + let _t = Thread::spawn(move|| { for i in range(0, AMT) { if i % 2 == 0 { - tx1.send(i); + tx1.send(i).unwrap(); } else { - tx2.send(i); + tx2.send(i).unwrap(); } - rx3.recv(); + rx3.recv().unwrap(); } }); for i in range(0, AMT) { select! { - i1 = rx1.recv() => { assert!(i % 2 == 0 && i == i1); }, - i2 = rx2.recv() => { assert!(i % 2 == 1 && i == i2); } + i1 = rx1.recv() => { assert!(i % 2 == 0 && i == i1.unwrap()); }, + i2 = rx2.recv() => { assert!(i % 2 == 1 && i == i2.unwrap()); } } - tx3.send(()); + tx3.send(()).unwrap(); } - } } + } - test! { fn cloning() { + #[test] + fn cloning() { let (tx1, rx1) = channel::(); let (_tx2, rx2) = channel::(); let (tx3, rx3) = channel::<()>(); - spawn(move|| { - rx3.recv(); + let _t = Thread::spawn(move|| { + rx3.recv().unwrap(); tx1.clone(); - assert_eq!(rx3.try_recv(), Err(Empty)); - tx1.send(2); - rx3.recv(); + assert_eq!(rx3.try_recv(), Err(TryRecvError::Empty)); + tx1.send(2).unwrap(); + rx3.recv().unwrap(); }); - tx3.send(()); + tx3.send(()).unwrap(); select! { _i1 = rx1.recv() => {}, _i2 = rx2.recv() => panic!() } - tx3.send(()); - } } + tx3.send(()).unwrap(); + } - test! { fn cloning2() { + #[test] + fn cloning2() { let (tx1, rx1) = channel::(); let (_tx2, rx2) = channel::(); let (tx3, rx3) = channel::<()>(); - spawn(move|| { - rx3.recv(); + let _t = Thread::spawn(move|| { + rx3.recv().unwrap(); tx1.clone(); - assert_eq!(rx3.try_recv(), Err(Empty)); - tx1.send(2); - rx3.recv(); + assert_eq!(rx3.try_recv(), Err(TryRecvError::Empty)); + tx1.send(2).unwrap(); + rx3.recv().unwrap(); }); - tx3.send(()); + tx3.send(()).unwrap(); select! { _i1 = rx1.recv() => {}, _i2 = rx2.recv() => panic!() } - tx3.send(()); - } } + tx3.send(()).unwrap(); + } - test! { fn cloning3() { + #[test] + fn cloning3() { let (tx1, rx1) = channel::<()>(); let (tx2, rx2) = channel::<()>(); let (tx3, rx3) = channel::<()>(); - spawn(move|| { + let _t = Thread::spawn(move|| { let s = Select::new(); let mut h1 = s.handle(&rx1); let mut h2 = s.handle(&rx2); unsafe { h2.add(); } unsafe { h1.add(); } assert_eq!(s.wait(), h2.id); - tx3.send(()); + tx3.send(()).unwrap(); }); for _ in range(0u, 1000) { Thread::yield_now(); } drop(tx1.clone()); - tx2.send(()); - rx3.recv(); - } } + tx2.send(()).unwrap(); + rx3.recv().unwrap(); + } - test! { fn preflight1() { + #[test] + fn preflight1() { let (tx, rx) = channel(); - tx.send(()); + tx.send(()).unwrap(); select! { - () = rx.recv() => {} + _n = rx.recv() => {} } - } } + } - test! { fn preflight2() { + #[test] + fn preflight2() { let (tx, rx) = channel(); - tx.send(()); - tx.send(()); + tx.send(()).unwrap(); + tx.send(()).unwrap(); select! { - () = rx.recv() => {} + _n = rx.recv() => {} } - } } + } - test! { fn preflight3() { + #[test] + fn preflight3() { let (tx, rx) = channel(); drop(tx.clone()); - tx.send(()); + tx.send(()).unwrap(); select! { - () = rx.recv() => {} + _n = rx.recv() => {} } - } } + } - test! { fn preflight4() { + #[test] + fn preflight4() { let (tx, rx) = channel(); - tx.send(()); + tx.send(()).unwrap(); let s = Select::new(); let mut h = s.handle(&rx); unsafe { h.add(); } assert_eq!(s.wait2(false), h.id); - } } + } - test! { fn preflight5() { + #[test] + fn preflight5() { let (tx, rx) = channel(); - tx.send(()); - tx.send(()); + tx.send(()).unwrap(); + tx.send(()).unwrap(); let s = Select::new(); let mut h = s.handle(&rx); unsafe { h.add(); } assert_eq!(s.wait2(false), h.id); - } } + } - test! { fn preflight6() { + #[test] + fn preflight6() { let (tx, rx) = channel(); drop(tx.clone()); - tx.send(()); + tx.send(()).unwrap(); let s = Select::new(); let mut h = s.handle(&rx); unsafe { h.add(); } assert_eq!(s.wait2(false), h.id); - } } + } - test! { fn preflight7() { + #[test] + fn preflight7() { let (tx, rx) = channel::<()>(); drop(tx); let s = Select::new(); let mut h = s.handle(&rx); unsafe { h.add(); } assert_eq!(s.wait2(false), h.id); - } } + } - test! { fn preflight8() { + #[test] + fn preflight8() { let (tx, rx) = channel(); - tx.send(()); + tx.send(()).unwrap(); drop(tx); - rx.recv(); + rx.recv().unwrap(); let s = Select::new(); let mut h = s.handle(&rx); unsafe { h.add(); } assert_eq!(s.wait2(false), h.id); - } } + } - test! { fn preflight9() { + #[test] + fn preflight9() { let (tx, rx) = channel(); drop(tx.clone()); - tx.send(()); + tx.send(()).unwrap(); drop(tx); - rx.recv(); + rx.recv().unwrap(); let s = Select::new(); let mut h = s.handle(&rx); unsafe { h.add(); } assert_eq!(s.wait2(false), h.id); - } } + } - test! { fn oneshot_data_waiting() { + #[test] + fn oneshot_data_waiting() { let (tx1, rx1) = channel(); let (tx2, rx2) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { select! { - () = rx1.recv() => {} + _n = rx1.recv() => {} } - tx2.send(()); + tx2.send(()).unwrap(); }); for _ in range(0u, 100) { Thread::yield_now() } - tx1.send(()); - rx2.recv(); - } } + tx1.send(()).unwrap(); + rx2.recv().unwrap(); + } - test! { fn stream_data_waiting() { + #[test] + fn stream_data_waiting() { let (tx1, rx1) = channel(); let (tx2, rx2) = channel(); - tx1.send(()); - tx1.send(()); - rx1.recv(); - rx1.recv(); - spawn(move|| { + tx1.send(()).unwrap(); + tx1.send(()).unwrap(); + rx1.recv().unwrap(); + rx1.recv().unwrap(); + let _t = Thread::spawn(move|| { select! { - () = rx1.recv() => {} + _n = rx1.recv() => {} } - tx2.send(()); + tx2.send(()).unwrap(); }); for _ in range(0u, 100) { Thread::yield_now() } - tx1.send(()); - rx2.recv(); - } } + tx1.send(()).unwrap(); + rx2.recv().unwrap(); + } - test! { fn shared_data_waiting() { + #[test] + fn shared_data_waiting() { let (tx1, rx1) = channel(); let (tx2, rx2) = channel(); drop(tx1.clone()); - tx1.send(()); - rx1.recv(); - spawn(move|| { + tx1.send(()).unwrap(); + rx1.recv().unwrap(); + let _t = Thread::spawn(move|| { select! { - () = rx1.recv() => {} + _n = rx1.recv() => {} } - tx2.send(()); + tx2.send(()).unwrap(); }); for _ in range(0u, 100) { Thread::yield_now() } - tx1.send(()); - rx2.recv(); - } } + tx1.send(()).unwrap(); + rx2.recv().unwrap(); + } - test! { fn sync1() { + #[test] + fn sync1() { let (tx, rx) = sync_channel::(1); - tx.send(1); + tx.send(1).unwrap(); select! { - n = rx.recv() => { assert_eq!(n, 1); } + n = rx.recv() => { assert_eq!(n.unwrap(), 1); } } - } } + } - test! { fn sync2() { + #[test] + fn sync2() { let (tx, rx) = sync_channel::(0); - spawn(move|| { + let _t = Thread::spawn(move|| { for _ in range(0u, 100) { Thread::yield_now() } - tx.send(1); + tx.send(1).unwrap(); }); select! { - n = rx.recv() => { assert_eq!(n, 1); } + n = rx.recv() => { assert_eq!(n.unwrap(), 1); } } - } } + } - test! { fn sync3() { + #[test] + fn sync3() { let (tx1, rx1) = sync_channel::(0); let (tx2, rx2): (Sender, Receiver) = channel(); - spawn(move|| { tx1.send(1); }); - spawn(move|| { tx2.send(2); }); + let _t = Thread::spawn(move|| { tx1.send(1).unwrap(); }); + let _t = Thread::spawn(move|| { tx2.send(2).unwrap(); }); select! { n = rx1.recv() => { + let n = n.unwrap(); assert_eq!(n, 1); - assert_eq!(rx2.recv(), 2); + assert_eq!(rx2.recv().unwrap(), 2); }, n = rx2.recv() => { + let n = n.unwrap(); assert_eq!(n, 2); - assert_eq!(rx1.recv(), 1); + assert_eq!(rx1.recv().unwrap(), 1); } } - } } + } } diff --git a/src/libstd/comm/shared.rs b/src/libstd/sync/mpsc/shared.rs similarity index 99% rename from src/libstd/comm/shared.rs rename to src/libstd/sync/mpsc/shared.rs index 1022694e634f6..e1606cb4317a1 100644 --- a/src/libstd/comm/shared.rs +++ b/src/libstd/sync/mpsc/shared.rs @@ -26,10 +26,10 @@ use core::cmp; use core::int; use sync::{atomic, Mutex, MutexGuard}; -use comm::mpsc_queue as mpsc; -use comm::blocking::{mod, SignalToken}; -use comm::select::StartResult; -use comm::select::StartResult::*; +use sync::mpsc::mpsc_queue as mpsc; +use sync::mpsc::blocking::{mod, SignalToken}; +use sync::mpsc::select::StartResult; +use sync::mpsc::select::StartResult::*; use thread::Thread; const DISCONNECTED: int = int::MIN; diff --git a/src/libstd/comm/spsc_queue.rs b/src/libstd/sync/mpsc/spsc_queue.rs similarity index 98% rename from src/libstd/comm/spsc_queue.rs rename to src/libstd/sync/mpsc/spsc_queue.rs index becb78063aeb5..15624601157fd 100644 --- a/src/libstd/comm/spsc_queue.rs +++ b/src/libstd/sync/mpsc/spsc_queue.rs @@ -240,10 +240,12 @@ impl Drop for Queue { #[cfg(test)] mod test { - use prelude::*; + use prelude::v1::*; use sync::Arc; use super::Queue; + use thread::Thread; + use sync::mpsc::channel; #[test] fn smoke() { @@ -320,7 +322,7 @@ mod test { let (tx, rx) = channel(); let q2 = q.clone(); - spawn(move|| { + let _t = Thread::spawn(move|| { for _ in range(0u, 100000) { loop { match q2.pop() { @@ -330,12 +332,12 @@ mod test { } } } - tx.send(()); + tx.send(()).unwrap(); }); for _ in range(0i, 100000) { q.push(1); } - rx.recv(); + rx.recv().unwrap(); } } } diff --git a/src/libstd/comm/stream.rs b/src/libstd/sync/mpsc/stream.rs similarity index 99% rename from src/libstd/comm/stream.rs rename to src/libstd/sync/mpsc/stream.rs index b68f626060eda..01b799283ee3b 100644 --- a/src/libstd/comm/stream.rs +++ b/src/libstd/sync/mpsc/stream.rs @@ -28,10 +28,10 @@ use core::cmp; use core::int; use thread::Thread; +use sync::mpsc::blocking::{mod, SignalToken}; +use sync::mpsc::spsc_queue as spsc; +use sync::mpsc::Receiver; use sync::atomic; -use comm::spsc_queue as spsc; -use comm::Receiver; -use comm::blocking::{mod, SignalToken}; const DISCONNECTED: int = int::MIN; #[cfg(test)] diff --git a/src/libstd/comm/sync.rs b/src/libstd/sync/mpsc/sync.rs similarity index 98% rename from src/libstd/comm/sync.rs rename to src/libstd/sync/mpsc/sync.rs index 88338849965b0..28005831d4f6b 100644 --- a/src/libstd/comm/sync.rs +++ b/src/libstd/sync/mpsc/sync.rs @@ -42,8 +42,8 @@ use vec::Vec; use core::mem; use sync::{atomic, Mutex, MutexGuard}; -use comm::blocking::{mod, WaitToken, SignalToken}; -use comm::select::StartResult::{mod, Installed, Abort}; +use sync::mpsc::blocking::{mod, WaitToken, SignalToken}; +use sync::mpsc::select::StartResult::{mod, Installed, Abort}; pub struct Packet { /// Only field outside of the mutex. Just done for kicks, but mainly because @@ -204,14 +204,14 @@ impl Packet { pub fn try_send(&self, t: T) -> Result<(), super::TrySendError> { let mut guard = self.lock.lock(); if guard.disconnected { - Err(super::RecvDisconnected(t)) + Err(super::TrySendError::Disconnected(t)) } else if guard.buf.size() == guard.buf.cap() { - Err(super::Full(t)) + Err(super::TrySendError::Full(t)) } else if guard.cap == 0 { // With capacity 0, even though we have buffer space we can't // transfer the data unless there's a receiver waiting. match mem::replace(&mut guard.blocker, NoneBlocked) { - NoneBlocked => Err(super::Full(t)), + NoneBlocked => Err(super::TrySendError::Full(t)), BlockedSender(..) => unreachable!(), BlockedReceiver(token) => { guard.buf.enqueue(t); diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs index 4d2fbfc4055f4..1562031499fc8 100644 --- a/src/libstd/sync/mutex.rs +++ b/src/libstd/sync/mutex.rs @@ -8,10 +8,11 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use prelude::*; +use prelude::v1::*; use cell::UnsafeCell; use kinds::marker; +use ops::{Deref, DerefMut}; use sync::{poison, AsMutexGuard}; use sys_common::mutex as sys; @@ -36,6 +37,8 @@ use sys_common::mutex as sys; /// ```rust /// use std::sync::{Arc, Mutex}; /// use std::thread::Thread; +/// use std::sync::mpsc::channel; +/// /// const N: uint = 10; /// /// // Spawn a few threads to increment a shared variable (non-atomically), and @@ -55,13 +58,13 @@ use sys_common::mutex as sys; /// let mut data = data.lock(); /// *data += 1; /// if *data == N { -/// tx.send(()); +/// tx.send(()).unwrap(); /// } /// // the lock is unlocked here when `data` goes out of scope. /// }).detach(); /// } /// -/// rx.recv(); +/// rx.recv().unwrap(); /// ``` pub struct Mutex { // Note that this static mutex is in a *box*, not inlined into the struct @@ -279,10 +282,11 @@ impl Drop for StaticMutexGuard { #[cfg(test)] mod test { - use prelude::*; + use prelude::v1::*; - use thread::Thread; + use sync::mpsc::channel; use sync::{Arc, Mutex, StaticMutex, MUTEX_INIT, Condvar}; + use thread::Thread; struct Packet(Arc<(Mutex, Condvar)>); @@ -325,14 +329,14 @@ mod test { let (tx, rx) = channel(); for _ in range(0, K) { let tx2 = tx.clone(); - spawn(move|| { inc(); tx2.send(()); }); + Thread::spawn(move|| { inc(); tx2.send(()).unwrap(); }).detach(); let tx2 = tx.clone(); - spawn(move|| { inc(); tx2.send(()); }); + Thread::spawn(move|| { inc(); tx2.send(()).unwrap(); }).detach(); } drop(tx); for _ in range(0, 2 * K) { - rx.recv(); + rx.recv().unwrap(); } assert_eq!(unsafe {CNT}, J * K * 2); unsafe { @@ -351,9 +355,9 @@ mod test { let packet = Packet(Arc::new((Mutex::new(false), Condvar::new()))); let packet2 = Packet(packet.0.clone()); let (tx, rx) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { // wait until parent gets in - rx.recv(); + rx.recv().unwrap(); let &(ref lock, ref cvar) = &*packet2.0; let mut lock = lock.lock(); *lock = true; @@ -362,7 +366,7 @@ mod test { let &(ref lock, ref cvar) = &*packet.0; let lock = lock.lock(); - tx.send(()); + tx.send(()).unwrap(); assert!(!*lock); while !*lock { cvar.wait(&lock); @@ -376,8 +380,8 @@ mod test { let packet2 = Packet(packet.0.clone()); let (tx, rx) = channel(); - spawn(move|| { - rx.recv(); + let _t = Thread::spawn(move || -> () { + rx.recv().unwrap(); let &(ref lock, ref cvar) = &*packet2.0; let _g = lock.lock(); cvar.notify_one(); @@ -387,7 +391,7 @@ mod test { let &(ref lock, ref cvar) = &*packet.0; let lock = lock.lock(); - tx.send(()); + tx.send(()).unwrap(); while *lock == 1 { cvar.wait(&lock); } @@ -413,13 +417,13 @@ mod test { let arc = Arc::new(Mutex::new(1i)); let arc2 = Arc::new(Mutex::new(arc)); let (tx, rx) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { let lock = arc2.lock(); - let lock2 = lock.deref().lock(); + let lock2 = lock.lock(); assert_eq!(*lock2, 1); - tx.send(()); + tx.send(()).unwrap(); }); - rx.recv(); + rx.recv().unwrap(); } #[test] diff --git a/src/libstd/sync/once.rs b/src/libstd/sync/once.rs index 4d9fbb5990840..17b7b70c301b9 100644 --- a/src/libstd/sync/once.rs +++ b/src/libstd/sync/once.rs @@ -122,10 +122,11 @@ impl Once { #[cfg(test)] mod test { - use prelude::*; + use prelude::v1::*; use thread::Thread; use super::{ONCE_INIT, Once}; + use sync::mpsc::channel; #[test] fn smoke_once() { @@ -145,7 +146,7 @@ mod test { let (tx, rx) = channel(); for _ in range(0u, 10) { let tx = tx.clone(); - spawn(move|| { + Thread::spawn(move|| { for _ in range(0u, 4) { Thread::yield_now() } unsafe { O.doit(|| { @@ -154,8 +155,8 @@ mod test { }); assert!(run); } - tx.send(()); - }); + tx.send(()).unwrap(); + }).detach(); } unsafe { @@ -167,7 +168,7 @@ mod test { } for _ in range(0u, 10) { - rx.recv(); + rx.recv().unwrap(); } } } diff --git a/src/libstd/sync/rwlock.rs b/src/libstd/sync/rwlock.rs index 76d05d9bfd419..3c4283c72e2a0 100644 --- a/src/libstd/sync/rwlock.rs +++ b/src/libstd/sync/rwlock.rs @@ -8,12 +8,13 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use prelude::*; +use prelude::v1::*; -use kinds::marker; use cell::UnsafeCell; -use sys_common::rwlock as sys; +use kinds::marker; +use ops::{Deref, DerefMut}; use sync::poison; +use sys_common::rwlock as sys; /// A reader-writer lock /// @@ -359,9 +360,10 @@ impl Drop for StaticRWLockWriteGuard { #[cfg(test)] mod tests { - use prelude::*; + use prelude::v1::*; use rand::{mod, Rng}; + use sync::mpsc::channel; use thread::Thread; use sync::{Arc, RWLock, StaticRWLock, RWLOCK_INIT}; @@ -393,7 +395,7 @@ mod tests { let (tx, rx) = channel::<()>(); for _ in range(0, N) { let tx = tx.clone(); - spawn(move|| { + Thread::spawn(move|| { let mut rng = rand::task_rng(); for _ in range(0, M) { if rng.gen_weighted_bool(N) { @@ -403,10 +405,10 @@ mod tests { } } drop(tx); - }); + }).detach(); } drop(tx); - let _ = rx.recv_opt(); + let _ = rx.recv(); unsafe { R.destroy(); } } @@ -473,7 +475,7 @@ mod tests { Thread::yield_now(); *lock = tmp + 1; } - tx.send(()); + tx.send(()).unwrap(); }).detach(); // Readers try to catch the writer in the act @@ -492,7 +494,7 @@ mod tests { } // Wait for writer to finish - rx.recv(); + rx.recv().unwrap(); let lock = arc.read(); assert_eq!(*lock, 10); } diff --git a/src/libstd/sync/semaphore.rs b/src/libstd/sync/semaphore.rs index 574b0f22bee00..784b173b99eb8 100644 --- a/src/libstd/sync/semaphore.rs +++ b/src/libstd/sync/semaphore.rs @@ -104,10 +104,12 @@ impl<'a> Drop for SemaphoreGuard<'a> { #[cfg(test)] mod tests { - use prelude::*; + use prelude::v1::*; use sync::Arc; use super::Semaphore; + use sync::mpsc::channel; + use thread::Thread; #[test] fn test_sem_acquire_release() { @@ -127,7 +129,7 @@ mod tests { fn test_sem_as_mutex() { let s = Arc::new(Semaphore::new(1)); let s2 = s.clone(); - spawn(move|| { + let _t = Thread::spawn(move|| { let _g = s2.access(); }); let _g = s.access(); @@ -139,9 +141,9 @@ mod tests { let (tx, rx) = channel(); let s = Arc::new(Semaphore::new(0)); let s2 = s.clone(); - spawn(move|| { + let _t = Thread::spawn(move|| { s2.acquire(); - tx.send(()); + tx.send(()).unwrap(); }); s.release(); let _ = rx.recv(); @@ -150,12 +152,12 @@ mod tests { let (tx, rx) = channel(); let s = Arc::new(Semaphore::new(0)); let s2 = s.clone(); - spawn(move|| { + let _t = Thread::spawn(move|| { s2.release(); let _ = rx.recv(); }); s.acquire(); - tx.send(()); + tx.send(()).unwrap(); } #[test] @@ -166,14 +168,14 @@ mod tests { let s2 = s.clone(); let (tx1, rx1) = channel(); let (tx2, rx2) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { let _g = s2.access(); let _ = rx2.recv(); - tx1.send(()); + tx1.send(()).unwrap(); }); let _g = s.access(); - tx2.send(()); - let _ = rx1.recv(); + tx2.send(()).unwrap(); + rx1.recv().unwrap(); } #[test] @@ -183,13 +185,13 @@ mod tests { let (tx, rx) = channel(); { let _g = s.access(); - spawn(move|| { - tx.send(()); + Thread::spawn(move|| { + tx.send(()).unwrap(); drop(s2.access()); - tx.send(()); - }); - rx.recv(); // wait for child to come alive + tx.send(()).unwrap(); + }).detach(); + rx.recv().unwrap(); // wait for child to come alive } - rx.recv(); // wait for child to be done + rx.recv().unwrap(); // wait for child to be done } } diff --git a/src/libstd/sync/task_pool.rs b/src/libstd/sync/task_pool.rs index 366e4b7d35b01..b03259983582a 100644 --- a/src/libstd/sync/task_pool.rs +++ b/src/libstd/sync/task_pool.rs @@ -12,9 +12,9 @@ use core::prelude::*; -use thread::Thread; -use comm::{channel, Sender, Receiver}; use sync::{Arc, Mutex}; +use sync::mpsc::{channel, Sender, Receiver}; +use thread::Thread; use thunk::Thunk; struct Sentinel<'a> { @@ -53,8 +53,9 @@ impl<'a> Drop for Sentinel<'a> { /// # Example /// /// ```rust -/// # use std::sync::TaskPool; -/// # use std::iter::AdditiveIterator; +/// use std::sync::TaskPool; +/// use std::iter::AdditiveIterator; +/// use std::sync::mpsc::channel; /// /// let pool = TaskPool::new(4u); /// @@ -62,7 +63,7 @@ impl<'a> Drop for Sentinel<'a> { /// for _ in range(0, 8u) { /// let tx = tx.clone(); /// pool.execute(move|| { -/// tx.send(1u); +/// tx.send(1u).unwrap(); /// }); /// } /// @@ -100,7 +101,7 @@ impl TaskPool { pub fn execute(&self, job: F) where F : FnOnce(), F : Send { - self.jobs.send(Thunk::new(job)); + self.jobs.send(Thunk::new(job)).unwrap(); } } @@ -114,7 +115,7 @@ fn spawn_in_pool(jobs: Arc>>) { // Only lock jobs for the time it takes // to get a job, not run it. let lock = jobs.lock(); - lock.recv_opt() + lock.recv() }; match message { @@ -131,8 +132,9 @@ fn spawn_in_pool(jobs: Arc>>) { #[cfg(test)] mod test { - use prelude::*; + use prelude::v1::*; use super::*; + use sync::mpsc::channel; const TEST_TASKS: uint = 4u; @@ -146,7 +148,7 @@ mod test { for _ in range(0, TEST_TASKS) { let tx = tx.clone(); pool.execute(move|| { - tx.send(1u); + tx.send(1u).unwrap(); }); } @@ -175,7 +177,7 @@ mod test { for _ in range(0, TEST_TASKS) { let tx = tx.clone(); pool.execute(move|| { - tx.send(1u); + tx.send(1u).unwrap(); }); } diff --git a/src/libstd/sys/common/backtrace.rs b/src/libstd/sys/common/backtrace.rs index 1d646eb06b167..c1aace764fc62 100644 --- a/src/libstd/sys/common/backtrace.rs +++ b/src/libstd/sys/common/backtrace.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use prelude::*; +use prelude::v1::*; use io::IoResult; diff --git a/src/libstd/sys/common/helper_thread.rs b/src/libstd/sys/common/helper_thread.rs index a629f035b07af..b9dc5f0e39845 100644 --- a/src/libstd/sys/common/helper_thread.rs +++ b/src/libstd/sys/common/helper_thread.rs @@ -20,12 +20,13 @@ //! can be created in the future and there must be no active timers at that //! time. -use prelude::*; +use prelude::v1::*; use cell::UnsafeCell; use mem; -use sync::{StaticMutex, StaticCondvar}; use rt; +use sync::{StaticMutex, StaticCondvar}; +use sync::mpsc::{channel, Sender, Receiver}; use sys::helper_signal; use thread::Thread; @@ -117,7 +118,7 @@ impl Helper { // message. Otherwise it could wake up and go to sleep before we // send the message. assert!(!self.chan.get().is_null()); - (**self.chan.get()).send(msg); + (**self.chan.get()).send(msg).unwrap(); helper_signal::signal(*self.signal.get() as helper_signal::signal); } } diff --git a/src/libstd/sys/common/mod.rs b/src/libstd/sys/common/mod.rs index dc0ad08cdbef6..97015f74a4a10 100644 --- a/src/libstd/sys/common/mod.rs +++ b/src/libstd/sys/common/mod.rs @@ -12,7 +12,7 @@ #![allow(dead_code)] use io::{mod, IoError, IoResult}; -use prelude::*; +use prelude::v1::*; use sys::{last_error, retry}; use c_str::CString; use num::Int; diff --git a/src/libstd/sys/common/net.rs b/src/libstd/sys/common/net.rs index 382f6875b281d..9ab5077ae79a8 100644 --- a/src/libstd/sys/common/net.rs +++ b/src/libstd/sys/common/net.rs @@ -8,23 +8,23 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use prelude::v1::*; use self::SocketStatus::*; use self::InAddr::*; -use alloc::arc::Arc; +use c_str::ToCStr; +use io::net::addrinfo; +use io::net::ip::{SocketAddr, IpAddr, Ipv4Addr, Ipv6Addr}; +use io::{IoResult, IoError}; use libc::{mod, c_char, c_int}; use mem; use num::Int; use ptr::{mod, null, null_mut}; -use io::net::ip::{SocketAddr, IpAddr, Ipv4Addr, Ipv6Addr}; -use io::net::addrinfo; -use io::{IoResult, IoError}; use sys::{mod, retry, c, sock_t, last_error, last_net_error, last_gai_error, close_sock, wrlen, msglen_t, os, wouldblock, set_nonblocking, timer, ms_to_timeval, decode_error_detailed}; -use sync::{Mutex, MutexGuard}; +use sync::{Arc, Mutex, MutexGuard}; use sys_common::{mod, keep_going, short_write, timeout}; -use prelude::*; use cmp; use io; diff --git a/src/libstd/sys/common/thread_local.rs b/src/libstd/sys/common/thread_local.rs index fe7a7d8d03716..405dd4eacf399 100644 --- a/src/libstd/sys/common/thread_local.rs +++ b/src/libstd/sys/common/thread_local.rs @@ -56,7 +56,7 @@ #![allow(non_camel_case_types)] -use prelude::*; +use prelude::v1::*; use sync::atomic::{mod, AtomicUint}; use sync::{Mutex, Once, ONCE_INIT}; @@ -246,7 +246,7 @@ impl Drop for Key { #[cfg(test)] mod tests { - use prelude::*; + use prelude::v1::*; use super::{Key, StaticKey, INIT_INNER}; fn assert_sync() {} diff --git a/src/libstd/sys/unix/fs.rs b/src/libstd/sys/unix/fs.rs index 98d860f964649..d537579d45386 100644 --- a/src/libstd/sys/unix/fs.rs +++ b/src/libstd/sys/unix/fs.rs @@ -10,16 +10,15 @@ //! Blocking posix-based file I/O -use libc::{mod, c_int, c_void}; -use c_str::CString; -use mem; -use io; - -use prelude::*; +use prelude::v1::*; +use c_str::{CString, ToCStr}; use io::{FilePermission, Write, UnstableFileStat, Open, FileAccess, FileMode}; use io::{IoResult, FileStat, SeekStyle}; use io::{Read, Truncate, SeekCur, SeekSet, ReadWrite, SeekEnd, Append}; +use io; +use libc::{mod, c_int, c_void}; +use mem; use sys::retry; use sys_common::{keep_going, eof, mkerr_libc}; @@ -360,7 +359,7 @@ mod tests { use super::FileDesc; use libc; use os; - use prelude::*; + use prelude::v1::*; #[cfg_attr(target_os = "freebsd", ignore)] // hmm, maybe pipes have a tiny buffer #[test] diff --git a/src/libstd/sys/unix/mod.rs b/src/libstd/sys/unix/mod.rs index f3babca32871a..15dad8107561e 100644 --- a/src/libstd/sys/unix/mod.rs +++ b/src/libstd/sys/unix/mod.rs @@ -19,7 +19,7 @@ extern crate libc; use num; use num::{Int, SignedInt}; -use prelude::*; +use prelude::v1::*; use io::{mod, IoResult, IoError}; use sys_common::mkerr_libc; diff --git a/src/libstd/sys/unix/os.rs b/src/libstd/sys/unix/os.rs index cafe52f8403b6..a221a6bc15bb6 100644 --- a/src/libstd/sys/unix/os.rs +++ b/src/libstd/sys/unix/os.rs @@ -10,17 +10,18 @@ //! Implementation of `std::os` functionality for unix systems -use prelude::*; +use prelude::v1::*; +use c_str::ToCStr; use error::{FromError, Error}; use fmt; use io::{IoError, IoResult}; use libc::{mod, c_int, c_char, c_void}; -use path::BytesContainer; +use os; +use path::{BytesContainer}; use ptr; use sync::atomic::{AtomicInt, INIT_ATOMIC_INT, SeqCst}; use sys::fs::FileDesc; -use os; use os::TMPBUF_SZ; diff --git a/src/libstd/sys/unix/pipe.rs b/src/libstd/sys/unix/pipe.rs index f1b078b4e80ab..6954866257ebf 100644 --- a/src/libstd/sys/unix/pipe.rs +++ b/src/libstd/sys/unix/pipe.rs @@ -8,13 +8,13 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use alloc::arc::Arc; +use prelude::v1::*; + use libc; use c_str::CString; use mem; -use sync::{atomic, Mutex}; +use sync::{atomic, Arc, Mutex}; use io::{mod, IoResult, IoError}; -use prelude::*; use sys::{mod, timer, retry, c, set_nonblocking, wouldblock}; use sys::fs::{fd_t, FileDesc}; diff --git a/src/libstd/sys/unix/process.rs b/src/libstd/sys/unix/process.rs index 835f4279d9bc6..a11fe3487a8e4 100644 --- a/src/libstd/sys/unix/process.rs +++ b/src/libstd/sys/unix/process.rs @@ -7,22 +7,23 @@ // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. + +use prelude::v1::*; use self::Req::*; -use libc::{mod, pid_t, c_void, c_int}; -use c_str::CString; +use c_str::{CString, ToCStr}; +use collections; +use hash::Hash; +use io::process::{ProcessExit, ExitStatus, ExitSignal}; use io::{mod, IoResult, IoError, EndOfFile}; +use libc::{mod, pid_t, c_void, c_int}; use mem; use os; -use ptr; -use prelude::*; -use io::process::{ProcessExit, ExitStatus, ExitSignal}; -use collections; use path::BytesContainer; -use hash::Hash; - -use sys::{mod, retry, c, wouldblock, set_nonblocking, ms_to_timeval}; +use ptr; +use sync::mpsc::{channel, Sender, Receiver}; use sys::fs::FileDesc; +use sys::{mod, retry, c, wouldblock, set_nonblocking, ms_to_timeval}; use sys_common::helper_thread::Helper; use sys_common::{AsInner, mkerr_libc, timeout}; @@ -276,8 +277,8 @@ impl Process { } pub fn wait(&self, deadline: u64) -> IoResult { - use std::cmp; - use std::comm; + use cmp; + use sync::mpsc::TryRecvError; static mut WRITE_FD: libc::c_int = 0; @@ -336,9 +337,9 @@ impl Process { let (tx, rx) = channel(); unsafe { HELPER.send(NewChild(self.pid, tx, deadline)); } - return match rx.recv_opt() { + return match rx.recv() { Ok(e) => Ok(e), - Err(()) => Err(timeout("wait timed out")), + Err(..) => Err(timeout("wait timed out")), }; // Register a new SIGCHLD handler, returning the reading half of the @@ -419,11 +420,11 @@ impl Process { Ok(NewChild(pid, tx, deadline)) => { active.push((pid, tx, deadline)); } - Err(comm::Disconnected) => { + Err(TryRecvError::Disconnected) => { assert!(active.len() == 0); break 'outer; } - Err(comm::Empty) => break, + Err(TryRecvError::Empty) => break, } } } @@ -459,7 +460,7 @@ impl Process { active.retain(|&(pid, ref tx, _)| { let pr = Process { pid: pid }; match pr.try_wait() { - Some(msg) => { tx.send(msg); false } + Some(msg) => { tx.send(msg).unwrap(); false } None => true, } }); diff --git a/src/libstd/sys/unix/tcp.rs b/src/libstd/sys/unix/tcp.rs index e2a78947e167a..13ccf685fd7fc 100644 --- a/src/libstd/sys/unix/tcp.rs +++ b/src/libstd/sys/unix/tcp.rs @@ -8,12 +8,13 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use prelude::v1::*; + use io::net::ip; use io::IoResult; use libc; use mem; use ptr; -use prelude::*; use super::{last_error, last_net_error, retry, sock_t}; use sync::{Arc, atomic}; use sys::fs::FileDesc; diff --git a/src/libstd/sys/unix/thread_local.rs b/src/libstd/sys/unix/thread_local.rs index b300e93eeb602..e507377a8fcdd 100644 --- a/src/libstd/sys/unix/thread_local.rs +++ b/src/libstd/sys/unix/thread_local.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use prelude::*; +use prelude::v1::*; use libc::c_int; pub type Key = pthread_key_t; diff --git a/src/libstd/sys/unix/timer.rs b/src/libstd/sys/unix/timer.rs index fe393b81e3d9a..4afe13d87357d 100644 --- a/src/libstd/sys/unix/timer.rs +++ b/src/libstd/sys/unix/timer.rs @@ -46,19 +46,19 @@ //! //! Note that all time units in this file are in *milliseconds*. +use prelude::v1::*; use self::Req::*; +use io::IoResult; use libc; use mem; use os; use ptr; use sync::atomic; -use comm; +use sync::mpsc::{channel, Sender, Receiver, TryRecvError}; use sys::c; use sys::fs::FileDesc; use sys_common::helper_thread::Helper; -use prelude::*; -use io::IoResult; helper_init! { static HELPER: Helper } @@ -168,7 +168,7 @@ fn helper(input: libc::c_int, messages: Receiver, _: ()) { 1 => { loop { match messages.try_recv() { - Err(comm::Disconnected) => { + Err(TryRecvError::Disconnected) => { assert!(active.len() == 0); break 'outer; } @@ -179,7 +179,7 @@ fn helper(input: libc::c_int, messages: Receiver, _: ()) { match dead.iter().position(|&(i, _)| id == i) { Some(i) => { let (_, i) = dead.remove(i).unwrap(); - ack.send(i); + ack.send(i).unwrap(); continue } None => {} @@ -187,7 +187,7 @@ fn helper(input: libc::c_int, messages: Receiver, _: ()) { let i = active.iter().position(|i| i.id == id); let i = i.expect("no timer found"); let t = active.remove(i).unwrap(); - ack.send(t); + ack.send(t).unwrap(); } Err(..) => break } @@ -271,7 +271,7 @@ impl Timer { None => { let (tx, rx) = channel(); HELPER.send(RemoveTimer(self.id, tx)); - rx.recv() + rx.recv().unwrap() } } } diff --git a/src/libstd/sys/unix/tty.rs b/src/libstd/sys/unix/tty.rs index 28c17fd4966c0..4ef687d41d8ee 100644 --- a/src/libstd/sys/unix/tty.rs +++ b/src/libstd/sys/unix/tty.rs @@ -8,8 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use prelude::v1::*; + use sys::fs::FileDesc; -use prelude::*; use libc::{mod, c_int}; use io::{mod, IoResult, IoError}; use sys_common; diff --git a/src/libstd/sys/windows/c.rs b/src/libstd/sys/windows/c.rs index d1cb91bcdb377..d1177776dd8b1 100644 --- a/src/libstd/sys/windows/c.rs +++ b/src/libstd/sys/windows/c.rs @@ -15,7 +15,7 @@ #![allow(non_camel_case_types)] use libc; -use prelude::*; +use prelude::v1::*; pub const WSADESCRIPTION_LEN: uint = 256; pub const WSASYS_STATUS_LEN: uint = 128; @@ -133,7 +133,7 @@ pub mod compat { use intrinsics::{atomic_store_relaxed, transmute}; use iter::IteratorExt; use libc::types::os::arch::extra::{LPCWSTR, HMODULE, LPCSTR, LPVOID}; - use prelude::*; + use prelude::v1::*; extern "system" { fn GetModuleHandleW(lpModuleName: LPCWSTR) -> HMODULE; diff --git a/src/libstd/sys/windows/fs.rs b/src/libstd/sys/windows/fs.rs index 15eddd569beec..632261f0ad921 100644 --- a/src/libstd/sys/windows/fs.rs +++ b/src/libstd/sys/windows/fs.rs @@ -21,7 +21,7 @@ use ptr; use str; use io; -use prelude::*; +use prelude::v1::*; use sys; use sys::os; use sys_common::{keep_going, eof, mkerr_libc}; diff --git a/src/libstd/sys/windows/mod.rs b/src/libstd/sys/windows/mod.rs index 6924687d8c470..94f5822ccea32 100644 --- a/src/libstd/sys/windows/mod.rs +++ b/src/libstd/sys/windows/mod.rs @@ -18,9 +18,10 @@ extern crate libc; +use prelude::v1::*; + use num; use mem; -use prelude::*; use io::{mod, IoResult, IoError}; use sync::{Once, ONCE_INIT}; diff --git a/src/libstd/sys/windows/mutex.rs b/src/libstd/sys/windows/mutex.rs index 3ac7c09154e35..c7b4a4cec09ec 100644 --- a/src/libstd/sys/windows/mutex.rs +++ b/src/libstd/sys/windows/mutex.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use prelude::*; +use prelude::v1::*; use sync::atomic; use alloc::{mod, heap}; diff --git a/src/libstd/sys/windows/os.rs b/src/libstd/sys/windows/os.rs index e007b46b261b4..159512525d8b3 100644 --- a/src/libstd/sys/windows/os.rs +++ b/src/libstd/sys/windows/os.rs @@ -13,7 +13,7 @@ // FIXME: move various extern bindings from here into liblibc or // something similar -use prelude::*; +use prelude::v1::*; use fmt; use io::{IoResult, IoError}; diff --git a/src/libstd/sys/windows/pipe.rs b/src/libstd/sys/windows/pipe.rs index fc3640f260437..f173d5fc6d4cb 100644 --- a/src/libstd/sys/windows/pipe.rs +++ b/src/libstd/sys/windows/pipe.rs @@ -84,14 +84,14 @@ //! the test suite passing (the suite is in libstd), and that's good enough for //! me! -use alloc::arc::Arc; +use prelude::v1::*; + use libc; use c_str::CString; use mem; use ptr; -use sync::{atomic, Mutex}; +use sync::{atomic, Arc, Mutex}; use io::{mod, IoError, IoResult}; -use prelude::*; use sys_common::{mod, eof}; diff --git a/src/libstd/sys/windows/process.rs b/src/libstd/sys/windows/process.rs index 0c2c76077dd54..f99995eb028a2 100644 --- a/src/libstd/sys/windows/process.rs +++ b/src/libstd/sys/windows/process.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use prelude::v1::*; + use libc::{pid_t, c_void, c_int}; use libc; use c_str::CString; @@ -15,7 +17,6 @@ use io; use mem; use os; use ptr; -use prelude::*; use io::process::{ProcessExit, ExitStatus, ExitSignal}; use collections; use path::BytesContainer; @@ -469,7 +470,7 @@ mod tests { #[test] fn test_make_command_line() { - use prelude::*; + use prelude::v1::*; use str; use c_str::CString; use super::make_command_line; diff --git a/src/libstd/sys/windows/tcp.rs b/src/libstd/sys/windows/tcp.rs index 513c1d38e3634..5a929f6b2b5ff 100644 --- a/src/libstd/sys/windows/tcp.rs +++ b/src/libstd/sys/windows/tcp.rs @@ -13,7 +13,7 @@ use io::IoResult; use libc; use mem; use ptr; -use prelude::*; +use prelude::v1::*; use super::{last_error, last_net_error, retry, sock_t}; use sync::{Arc, atomic}; use sys::fs::FileDesc; diff --git a/src/libstd/sys/windows/thread_local.rs b/src/libstd/sys/windows/thread_local.rs index 60b0d584db3a7..b96e26c7a86a6 100644 --- a/src/libstd/sys/windows/thread_local.rs +++ b/src/libstd/sys/windows/thread_local.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use prelude::*; +use prelude::v1::*; use libc::types::os::arch::extra::{DWORD, LPVOID, BOOL}; diff --git a/src/libstd/sys/windows/timer.rs b/src/libstd/sys/windows/timer.rs index 874838950cd12..3df0debff51ba 100644 --- a/src/libstd/sys/windows/timer.rs +++ b/src/libstd/sys/windows/timer.rs @@ -29,7 +29,7 @@ use comm; use sys::c; use sys::fs::FileDesc; use sys_common::helper_thread::Helper; -use prelude::*; +use prelude::v1::*; use io::IoResult; helper_init! { static HELPER: Helper } diff --git a/src/libstd/sys/windows/tty.rs b/src/libstd/sys/windows/tty.rs index f793de5bb57ef..dfa3440067a69 100644 --- a/src/libstd/sys/windows/tty.rs +++ b/src/libstd/sys/windows/tty.rs @@ -25,6 +25,8 @@ //! wrapper that performs encoding/decoding, this implementation should switch //! to working in raw UTF-16, with such a wrapper around it. +use prelude::v1::*; + use super::c::{ReadConsoleW, WriteConsoleW, GetConsoleMode, SetConsoleMode}; use super::c::{ERROR_ILLEGAL_CHARACTER}; use super::c::{ENABLE_ECHO_INPUT, ENABLE_EXTENDED_FLAGS}; @@ -34,7 +36,6 @@ use libc::{c_int, HANDLE, LPDWORD, DWORD, LPVOID}; use libc::{get_osfhandle, CloseHandle}; use libc::types::os::arch::extra::LPCVOID; use io::{mod, IoError, IoResult, MemReader}; -use prelude::*; use ptr; use str::from_utf8; diff --git a/src/libstd/thread.rs b/src/libstd/thread.rs index 56731bd7ec3ee..5c9e6153afb41 100644 --- a/src/libstd/thread.rs +++ b/src/libstd/thread.rs @@ -439,13 +439,15 @@ impl Drop for JoinGuard { #[cfg(test)] mod test { - use prelude::*; + use prelude::v1::*; + use any::{Any, AnyRefExt}; use boxed::BoxAny; + use sync::mpsc::{channel, Sender}; use result; use std::io::{ChanReader, ChanWriter}; - use thunk::Thunk; use super::{Thread, Builder}; + use thunk::Thunk; // !!! These tests are dangerous. If something is buggy, they will hang, !!! // !!! instead of exiting cleanly. This might wedge the buildbots. !!! @@ -468,9 +470,9 @@ mod test { fn test_run_basic() { let (tx, rx) = channel(); Thread::spawn(move|| { - tx.send(()); + tx.send(()).unwrap(); }).detach(); - rx.recv(); + rx.recv().unwrap(); } #[test] @@ -503,7 +505,7 @@ mod test { let tx = tx.clone(); Thread::spawn(move|| { if i == 0 { - tx.send(()); + tx.send(()).unwrap(); } else { f(i - 1, tx); } @@ -511,7 +513,7 @@ mod test { } f(10, tx); - rx.recv(); + rx.recv().unwrap(); } #[test] @@ -520,11 +522,11 @@ mod test { Thread::spawn(move|| { Thread::spawn(move|| { - tx.send(()); + tx.send(()).unwrap(); }).detach(); }).detach(); - rx.recv(); + rx.recv().unwrap(); } fn avoid_copying_the_body(spawnfn: F) where F: FnOnce(Thunk) { @@ -535,10 +537,10 @@ mod test { spawnfn(Thunk::new(move|| { let x_in_child = (&*x) as *const int as uint; - tx.send(x_in_child); + tx.send(x_in_child).unwrap(); })); - let x_in_child = rx.recv(); + let x_in_child = rx.recv().unwrap(); assert_eq!(x_in_parent, x_in_child); } diff --git a/src/libstd/thread_local/mod.rs b/src/libstd/thread_local/mod.rs index 242dceb425636..6cd26a366aef9 100644 --- a/src/libstd/thread_local/mod.rs +++ b/src/libstd/thread_local/mod.rs @@ -37,7 +37,7 @@ #![macro_escape] #![experimental] -use prelude::*; +use prelude::v1::*; use cell::UnsafeCell; @@ -258,7 +258,7 @@ impl Key { #[cfg(any(target_os = "macos", target_os = "linux"))] mod imp { - use prelude::*; + use prelude::v1::*; use cell::UnsafeCell; use intrinsics; @@ -396,7 +396,7 @@ mod imp { #[cfg(not(any(target_os = "macos", target_os = "linux")))] mod imp { - use prelude::*; + use prelude::v1::*; use cell::UnsafeCell; use mem; @@ -469,8 +469,9 @@ mod imp { #[cfg(test)] mod tests { - use prelude::*; + use prelude::v1::*; + use sync::mpsc::{channel, Sender}; use cell::UnsafeCell; use thread::Thread; @@ -479,7 +480,7 @@ mod tests { impl Drop for Foo { fn drop(&mut self) { let Foo(ref s) = *self; - s.send(()); + s.send(()).unwrap(); } } @@ -492,13 +493,13 @@ mod tests { *f.get() = 2; }); let (tx, rx) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| { FOO.with(|f| unsafe { assert_eq!(*f.get(), 1); }); - tx.send(()); + tx.send(()).unwrap(); }); - rx.recv(); + rx.recv().unwrap(); FOO.with(|f| unsafe { assert_eq!(*f.get(), 2); @@ -512,13 +513,13 @@ mod tests { }); let (tx, rx) = channel(); - spawn(move|| unsafe { + let _t = Thread::spawn(move|| unsafe { let mut tx = Some(tx); FOO.with(|f| { *f.get() = Some(Foo(tx.take().unwrap())); }); }); - rx.recv(); + rx.recv().unwrap(); } #[test] @@ -562,7 +563,7 @@ mod tests { Thread::spawn(move|| { drop(S1); - }).join(); + }).join().ok().unwrap(); } #[test] @@ -580,7 +581,7 @@ mod tests { Thread::spawn(move|| unsafe { K1.with(|s| *s.get() = Some(S1)); - }).join(); + }).join().ok().unwrap(); } #[test] @@ -605,17 +606,17 @@ mod tests { } let (tx, rx) = channel(); - spawn(move|| unsafe { + let _t = Thread::spawn(move|| unsafe { let mut tx = Some(tx); K1.with(|s| *s.get() = Some(S1(tx.take().unwrap()))); }); - rx.recv(); + rx.recv().unwrap(); } } #[cfg(test)] mod dynamic_tests { - use prelude::*; + use prelude::v1::*; use cell::RefCell; use collections::HashMap; diff --git a/src/libstd/thread_local/scoped.rs b/src/libstd/thread_local/scoped.rs index 756c86c211547..a06048aa706f1 100644 --- a/src/libstd/thread_local/scoped.rs +++ b/src/libstd/thread_local/scoped.rs @@ -40,7 +40,7 @@ #![macro_escape] -use prelude::*; +use prelude::v1::*; // macro hygiene sure would be nice, wouldn't it? #[doc(hidden)] pub use self::imp::KeyInner; @@ -238,7 +238,7 @@ mod imp { #[cfg(test)] mod tests { use cell::Cell; - use prelude::*; + use prelude::v1::*; #[test] fn smoke() { diff --git a/src/libstd/tuple.rs b/src/libstd/tuple.rs index 5cd60d6e153ea..fc90bffa03c2f 100644 --- a/src/libstd/tuple.rs +++ b/src/libstd/tuple.rs @@ -35,14 +35,14 @@ //! //! # Examples //! -//! Using methods: +//! Using fields: //! //! ``` //! #[allow(deprecated)] //! # fn main() { //! let pair = ("pi", 3.14f64); -//! assert_eq!(pair.val0(), "pi"); -//! assert_eq!(pair.val1(), 3.14f64); +//! assert_eq!(pair.0, "pi"); +//! assert_eq!(pair.1, 3.14f64); //! # } //! ``` //! diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index 6b9af29c60457..042a1bd0781cf 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -10,19 +10,24 @@ // // ignore-lexer-test FIXME #15679 -//! The CodeMap tracks all the source code used within a single crate, mapping from integer byte -//! positions to the original source code location. Each bit of source parsed during crate parsing -//! (typically files, in-memory strings, or various bits of macro expansion) cover a continuous -//! range of bytes in the CodeMap and are represented by FileMaps. Byte positions are stored in -//! `spans` and used pervasively in the compiler. They are absolute positions within the CodeMap, -//! which upon request can be converted to line and column information, source code snippets, etc. +//! The CodeMap tracks all the source code used within a single crate, mapping +//! from integer byte positions to the original source code location. Each bit +//! of source parsed during crate parsing (typically files, in-memory strings, +//! or various bits of macro expansion) cover a continuous range of bytes in the +//! CodeMap and are represented by FileMaps. Byte positions are stored in +//! `spans` and used pervasively in the compiler. They are absolute positions +//! within the CodeMap, which upon request can be converted to line and column +//! information, source code snippets, etc. pub use self::MacroFormat::*; -use serialize::{Encodable, Decodable, Encoder, Decoder}; use std::cell::RefCell; +use std::num::ToPrimitive; +use std::ops::{Add, Sub}; use std::rc::Rc; + use libc::c_uint; +use serialize::{Encodable, Decodable, Encoder, Decoder}; pub trait Pos { fn from_uint(n: uint) -> Self; diff --git a/src/libsyntax/ext/bytes.rs b/src/libsyntax/ext/bytes.rs index 2844c0b523e5d..9f225d55b444f 100644 --- a/src/libsyntax/ext/bytes.rs +++ b/src/libsyntax/ext/bytes.rs @@ -17,7 +17,6 @@ use ext::base; use ext::build::AstBuilder; use std::ascii::AsciiExt; - pub fn expand_syntax_ext<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) diff --git a/src/libsyntax/ext/quote.rs b/src/libsyntax/ext/quote.rs index 368d4fa84476f..4aadc78babd09 100644 --- a/src/libsyntax/ext/quote.rs +++ b/src/libsyntax/ext/quote.rs @@ -50,8 +50,7 @@ pub mod rt { impl ToTokens for Vec { fn to_tokens(&self, cx: &ExtCtxt) -> Vec { - let a = self.iter().flat_map(|t| t.to_tokens(cx).into_iter()); - FromIterator::from_iter(a) + self.iter().flat_map(|t| t.to_tokens(cx).into_iter()).collect() } } diff --git a/src/libsyntax/owned_slice.rs b/src/libsyntax/owned_slice.rs index 3023c547fb053..f7d2331c9ec58 100644 --- a/src/libsyntax/owned_slice.rs +++ b/src/libsyntax/owned_slice.rs @@ -8,8 +8,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::fmt; use std::default::Default; +use std::fmt; +use std::iter::FromIterator; +use std::ops::Deref; use std::vec; use serialize::{Encodable, Decodable, Encoder, Decoder}; diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs index 13d020f6ae31b..0f5ff33021cc9 100644 --- a/src/libsyntax/parse/lexer/mod.rs +++ b/src/libsyntax/parse/lexer/mod.rs @@ -16,6 +16,7 @@ use ext::tt::transcribe::tt_next_token; use parse::token; use parse::token::{str_to_ident}; +use std::borrow::IntoCow; use std::char; use std::fmt; use std::mem::replace; @@ -358,7 +359,7 @@ impl<'a> StringReader<'a> { pub fn nextnextch(&self) -> Option { let offset = self.byte_offset(self.pos).to_uint(); - let s = self.filemap.deref().src[]; + let s = self.filemap.src.as_slice(); if offset >= s.len() { return None } let str::CharRange { next, .. } = s.char_range_at(offset); if next < s.len() { diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index a2e2abab03e55..7b40ae85c7d79 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -84,11 +84,12 @@ use owned_slice::OwnedSlice; use std::collections::HashSet; use std::io::fs::PathExtensions; +use std::iter; use std::mem; use std::num::Float; use std::rc::Rc; -use std::iter; use std::slice; +use std::str::from_str; bitflags! { flags Restrictions: u8 { diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index f575d3d6c676b..dbc0cef8340a8 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -22,8 +22,10 @@ use util::interner::{RcStr, StrInterner}; use util::interner; use serialize::{Decodable, Decoder, Encodable, Encoder}; +use std::cmp::Equiv; use std::fmt; use std::mem; +use std::ops::Deref; use std::path::BytesContainer; use std::rc::Rc; diff --git a/src/libsyntax/ptr.rs b/src/libsyntax/ptr.rs index 1b3ebde2461e6..8b1aed483c34f 100644 --- a/src/libsyntax/ptr.rs +++ b/src/libsyntax/ptr.rs @@ -10,16 +10,18 @@ //! The AST pointer //! -//! Provides `P`, a frozen owned smart pointer, as a replacement for `@T` in the AST. +//! Provides `P`, a frozen owned smart pointer, as a replacement for `@T` in +//! the AST. //! //! # Motivations and benefits //! -//! * **Identity**: sharing AST nodes is problematic for the various analysis passes -//! (e.g. one may be able to bypass the borrow checker with a shared `ExprAddrOf` -//! node taking a mutable borrow). The only reason `@T` in the AST hasn't caused -//! issues is because of inefficient folding passes which would always deduplicate -//! any such shared nodes. Even if the AST were to switch to an arena, this would -//! still hold, i.e. it couldn't use `&'a T`, but rather a wrapper like `P<'a, T>`. +//! * **Identity**: sharing AST nodes is problematic for the various analysis +//! passes (e.g. one may be able to bypass the borrow checker with a shared +//! `ExprAddrOf` node taking a mutable borrow). The only reason `@T` in the +//! AST hasn't caused issues is because of inefficient folding passes which +//! would always deduplicate any such shared nodes. Even if the AST were to +//! switch to an arena, this would still hold, i.e. it couldn't use `&'a T`, +//! but rather a wrapper like `P<'a, T>`. //! //! * **Immutability**: `P` disallows mutating its inner `T`, unlike `Box` //! (unless it contains an `Unsafe` interior, but that may be denied later). @@ -34,9 +36,9 @@ //! implementation changes (using a special thread-local heap, for example). //! Moreover, a switch to, e.g. `P<'a, T>` would be easy and mostly automated. -use std::fmt; -use std::fmt::Show; +use std::fmt::{mod, Show}; use std::hash::Hash; +use std::ops::Deref; use std::ptr; use serialize::{Encodable, Decodable, Encoder, Decoder}; diff --git a/src/libsyntax/std_inject.rs b/src/libsyntax/std_inject.rs index e1c8ff5011b26..0d89403ab6c71 100644 --- a/src/libsyntax/std_inject.rs +++ b/src/libsyntax/std_inject.rs @@ -152,7 +152,7 @@ impl<'a> fold::Folder for PreludeInjector<'a> { let prelude_path = ast::Path { span: DUMMY_SP, global: false, - segments: vec!( + segments: vec![ ast::PathSegment { identifier: token::str_to_ident("std"), parameters: ast::PathParameters::none(), @@ -160,7 +160,12 @@ impl<'a> fold::Folder for PreludeInjector<'a> { ast::PathSegment { identifier: token::str_to_ident("prelude"), parameters: ast::PathParameters::none(), - }), + }, + ast::PathSegment { + identifier: token::str_to_ident("v1"), + parameters: ast::PathParameters::none(), + }, + ], }; let (crates, uses) = view_items.partitioned(|x| { diff --git a/src/libsyntax/util/interner.rs b/src/libsyntax/util/interner.rs index 97eb43165833a..d25161a12a741 100644 --- a/src/libsyntax/util/interner.rs +++ b/src/libsyntax/util/interner.rs @@ -15,10 +15,12 @@ use ast::Name; use std::borrow::BorrowFrom; -use std::collections::HashMap; use std::cell::RefCell; +use std::cmp::Ordering; +use std::collections::HashMap; use std::fmt; use std::hash::Hash; +use std::ops::Deref; use std::rc::Rc; pub struct Interner { diff --git a/src/libsyntax/util/small_vector.rs b/src/libsyntax/util/small_vector.rs index 946181770c8e9..953a7ae960e8c 100644 --- a/src/libsyntax/util/small_vector.rs +++ b/src/libsyntax/util/small_vector.rs @@ -7,9 +7,11 @@ // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. + use self::SmallVectorRepr::*; use self::IntoIterRepr::*; +use std::iter::FromIterator; use std::mem; use std::slice; use std::vec; diff --git a/src/libtest/lib.rs b/src/libtest/lib.rs index 88dd6fce88f04..c70aa41c569cd 100644 --- a/src/libtest/lib.rs +++ b/src/libtest/lib.rs @@ -49,8 +49,6 @@ use self::TestEvent::*; use self::NamePadding::*; use self::OutputLocation::*; -use std::any::{Any, AnyRefExt}; -use std::collections::BTreeMap; use stats::Stats; use getopts::{OptGroup, optflag, optopt}; use regex::Regex; @@ -58,7 +56,9 @@ use serialize::{json, Decodable, Encodable}; use term::Terminal; use term::color::{Color, RED, YELLOW, GREEN, CYAN}; +use std::any::{Any, AnyRefExt}; use std::cmp; +use std::collections::BTreeMap; use std::f64; use std::fmt::Show; use std::fmt; @@ -69,11 +69,11 @@ use std::io; use std::iter::repeat; use std::num::{Float, FloatMath, Int}; use std::os; -use std::str::FromStr; -use std::string::String; +use std::str::{FromStr, from_str}; +use std::sync::mpsc::{channel, Sender}; use std::thread::{mod, Thread}; -use std::time::Duration; use std::thunk::{Thunk, Invoke}; +use std::time::Duration; // to be used by rustc to compile tests in libtest pub mod test { @@ -1021,7 +1021,7 @@ fn run_tests(opts: &TestOpts, pending += 1; } - let (desc, result, stdout) = rx.recv(); + let (desc, result, stdout) = rx.recv().unwrap(); if concurrency != 1 { try!(callback(TeWait(desc.clone(), PadNone))); } @@ -1034,7 +1034,7 @@ fn run_tests(opts: &TestOpts, for b in filtered_benchs_and_metrics.into_iter() { try!(callback(TeWait(b.desc.clone(), b.testfn.padding()))); run_test(opts, !opts.run_benchmarks, b, tx.clone()); - let (test, result, stdout) = rx.recv(); + let (test, result, stdout) = rx.recv().unwrap(); try!(callback(TeResult(test, result, stdout))); } Ok(()) @@ -1111,7 +1111,7 @@ pub fn run_test(opts: &TestOpts, let TestDescAndFn {desc, testfn} = test; if force_ignore || desc.ignore { - monitor_ch.send((desc, TrIgnored, Vec::new())); + monitor_ch.send((desc, TrIgnored, Vec::new())).unwrap(); return; } @@ -1138,31 +1138,31 @@ pub fn run_test(opts: &TestOpts, let result_guard = cfg.spawn(move || { testfn.invoke(()) }); let stdout = reader.read_to_end().unwrap().into_iter().collect(); let test_result = calc_result(&desc, result_guard.join()); - monitor_ch.send((desc.clone(), test_result, stdout)); + monitor_ch.send((desc.clone(), test_result, stdout)).unwrap(); }).detach(); } match testfn { DynBenchFn(bencher) => { let bs = ::bench::benchmark(|harness| bencher.run(harness)); - monitor_ch.send((desc, TrBench(bs), Vec::new())); + monitor_ch.send((desc, TrBench(bs), Vec::new())).unwrap(); return; } StaticBenchFn(benchfn) => { let bs = ::bench::benchmark(|harness| (benchfn.clone())(harness)); - monitor_ch.send((desc, TrBench(bs), Vec::new())); + monitor_ch.send((desc, TrBench(bs), Vec::new())).unwrap(); return; } DynMetricFn(f) => { let mut mm = MetricMap::new(); f.invoke(&mut mm); - monitor_ch.send((desc, TrMetrics(mm), Vec::new())); + monitor_ch.send((desc, TrMetrics(mm), Vec::new())).unwrap(); return; } StaticMetricFn(f) => { let mut mm = MetricMap::new(); f(&mut mm); - monitor_ch.send((desc, TrMetrics(mm), Vec::new())); + monitor_ch.send((desc, TrMetrics(mm), Vec::new())).unwrap(); return; } DynTestFn(f) => run_test_inner(desc, monitor_ch, opts.nocapture, f), @@ -1466,6 +1466,7 @@ mod tests { StaticTestName, DynTestName, DynTestFn, ShouldFail}; use std::io::TempDir; use std::thunk::Thunk; + use std::sync::mpsc::channel; #[test] pub fn do_not_run_ignored_tests() { @@ -1480,7 +1481,7 @@ mod tests { }; let (tx, rx) = channel(); run_test(&TestOpts::new(), false, desc, tx); - let (_, res, _) = rx.recv(); + let (_, res, _) = rx.recv().unwrap(); assert!(res != TrOk); } @@ -1497,7 +1498,7 @@ mod tests { }; let (tx, rx) = channel(); run_test(&TestOpts::new(), false, desc, tx); - let (_, res, _) = rx.recv(); + let (_, res, _) = rx.recv().unwrap(); assert!(res == TrIgnored); } @@ -1514,7 +1515,7 @@ mod tests { }; let (tx, rx) = channel(); run_test(&TestOpts::new(), false, desc, tx); - let (_, res, _) = rx.recv(); + let (_, res, _) = rx.recv().unwrap(); assert!(res == TrOk); } @@ -1531,7 +1532,7 @@ mod tests { }; let (tx, rx) = channel(); run_test(&TestOpts::new(), false, desc, tx); - let (_, res, _) = rx.recv(); + let (_, res, _) = rx.recv().unwrap(); assert!(res == TrOk); } @@ -1548,7 +1549,7 @@ mod tests { }; let (tx, rx) = channel(); run_test(&TestOpts::new(), false, desc, tx); - let (_, res, _) = rx.recv(); + let (_, res, _) = rx.recv().unwrap(); assert!(res == TrFailed); } @@ -1565,7 +1566,7 @@ mod tests { }; let (tx, rx) = channel(); run_test(&TestOpts::new(), false, desc, tx); - let (_, res, _) = rx.recv(); + let (_, res, _) = rx.recv().unwrap(); assert!(res == TrFailed); } diff --git a/src/libtest/stats.rs b/src/libtest/stats.rs index 41146cded704c..ed6a00a8e9115 100644 --- a/src/libtest/stats.rs +++ b/src/libtest/stats.rs @@ -10,13 +10,14 @@ #![allow(missing_docs)] -use std::collections::hash_map; +use std::cmp::Ordering::{mod, Less, Greater, Equal}; use std::collections::hash_map::Entry::{Occupied, Vacant}; +use std::collections::hash_map; use std::fmt::Show; use std::hash::Hash; use std::io; use std::mem; -use std::num::{Float, FloatMath}; +use std::num::{Float, FloatMath, FromPrimitive}; fn local_cmp(x: T, y: T) -> Ordering { // arbitrarily decide that NaNs are larger than everything. diff --git a/src/libtime/lib.rs b/src/libtime/lib.rs index e58a0229d6962..636e4ca83a8e6 100644 --- a/src/libtime/lib.rs +++ b/src/libtime/lib.rs @@ -32,10 +32,9 @@ extern crate libc; pub use self::ParseError::*; use self::Fmt::*; -use std::fmt::Show; -use std::fmt; +use std::fmt::{mod, Show}; use std::num::SignedInt; -use std::string::String; +use std::ops::{Add, Sub}; use std::time::Duration; static NSEC_PER_SEC: i32 = 1_000_000_000_i32; diff --git a/src/test/auxiliary/cci_capture_clause.rs b/src/test/auxiliary/cci_capture_clause.rs index 1cccb0f7ccbe6..ec470ddc21343 100644 --- a/src/test/auxiliary/cci_capture_clause.rs +++ b/src/test/auxiliary/cci_capture_clause.rs @@ -9,6 +9,7 @@ // except according to those terms. use std::task; +use std::sync::mpsc::{Receiver, channel}; pub fn foo(x: T) -> Receiver { let (tx, rx) = channel(); diff --git a/src/test/auxiliary/static-methods-crate.rs b/src/test/auxiliary/static-methods-crate.rs index 811d8f1169239..ea4751bf4ed20 100644 --- a/src/test/auxiliary/static-methods-crate.rs +++ b/src/test/auxiliary/static-methods-crate.rs @@ -12,6 +12,7 @@ #![crate_type = "lib"] use std::int; +use std::str::from_str; pub trait read { fn readMaybe(s: String) -> Option; diff --git a/src/test/auxiliary/trait_inheritance_overloading_xc.rs b/src/test/auxiliary/trait_inheritance_overloading_xc.rs index 61854aba2790d..7de34d52f513c 100644 --- a/src/test/auxiliary/trait_inheritance_overloading_xc.rs +++ b/src/test/auxiliary/trait_inheritance_overloading_xc.rs @@ -9,6 +9,7 @@ // except according to those terms. use std::cmp::PartialEq; +use std::ops::{Add, Sub, Mul}; pub trait MyNum : Add + Sub + Mul + PartialEq + Clone { } diff --git a/src/test/auxiliary/unboxed-closures-cross-crate.rs b/src/test/auxiliary/unboxed-closures-cross-crate.rs index 9a6a2c7495b79..0b65fa913cb77 100644 --- a/src/test/auxiliary/unboxed-closures-cross-crate.rs +++ b/src/test/auxiliary/unboxed-closures-cross-crate.rs @@ -10,6 +10,8 @@ #![feature(unboxed_closures)] +use std::ops::Add; + #[inline] pub fn has_closures() -> uint { let x = 1u; diff --git a/src/test/bench/core-map.rs b/src/test/bench/core-map.rs index 60331dfb5505a..0ada1cb991c6b 100644 --- a/src/test/bench/core-map.rs +++ b/src/test/bench/core-map.rs @@ -13,6 +13,7 @@ use std::collections::{BTreeMap, HashMap, HashSet}; use std::os; use std::rand::{Rng, IsaacRng, SeedableRng}; +use std::str::from_str; use std::time::Duration; use std::uint; diff --git a/src/test/bench/core-set.rs b/src/test/bench/core-set.rs index 49f5c7751d9a0..52380001c6c0d 100644 --- a/src/test/bench/core-set.rs +++ b/src/test/bench/core-set.rs @@ -15,11 +15,12 @@ extern crate collections; extern crate rand; +use std::collections::BTreeSet; use std::collections::BitvSet; use std::collections::HashSet; -use std::collections::BTreeSet; use std::hash::Hash; use std::os; +use std::str::from_str; use std::time::Duration; use std::uint; diff --git a/src/test/bench/core-uint-to-str.rs b/src/test/bench/core-uint-to-str.rs index 98113cb834767..08637b4bf1c1c 100644 --- a/src/test/bench/core-uint-to-str.rs +++ b/src/test/bench/core-uint-to-str.rs @@ -9,6 +9,7 @@ // except according to those terms. use std::os; +use std::str::from_str; use std::uint; fn main() { diff --git a/src/test/bench/msgsend-pipes-shared.rs b/src/test/bench/msgsend-pipes-shared.rs index 645c029f935a7..94b7e58a54c1c 100644 --- a/src/test/bench/msgsend-pipes-shared.rs +++ b/src/test/bench/msgsend-pipes-shared.rs @@ -18,8 +18,10 @@ // different scalability characteristics compared to the select // version. +use std::comm::{channel, Sender, Receiver}; use std::comm; use std::os; +use std::str::from_str; use std::thread::Thread; use std::time::Duration; use std::uint; diff --git a/src/test/bench/msgsend-pipes.rs b/src/test/bench/msgsend-pipes.rs index ed96c6406d836..4fb84c8610695 100644 --- a/src/test/bench/msgsend-pipes.rs +++ b/src/test/bench/msgsend-pipes.rs @@ -14,7 +14,9 @@ // // I *think* it's the same, more or less. +use std::comm::{channel, Sender, Receiver}; use std::os; +use std::str::from_str; use std::thread::Thread; use std::time::Duration; use std::uint; diff --git a/src/test/bench/msgsend-ring-mutex-arcs.rs b/src/test/bench/msgsend-ring-mutex-arcs.rs index 49f53bf9d3883..c0b2edd300146 100644 --- a/src/test/bench/msgsend-ring-mutex-arcs.rs +++ b/src/test/bench/msgsend-ring-mutex-arcs.rs @@ -19,6 +19,7 @@ // ignore-lexer-test FIXME #15679 use std::os; +use std::str::from_str; use std::sync::{Arc, Future, Mutex, Condvar}; use std::time::Duration; use std::uint; diff --git a/src/test/bench/rt-messaging-ping-pong.rs b/src/test/bench/rt-messaging-ping-pong.rs index 73d54372b274f..d3a340d488b57 100644 --- a/src/test/bench/rt-messaging-ping-pong.rs +++ b/src/test/bench/rt-messaging-ping-pong.rs @@ -17,7 +17,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::comm::channel; use std::os; +use std::str::from_str; +use std::thread::Thread; use std::uint; // This is a simple bench that creates M pairs of tasks. These @@ -34,21 +37,21 @@ fn ping_pong_bench(n: uint, m: uint) { // Create a stream B->A let (btx, brx) = channel::<()>(); - spawn(move|| { + Thread::spawn(move|| { let (tx, rx) = (atx, brx); for _ in range(0, n) { tx.send(()); rx.recv(); } - }); + }).detach(); - spawn(move|| { + Thread::spawn(move|| { let (tx, rx) = (btx, arx); for _ in range(0, n) { rx.recv(); tx.send(()); } - }); + }).detach(); } for _ in range(0, m) { diff --git a/src/test/bench/rt-parfib.rs b/src/test/bench/rt-parfib.rs index bdf22cd739588..0a513c32aafc8 100644 --- a/src/test/bench/rt-parfib.rs +++ b/src/test/bench/rt-parfib.rs @@ -8,7 +8,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::comm::channel; use std::os; +use std::str::from_str; +use std::thread::Thread; use std::uint; // A simple implementation of parfib. One subtree is found in a new @@ -21,9 +24,9 @@ fn parfib(n: uint) -> uint { } let (tx, rx) = channel(); - spawn(move|| { + Thread::spawn(move|| { tx.send(parfib(n-1)); - }); + }).detach(); let m2 = parfib(n-2); return (rx.recv() + m2); } diff --git a/src/test/bench/shootout-ackermann.rs b/src/test/bench/shootout-ackermann.rs index e7a50382c9469..f7810d5d740c0 100644 --- a/src/test/bench/shootout-ackermann.rs +++ b/src/test/bench/shootout-ackermann.rs @@ -9,6 +9,7 @@ // except according to those terms. use std::os; +use std::str::from_str; fn ack(m: int, n: int) -> int { if m == 0 { diff --git a/src/test/bench/shootout-binarytrees.rs b/src/test/bench/shootout-binarytrees.rs index 0b16e8011e832..2f25c37a911df 100644 --- a/src/test/bench/shootout-binarytrees.rs +++ b/src/test/bench/shootout-binarytrees.rs @@ -41,7 +41,9 @@ extern crate arena; use std::iter::range_step; +use std::str::from_str; use std::sync::Future; + use arena::TypedArena; enum Tree<'a> { diff --git a/src/test/bench/shootout-chameneos-redux.rs b/src/test/bench/shootout-chameneos-redux.rs index dcdb90a11c88c..6bbf6cde4ea29 100644 --- a/src/test/bench/shootout-chameneos-redux.rs +++ b/src/test/bench/shootout-chameneos-redux.rs @@ -41,8 +41,10 @@ // no-pretty-expanded use self::Color::{Red, Yellow, Blue}; -use std::string::String; +use std::comm::{channel, Sender, Receiver}; use std::fmt; +use std::str::from_str; +use std::thread::Thread; fn print_complements() { let all = [Blue, Red, Yellow]; @@ -188,13 +190,13 @@ fn rendezvous(nn: uint, set: Vec) { let to_rendezvous = to_rendezvous.clone(); let to_rendezvous_log = to_rendezvous_log.clone(); let (to_creature, from_rendezvous) = channel(); - spawn(move|| { + Thread::spawn(move|| { creature(ii, col, from_rendezvous, to_rendezvous, to_rendezvous_log); - }); + }).detach(); to_creature }).collect(); diff --git a/src/test/bench/shootout-fannkuch-redux.rs b/src/test/bench/shootout-fannkuch-redux.rs index 723b2b722d7e1..73e0c9e0a1fd2 100644 --- a/src/test/bench/shootout-fannkuch-redux.rs +++ b/src/test/bench/shootout-fannkuch-redux.rs @@ -40,8 +40,9 @@ #![feature(slicing_syntax)] -use std::{cmp, iter, mem}; +use std::str::from_str; use std::sync::Future; +use std::{cmp, iter, mem}; fn rotate(x: &mut [i32]) { let mut prev = x[0]; diff --git a/src/test/bench/shootout-fasta-redux.rs b/src/test/bench/shootout-fasta-redux.rs index eb18cfdaed3ad..05524492c28ee 100644 --- a/src/test/bench/shootout-fasta-redux.rs +++ b/src/test/bench/shootout-fasta-redux.rs @@ -44,6 +44,7 @@ use std::cmp::min; use std::io::{stdout, IoResult}; use std::os; use std::slice::bytes::copy_memory; +use std::str::from_str; const LINE_LEN: uint = 60; const LOOKUP_SIZE: uint = 4 * 1024; diff --git a/src/test/bench/shootout-fasta.rs b/src/test/bench/shootout-fasta.rs index 2de61cf3572c9..7009dd4c1a76f 100644 --- a/src/test/bench/shootout-fasta.rs +++ b/src/test/bench/shootout-fasta.rs @@ -40,11 +40,12 @@ #![feature(slicing_syntax)] -use std::io; -use std::io::{BufferedWriter, File}; use std::cmp::min; +use std::io::{BufferedWriter, File}; +use std::io; use std::num::Float; use std::os; +use std::str::from_str; const LINE_LENGTH: uint = 60; const IM: u32 = 139968; diff --git a/src/test/bench/shootout-fibo.rs b/src/test/bench/shootout-fibo.rs index 10c0d0a8044cb..cbacf415f6f7f 100644 --- a/src/test/bench/shootout-fibo.rs +++ b/src/test/bench/shootout-fibo.rs @@ -9,6 +9,7 @@ // except according to those terms. use std::os; +use std::str::from_str; fn fib(n: int) -> int { if n < 2 { diff --git a/src/test/bench/shootout-k-nucleotide-pipes.rs b/src/test/bench/shootout-k-nucleotide-pipes.rs index f49b648e21579..b59eef916dc09 100644 --- a/src/test/bench/shootout-k-nucleotide-pipes.rs +++ b/src/test/bench/shootout-k-nucleotide-pipes.rs @@ -18,12 +18,15 @@ extern crate collections; use std::ascii::{AsciiExt, OwnedAsciiExt}; +use std::cmp::Ordering::{mod, Less, Greater, Equal}; use std::collections::HashMap; +use std::comm::{channel, Sender, Receiver}; use std::mem::replace; use std::num::Float; use std::option; use std::os; -use std::string::String; +use std::string::IntoString; +use std::thread::Thread; fn f64_cmp(x: f64, y: f64) -> Ordering { // arbitrarily decide that NaNs are larger than everything. @@ -167,9 +170,9 @@ fn main() { let (to_child, from_parent) = channel(); - spawn(move|| { + Thread::spawn(move|| { make_sequence_processor(sz, &from_parent, &to_parent_); - }); + }).detach(); to_child }).collect:: >> >(); diff --git a/src/test/bench/shootout-k-nucleotide.rs b/src/test/bench/shootout-k-nucleotide.rs index a0ef392ed3af2..3dc5180591712 100644 --- a/src/test/bench/shootout-k-nucleotide.rs +++ b/src/test/bench/shootout-k-nucleotide.rs @@ -43,7 +43,6 @@ #![feature(slicing_syntax)] use std::ascii::OwnedAsciiExt; -use std::string::String; use std::slice; use std::sync::{Arc, Future}; diff --git a/src/test/bench/shootout-mandelbrot.rs b/src/test/bench/shootout-mandelbrot.rs index bb0e09370d8e9..51ce4cbaa841d 100644 --- a/src/test/bench/shootout-mandelbrot.rs +++ b/src/test/bench/shootout-mandelbrot.rs @@ -47,6 +47,7 @@ use std::io; use std::os; use std::simd::f64x2; +use std::str::from_str; use std::sync::{Arc, Future}; const ITER: int = 50; diff --git a/src/test/bench/shootout-meteor.rs b/src/test/bench/shootout-meteor.rs index 9a3b6953062b4..2e229a50d16ef 100644 --- a/src/test/bench/shootout-meteor.rs +++ b/src/test/bench/shootout-meteor.rs @@ -40,7 +40,9 @@ // no-pretty-expanded FIXME #15189 +use std::comm::channel; use std::sync::Arc; +use std::thread::Thread; // // Utilities. @@ -310,11 +312,11 @@ fn par_search(masks: Vec>>) -> Data { let masks = masks.clone(); let tx = tx.clone(); let m = *m; - spawn(move|| { + Thread::spawn(move|| { let mut data = Data::new(); search(&*masks, m, 1, List::Cons(m, &List::Nil), &mut data); tx.send(data); - }); + }).detach(); } // collecting the results diff --git a/src/test/bench/shootout-nbody.rs b/src/test/bench/shootout-nbody.rs index dab67331120a9..6a325798f5805 100644 --- a/src/test/bench/shootout-nbody.rs +++ b/src/test/bench/shootout-nbody.rs @@ -39,6 +39,7 @@ // OF THE POSSIBILITY OF SUCH DAMAGE. use std::num::Float; +use std::str::from_str; const PI: f64 = 3.141592653589793; const SOLAR_MASS: f64 = 4.0 * PI * PI; diff --git a/src/test/bench/shootout-pfib.rs b/src/test/bench/shootout-pfib.rs index f7e8fc8fe1b7a..e58303a724adb 100644 --- a/src/test/bench/shootout-pfib.rs +++ b/src/test/bench/shootout-pfib.rs @@ -20,8 +20,10 @@ extern crate getopts; +use std::comm::{channel, Sender}; use std::os; use std::result::Result::{Ok, Err}; +use std::str::from_str; use std::thread::Thread; use std::time::Duration; diff --git a/src/test/bench/shootout-reverse-complement.rs b/src/test/bench/shootout-reverse-complement.rs index 66965110f73ee..e286efeb30450 100644 --- a/src/test/bench/shootout-reverse-complement.rs +++ b/src/test/bench/shootout-reverse-complement.rs @@ -45,9 +45,10 @@ extern crate libc; use std::io::stdio::{stdin_raw, stdout_raw}; +use std::io::{IoResult, EndOfFile}; use std::num::{div_rem}; use std::ptr::{copy_memory, Unique}; -use std::io::{IoResult, EndOfFile}; +use std::thread::Thread; struct Tables { table8: [u8;1 << 8], @@ -229,26 +230,29 @@ unsafe impl Send for Racy {} fn parallel<'a, I, T, F>(mut iter: I, f: F) where T: 'a+Send + Sync, I: Iterator<&'a mut [T]>, - F: Fn(&'a mut [T]) + Sync { + F: Fn(&mut [T]) + Sync { use std::mem; use std::raw::Repr; - let (tx, rx) = channel(); - for chunk in iter { - let tx = tx.clone(); - + iter.map(|chunk| { // Need to convert `f` and `chunk` to something that can cross the task // boundary. +<<<<<<< HEAD let f = Racy(&f as *const F as *const uint); let raw = Racy(chunk.repr()); spawn(move|| { let f = f.0 as *const F; unsafe { (*f)(mem::transmute(raw.0)) } drop(tx) +======= + let f = &f as *const F as *const uint; + let raw = chunk.repr(); + Thread::spawn(move|| { + let f = f as *const F; + unsafe { (*f)(mem::transmute(raw)) } +>>>>>>> std: Stabilize the prelude module }); - } - drop(tx); - for () in rx.iter() {} + }).collect::>(); } fn main() { diff --git a/src/test/bench/shootout-spectralnorm.rs b/src/test/bench/shootout-spectralnorm.rs index df388fbdde54f..b8bb39d4b0527 100644 --- a/src/test/bench/shootout-spectralnorm.rs +++ b/src/test/bench/shootout-spectralnorm.rs @@ -44,11 +44,13 @@ #![feature(unboxed_closures)] use std::iter::AdditiveIterator; +use std::thread::Thread; use std::mem; use std::num::Float; use std::os; use std::raw::Repr; use std::simd::f64x2; +use std::str::from_str; fn main() { let args = os::args(); @@ -80,14 +82,15 @@ fn mult_AtAv(v: &[f64], out: &mut [f64], tmp: &mut [f64]) { } fn mult_Av(v: &[f64], out: &mut [f64]) { - parallel(out, |&: start, out| mult(v, out, start, |i, j| A(i, j))); + parallel(out, |start, out| mult(v, out, start, |i, j| A(i, j))); } fn mult_Atv(v: &[f64], out: &mut [f64]) { - parallel(out, |&: start, out| mult(v, out, start, |i, j| A(j, i))); + parallel(out, |start, out| mult(v, out, start, |i, j| A(j, i))); } -fn mult(v: &[f64], out: &mut [f64], start: uint, a: |uint, uint| -> f64) { +fn mult(v: &[f64], out: &mut [f64], start: uint, a: F) + where F: Fn(uint, uint) -> f64 { for (i, slot) in out.iter_mut().enumerate().map(|(i, s)| (i + start, s)) { let mut sum = f64x2(0.0, 0.0); for (j, chunk) in v.chunks(2).enumerate().map(|(j, s)| (2 * j, s)) { @@ -116,25 +119,20 @@ unsafe impl Send for Racy {} // Executes a closure in parallel over the given mutable slice. The closure `f` // is run in parallel and yielded the starting index within `v` as well as a // sub-slice of `v`. -fn parallel<'a, T, F>(v: &'a mut [T], f: F) - where T: Send + Sync, - F: Fn(uint, &'a mut [T]) + Sync { - let (tx, rx) = channel(); +fn parallel(v: &mut [T], f: F) + where T: Send + Sync, + F: Fn(uint, &mut [T]) + Sync { let size = v.len() / os::num_cpus() + 1; - for (i, chunk) in v.chunks_mut(size).enumerate() { - let tx = tx.clone(); - + v.chunks_mut(size).enumerate().map(|(i, chunk)| { // Need to convert `f` and `chunk` to something that can cross the task // boundary. let f = Racy(&f as *const _ as *const uint); let raw = Racy(chunk.repr()); - spawn(move|| { + Thread::spawn(move|| { let f = f.0 as *const F; unsafe { (*f)(i * size, mem::transmute(raw.0)) } drop(tx) - }); - } - drop(tx); - for () in rx.iter() {} + }) + }).collect::>(); } diff --git a/src/test/bench/shootout-threadring.rs b/src/test/bench/shootout-threadring.rs index 111a92b083aa3..94d958ea8d524 100644 --- a/src/test/bench/shootout-threadring.rs +++ b/src/test/bench/shootout-threadring.rs @@ -38,15 +38,19 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. +use std::comm::{channel, Sender, Receiver}; +use std::str::from_str; +use std::thread::Thread; + fn start(n_tasks: int, token: int) { let (tx, mut rx) = channel(); tx.send(token); for i in range(2, n_tasks + 1) { let (tx, next_rx) = channel(); - spawn(move|| roundtrip(i, tx, rx)); + Thread::spawn(move|| roundtrip(i, tx, rx)).detach(); rx = next_rx; } - spawn(move|| roundtrip(1, tx, rx)); + Thread::spawn(move|| roundtrip(1, tx, rx)).detach(); } fn roundtrip(id: int, tx: Sender, rx: Receiver) { diff --git a/src/test/bench/spawnone.rs b/src/test/bench/spawnone.rs deleted file mode 100644 index ca36d99014cf4..0000000000000 --- a/src/test/bench/spawnone.rs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// Useful for checking syscall usage of baseline scheduler usage -fn main() { - spawn(move|| {}); -} diff --git a/src/test/bench/std-smallintmap.rs b/src/test/bench/std-smallintmap.rs index 576d96ba2a355..035b222e6ce62 100644 --- a/src/test/bench/std-smallintmap.rs +++ b/src/test/bench/std-smallintmap.rs @@ -12,6 +12,7 @@ use std::collections::VecMap; use std::os; +use std::str::from_str; use std::time::Duration; use std::uint; diff --git a/src/test/bench/sudoku.rs b/src/test/bench/sudoku.rs index 5fb7e2c3a8498..cccc9362a729b 100644 --- a/src/test/bench/sudoku.rs +++ b/src/test/bench/sudoku.rs @@ -12,11 +12,12 @@ #![allow(non_snake_case)] -use std::io; -use std::io::stdio::StdReader; use std::io::BufferedReader; +use std::io::stdio::StdReader; +use std::io; use std::num::Int; use std::os; +use std::str::from_str; // Computes a single solution to a given 9x9 sudoku // diff --git a/src/test/bench/task-perf-jargon-metal-smoke.rs b/src/test/bench/task-perf-jargon-metal-smoke.rs index 789ccb6142a11..287b3fc6c460d 100644 --- a/src/test/bench/task-perf-jargon-metal-smoke.rs +++ b/src/test/bench/task-perf-jargon-metal-smoke.rs @@ -17,16 +17,18 @@ // ignore-pretty very bad with line comments -use std::comm; +use std::comm::{mod, channel}; use std::os; +use std::str::from_str; use std::task; +use std::thread::Thread; use std::uint; fn child_generation(gens_left: uint, tx: comm::Sender<()>) { // This used to be O(n^2) in the number of generations that ever existed. // With this code, only as many generations are alive at a time as tasks // alive at a time, - spawn(move|| { + Thread::spawn(move|| { if gens_left & 1 == 1 { task::deschedule(); // shake things up a bit } @@ -35,7 +37,7 @@ fn child_generation(gens_left: uint, tx: comm::Sender<()>) { } else { tx.send(()) } - }); + }).detach(); } fn main() { diff --git a/src/test/bench/task-perf-spawnalot.rs b/src/test/bench/task-perf-spawnalot.rs index a6852d396d9cf..7e2c6fcf0ecd4 100644 --- a/src/test/bench/task-perf-spawnalot.rs +++ b/src/test/bench/task-perf-spawnalot.rs @@ -11,6 +11,7 @@ use std::os; use std::task; use std::uint; +use std::str::from_str; fn f(n: uint) { let mut i = 0u; diff --git a/src/test/compile-fail/bind-by-move-no-guards.rs b/src/test/compile-fail/bind-by-move-no-guards.rs index 18534db0dd5a0..bb6060f2543e2 100644 --- a/src/test/compile-fail/bind-by-move-no-guards.rs +++ b/src/test/compile-fail/bind-by-move-no-guards.rs @@ -8,13 +8,16 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::sync::mpsc::channel; + fn main() { let (tx, rx) = channel(); let x = Some(rx); tx.send(false); match x { - Some(z) if z.recv() => { panic!() }, //~ ERROR cannot bind by-move into a pattern guard - Some(z) => { assert!(!z.recv()); }, + Some(z) if z.recv().unwrap() => { panic!() }, + //~^ ERROR cannot bind by-move into a pattern guard + Some(z) => { assert!(!z.recv().unwrap()); }, None => panic!() } } diff --git a/src/test/compile-fail/binop-consume-args.rs b/src/test/compile-fail/binop-consume-args.rs index 2bdd148b99bd0..afa255be699e7 100644 --- a/src/test/compile-fail/binop-consume-args.rs +++ b/src/test/compile-fail/binop-consume-args.rs @@ -10,6 +10,8 @@ // Test that binary operators consume their arguments +use std::ops::{Add, Sub, Mul, Div, Rem, BitAnd, BitXor, BitOr, Shl, Shr}; + fn add, B>(lhs: A, rhs: B) { lhs + rhs; drop(lhs); //~ ERROR use of moved value: `lhs` diff --git a/src/test/compile-fail/binop-move-semantics.rs b/src/test/compile-fail/binop-move-semantics.rs index d9440e1837572..e48c88a49f0bf 100644 --- a/src/test/compile-fail/binop-move-semantics.rs +++ b/src/test/compile-fail/binop-move-semantics.rs @@ -10,6 +10,8 @@ // Test that move restrictions are enforced on overloaded binary operations +use std::ops::Add; + fn double_move>(x: T) { x + diff --git a/src/test/compile-fail/borrowck-loan-in-overloaded-op.rs b/src/test/compile-fail/borrowck-loan-in-overloaded-op.rs index 692303fc1e481..af9a18acbf2ad 100644 --- a/src/test/compile-fail/borrowck-loan-in-overloaded-op.rs +++ b/src/test/compile-fail/borrowck-loan-in-overloaded-op.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::ops::Add; #[deriving(Clone)] struct foo(Box); diff --git a/src/test/compile-fail/borrowck-loan-rcvr-overloaded-op.rs b/src/test/compile-fail/borrowck-loan-rcvr-overloaded-op.rs index b83e1544c96d3..b571af2425a5c 100644 --- a/src/test/compile-fail/borrowck-loan-rcvr-overloaded-op.rs +++ b/src/test/compile-fail/borrowck-loan-rcvr-overloaded-op.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::ops::Add; + #[deriving(Copy)] struct Point { x: int, diff --git a/src/test/compile-fail/borrowck-overloaded-index-2.rs b/src/test/compile-fail/borrowck-overloaded-index-2.rs index d9d7a43d46c41..01afe405d5e12 100644 --- a/src/test/compile-fail/borrowck-overloaded-index-2.rs +++ b/src/test/compile-fail/borrowck-overloaded-index-2.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::ops::Index; + struct MyVec { data: Vec, } diff --git a/src/test/compile-fail/borrowck-overloaded-index-autoderef.rs b/src/test/compile-fail/borrowck-overloaded-index-autoderef.rs index 2253d7512c053..e8949d4b30bef 100644 --- a/src/test/compile-fail/borrowck-overloaded-index-autoderef.rs +++ b/src/test/compile-fail/borrowck-overloaded-index-autoderef.rs @@ -11,6 +11,8 @@ // Test that we still see borrowck errors of various kinds when using // indexing and autoderef in combination. +use std::ops::{Index, IndexMut}; + struct Foo { x: int, y: int, diff --git a/src/test/compile-fail/borrowck-overloaded-index.rs b/src/test/compile-fail/borrowck-overloaded-index.rs index 0422f6381dc3d..933d0f15e4e70 100644 --- a/src/test/compile-fail/borrowck-overloaded-index.rs +++ b/src/test/compile-fail/borrowck-overloaded-index.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::ops::{Index, IndexMut}; + struct Foo { x: int, y: int, diff --git a/src/test/compile-fail/builtin-superkinds-self-type.rs b/src/test/compile-fail/builtin-superkinds-self-type.rs index 4c7ff60fbdd0f..9826a5a0126f4 100644 --- a/src/test/compile-fail/builtin-superkinds-self-type.rs +++ b/src/test/compile-fail/builtin-superkinds-self-type.rs @@ -11,6 +11,8 @@ // Tests (negatively) the ability for the Self type in default methods // to use capabilities granted by builtin kinds as supertraits. +use std::sync::mpsc::{channel, Sender}; + trait Foo : Sync+'static { fn foo(self, mut chan: Sender) { } } diff --git a/src/test/compile-fail/comm-not-freeze-receiver.rs b/src/test/compile-fail/comm-not-freeze-receiver.rs index 8cb4b6328c490..2e535b3950938 100644 --- a/src/test/compile-fail/comm-not-freeze-receiver.rs +++ b/src/test/compile-fail/comm-not-freeze-receiver.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::sync::mpsc::Receiver; + fn test() {} fn main() { diff --git a/src/test/compile-fail/comm-not-freeze.rs b/src/test/compile-fail/comm-not-freeze.rs index 8c17895eb8a02..1b1c43e4793e3 100644 --- a/src/test/compile-fail/comm-not-freeze.rs +++ b/src/test/compile-fail/comm-not-freeze.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::sync::mpsc::Sender; + fn test() {} fn main() { diff --git a/src/test/compile-fail/issue-12041.rs b/src/test/compile-fail/issue-12041.rs index 1878b5f5dea8d..094f6d64edc2e 100644 --- a/src/test/compile-fail/issue-12041.rs +++ b/src/test/compile-fail/issue-12041.rs @@ -8,9 +8,12 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::sync::mpsc::channel; +use std::thread::Thread; + fn main() { let (tx, rx) = channel(); - spawn(move|| { + let _t = Thread::spawn(move|| -> () { loop { let tx = tx; //~^ ERROR: use of moved value: `tx` diff --git a/src/test/compile-fail/issue-16709.rs b/src/test/compile-fail/issue-16709.rs index fc15801eb75b9..327f50ee059f9 100644 --- a/src/test/compile-fail/issue-16709.rs +++ b/src/test/compile-fail/issue-16709.rs @@ -11,6 +11,8 @@ use std::ptr; use std::raw; +trait Slice {} + fn main() { unsafe { let nil: *const u8 = ptr::null(); diff --git a/src/test/compile-fail/issue-18566.rs b/src/test/compile-fail/issue-18566.rs index f64d8fee2d8b3..c2e4629e14de0 100644 --- a/src/test/compile-fail/issue-18566.rs +++ b/src/test/compile-fail/issue-18566.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::ops::Deref; + struct MyPtr<'a>(&'a mut uint); impl<'a> Deref for MyPtr<'a> { fn deref<'b>(&'b self) -> &'b uint { self.0 } diff --git a/src/test/compile-fail/issue-3702-2.rs b/src/test/compile-fail/issue-3702-2.rs index 54100d543dda0..1e80fd7a7e910 100644 --- a/src/test/compile-fail/issue-3702-2.rs +++ b/src/test/compile-fail/issue-3702-2.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::num::ToPrimitive; + trait Add { fn to_int(&self) -> int; fn add_dynamic(&self, other: &Add) -> int; diff --git a/src/test/compile-fail/unop-move-semantics.rs b/src/test/compile-fail/unop-move-semantics.rs index ccdc7b833e714..c458c539c0766 100644 --- a/src/test/compile-fail/unop-move-semantics.rs +++ b/src/test/compile-fail/unop-move-semantics.rs @@ -10,6 +10,8 @@ // Test that move restrictions are enforced on overloaded unary operations +use std::ops::Not; + fn move_then_borrow + Clone>(x: T) { !x; diff --git a/src/test/compile-fail/unsendable-class.rs b/src/test/compile-fail/unsendable-class.rs index cd5918e2f47ff..993df8e59f3e0 100644 --- a/src/test/compile-fail/unsendable-class.rs +++ b/src/test/compile-fail/unsendable-class.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::sync::mpsc::channel; // Test that a class with an unsendable field can't be // sent diff --git a/src/test/compile-fail/wrong-mul-method-signature.rs b/src/test/compile-fail/wrong-mul-method-signature.rs index b5e4cac75550f..bde5b853078f2 100644 --- a/src/test/compile-fail/wrong-mul-method-signature.rs +++ b/src/test/compile-fail/wrong-mul-method-signature.rs @@ -13,6 +13,8 @@ // (In this case the mul method should take &f64 and not f64) // See: #11450 +use std::ops::Mul; + struct Vec1 { x: f64 } diff --git a/src/test/pretty/issue-4264.pp b/src/test/pretty/issue-4264.pp index c2ebd764ad6b9..35bd22880cef7 100644 --- a/src/test/pretty/issue-4264.pp +++ b/src/test/pretty/issue-4264.pp @@ -4,7 +4,7 @@ #[phase(plugin, link)] extern crate "std" as std; #[prelude_import] -use std::prelude::*; +use std::prelude::v1::*; // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. diff --git a/src/test/run-pass/bool.rs b/src/test/run-pass/bool.rs index 238d0ecdca7f8..b3c4802530ed3 100644 --- a/src/test/run-pass/bool.rs +++ b/src/test/run-pass/bool.rs @@ -10,6 +10,9 @@ // Basic boolean tests +use std::cmp::Ordering::{Equal, Greater, Less}; +use std::ops::{BitAnd, BitOr, BitXor}; + fn main() { assert_eq!(false.eq(&true), false); assert_eq!(false == false, true); diff --git a/src/test/run-pass/builtin-superkinds-capabilities-transitive.rs b/src/test/run-pass/builtin-superkinds-capabilities-transitive.rs index 2abc58d8a4954..365670db6f928 100644 --- a/src/test/run-pass/builtin-superkinds-capabilities-transitive.rs +++ b/src/test/run-pass/builtin-superkinds-capabilities-transitive.rs @@ -14,6 +14,8 @@ // a Send. Basically this just makes sure rustc is using // each_bound_trait_and_supertraits in type_contents correctly. +use std::sync::mpsc::{channel, Sender}; + trait Bar : Send { } trait Foo : Bar { } @@ -21,11 +23,11 @@ impl Foo for T { } impl Bar for T { } fn foo(val: T, chan: Sender) { - chan.send(val); + chan.send(val).unwrap(); } pub fn main() { let (tx, rx) = channel(); foo(31337i, tx); - assert!(rx.recv() == 31337i); + assert!(rx.recv().unwrap() == 31337i); } diff --git a/src/test/run-pass/builtin-superkinds-capabilities-xc.rs b/src/test/run-pass/builtin-superkinds-capabilities-xc.rs index c2b874c61a77f..1f42076f6d6e1 100644 --- a/src/test/run-pass/builtin-superkinds-capabilities-xc.rs +++ b/src/test/run-pass/builtin-superkinds-capabilities-xc.rs @@ -15,6 +15,8 @@ // even when using them cross-crate. extern crate trait_superkinds_in_metadata; + +use std::sync::mpsc::{channel, Sender, Receiver}; use trait_superkinds_in_metadata::{RequiresRequiresShareAndSend, RequiresShare}; #[deriving(PartialEq)] @@ -24,11 +26,11 @@ impl RequiresShare for X { } impl RequiresRequiresShareAndSend for X { } fn foo(val: T, chan: Sender) { - chan.send(val); + chan.send(val).unwrap(); } pub fn main() { let (tx, rx): (Sender>, Receiver>) = channel(); foo(X(31337i), tx); - assert!(rx.recv() == X(31337i)); + assert!(rx.recv().unwrap() == X(31337i)); } diff --git a/src/test/run-pass/builtin-superkinds-capabilities.rs b/src/test/run-pass/builtin-superkinds-capabilities.rs index fb3e1b0272858..7f4a2398f54ba 100644 --- a/src/test/run-pass/builtin-superkinds-capabilities.rs +++ b/src/test/run-pass/builtin-superkinds-capabilities.rs @@ -12,16 +12,18 @@ // builtin-kinds, e.g., if a trait requires Send to implement, then // at usage site of that trait, we know we have the Send capability. +use std::sync::mpsc::{channel, Sender, Receiver}; + trait Foo : Send { } impl Foo for T { } fn foo(val: T, chan: Sender) { - chan.send(val); + chan.send(val).unwrap(); } pub fn main() { let (tx, rx): (Sender, Receiver) = channel(); foo(31337i, tx); - assert!(rx.recv() == 31337i); + assert!(rx.recv().unwrap() == 31337i); } diff --git a/src/test/run-pass/builtin-superkinds-self-type.rs b/src/test/run-pass/builtin-superkinds-self-type.rs index 1c156f6551c8d..bf06bf8b8c65a 100644 --- a/src/test/run-pass/builtin-superkinds-self-type.rs +++ b/src/test/run-pass/builtin-superkinds-self-type.rs @@ -11,9 +11,11 @@ // Tests the ability for the Self type in default methods to use // capabilities granted by builtin kinds as supertraits. +use std::sync::mpsc::{Sender, channel}; + trait Foo : Send { fn foo(self, tx: Sender) { - tx.send(self); + tx.send(self).unwrap(); } } @@ -22,5 +24,5 @@ impl Foo for T { } pub fn main() { let (tx, rx) = channel(); 1193182i.foo(tx); - assert!(rx.recv() == 1193182i); + assert!(rx.recv().unwrap() == 1193182i); } diff --git a/src/test/run-pass/c-stack-returning-int64.rs b/src/test/run-pass/c-stack-returning-int64.rs index 597e067b8b6ae..c95cf0bfdee45 100644 --- a/src/test/run-pass/c-stack-returning-int64.rs +++ b/src/test/run-pass/c-stack-returning-int64.rs @@ -12,6 +12,8 @@ extern crate libc; +use std::c_str::ToCStr; + mod mlibc { use libc::{c_char, c_long, c_longlong}; diff --git a/src/test/run-pass/capturing-logging.rs b/src/test/run-pass/capturing-logging.rs index f2df5ef38c382..3f6d6a02c7926 100644 --- a/src/test/run-pass/capturing-logging.rs +++ b/src/test/run-pass/capturing-logging.rs @@ -17,8 +17,10 @@ extern crate log; use log::{set_logger, Logger, LogRecord}; +use std::sync::mpsc::channel; use std::fmt; use std::io::{ChanReader, ChanWriter}; +use std::thread::Thread; struct MyWriter(ChanWriter); @@ -32,7 +34,7 @@ impl Logger for MyWriter { fn main() { let (tx, rx) = channel(); let (mut r, w) = (ChanReader::new(rx), ChanWriter::new(tx)); - spawn(move|| { + let _t = Thread::spawn(move|| { set_logger(box MyWriter(w) as Box); debug!("debug"); info!("info"); diff --git a/src/test/run-pass/cci_capture_clause.rs b/src/test/run-pass/cci_capture_clause.rs index c4bf813150622..8b2947ba3eef0 100644 --- a/src/test/run-pass/cci_capture_clause.rs +++ b/src/test/run-pass/cci_capture_clause.rs @@ -16,5 +16,5 @@ extern crate cci_capture_clause; pub fn main() { - cci_capture_clause::foo(()).recv() + cci_capture_clause::foo(()).recv().unwrap(); } diff --git a/src/test/run-pass/closure-bounds-can-capture-chan.rs b/src/test/run-pass/closure-bounds-can-capture-chan.rs index cdcdad47ea497..816b28c3a9ae1 100644 --- a/src/test/run-pass/closure-bounds-can-capture-chan.rs +++ b/src/test/run-pass/closure-bounds-can-capture-chan.rs @@ -10,7 +10,7 @@ #![feature(unboxed_closures)] -use std::comm; +use std::sync::mpsc::channel; fn foo(blk: F) { blk(); @@ -19,7 +19,7 @@ fn foo(blk: F) { pub fn main() { let (tx, rx) = channel(); foo(move || { - tx.send(()); + tx.send(()).unwrap(); }); - rx.recv(); + rx.recv().unwrap(); } diff --git a/src/test/run-pass/cmp-default.rs b/src/test/run-pass/cmp-default.rs index cfba87c3f6994..fd040d109108f 100644 --- a/src/test/run-pass/cmp-default.rs +++ b/src/test/run-pass/cmp-default.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::cmp::Ordering; + // Test default methods in PartialOrd and PartialEq // struct Fool(bool); diff --git a/src/test/run-pass/comm.rs b/src/test/run-pass/comm.rs index edd4d5642b5bf..5cfc692aae43d 100644 --- a/src/test/run-pass/comm.rs +++ b/src/test/run-pass/comm.rs @@ -9,11 +9,12 @@ // except according to those terms. use std::task; +use std::sync::mpsc::{channel, Sender}; pub fn main() { let (tx, rx) = channel(); let _t = task::spawn(move|| { child(&tx) }); - let y = rx.recv(); + let y = rx.recv().unwrap(); println!("received"); println!("{}", y); assert_eq!(y, 10); @@ -21,6 +22,6 @@ pub fn main() { fn child(c: &Sender) { println!("sending"); - c.send(10); + c.send(10).unwrap(); println!("value sent"); } diff --git a/src/test/run-pass/const-str-ptr.rs b/src/test/run-pass/const-str-ptr.rs index d6f0296619ab4..e0e8ca5618e50 100644 --- a/src/test/run-pass/const-str-ptr.rs +++ b/src/test/run-pass/const-str-ptr.rs @@ -9,6 +9,7 @@ // except according to those terms. use std::{str, string}; +use std::c_str::ToCStr; const A: [u8; 2] = ['h' as u8, 'i' as u8]; const B: &'static [u8; 2] = &A; diff --git a/src/test/run-pass/core-run-destroy.rs b/src/test/run-pass/core-run-destroy.rs index a0fa2d178b949..c1db8a6eb13f4 100644 --- a/src/test/run-pass/core-run-destroy.rs +++ b/src/test/run-pass/core-run-destroy.rs @@ -23,6 +23,8 @@ extern crate libc; use std::io::{Process, Command, timer}; use std::time::Duration; use std::str; +use std::sync::mpsc::channel; +use std::thread::Thread; macro_rules! succeed( ($e:expr) => ( match $e { Ok(..) => {}, Err(e) => panic!("panic: {}", e) } @@ -84,15 +86,15 @@ pub fn test_destroy_actually_kills(force: bool) { let (tx, rx1) = channel(); let mut t = timer::Timer::new().unwrap(); let rx2 = t.oneshot(Duration::milliseconds(1000)); - spawn(move|| { + Thread::spawn(move|| { select! { - () = rx2.recv() => unsafe { libc::exit(1) }, - () = rx1.recv() => {} + _ = rx2.recv() => unsafe { libc::exit(1) }, + _ = rx1.recv() => {} } - }); + }).detach(); match p.wait().unwrap() { ExitStatus(..) => panic!("expected a signal"), - ExitSignal(..) => tx.send(()), + ExitSignal(..) => tx.send(()).unwrap(), } } diff --git a/src/test/run-pass/deref-mut-on-ref.rs b/src/test/run-pass/deref-mut-on-ref.rs index dcf7c483b2cdc..5a98952c127d8 100644 --- a/src/test/run-pass/deref-mut-on-ref.rs +++ b/src/test/run-pass/deref-mut-on-ref.rs @@ -10,6 +10,8 @@ // Test that `&mut T` implements `DerefMut` +use std::ops::DerefMut; + fn inc>(mut t: T) { *t += 1; } diff --git a/src/test/run-pass/deref-on-ref.rs b/src/test/run-pass/deref-on-ref.rs index 27e7d8f3ba2a4..f245c11f0904b 100644 --- a/src/test/run-pass/deref-on-ref.rs +++ b/src/test/run-pass/deref-on-ref.rs @@ -10,6 +10,8 @@ // Test that `&T` and `&mut T` implement `Deref` +use std::ops::Deref; + fn deref>(t: T) -> U { *t } diff --git a/src/test/run-pass/deriving-cmp-shortcircuit.rs b/src/test/run-pass/deriving-cmp-shortcircuit.rs index b68d8058381d2..fb81dd558d2c4 100644 --- a/src/test/run-pass/deriving-cmp-shortcircuit.rs +++ b/src/test/run-pass/deriving-cmp-shortcircuit.rs @@ -12,6 +12,8 @@ // where possible, by having a type that panics when compared as the // second element, so this passes iff the instances shortcircuit. +use std::cmp::Ordering; + pub struct FailCmp; impl PartialEq for FailCmp { fn eq(&self, _: &FailCmp) -> bool { panic!("eq") } diff --git a/src/test/run-pass/deriving-zero.rs b/src/test/run-pass/deriving-zero.rs index 88f3e5775b78b..b8903d05cd899 100644 --- a/src/test/run-pass/deriving-zero.rs +++ b/src/test/run-pass/deriving-zero.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. - +use std::ops::Add; use std::num::Zero; #[deriving(Zero)] diff --git a/src/test/run-pass/drop-trait-enum.rs b/src/test/run-pass/drop-trait-enum.rs index 24915d84e7eb1..1ad0e87b6453e 100644 --- a/src/test/run-pass/drop-trait-enum.rs +++ b/src/test/run-pass/drop-trait-enum.rs @@ -9,6 +9,7 @@ // except according to those terms. use std::task; +use std::sync::mpsc::{channel, Sender}; #[deriving(PartialEq, Show)] enum Message { @@ -22,7 +23,7 @@ struct SendOnDrop { impl Drop for SendOnDrop { fn drop(&mut self) { - self.sender.send(Message::Dropped); + self.sender.send(Message::Dropped).unwrap(); } } @@ -36,10 +37,10 @@ impl Drop for Foo { fn drop(&mut self) { match self { &Foo::SimpleVariant(ref mut sender) => { - sender.send(Message::DestructorRan); + sender.send(Message::DestructorRan).unwrap(); } &Foo::NestedVariant(_, _, ref mut sender) => { - sender.send(Message::DestructorRan); + sender.send(Message::DestructorRan).unwrap(); } &Foo::FailingVariant { .. } => { panic!("Failed"); @@ -53,23 +54,23 @@ pub fn main() { { let v = Foo::SimpleVariant(sender); } - assert_eq!(receiver.recv(), Message::DestructorRan); - assert_eq!(receiver.recv_opt().ok(), None); + assert_eq!(receiver.recv().unwrap(), Message::DestructorRan); + assert_eq!(receiver.recv().ok(), None); let (sender, receiver) = channel(); { let v = Foo::NestedVariant(box 42u, SendOnDrop { sender: sender.clone() }, sender); } - assert_eq!(receiver.recv(), Message::DestructorRan); - assert_eq!(receiver.recv(), Message::Dropped); - assert_eq!(receiver.recv_opt().ok(), None); + assert_eq!(receiver.recv().unwrap(), Message::DestructorRan); + assert_eq!(receiver.recv().unwrap(), Message::Dropped); + assert_eq!(receiver.recv().ok(), None); let (sender, receiver) = channel(); task::spawn(move|| { let v = Foo::FailingVariant { on_drop: SendOnDrop { sender: sender } }; }); - assert_eq!(receiver.recv(), Message::Dropped); - assert_eq!(receiver.recv_opt().ok(), None); + assert_eq!(receiver.recv().unwrap(), Message::Dropped); + assert_eq!(receiver.recv().ok(), None); let (sender, receiver) = channel(); { @@ -82,11 +83,11 @@ pub fn main() { v = Foo::FailingVariant { on_drop: SendOnDrop { sender: sender } }; }); } - assert_eq!(receiver.recv(), Message::DestructorRan); - assert_eq!(receiver.recv(), Message::Dropped); - assert_eq!(receiver.recv(), Message::DestructorRan); - assert_eq!(receiver.recv(), Message::Dropped); - assert_eq!(receiver.recv(), Message::DestructorRan); - assert_eq!(receiver.recv(), Message::Dropped); - assert_eq!(receiver.recv_opt().ok(), None); + assert_eq!(receiver.recv().unwrap(), Message::DestructorRan); + assert_eq!(receiver.recv().unwrap(), Message::Dropped); + assert_eq!(receiver.recv().unwrap(), Message::DestructorRan); + assert_eq!(receiver.recv().unwrap(), Message::Dropped); + assert_eq!(receiver.recv().unwrap(), Message::DestructorRan); + assert_eq!(receiver.recv().unwrap(), Message::Dropped); + assert_eq!(receiver.recv().ok(), None); } diff --git a/src/test/run-pass/dst-deref-mut.rs b/src/test/run-pass/dst-deref-mut.rs index c2707a1ae6e90..0cbcee3e253e1 100644 --- a/src/test/run-pass/dst-deref-mut.rs +++ b/src/test/run-pass/dst-deref-mut.rs @@ -10,6 +10,8 @@ // Test that a custom deref with a fat pointer return type does not ICE +use std::ops::{Deref, DerefMut}; + pub struct Arr { ptr: Box<[uint]> } diff --git a/src/test/run-pass/dst-deref.rs b/src/test/run-pass/dst-deref.rs index 43b7d116d3038..96a9c117dea46 100644 --- a/src/test/run-pass/dst-deref.rs +++ b/src/test/run-pass/dst-deref.rs @@ -10,6 +10,8 @@ // Test that a custom deref with a fat pointer return type does not ICE +use std::ops::Deref; + pub struct Arr { ptr: Box<[uint]> } diff --git a/src/test/run-pass/fixup-deref-mut.rs b/src/test/run-pass/fixup-deref-mut.rs index d2812ce1d2ce9..70d14ba362323 100644 --- a/src/test/run-pass/fixup-deref-mut.rs +++ b/src/test/run-pass/fixup-deref-mut.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::ops::{Deref, DerefMut}; + // Generic unique/owned smaht pointer. struct Own { value: *mut T diff --git a/src/test/run-pass/foreign-fn-linkname.rs b/src/test/run-pass/foreign-fn-linkname.rs index 750c0c8ed682a..8a75fdd685dd1 100644 --- a/src/test/run-pass/foreign-fn-linkname.rs +++ b/src/test/run-pass/foreign-fn-linkname.rs @@ -11,10 +11,10 @@ // ignore-fast doesn't like extern crate extern crate libc; +use std::c_str::ToCStr; mod mlibc { - extern crate libc; - use self::libc::{c_char, size_t}; + use libc::{c_char, size_t}; extern { #[link_name = "strlen"] diff --git a/src/test/run-pass/hashmap-memory.rs b/src/test/run-pass/hashmap-memory.rs index a92b361dd3355..162d7f1025589 100644 --- a/src/test/run-pass/hashmap-memory.rs +++ b/src/test/run-pass/hashmap-memory.rs @@ -9,9 +9,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. - -extern crate collections; - /** A somewhat reduced test case to expose some Valgrind issues. @@ -24,6 +21,7 @@ pub fn map(filename: String, emit: map_reduce::putter) { mod map_reduce { use std::collections::HashMap; + use std::sync::mpsc::{channel, Sender}; use std::str; use std::task; @@ -52,16 +50,16 @@ mod map_reduce { } let (tx, rx) = channel(); println!("sending find_reducer"); - ctrl.send(ctrl_proto::find_reducer(key.as_bytes().to_vec(), tx)); + ctrl.send(ctrl_proto::find_reducer(key.as_bytes().to_vec(), tx)).unwrap(); println!("receiving"); - let c = rx.recv(); + let c = rx.recv().unwrap(); println!("{}", c); im.insert(key, c); } let ctrl_clone = ctrl.clone(); ::map(input, |a,b| emit(&mut intermediates, ctrl.clone(), a, b) ); - ctrl_clone.send(ctrl_proto::mapper_done); + ctrl_clone.send(ctrl_proto::mapper_done).unwrap(); } pub fn map_reduce(inputs: Vec) { @@ -79,7 +77,7 @@ mod map_reduce { let mut num_mappers = inputs.len() as int; while num_mappers > 0 { - match rx.recv() { + match rx.recv().unwrap() { ctrl_proto::mapper_done => { num_mappers -= 1; } ctrl_proto::find_reducer(k, cc) => { let mut c; @@ -88,7 +86,7 @@ mod map_reduce { Some(&_c) => { c = _c; } None => { c = 0; } } - cc.send(c); + cc.send(c).unwrap(); } } } diff --git a/src/test/run-pass/issue-13264.rs b/src/test/run-pass/issue-13264.rs index 06ab67f2f3e97..33377d1f21726 100644 --- a/src/test/run-pass/issue-13264.rs +++ b/src/test/run-pass/issue-13264.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::ops::Deref; + struct Root { jsref: JSRef } diff --git a/src/test/run-pass/issue-13494.rs b/src/test/run-pass/issue-13494.rs index be851ddefc645..b9339c1cc0d03 100644 --- a/src/test/run-pass/issue-13494.rs +++ b/src/test/run-pass/issue-13494.rs @@ -11,22 +11,25 @@ // This test may not always fail, but it can be flaky if the race it used to // expose is still present. +use std::sync::mpsc::{channel, Sender, Receiver}; +use std::thread::Thread; + fn helper(rx: Receiver>) { for tx in rx.iter() { - let _ = tx.send_opt(()); + let _ = tx.send(()); } } fn main() { let (tx, rx) = channel(); - spawn(move|| { helper(rx) }); + let _t = Thread::spawn(move|| { helper(rx) }).detach(); let (snd, rcv) = channel::(); for _ in range(1i, 100000i) { - snd.send(1i); + snd.send(1i).unwrap(); let (tx2, rx2) = channel(); - tx.send(tx2); + tx.send(tx2).unwrap(); select! { - () = rx2.recv() => (), + _ = rx2.recv() => (), _ = rcv.recv() => () } } diff --git a/src/test/run-pass/issue-15734.rs b/src/test/run-pass/issue-15734.rs index ea5bd550d53da..8aa7447ccd2e9 100644 --- a/src/test/run-pass/issue-15734.rs +++ b/src/test/run-pass/issue-15734.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::ops::Index; + struct Mat { data: Vec, cols: uint, } impl Mat { diff --git a/src/test/run-pass/issue-16560.rs b/src/test/run-pass/issue-16560.rs index f329e7eed0d5d..b2b819a110305 100644 --- a/src/test/run-pass/issue-16560.rs +++ b/src/test/run-pass/issue-16560.rs @@ -10,6 +10,7 @@ #![feature(unboxed_closures)] +use std::thread::Thread; use std::mem; fn main() { @@ -19,7 +20,7 @@ fn main() { // Check that both closures are capturing by value assert_eq!(1, mem::size_of_val(&closure)); - spawn(move|| { + Thread::spawn(move|| { let ok = closure; - }) + }).join().ok().unwrap(); } diff --git a/src/test/run-pass/issue-16774.rs b/src/test/run-pass/issue-16774.rs index ebc879d82fbb1..0b9a85851c591 100644 --- a/src/test/run-pass/issue-16774.rs +++ b/src/test/run-pass/issue-16774.rs @@ -10,6 +10,8 @@ #![feature(unboxed_closures)] +use std::ops::{Deref, DerefMut}; + struct X(Box); static mut DESTRUCTOR_RAN: bool = false; diff --git a/src/test/run-pass/issue-3609.rs b/src/test/run-pass/issue-3609.rs index f17f9411d15e8..a02dbb6035bfa 100644 --- a/src/test/run-pass/issue-3609.rs +++ b/src/test/run-pass/issue-3609.rs @@ -11,6 +11,7 @@ #![feature(default_type_params)] use std::task; +use std::sync::mpsc::Sender; use std::thunk::Invoke; type RingBuffer = Vec ; diff --git a/src/test/run-pass/issue-3743.rs b/src/test/run-pass/issue-3743.rs index 80d3d29bc004d..c88022f3eb706 100644 --- a/src/test/run-pass/issue-3743.rs +++ b/src/test/run-pass/issue-3743.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::ops::Mul; + struct Vec2 { x: f64, y: f64 diff --git a/src/test/run-pass/issue-3979-generics.rs b/src/test/run-pass/issue-3979-generics.rs index 86cdd6135ecf2..93c72e2e35091 100644 --- a/src/test/run-pass/issue-3979-generics.rs +++ b/src/test/run-pass/issue-3979-generics.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::ops::Add; + trait Positioned { fn SetX(&mut self, S); fn X(&self) -> S; diff --git a/src/test/run-pass/issue-4446.rs b/src/test/run-pass/issue-4446.rs index daa80aec28c04..30e1a14ecff8f 100644 --- a/src/test/run-pass/issue-4446.rs +++ b/src/test/run-pass/issue-4446.rs @@ -9,13 +9,15 @@ // except according to those terms. use std::io::println; +use std::sync::mpsc::channel; +use std::thread::Thread; pub fn main() { let (tx, rx) = channel(); - tx.send("hello, world"); + tx.send("hello, world").unwrap(); - spawn(move|| { - println(rx.recv()); - }); + Thread::spawn(move|| { + println(rx.recv().unwrap()); + }).join().ok().unwrap(); } diff --git a/src/test/run-pass/issue-4448.rs b/src/test/run-pass/issue-4448.rs index 3ea968c416f45..7e53722726f2c 100644 --- a/src/test/run-pass/issue-4448.rs +++ b/src/test/run-pass/issue-4448.rs @@ -8,14 +8,16 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::task; +use std::sync::mpsc::channel; +use std::thread::Thread; pub fn main() { let (tx, rx) = channel::<&'static str>(); - task::spawn(move|| { - assert_eq!(rx.recv(), "hello, world"); + let t = Thread::spawn(move|| { + assert_eq!(rx.recv().unwrap(), "hello, world"); }); - tx.send("hello, world"); + tx.send("hello, world").unwrap(); + t.join().ok().unwrap(); } diff --git a/src/test/run-pass/issue-7784.rs b/src/test/run-pass/issue-7784.rs index b936eb322fc5f..43785edc2eb03 100644 --- a/src/test/run-pass/issue-7784.rs +++ b/src/test/run-pass/issue-7784.rs @@ -10,6 +10,8 @@ #![feature(advanced_slice_patterns)] +use std::ops::Add; + fn foo + Clone>([x, y, z]: [T; 3]) -> (T, T, T) { (x.clone(), x.clone() + y.clone(), x + y + z) } diff --git a/src/test/run-pass/issue-8827.rs b/src/test/run-pass/issue-8827.rs index 7397ad744950e..39695a8339f08 100644 --- a/src/test/run-pass/issue-8827.rs +++ b/src/test/run-pass/issue-8827.rs @@ -8,37 +8,40 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::thread::Thread; +use std::sync::mpsc::{channel, Receiver}; + fn periodical(n: int) -> Receiver { let (chan, port) = channel(); - spawn(move|| { + Thread::spawn(move|| { loop { for _ in range(1, n) { - match chan.send_opt(false) { + match chan.send(false) { Ok(()) => {} Err(..) => break, } } - match chan.send_opt(true) { + match chan.send(true) { Ok(()) => {} Err(..) => break } } - }); + }).detach(); return port; } fn integers() -> Receiver { let (chan, port) = channel(); - spawn(move|| { + Thread::spawn(move|| { let mut i = 1; loop { - match chan.send_opt(i) { + match chan.send(i) { Ok(()) => {} Err(..) => break, } i = i + 1; } - }); + }).detach(); return port; } @@ -47,7 +50,7 @@ fn main() { let threes = periodical(3); let fives = periodical(5); for _ in range(1i, 100i) { - match (ints.recv(), threes.recv(), fives.recv()) { + match (ints.recv().unwrap(), threes.recv().unwrap(), fives.recv().unwrap()) { (_, true, true) => println!("FizzBuzz"), (_, true, false) => println!("Fizz"), (_, false, true) => println!("Buzz"), diff --git a/src/test/run-pass/issue-9396.rs b/src/test/run-pass/issue-9396.rs index 588e0c1cf16cf..34bb50c5cf669 100644 --- a/src/test/run-pass/issue-9396.rs +++ b/src/test/run-pass/issue-9396.rs @@ -8,22 +8,23 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::comm; +use std::sync::mpsc::{TryRecvError, channel}; use std::io::timer::Timer; +use std::thread::Thread; use std::time::Duration; pub fn main() { let (tx, rx) = channel(); - spawn(move||{ + let _t = Thread::spawn(move||{ let mut timer = Timer::new().unwrap(); timer.sleep(Duration::milliseconds(10)); - tx.send(()); + tx.send(()).unwrap(); }); loop { match rx.try_recv() { Ok(()) => break, - Err(comm::Empty) => {} - Err(comm::Disconnected) => unreachable!() + Err(TryRecvError::Empty) => {} + Err(TryRecvError::Disconnected) => unreachable!() } } } diff --git a/src/test/run-pass/ivec-tag.rs b/src/test/run-pass/ivec-tag.rs index 1f7edcf43b887..a9a50b9ef25af 100644 --- a/src/test/run-pass/ivec-tag.rs +++ b/src/test/run-pass/ivec-tag.rs @@ -9,11 +9,12 @@ // except according to those terms. use std::task; +use std::sync::mpsc::{channel, Sender}; fn producer(tx: &Sender>) { tx.send( vec!(1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 8u8, 9u8, 10u8, 11u8, 12u8, - 13u8)); + 13u8)).unwrap(); } pub fn main() { @@ -22,5 +23,5 @@ pub fn main() { producer(&tx) }); - let _data: Vec = rx.recv(); + let _data: Vec = rx.recv().unwrap(); } diff --git a/src/test/run-pass/logging-only-prints-once.rs b/src/test/run-pass/logging-only-prints-once.rs index 1e05c05cc0dd1..509afff3d133b 100644 --- a/src/test/run-pass/logging-only-prints-once.rs +++ b/src/test/run-pass/logging-only-prints-once.rs @@ -13,6 +13,7 @@ use std::cell::Cell; use std::fmt; +use std::thread::Thread; struct Foo(Cell); @@ -26,13 +27,10 @@ impl fmt::Show for Foo { } pub fn main() { - let (tx, rx) = channel(); - spawn(move|| { + Thread::spawn(move|| { let mut f = Foo(Cell::new(0)); println!("{}", f); let Foo(ref mut f) = f; assert!(f.get() == 1); - tx.send(()); - }); - rx.recv(); + }).join().ok().unwrap(); } diff --git a/src/test/run-pass/macro-with-braces-in-expr-position.rs b/src/test/run-pass/macro-with-braces-in-expr-position.rs index 024dc4c03e1b7..a6e579ddff304 100644 --- a/src/test/run-pass/macro-with-braces-in-expr-position.rs +++ b/src/test/run-pass/macro-with-braces-in-expr-position.rs @@ -10,11 +10,13 @@ #![feature(macro_rules)] +use std::thread::Thread; + macro_rules! expr (($e: expr) => { $e }); macro_rules! spawn { ($($code: tt)*) => { - expr!(spawn(move|| {$($code)*})) + expr!(Thread::spawn(move|| {$($code)*}).detach()) } } diff --git a/src/test/run-pass/match-with-ret-arm.rs b/src/test/run-pass/match-with-ret-arm.rs index 2109f7ef1eafc..2cba1dec2dc99 100644 --- a/src/test/run-pass/match-with-ret-arm.rs +++ b/src/test/run-pass/match-with-ret-arm.rs @@ -9,6 +9,7 @@ // except according to those terms. use std::uint; +use std::str::from_str; pub fn main() { // sometimes we have had trouble finding diff --git a/src/test/run-pass/numeric-method-autoexport.rs b/src/test/run-pass/numeric-method-autoexport.rs index f8184d248ff01..b4d079d79d650 100644 --- a/src/test/run-pass/numeric-method-autoexport.rs +++ b/src/test/run-pass/numeric-method-autoexport.rs @@ -15,6 +15,9 @@ // necessary. Testing the methods of the impls is done within the source // file for each numeric type. +use std::ops::Add; +use std::num::ToPrimitive; + pub fn main() { // ints // num diff --git a/src/test/run-pass/out-of-stack-new-thread-no-split.rs b/src/test/run-pass/out-of-stack-new-thread-no-split.rs index 674d0dc86da1c..7aac2d705a854 100644 --- a/src/test/run-pass/out-of-stack-new-thread-no-split.rs +++ b/src/test/run-pass/out-of-stack-new-thread-no-split.rs @@ -17,6 +17,7 @@ use std::io::process::Command; use std::os; +use std::thread::Thread; // lifted from the test module // Inlining to avoid llvm turning the recursive functions into tail calls, @@ -36,12 +37,7 @@ fn main() { let args = os::args(); let args = args.as_slice(); if args.len() > 1 && args[1].as_slice() == "recurse" { - let (tx, rx) = channel(); - spawn(move|| { - recurse(); - tx.send(()); - }); - rx.recv(); + let _t = Thread::spawn(recurse); } else { let recurse = Command::new(args[0].as_slice()).arg("recurse").output().unwrap(); assert!(!recurse.status.success()); diff --git a/src/test/run-pass/overloaded-autoderef-indexing.rs b/src/test/run-pass/overloaded-autoderef-indexing.rs index 5c4befcd0c825..d1fb69b87a30e 100644 --- a/src/test/run-pass/overloaded-autoderef-indexing.rs +++ b/src/test/run-pass/overloaded-autoderef-indexing.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::ops::Deref; + struct DerefArray<'a, T:'a> { inner: &'a [T] } diff --git a/src/test/run-pass/overloaded-autoderef-order.rs b/src/test/run-pass/overloaded-autoderef-order.rs index f0daf371ca79e..23a8285063ffb 100644 --- a/src/test/run-pass/overloaded-autoderef-order.rs +++ b/src/test/run-pass/overloaded-autoderef-order.rs @@ -9,6 +9,7 @@ // except according to those terms. use std::rc::Rc; +use std::ops::Deref; struct DerefWrapper { x: X, @@ -30,6 +31,8 @@ impl Deref for DerefWrapper { } mod priv_test { + use std::ops::Deref; + pub struct DerefWrapperHideX { x: X, pub y: Y diff --git a/src/test/run-pass/overloaded-autoderef.rs b/src/test/run-pass/overloaded-autoderef.rs index 2975b209d0690..222e2825c0404 100644 --- a/src/test/run-pass/overloaded-autoderef.rs +++ b/src/test/run-pass/overloaded-autoderef.rs @@ -10,7 +10,7 @@ use std::cell::RefCell; use std::rc::Rc; -use std::string::String; +use std::num::ToPrimitive; #[deriving(PartialEq, Show)] struct Point { @@ -31,7 +31,6 @@ pub fn main() { assert_eq!((i_value, *i.borrow()), (2, 5)); let s = Rc::new("foo".to_string()); - assert!(s.equiv(&("foo"))); assert_eq!(s.as_slice(), "foo"); let mut_s = Rc::new(RefCell::new(String::from_str("foo"))); diff --git a/src/test/run-pass/overloaded-calls-param-vtables.rs b/src/test/run-pass/overloaded-calls-param-vtables.rs index 2e8ec3916bd89..95df1ed0d837e 100644 --- a/src/test/run-pass/overloaded-calls-param-vtables.rs +++ b/src/test/run-pass/overloaded-calls-param-vtables.rs @@ -13,6 +13,7 @@ #![feature(unboxed_closures)] use std::ops::Fn; +use std::ops::Add; struct G; diff --git a/src/test/run-pass/overloaded-index-autoderef.rs b/src/test/run-pass/overloaded-index-autoderef.rs index d51956da89409..dcb0c40c6088a 100644 --- a/src/test/run-pass/overloaded-index-autoderef.rs +++ b/src/test/run-pass/overloaded-index-autoderef.rs @@ -10,6 +10,8 @@ // Test overloaded indexing combined with autoderef. +use std::ops::{Index, IndexMut}; + struct Foo { x: int, y: int, diff --git a/src/test/run-pass/overloaded-index-in-field.rs b/src/test/run-pass/overloaded-index-in-field.rs index e8b0408ca0dc0..1c06ed64fc7b8 100644 --- a/src/test/run-pass/overloaded-index-in-field.rs +++ b/src/test/run-pass/overloaded-index-in-field.rs @@ -11,6 +11,8 @@ // Test using overloaded indexing when the "map" is stored in a // field. This caused problems at some point. +use std::ops::Index; + struct Foo { x: int, y: int, diff --git a/src/test/run-pass/overloaded-index.rs b/src/test/run-pass/overloaded-index.rs index 23bebfa35d7f3..fdf7e7e2cbb13 100644 --- a/src/test/run-pass/overloaded-index.rs +++ b/src/test/run-pass/overloaded-index.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::ops::{Index, IndexMut}; + struct Foo { x: int, y: int, diff --git a/src/test/run-pass/rename-directory.rs b/src/test/run-pass/rename-directory.rs index b5cee20232b63..c7aa405b513e4 100644 --- a/src/test/run-pass/rename-directory.rs +++ b/src/test/run-pass/rename-directory.rs @@ -14,6 +14,7 @@ extern crate libc; use std::io::TempDir; +use std::c_str::ToCStr; use std::io::fs::PathExtensions; use std::io::fs; use std::io; diff --git a/src/test/run-pass/running-with-no-runtime.rs b/src/test/run-pass/running-with-no-runtime.rs index 4cf8c52f2bb44..0aeade935dadb 100644 --- a/src/test/run-pass/running-with-no-runtime.rs +++ b/src/test/run-pass/running-with-no-runtime.rs @@ -10,12 +10,12 @@ use std::io::process::{Command, ProcessOutput}; use std::os; -use std::str; +use std::rt::unwind::try; use std::rt; +use std::str; +use std::thread::Thread; use std::thunk::Thunk; -use std::rt::unwind::try; - #[start] fn start(argc: int, argv: *const *const u8) -> int { if argc > 1 { @@ -25,8 +25,7 @@ fn start(argc: int, argv: *const *const u8) -> int { 2 => println!("foo"), 3 => assert!(try(|| {}).is_ok()), 4 => assert!(try(|| panic!()).is_err()), - 5 => assert!(try(|| spawn(move|| {})).is_err()), - 6 => assert!(Command::new("test").spawn().is_err()), + 5 => assert!(Command::new("test").spawn().is_err()), _ => panic!() } } @@ -50,8 +49,6 @@ fn start(argc: int, argv: *const *const u8) -> int { pass(Command::new(me).arg(x).output().unwrap()); let x: &[u8] = &[5u8]; pass(Command::new(me).arg(x).output().unwrap()); - let x: &[u8] = &[6u8]; - pass(Command::new(me).arg(x).output().unwrap()); 0 } diff --git a/src/test/run-pass/rust-log-filter.rs b/src/test/run-pass/rust-log-filter.rs index 88d30318f2a99..2612483ded486 100644 --- a/src/test/run-pass/rust-log-filter.rs +++ b/src/test/run-pass/rust-log-filter.rs @@ -14,6 +14,9 @@ #[phase(plugin,link)] extern crate log; +use std::sync::mpsc::{channel, Sender, Receiver}; +use std::thread::Thread; + pub struct ChannelLogger { tx: Sender } @@ -27,14 +30,14 @@ impl ChannelLogger { impl log::Logger for ChannelLogger { fn log(&mut self, record: &log::LogRecord) { - self.tx.send(format!("{}", record.args)); + self.tx.send(format!("{}", record.args)).unwrap(); } } pub fn main() { let (logger, rx) = ChannelLogger::new(); - spawn(move|| { + let _t = Thread::spawn(move|| { log::set_logger(logger); // our regex is "f.o" @@ -46,9 +49,9 @@ pub fn main() { info!("f1o"); }); - assert_eq!(rx.recv().as_slice(), "foo"); - assert_eq!(rx.recv().as_slice(), "foo bar"); - assert_eq!(rx.recv().as_slice(), "bar foo"); - assert_eq!(rx.recv().as_slice(), "f1o"); - assert!(rx.recv_opt().is_err()); + assert_eq!(rx.recv().unwrap().as_slice(), "foo"); + assert_eq!(rx.recv().unwrap().as_slice(), "foo bar"); + assert_eq!(rx.recv().unwrap().as_slice(), "bar foo"); + assert_eq!(rx.recv().unwrap().as_slice(), "f1o"); + assert!(rx.recv().is_err()); } diff --git a/src/test/run-pass/send-resource.rs b/src/test/run-pass/send-resource.rs index 6001c360ab99f..7fd9706bd0fea 100644 --- a/src/test/run-pass/send-resource.rs +++ b/src/test/run-pass/send-resource.rs @@ -9,6 +9,7 @@ // except according to those terms. use std::task; +use std::sync::mpsc::channel; struct test { f: int, @@ -29,10 +30,10 @@ pub fn main() { task::spawn(move|| { let (tx2, rx2) = channel(); - tx.send(tx2); + tx.send(tx2).unwrap(); - let _r = rx2.recv(); + let _r = rx2.recv().unwrap(); }); - rx.recv().send(test(42)); + rx.recv().unwrap().send(test(42)).unwrap(); } diff --git a/src/test/run-pass/send-type-inference.rs b/src/test/run-pass/send-type-inference.rs index 508bd99d77d7c..ae992a0a358d1 100644 --- a/src/test/run-pass/send-type-inference.rs +++ b/src/test/run-pass/send-type-inference.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::sync::mpsc::{channel, Sender}; + // tests that ctrl's type gets inferred properly struct Command { key: K, diff --git a/src/test/run-pass/send_str_hashmap.rs b/src/test/run-pass/send_str_hashmap.rs index 1b0f2ec0a327f..bfeff58b802df 100644 --- a/src/test/run-pass/send_str_hashmap.rs +++ b/src/test/run-pass/send_str_hashmap.rs @@ -11,8 +11,8 @@ extern crate collections; use std::collections::HashMap; -use std::option::Option::Some; use std::str::SendStr; +use std::borrow::IntoCow; pub fn main() { let mut map: HashMap = HashMap::new(); diff --git a/src/test/run-pass/send_str_treemap.rs b/src/test/run-pass/send_str_treemap.rs index 24480d8527205..8c70738de48f1 100644 --- a/src/test/run-pass/send_str_treemap.rs +++ b/src/test/run-pass/send_str_treemap.rs @@ -11,9 +11,8 @@ extern crate collections; use self::collections::BTreeMap; -use std::option::Option::Some; use std::str::SendStr; -use std::string::ToString; +use std::borrow::IntoCow; pub fn main() { let mut map: BTreeMap = BTreeMap::new(); diff --git a/src/test/run-pass/sendable-class.rs b/src/test/run-pass/sendable-class.rs index 007a83d2c8878..8691d5e875bfc 100644 --- a/src/test/run-pass/sendable-class.rs +++ b/src/test/run-pass/sendable-class.rs @@ -10,6 +10,8 @@ // Test that a class with only sendable fields can be sent +use std::sync::mpsc::channel; + struct foo { i: int, j: char, diff --git a/src/test/run-pass/spawn-types.rs b/src/test/run-pass/spawn-types.rs index 9b533c69f3209..1c86e3e6ea236 100644 --- a/src/test/run-pass/spawn-types.rs +++ b/src/test/run-pass/spawn-types.rs @@ -15,6 +15,7 @@ */ use std::task; +use std::sync::mpsc::{channel, Sender}; type ctx = Sender; diff --git a/src/test/run-pass/supertrait-default-generics.rs b/src/test/run-pass/supertrait-default-generics.rs index 873941395fead..4465561f874eb 100644 --- a/src/test/run-pass/supertrait-default-generics.rs +++ b/src/test/run-pass/supertrait-default-generics.rs @@ -10,6 +10,8 @@ // There is some other borrowck bug, so we make the stuff not mut. +use std::ops::Add; + trait Positioned { fn SetX(&mut self, S); fn X(&self) -> S; diff --git a/src/test/run-pass/task-comm-0.rs b/src/test/run-pass/task-comm-0.rs index 9e3511ba6034f..de077ffd19020 100644 --- a/src/test/run-pass/task-comm-0.rs +++ b/src/test/run-pass/task-comm-0.rs @@ -8,28 +8,28 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. - use std::task; +use std::sync::mpsc::{channel, Sender}; pub fn main() { test05(); } fn test05_start(tx : &Sender) { - tx.send(10); + tx.send(10).unwrap(); println!("sent 10"); - tx.send(20); + tx.send(20).unwrap(); println!("sent 20"); - tx.send(30); + tx.send(30).unwrap(); println!("sent 30"); } fn test05() { let (tx, rx) = channel(); task::spawn(move|| { test05_start(&tx) }); - let mut value: int = rx.recv(); + let mut value: int = rx.recv().unwrap(); println!("{}", value); - value = rx.recv(); + value = rx.recv().unwrap(); println!("{}", value); - value = rx.recv(); + value = rx.recv().unwrap(); println!("{}", value); assert_eq!(value, 30); } diff --git a/src/test/run-pass/task-comm-10.rs b/src/test/run-pass/task-comm-10.rs index dd3c90991f627..93dca923b6b98 100644 --- a/src/test/run-pass/task-comm-10.rs +++ b/src/test/run-pass/task-comm-10.rs @@ -8,19 +8,19 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. - use std::task; +use std::sync::mpsc::{channel, Sender}; fn start(tx: &Sender>) { let (tx2, rx) = channel(); - tx.send(tx2); + tx.send(tx2).unwrap(); let mut a; let mut b; - a = rx.recv(); + a = rx.recv().unwrap(); assert!(a == "A".to_string()); println!("{}", a); - b = rx.recv(); + b = rx.recv().unwrap(); assert!(b == "B".to_string()); println!("{}", b); } @@ -29,8 +29,8 @@ pub fn main() { let (tx, rx) = channel(); let _child = task::spawn(move|| { start(&tx) }); - let mut c = rx.recv(); - c.send("A".to_string()); - c.send("B".to_string()); + let mut c = rx.recv().unwrap(); + c.send("A".to_string()).unwrap(); + c.send("B".to_string()).unwrap(); task::deschedule(); } diff --git a/src/test/run-pass/task-comm-11.rs b/src/test/run-pass/task-comm-11.rs index aefc91df4e780..8168e84e42674 100644 --- a/src/test/run-pass/task-comm-11.rs +++ b/src/test/run-pass/task-comm-11.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. - +use std::sync::mpsc::{channel, Sender}; use std::task; fn start(tx: &Sender>) { diff --git a/src/test/run-pass/task-comm-13.rs b/src/test/run-pass/task-comm-13.rs index c6c0691b74989..bb92ef38728fa 100644 --- a/src/test/run-pass/task-comm-13.rs +++ b/src/test/run-pass/task-comm-13.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. - +use std::sync::mpsc::{channel, Sender}; use std::task; fn start(tx: &Sender, start: int, number_of_messages: int) { diff --git a/src/test/run-pass/task-comm-14.rs b/src/test/run-pass/task-comm-14.rs index 0e48381366555..d63cbd5c8ba17 100644 --- a/src/test/run-pass/task-comm-14.rs +++ b/src/test/run-pass/task-comm-14.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. - +use std::sync::mpsc::{channel, Sender}; use std::task; pub fn main() { diff --git a/src/test/run-pass/task-comm-15.rs b/src/test/run-pass/task-comm-15.rs index 3095c2098ff33..7c652ddc406fc 100644 --- a/src/test/run-pass/task-comm-15.rs +++ b/src/test/run-pass/task-comm-15.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. - +use std::sync::mpsc::{channel, Sender}; use std::task; fn start(tx: &Sender, i0: int) { diff --git a/src/test/run-pass/task-comm-16.rs b/src/test/run-pass/task-comm-16.rs index 9143385254095..b7098eb30a3be 100644 --- a/src/test/run-pass/task-comm-16.rs +++ b/src/test/run-pass/task-comm-16.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::sync::mpsc::channel; use std::cmp; // Tests of ports and channels on various types @@ -16,9 +17,9 @@ fn test_rec() { let (tx, rx) = channel(); let r0: R = R {val0: 0, val1: 1u8, val2: '2'}; - tx.send(r0); + tx.send(r0).unwrap(); let mut r1: R; - r1 = rx.recv(); + r1 = rx.recv().unwrap(); assert_eq!(r1.val0, 0); assert_eq!(r1.val1, 1u8); assert_eq!(r1.val2, '2'); @@ -27,8 +28,8 @@ fn test_rec() { fn test_vec() { let (tx, rx) = channel(); let v0: Vec = vec!(0, 1, 2); - tx.send(v0); - let v1 = rx.recv(); + tx.send(v0).unwrap(); + let v1 = rx.recv().unwrap(); assert_eq!(v1[0], 0); assert_eq!(v1[1], 1); assert_eq!(v1[2], 2); @@ -37,8 +38,8 @@ fn test_vec() { fn test_str() { let (tx, rx) = channel(); let s0 = "test".to_string(); - tx.send(s0); - let s1 = rx.recv(); + tx.send(s0).unwrap(); + let s1 = rx.recv().unwrap(); assert_eq!(s1.as_bytes()[0], 't' as u8); assert_eq!(s1.as_bytes()[1], 'e' as u8); assert_eq!(s1.as_bytes()[2], 's' as u8); @@ -81,28 +82,28 @@ impl cmp::PartialEq for t { fn test_tag() { let (tx, rx) = channel(); - tx.send(t::tag1); - tx.send(t::tag2(10)); - tx.send(t::tag3(10, 11u8, 'A')); + tx.send(t::tag1).unwrap(); + tx.send(t::tag2(10)).unwrap(); + tx.send(t::tag3(10, 11u8, 'A')).unwrap(); let mut t1: t; - t1 = rx.recv(); + t1 = rx.recv().unwrap(); assert_eq!(t1, t::tag1); - t1 = rx.recv(); + t1 = rx.recv().unwrap(); assert_eq!(t1, t::tag2(10)); - t1 = rx.recv(); + t1 = rx.recv().unwrap(); assert_eq!(t1, t::tag3(10, 11u8, 'A')); } fn test_chan() { let (tx1, rx1) = channel(); let (tx2, rx2) = channel(); - tx1.send(tx2); - let tx2 = rx1.recv(); + tx1.send(tx2).unwrap(); + let tx2 = rx1.recv().unwrap(); // Does the transmitted channel still work? - tx2.send(10); + tx2.send(10).unwrap(); let mut i: int; - i = rx2.recv(); + i = rx2.recv().unwrap(); assert_eq!(i, 10); } diff --git a/src/test/run-pass/task-comm-3.rs b/src/test/run-pass/task-comm-3.rs index 73f6eb563c1ce..a002a597481e4 100644 --- a/src/test/run-pass/task-comm-3.rs +++ b/src/test/run-pass/task-comm-3.rs @@ -11,6 +11,7 @@ // no-pretty-expanded FIXME #15189 use std::thread::Thread; +use std::sync::mpsc::{channel, Sender}; pub fn main() { println!("===== WITHOUT THREADS ====="); test00(); } @@ -19,7 +20,7 @@ fn test00_start(ch: &Sender, message: int, count: int) { let mut i: int = 0; while i < count { println!("Sending Message"); - ch.send(message + 0); + ch.send(message + 0).unwrap(); i = i + 1; } println!("Ending test00_start"); @@ -53,7 +54,7 @@ fn test00() { for _r in results.iter() { i = 0; while i < number_of_messages { - let value = rx.recv(); + let value = rx.recv().unwrap(); sum += value; i = i + 1; } diff --git a/src/test/run-pass/task-comm-4.rs b/src/test/run-pass/task-comm-4.rs index 2e2b1fbff0ff7..1f1b750aa5727 100644 --- a/src/test/run-pass/task-comm-4.rs +++ b/src/test/run-pass/task-comm-4.rs @@ -10,42 +10,44 @@ #![allow(dead_assignment)] +use std::sync::mpsc::channel; + pub fn main() { test00(); } fn test00() { let mut r: int = 0; let mut sum: int = 0; let (tx, rx) = channel(); - tx.send(1); - tx.send(2); - tx.send(3); - tx.send(4); - r = rx.recv(); + tx.send(1).unwrap(); + tx.send(2).unwrap(); + tx.send(3).unwrap(); + tx.send(4).unwrap(); + r = rx.recv().unwrap(); sum += r; println!("{}", r); - r = rx.recv(); + r = rx.recv().unwrap(); sum += r; println!("{}", r); - r = rx.recv(); + r = rx.recv().unwrap(); sum += r; println!("{}", r); - r = rx.recv(); + r = rx.recv().unwrap(); sum += r; println!("{}", r); - tx.send(5); - tx.send(6); - tx.send(7); - tx.send(8); - r = rx.recv(); + tx.send(5).unwrap(); + tx.send(6).unwrap(); + tx.send(7).unwrap(); + tx.send(8).unwrap(); + r = rx.recv().unwrap(); sum += r; println!("{}", r); - r = rx.recv(); + r = rx.recv().unwrap(); sum += r; println!("{}", r); - r = rx.recv(); + r = rx.recv().unwrap(); sum += r; println!("{}", r); - r = rx.recv(); + r = rx.recv().unwrap(); sum += r; println!("{}", r); assert_eq!(sum, 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8); diff --git a/src/test/run-pass/task-comm-5.rs b/src/test/run-pass/task-comm-5.rs index e51e14f7fbe82..039308d5cfed7 100644 --- a/src/test/run-pass/task-comm-5.rs +++ b/src/test/run-pass/task-comm-5.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::sync::mpsc::channel; + pub fn main() { test00(); } fn test00() { @@ -16,8 +18,8 @@ fn test00() { let (tx, rx) = channel(); let number_of_messages: int = 1000; let mut i: int = 0; - while i < number_of_messages { tx.send(i + 0); i += 1; } + while i < number_of_messages { tx.send(i + 0).unwrap(); i += 1; } i = 0; - while i < number_of_messages { sum += rx.recv(); i += 1; } + while i < number_of_messages { sum += rx.recv().unwrap(); i += 1; } assert_eq!(sum, number_of_messages * (number_of_messages - 1) / 2); } diff --git a/src/test/run-pass/task-comm-6.rs b/src/test/run-pass/task-comm-6.rs index e783cd9b6beaf..7cdfddcdeb113 100644 --- a/src/test/run-pass/task-comm-6.rs +++ b/src/test/run-pass/task-comm-6.rs @@ -10,6 +10,8 @@ #![allow(dead_assignment)] +use std::sync::mpsc::channel; + pub fn main() { test00(); } fn test00() { @@ -23,21 +25,21 @@ fn test00() { let number_of_messages: int = 1000; let mut i: int = 0; while i < number_of_messages { - tx0.send(i + 0); - tx1.send(i + 0); - tx2.send(i + 0); - tx3.send(i + 0); + tx0.send(i + 0).unwrap(); + tx1.send(i + 0).unwrap(); + tx2.send(i + 0).unwrap(); + tx3.send(i + 0).unwrap(); i += 1; } i = 0; while i < number_of_messages { - r = rx.recv(); + r = rx.recv().unwrap(); sum += r; - r = rx.recv(); + r = rx.recv().unwrap(); sum += r; - r = rx.recv(); + r = rx.recv().unwrap(); sum += r; - r = rx.recv(); + r = rx.recv().unwrap(); sum += r; i += 1; } diff --git a/src/test/run-pass/task-comm-7.rs b/src/test/run-pass/task-comm-7.rs index 9d8caa426269b..054090eca3903 100644 --- a/src/test/run-pass/task-comm-7.rs +++ b/src/test/run-pass/task-comm-7.rs @@ -8,9 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. - #![allow(dead_assignment)] +use std::sync::mpsc::{channel, Sender}; use std::task; pub fn main() { test00(); } @@ -18,7 +18,7 @@ pub fn main() { test00(); } fn test00_start(c: &Sender, start: int, number_of_messages: int) { let mut i: int = 0; - while i < number_of_messages { c.send(start + i); i += 1; } + while i < number_of_messages { c.send(start + i).unwrap(); i += 1; } } fn test00() { @@ -46,13 +46,13 @@ fn test00() { let mut i: int = 0; while i < number_of_messages { - r = rx.recv(); + r = rx.recv().unwrap(); sum += r; - r = rx.recv(); + r = rx.recv().unwrap(); sum += r; - r = rx.recv(); + r = rx.recv().unwrap(); sum += r; - r = rx.recv(); + r = rx.recv().unwrap(); sum += r; i += 1; } diff --git a/src/test/run-pass/task-comm-9.rs b/src/test/run-pass/task-comm-9.rs index 69d70050437f1..d9faf6ee4e4b2 100644 --- a/src/test/run-pass/task-comm-9.rs +++ b/src/test/run-pass/task-comm-9.rs @@ -9,12 +9,13 @@ // except according to those terms. use std::thread::Thread; +use std::sync::mpsc::{channel, Sender}; pub fn main() { test00(); } fn test00_start(c: &Sender, number_of_messages: int) { let mut i: int = 0; - while i < number_of_messages { c.send(i + 0); i += 1; } + while i < number_of_messages { c.send(i + 0).unwrap(); i += 1; } } fn test00() { @@ -29,7 +30,7 @@ fn test00() { let mut i: int = 0; while i < number_of_messages { - sum += rx.recv(); + sum += rx.recv().unwrap(); println!("{}", r); i += 1; } diff --git a/src/test/run-pass/task-comm-chan-nil.rs b/src/test/run-pass/task-comm-chan-nil.rs index 3ea17898eada2..78a42632001d0 100644 --- a/src/test/run-pass/task-comm-chan-nil.rs +++ b/src/test/run-pass/task-comm-chan-nil.rs @@ -8,12 +8,14 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::sync::mpsc::channel; + // rustboot can't transmit nils across channels because they don't have // any size, but rustc currently can because they do have size. Whether // or not this is desirable I don't know, but here's a regression test. pub fn main() { let (tx, rx) = channel(); - tx.send(()); - let n: () = rx.recv(); + tx.send(()).unwrap(); + let n: () = rx.recv().unwrap(); assert_eq!(n, ()); } diff --git a/src/test/run-pass/task-spawn-move-and-copy.rs b/src/test/run-pass/task-spawn-move-and-copy.rs index 8d6b6005a63ba..623a30eda1a4b 100644 --- a/src/test/run-pass/task-spawn-move-and-copy.rs +++ b/src/test/run-pass/task-spawn-move-and-copy.rs @@ -9,6 +9,7 @@ // except according to those terms. use std::task; +use std::sync::mpsc::channel; pub fn main() { let (tx, rx) = channel::(); @@ -18,9 +19,9 @@ pub fn main() { task::spawn(move || { let x_in_child = &(*x) as *const int as uint; - tx.send(x_in_child); + tx.send(x_in_child).unwrap(); }); - let x_in_child = rx.recv(); + let x_in_child = rx.recv().unwrap(); assert_eq!(x_in_parent, x_in_child); } diff --git a/src/test/run-pass/task-stderr.rs b/src/test/run-pass/task-stderr.rs index ddeffcdf72204..a7eabe0edb384 100644 --- a/src/test/run-pass/task-stderr.rs +++ b/src/test/run-pass/task-stderr.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::sync::mpsc::channel; use std::io::{ChanReader, ChanWriter}; use std::thread; diff --git a/src/test/run-pass/tcp-accept-stress.rs b/src/test/run-pass/tcp-accept-stress.rs index 780cf23446639..07f71fe580e9f 100644 --- a/src/test/run-pass/tcp-accept-stress.rs +++ b/src/test/run-pass/tcp-accept-stress.rs @@ -13,8 +13,10 @@ // quite quickly and it takes a few seconds for the sockets to get // recycled. +use std::sync::mpsc::channel; use std::io::{TcpListener, Listener, Acceptor, EndOfFile, TcpStream}; use std::sync::{atomic, Arc}; +use std::thread::Thread; static N: uint = 8; static M: uint = 20; @@ -35,7 +37,7 @@ fn test() { let a = a.clone(); let cnt = cnt.clone(); let srv_tx = srv_tx.clone(); - spawn(move|| { + Thread::spawn(move|| { let mut a = a; loop { match a.accept() { @@ -49,17 +51,17 @@ fn test() { } } srv_tx.send(()); - }); + }).detach(); } for _ in range(0, N) { let cli_tx = cli_tx.clone(); - spawn(move|| { + Thread::spawn(move|| { for _ in range(0, M) { let _s = TcpStream::connect(addr).unwrap(); } cli_tx.send(()); - }); + }).detach(); } drop((cli_tx, srv_tx)); diff --git a/src/test/run-pass/tcp-connect-timeouts.rs b/src/test/run-pass/tcp-connect-timeouts.rs index 2e4b9da691e39..c33bdcf869801 100644 --- a/src/test/run-pass/tcp-connect-timeouts.rs +++ b/src/test/run-pass/tcp-connect-timeouts.rs @@ -27,6 +27,7 @@ use std::io::net::tcp::*; use std::io::test::*; use std::io; use std::time::Duration; +use std::sync::mpsc::channel; #[cfg_attr(target_os = "freebsd", ignore)] fn eventual_timeout() { @@ -36,10 +37,10 @@ fn eventual_timeout() { let (_tx2, rx2) = channel::<()>(); std::task::spawn(move|| { let _l = TcpListener::bind(addr).unwrap().listen(); - tx1.send(()); - let _ = rx2.recv_opt(); + tx1.send(()).unwrap(); + let _ = rx2.recv(); }); - rx1.recv(); + rx1.recv().unwrap(); let mut v = Vec::new(); for _ in range(0u, 10000) { diff --git a/src/test/run-pass/tempfile.rs b/src/test/run-pass/tempfile.rs index a866f497b8615..9e67095bb3031 100644 --- a/src/test/run-pass/tempfile.rs +++ b/src/test/run-pass/tempfile.rs @@ -23,6 +23,7 @@ use std::io::{fs, TempDir}; use std::io; use std::os; use std::task; +use std::sync::mpsc::channel; fn test_tempdir() { let path = { @@ -38,11 +39,11 @@ fn test_rm_tempdir() { let (tx, rx) = channel(); let f = move|:| -> () { let tmp = TempDir::new("test_rm_tempdir").unwrap(); - tx.send(tmp.path().clone()); + tx.send(tmp.path().clone()).unwrap(); panic!("panic to unwind past `tmp`"); }; task::try(f); - let path = rx.recv(); + let path = rx.recv().unwrap(); assert!(!path.exists()); let tmp = TempDir::new("test_rm_tempdir").unwrap(); @@ -79,12 +80,12 @@ fn test_rm_tempdir_close() { let (tx, rx) = channel(); let f = move|:| -> () { let tmp = TempDir::new("test_rm_tempdir").unwrap(); - tx.send(tmp.path().clone()); + tx.send(tmp.path().clone()).unwrap(); tmp.close(); panic!("panic when unwinding past `tmp`"); }; task::try(f); - let path = rx.recv(); + let path = rx.recv().unwrap(); assert!(!path.exists()); let tmp = TempDir::new("test_rm_tempdir").unwrap(); diff --git a/src/test/run-pass/trait-bounds-in-arc.rs b/src/test/run-pass/trait-bounds-in-arc.rs index d2c1461d65d0b..0d2cb60c213c1 100644 --- a/src/test/run-pass/trait-bounds-in-arc.rs +++ b/src/test/run-pass/trait-bounds-in-arc.rs @@ -11,8 +11,8 @@ // Tests that a heterogeneous list of existential types can be put inside an Arc // and shared between tasks as long as all types fulfill Send. - use std::sync::Arc; +use std::sync::mpsc::channel; use std::task; trait Pet { diff --git a/src/test/run-pass/trait-inheritance-overloading.rs b/src/test/run-pass/trait-inheritance-overloading.rs index 5f8e945cce860..1cd6e3ecebeb1 100644 --- a/src/test/run-pass/trait-inheritance-overloading.rs +++ b/src/test/run-pass/trait-inheritance-overloading.rs @@ -9,6 +9,7 @@ // except according to those terms. use std::cmp::PartialEq; +use std::ops::{Add, Sub, Mul}; trait MyNum : Add + Sub + Mul + PartialEq + Clone { } diff --git a/src/test/run-pass/trivial-message.rs b/src/test/run-pass/trivial-message.rs index 464ab1352281e..6bece8265c006 100644 --- a/src/test/run-pass/trivial-message.rs +++ b/src/test/run-pass/trivial-message.rs @@ -13,6 +13,8 @@ message. */ +use std::sync::mpsc::channel; + pub fn main() { let (tx, rx) = channel(); tx.send(42i); diff --git a/src/test/run-pass/unboxed-closures-infer-argument-types-from-expected-bound.rs b/src/test/run-pass/unboxed-closures-infer-argument-types-from-expected-bound.rs index 465c324122a44..fdd85b71cd270 100644 --- a/src/test/run-pass/unboxed-closures-infer-argument-types-from-expected-bound.rs +++ b/src/test/run-pass/unboxed-closures-infer-argument-types-from-expected-bound.rs @@ -13,6 +13,8 @@ #![feature(unboxed_closures)] +use std::num::ToPrimitive; + fn doit(val: T, f: &F) where F : Fn(T) { diff --git a/src/test/run-pass/unboxed-closures-infer-argument-types-from-expected-object-type.rs b/src/test/run-pass/unboxed-closures-infer-argument-types-from-expected-object-type.rs index 440292d202e48..cce8cd64a14db 100644 --- a/src/test/run-pass/unboxed-closures-infer-argument-types-from-expected-object-type.rs +++ b/src/test/run-pass/unboxed-closures-infer-argument-types-from-expected-object-type.rs @@ -13,6 +13,8 @@ #![feature(unboxed_closures)] +use std::num::ToPrimitive; + fn doit(val: T, f: &Fn(T)) { f.call((val,)) } pub fn main() { diff --git a/src/test/run-pass/unboxed-closures-infer-argument-types-with-bound-regions-from-expected-bound.rs b/src/test/run-pass/unboxed-closures-infer-argument-types-with-bound-regions-from-expected-bound.rs index b279eb5fbba90..8497bf7f987a0 100644 --- a/src/test/run-pass/unboxed-closures-infer-argument-types-with-bound-regions-from-expected-bound.rs +++ b/src/test/run-pass/unboxed-closures-infer-argument-types-with-bound-regions-from-expected-bound.rs @@ -13,6 +13,8 @@ #![feature(unboxed_closures)] +use std::num::ToPrimitive; + fn doit(val: T, f: &F) where F : Fn(&T) { diff --git a/src/test/run-pass/unique-send-2.rs b/src/test/run-pass/unique-send-2.rs index 672cd2d00e8bd..f88c458f2ed76 100644 --- a/src/test/run-pass/unique-send-2.rs +++ b/src/test/run-pass/unique-send-2.rs @@ -9,9 +9,10 @@ // except according to those terms. use std::task; +use std::sync::mpsc::{channel, Sender}; fn child(tx: &Sender>, i: uint) { - tx.send(box i); + tx.send(box i).unwrap(); } pub fn main() { @@ -28,7 +29,7 @@ pub fn main() { let mut actual = 0u; for _ in range(0u, n) { - let j = rx.recv(); + let j = rx.recv().unwrap(); actual += *j; } diff --git a/src/test/run-pass/unique-send.rs b/src/test/run-pass/unique-send.rs index 22b5a8cdaa4bf..afafb204c1c9f 100644 --- a/src/test/run-pass/unique-send.rs +++ b/src/test/run-pass/unique-send.rs @@ -8,9 +8,11 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::sync::mpsc::channel; + pub fn main() { let (tx, rx) = channel(); - tx.send(box 100i); - let v = rx.recv(); + tx.send(box 100i).unwrap(); + let v = rx.recv().unwrap(); assert_eq!(v, box 100i); } diff --git a/src/test/run-pass/unwind-resource.rs b/src/test/run-pass/unwind-resource.rs index 9789deef63649..943b2d3edd12e 100644 --- a/src/test/run-pass/unwind-resource.rs +++ b/src/test/run-pass/unwind-resource.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. - +use std::sync::mpsc::{channel, Sender}; use std::task; struct complainer { @@ -18,7 +18,7 @@ struct complainer { impl Drop for complainer { fn drop(&mut self) { println!("About to send!"); - self.tx.send(true); + self.tx.send(true).unwrap(); println!("Sent!"); } } @@ -39,5 +39,5 @@ pub fn main() { let (tx, rx) = channel(); task::spawn(move|| f(tx.clone())); println!("hiiiiiiiii"); - assert!(rx.recv()); + assert!(rx.recv().unwrap()); } diff --git a/src/test/run-pass/variadic-ffi.rs b/src/test/run-pass/variadic-ffi.rs index f8eef98856114..ec320c1f8a309 100644 --- a/src/test/run-pass/variadic-ffi.rs +++ b/src/test/run-pass/variadic-ffi.rs @@ -9,7 +9,8 @@ // except according to those terms. extern crate libc; -use std::c_str::CString; + +use std::c_str::{CString, ToCStr}; use libc::{c_char, c_int}; // ignore-fast doesn't like extern crate diff --git a/src/test/run-pass/wait-forked-but-failed-child.rs b/src/test/run-pass/wait-forked-but-failed-child.rs index 577e114945c66..624b41767049c 100644 --- a/src/test/run-pass/wait-forked-but-failed-child.rs +++ b/src/test/run-pass/wait-forked-but-failed-child.rs @@ -12,10 +12,10 @@ extern crate libc; use std::io::process::Command; use std::iter::IteratorExt; +use std::str::from_str; use libc::funcs::posix88::unistd; - // The output from "ps -A -o pid,ppid,args" should look like this: // PID PPID COMMAND // 1 0 /sbin/init