auto merge of #15163 : alexcrichton/rust/rollup, r=alexcrichton

This commit is contained in:
bors 2014-06-25 02:02:00 +00:00
commit 91be86af09
429 changed files with 2913 additions and 2646 deletions

2
configure vendored
View file

@ -869,6 +869,7 @@ do
make_dir $h/test/debuginfo-lldb
make_dir $h/test/codegen
make_dir $h/test/doc-tutorial
make_dir $h/test/doc-guide
make_dir $h/test/doc-guide-ffi
make_dir $h/test/doc-guide-runtime
make_dir $h/test/doc-guide-macros
@ -876,7 +877,6 @@ do
make_dir $h/test/doc-guide-pointers
make_dir $h/test/doc-guide-container
make_dir $h/test/doc-guide-tasks
make_dir $h/test/doc-complement-cheatsheet
make_dir $h/test/doc-rust
done

View file

@ -26,9 +26,9 @@
# L10N_LANGS are the languages for which the docs have been
# translated.
######################################################################
DOCS := index intro tutorial guide-ffi guide-macros guide-lifetimes \
DOCS := index intro tutorial guide guide-ffi guide-macros guide-lifetimes \
guide-tasks guide-container guide-pointers guide-testing \
guide-runtime complement-bugreport complement-cheatsheet \
guide-runtime complement-bugreport \
complement-lang-faq complement-design-faq complement-project-faq rust \
rustdoc guide-unsafe

View file

@ -42,9 +42,9 @@ SPACE :=
SPACE +=
ifneq ($(wildcard $(subst $(SPACE),\$(SPACE),$(CFG_GIT))),)
ifneq ($(wildcard $(subst $(SPACE),\$(SPACE),$(CFG_GIT_DIR))),)
CFG_VERSION += $(shell git --git-dir='$(CFG_GIT_DIR)' log -1 \
--pretty=format:'(%h %ci)')
CFG_VER_DATE = $(shell git --git-dir='$(CFG_GIT_DIR)' log -1 --pretty=format:'%ci')
CFG_VER_HASH = $(shell git --git-dir='$(CFG_GIT_DIR)' rev-parse HEAD)
CFG_VERSION += ($(CFG_VER_HASH) $(CFG_VER_DATE))
endif
endif
@ -272,6 +272,12 @@ $(foreach host,$(CFG_HOST), \
export CFG_SRC_DIR
export CFG_BUILD_DIR
ifdef CFG_VER_DATE
export CFG_VER_DATE
endif
ifdef CFG_VER_HASH
export CFG_VER_HASH
endif
export CFG_VERSION
export CFG_VERSION_WIN
export CFG_RELEASE

View file

@ -1,280 +0,0 @@
% Rust Cheatsheet
# How do I convert *X* to *Y*?
**Int to string**
Use [`ToStr`](std/to_str/trait.ToStr.html).
~~~
let x: int = 42;
let y: String = x.to_str();
~~~
**String to int**
Use [`FromStr`](std/from_str/trait.FromStr.html), and its helper function,
[`from_str`](std/from_str/fn.from_str.html).
~~~
let x: Option<int> = from_str("42");
let y: int = x.unwrap();
~~~
**Int to string, in non-base-10**
Use the `format!` syntax extension.
~~~
let x: int = 42;
let y: String = format!("{:t}", x); // binary
let y: String = format!("{:o}", x); // octal
let y: String = format!("{:x}", x); // lowercase hexadecimal
let y: String = format!("{:X}", x); // uppercase hexadecimal
~~~
**String to int, in non-base-10**
Use [`FromStrRadix`](std/num/trait.FromStrRadix.html), and its helper
function, [`from_str_radix`](std/num/fn.from_str_radix.html).
~~~
use std::num;
let x: Option<i64> = num::from_str_radix("deadbeef", 16);
let y: i64 = x.unwrap();
~~~
**Vector of Bytes to String**
To return a Borrowed String Slice (&str) use the str helper function
[`from_utf8`](std/str/fn.from_utf8.html).
~~~
use std::str;
let bytes = &[104u8,105u8];
let x: &str = str::from_utf8(bytes).unwrap();
~~~
To return an Owned String use the str helper function
[`from_utf8_owned`](std/str/fn.from_utf8_owned.html).
~~~
use std::str;
let x: Option<String> =
str::from_utf8([ 104u8, 105u8 ]).map(|x| x.to_string());
let y: String = x.unwrap();
~~~
To return a [`MaybeOwned`](std/str/type.MaybeOwned.html) use the str helper
function [`from_utf8_lossy`](std/str/fn.from_utf8_owned.html).
This function also replaces non-valid utf-8 sequences with U+FFFD replacement
character.
~~~
use std::str;
let x = b"Hello \xF0\x90\x80World!";
let y = str::from_utf8_lossy(x);
~~~
**`Vec<T>`/`String` to `&[T]`/`&str`**
The `.as_slice` method on each type provides a borrowed slice pointing
to the contents of a `Vec` or `String`. The slice points directly to
the data already stored in the vector or string, and so is a very
cheap operation (no allocations or complicated computations required).
~~~
let vec: Vec<u32> = vec![1, 2, 3];
let slice: &[u32] = vec.as_slice();
let string: String = "foo bar".to_string();
let str_slice: &str = string.as_slice();
~~~
`Vec` also provides the `.as_mut_slice` method for viewing the
contained data as a `&mut [T]`.
# File operations
## How do I read from a file?
Use
[`File::open`](std/io/fs/struct.File.html#method.open)
to create a
[`File`](std/io/fs/struct.File.html)
struct, which implements the
[`Reader`](std/io/trait.Reader.html)
trait.
~~~ {.ignore}
use std::path::Path;
use std::io::fs::File;
let path : Path = Path::new("Doc-FAQ-Cheatsheet.md");
let on_error = || fail!("open of {:?} failed", path);
let reader : File = File::open(&path).unwrap_or_else(on_error);
~~~
## How do I iterate over the lines in a file?
Use the [`lines`](std/io/trait.Buffer.html#method.lines) method on a
[`BufferedReader`](std/io/struct.BufferedReader.html).
~~~
use std::io::BufferedReader;
# use std::io::MemReader;
# let reader = MemReader::new(vec!());
let mut reader = BufferedReader::new(reader);
for line in reader.lines() {
print!("line: {}", line);
}
~~~
# String operations
## How do I search for a substring?
Use the [`find_str`](std/str/trait.StrSlice.html#tymethod.find_str) method.
~~~
let str = "Hello, this is some random string";
let index: Option<uint> = str.find_str("rand");
~~~
# Containers
## How do I get the length of a vector?
The [`Container`](std/container/trait.Container.html) trait provides the `len` method.
~~~
let u: Vec<u32> = vec![0, 1, 2];
let v: &[u32] = &[0, 1, 2, 3];
let w: [u32, .. 5] = [0, 1, 2, 3, 4];
println!("u: {}, v: {}, w: {}", u.len(), v.len(), w.len()); // 3, 4, 5
~~~
## How do I iterate over a vector?
Use the [`iter`](std/slice/trait.ImmutableVector.html#tymethod.iter) method.
~~~
let values: Vec<int> = vec![1, 2, 3, 4, 5];
for value in values.iter() { // value: &int
println!("{}", *value);
}
~~~
(See also [`mut_iter`](std/slice/trait.MutableVector.html#tymethod.mut_iter)
which yields `&mut int` and
[`move_iter`](std/slice/trait.OwnedVector.html#tymethod.move_iter) which yields
`int` while consuming the `values` vector.)
# Type system
## How do I store a function in a struct?
~~~
struct Foo {
myfunc: fn(int, uint) -> i32
}
struct FooClosure<'a> {
myfunc: |int, uint|: 'a -> i32
}
fn a(a: int, b: uint) -> i32 {
(a as uint + b) as i32
}
fn main() {
let f = Foo { myfunc: a };
let g = FooClosure { myfunc: |a, b| { (a - b as int) as i32 } };
println!("{}", (f.myfunc)(1, 2));
println!("{}", (g.myfunc)(3, 4));
}
~~~
Note that the parenthesis surrounding `f.myfunc` are necessary: they are how Rust disambiguates field lookup and method call. The `'a` on `FooClosure` is the lifetime of the closure's environment pointer.
## How do I express phantom types?
[Phantom types](http://www.haskell.org/haskellwiki/Phantom_type) are those that cannot be constructed at compile time. To express these in Rust, zero-variant `enum`s can be used:
~~~
enum Open {}
enum Closed {}
~~~
Phantom types are useful for enforcing state at compile time. For example:
~~~
struct Door<State>(String);
struct Open;
struct Closed;
fn close(Door(name): Door<Open>) -> Door<Closed> {
Door::<Closed>(name)
}
fn open(Door(name): Door<Closed>) -> Door<Open> {
Door::<Open>(name)
}
let _ = close(Door::<Open>("front".to_string()));
~~~
Attempting to close a closed door is prevented statically:
~~~ {.ignore}
let _ = close(Door::<Closed>("front".to_string())); // error: mismatched types: expected `main::Door<main::Open>` but found `main::Door<main::Closed>`
~~~
# FFI (Foreign Function Interface)
## C function signature conversions
| Description | C signature | Equivalent Rust signature |
|---------------------|-----------------------------------------------|------------------------------------------------|
| no parameters | `void foo(void);` | `fn foo();` |
| return value | `int foo(void);` | `fn foo() -> c_int;` |
| function parameters | `void foo(int x, int y);` | `fn foo(x: c_int, y: c_int);` |
| in-out pointers | `void foo(const int* in_ptr, int* out_ptr);` | `fn foo(in_ptr: *c_int, out_ptr: *mut c_int);` |
Note: The Rust signatures should be wrapped in an `extern "ABI" { ... }` block.
### Representing opaque handles
You might see things like this in C APIs:
~~~c
typedef struct Window Window;
Window* createWindow(int width, int height);
~~~
You can use a zero-element `enum` ([phantom type](#how-do-i-express-phantom-types)) to represent the opaque object handle. The FFI would look like this:
~~~ {.ignore}
enum Window {}
extern "C" {
fn createWindow(width: c_int, height: c_int) -> *Window;
}
~~~
Using a phantom type ensures that the handles cannot be (safely) constructed in client code.
# Contributing to this page
For small examples, have full type annotations, as much as is reasonable, to keep it clear what, exactly, everything is doing. Try to link to the API docs, as well.
Similar documents for other programming languages:
* [http://pleac.sourceforge.net/](http://pleac.sourceforge.net)

View file

@ -135,7 +135,7 @@ invalidation*. As long as an iterator is still in scope, the compiler will preve
modification of the container through another handle.
~~~
let mut xs = [1, 2, 3];
let mut xs = [1i, 2, 3];
{
let _it = xs.iter();
@ -155,7 +155,7 @@ example, the `fold` method will accumulate the items yielded by an `Iterator`
into a single value:
~~~
let xs = [1, 9, 2, 3, 14, 12];
let xs = [1i, 9, 2, 3, 14, 12];
let result = xs.iter().fold(0, |accumulator, item| accumulator - *item);
assert_eq!(result, -41);
~~~
@ -163,8 +163,8 @@ assert_eq!(result, -41);
Most adaptors return an adaptor object implementing the `Iterator` trait itself:
~~~
let xs = [1, 9, 2, 3, 14, 12];
let ys = [5, 2, 1, 8];
let xs = [1i, 9, 2, 3, 14, 12];
let ys = [5i, 2, 1, 8];
let sum = xs.iter().chain(ys.iter()).fold(0, |a, b| a + *b);
assert_eq!(sum, 57);
~~~
@ -180,8 +180,8 @@ iterator adaptor named `fuse()` is provided. This returns an iterator that will
never call its underlying iterator again once `None` has been returned:
~~~
let xs = [1,2,3,4,5];
let mut calls = 0;
let xs = [1i,2,3,4,5];
let mut calls = 0i;
{
let it = xs.iter().scan((), |_, x| {
@ -209,11 +209,11 @@ assert_eq!(calls, 3);
The function `range` (or `range_inclusive`) allows to simply iterate through a given range:
~~~
for i in range(0, 5) {
for i in range(0i, 5) {
print!("{} ", i) // prints "0 1 2 3 4"
}
for i in std::iter::range_inclusive(0, 5) { // needs explicit import
for i in std::iter::range_inclusive(0i, 5) { // needs explicit import
print!("{} ", i) // prints "0 1 2 3 4 5"
}
~~~
@ -238,7 +238,7 @@ For loops are *often* used with a temporary iterator object, as above. They can
also advance the state of an iterator in a mutable location:
~~~
let xs = [1, 2, 3, 4, 5];
let xs = [1i, 2, 3, 4, 5];
let ys = ["foo", "bar", "baz", "foobar"];
// create an iterator yielding tuples of elements from both vectors
@ -265,7 +265,7 @@ assert!(it.next().is_none());
Iterators offer generic conversion to containers with the `collect` adaptor:
~~~
let xs = [0, 1, 1, 2, 3, 5, 8];
let xs = [0i, 1, 1, 2, 3, 5, 8];
let ys = xs.iter().rev().skip(1).map(|&x| x * 2).collect::<Vec<int>>();
assert_eq!(ys, vec![10, 6, 4, 2, 2, 0]);
~~~
@ -347,7 +347,7 @@ A `DoubleEndedIterator` can have its direction changed with the `rev` adaptor,
returning another `DoubleEndedIterator` with `next` and `next_back` exchanged.
~~~
let xs = [1, 2, 3, 4, 5, 6];
let xs = [1i, 2, 3, 4, 5, 6];
let mut it = xs.iter();
println!("{}", it.next()); // prints `Some(1)`
println!("{}", it.next()); // prints `Some(2)`
@ -363,8 +363,8 @@ The `chain`, `map`, `filter`, `filter_map` and `inspect` adaptors are
`DoubleEndedIterator` implementations if the underlying iterators are.
~~~
let xs = [1, 2, 3, 4];
let ys = [5, 6, 7, 8];
let xs = [1i, 2, 3, 4];
let ys = [5i, 6, 7, 8];
let mut it = xs.iter().chain(ys.iter()).map(|&x| x * 2);
println!("{}", it.next()); // prints `Some(2)`
@ -380,9 +380,9 @@ mutable references. It can be used to reverse a container in-place. Note that
the trailing underscore is a workaround for issue #5898 and will be removed.
~~~
let mut ys = [1, 2, 3, 4, 5];
let mut ys = [1i, 2, 3, 4, 5];
ys.mut_iter().reverse_();
assert!(ys == [5, 4, 3, 2, 1]);
assert!(ys == [5i, 4, 3, 2, 1]);
~~~
## Random-access iterators
@ -395,8 +395,8 @@ The `chain` adaptor is an implementation of `RandomAccessIterator` if the
underlying iterators are.
~~~
let xs = [1, 2, 3, 4, 5];
let ys = [7, 9, 11];
let xs = [1i, 2, 3, 4, 5];
let ys = [7i, 9, 11];
let mut it = xs.iter().chain(ys.iter());
println!("{}", it.idx(0)); // prints `Some(1)`
println!("{}", it.idx(5)); // prints `Some(7)`

View file

@ -577,7 +577,7 @@ This is equivalent to the previous definition.
Named lifetime notation can also be used to control the flow of execution:
~~~
'h: for i in range(0,10) {
'h: for i in range(0u, 10) {
'g: loop {
if i % 2 == 0 { continue 'h; }
if i == 9 { break 'h; }

View file

@ -315,7 +315,7 @@ duration a 'lifetime'. Let's try a more complex example:
~~~rust
fn main() {
let mut x = box 5;
let mut x = box 5i;
if *x < 10 {
let y = &x;
println!("Oh no: {}", y);
@ -332,7 +332,7 @@ mutated, and therefore, lets us pass. This wouldn't work:
~~~rust{.ignore}
fn main() {
let mut x = box 5;
let mut x = box 5i;
if *x < 10 {
let y = &x;
*x -= 1;

View file

@ -269,7 +269,7 @@ use test::Bencher;
#[bench]
fn bench_xor_1000_ints(b: &mut Bencher) {
b.iter(|| {
range(0, 1000).fold(0, |old, new| old ^ new);
range(0u, 1000).fold(0, |old, new| old ^ new);
});
}
~~~
@ -293,7 +293,7 @@ example above by adjusting the `bh.iter` call to
# struct X; impl X { fn iter<T>(&self, _: || -> T) {} } let b = X;
b.iter(|| {
// note lack of `;` (could also use an explicit `return`).
range(0, 1000).fold(0, |old, new| old ^ new)
range(0u, 1000).fold(0, |old, new| old ^ new)
});
~~~
@ -307,7 +307,7 @@ extern crate test;
# fn main() {
# struct X; impl X { fn iter<T>(&self, _: || -> T) {} } let b = X;
b.iter(|| {
test::black_box(range(0, 1000).fold(0, |old, new| old ^ new));
test::black_box(range(0u, 1000).fold(0, |old, new| old ^ new));
});
# }
~~~

10
src/doc/guide.md Normal file
View file

@ -0,0 +1,10 @@
% The Rust Guide
<div style="border: 2px solid red; padding:5px;">
This guide is a work in progress. Until it is ready, we highly recommend that
you read the <a href="tutorial.html">Tutorial</a> instead. This work-in-progress Guide is being
displayed here in line with Rust's open development policy. Please open any
issues you find as usual.
</div>
Coming soon. :)

View file

@ -28,7 +28,6 @@ li {list-style-type: none; }
* [Language Design FAQ](complement-design-faq.html)
* [Language FAQ](complement-lang-faq.html)
* [Project FAQ](complement-project-faq.html)
* [Code cheatsheet](complement-cheatsheet.html) - "How do I do X?"
* [How to submit a bug report](complement-bugreport.html)
# Libraries

View file

@ -198,7 +198,7 @@ Typically, tasks do not share memory but instead communicate amongst each other
```
fn main() {
let numbers = vec![1,2,3];
let numbers = vec![1i, 2i, 3i];
let (tx, rx) = channel();
tx.send(numbers);
@ -237,7 +237,7 @@ try to modify the previous example to continue using the variable `numbers`:
```ignore
fn main() {
let numbers = vec![1,2,3];
let numbers = vec![1i, 2i, 3i];
let (tx, rx) = channel();
tx.send(numbers);
@ -267,9 +267,9 @@ Let's see an example that uses the `clone` method to create copies of the data:
```
fn main() {
let numbers = vec![1,2,3];
let numbers = vec![1i, 2i, 3i];
for num in range(0, 3) {
for num in range(0u, 3) {
let (tx, rx) = channel();
// Use `clone` to send a *copy* of the array
tx.send(numbers.clone());
@ -300,10 +300,10 @@ Here's some code:
use std::sync::Arc;
fn main() {
let numbers = vec![1,2,3];
let numbers = vec![1i, 2i, 3i];
let numbers = Arc::new(numbers);
for num in range(0, 3) {
for num in range(0u, 3) {
let (tx, rx) = channel();
tx.send(numbers.clone());
@ -346,10 +346,10 @@ and modify it to mutate the shared state:
use std::sync::{Arc, Mutex};
fn main() {
let numbers = vec![1,2,3];
let numbers = vec![1i, 2i, 3i];
let numbers_lock = Arc::new(Mutex::new(numbers));
for num in range(0, 3) {
for num in range(0u, 3) {
let (tx, rx) = channel();
tx.send(numbers_lock.clone());

View file

@ -955,11 +955,12 @@ use std::option::{Some, None};
# fn foo<T>(_: T){}
fn main() {
// Equivalent to 'std::iter::range_step(0, 10, 2);'
range_step(0, 10, 2);
// Equivalent to 'std::iter::range_step(0u, 10u, 2u);'
range_step(0u, 10u, 2u);
// Equivalent to 'foo(vec![std::option::Some(1.0), std::option::None]);'
foo(vec![Some(1.0), None]);
// Equivalent to 'foo(vec![std::option::Some(1.0f64),
// std::option::None]);'
foo(vec![Some(1.0f64), None]);
}
~~~~
@ -1475,7 +1476,7 @@ to pointers to the trait name, used as a type.
~~~~
# trait Shape { }
# impl Shape for int { }
# let mycircle = 0;
# let mycircle = 0i;
let myshape: Box<Shape> = box mycircle as Box<Shape>;
~~~~
@ -3613,7 +3614,7 @@ and no-return value closure has type `proc()`.
An example of creating and calling a closure:
```rust
let captured_var = 10;
let captured_var = 10i;
let closure_no_args = || println!("captured_var={}", captured_var);
@ -3685,7 +3686,7 @@ fn print(a: Box<Printable>) {
}
fn main() {
print(box 10 as Box<Printable>);
print(box 10i as Box<Printable>);
}
~~~~

View file

@ -1,5 +1,12 @@
% The Rust Language Tutorial
<div style="border: 2px solid red; padding:5px;">
The tutorial is undergoing a complete re-write as <a href="guide.html">the Guide</a>.
Until it's ready, this tutorial is the right place to come to start learning
Rust. Please submit improvements as pull requests, but understand that
eventually it will be going away.
</div>
# Introduction
Rust is a programming language with a focus on type safety, memory
@ -220,7 +227,7 @@ mut` instead.
~~~~
let hi = "hi";
let mut count = 0;
let mut count = 0i;
while count < 10 {
println!("count is {}", count);
@ -407,7 +414,7 @@ error when the types of the directives don't match the types of the arguments.
~~~
// `{}` will print the "default format" of a type
println!("{} is {}", "the answer", 43);
println!("{} is {}", "the answer", 43i);
~~~
~~~~
@ -535,7 +542,7 @@ A subpattern can also be bound to a variable, using `variable @ pattern`. For
example:
~~~~
# let age = 23;
# let age = 23i;
match age {
a @ 0..20 => println!("{} years old", a),
_ => println!("older than 21")
@ -594,7 +601,7 @@ it finds one that can be divided by five.
There is also a for-loop that can be used to iterate over a range of numbers:
~~~~
for n in range(0, 5) {
for n in range(0u, 5) {
println!("{}", n);
}
~~~~
@ -1124,7 +1131,7 @@ as it is only called a single time.
Avoiding a move can be done with the library-defined `clone` method:
~~~~
let x = box 5;
let x = box 5i;
let y = x.clone(); // `y` is a newly allocated box
let z = x; // no new memory allocated, `x` can no longer be used
~~~~
@ -1356,8 +1363,8 @@ impl<T: PartialEq> PartialEq for List<T> {
}
}
let xs = Cons(5, box Cons(10, box Nil));
let ys = Cons(5, box Cons(10, box Nil));
let xs = Cons(5i, box Cons(10i, box Nil));
let ys = Cons(5i, box Cons(10i, box Nil));
// The methods below are part of the PartialEq trait,
// which we implemented on our linked list.
assert!(xs.eq(&ys));
@ -1488,9 +1495,10 @@ For a more in-depth explanation of references and lifetimes, read the
## Freezing
Lending an &-pointer to an object freezes it and prevents mutation—even if the object was declared as `mut`.
`Freeze` objects have freezing enforced statically at compile-time. An example
of a non-`Freeze` type is [`RefCell<T>`][refcell].
Lending an &-pointer to an object freezes the pointed-to object and prevents
mutation—even if the object was declared as `mut`. `Freeze` objects have
freezing enforced statically at compile-time. An example of a non-`Freeze` type
is [`RefCell<T>`][refcell].
~~~~
let mut x = 5;
@ -1584,7 +1592,7 @@ elements are mutable if the vector is mutable. Fixed-size strings do not exist.
~~~
// A fixed-size vector
let numbers = [1, 2, 3];
let numbers = [1i, 2, 3];
let more_numbers = numbers;
// The type of a fixed-size vector is written as `[Type, ..length]`
@ -1599,7 +1607,7 @@ the elements are mutable if the vector is mutable.
use std::string::String;
// A dynamically sized vector (unique vector)
let mut numbers = vec![1, 2, 3];
let mut numbers = vec![1i, 2, 3];
numbers.push(4);
numbers.push(5);
@ -1694,11 +1702,11 @@ contained value are destroyed.
use std::rc::Rc;
// A fixed-size array allocated in a reference-counted box
let x = Rc::new([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
let x = Rc::new([1i, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
let y = x.clone(); // a new owner
let z = x; // this moves `x` into `z`, rather than creating a new owner
assert!(*z == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
assert!(*z == [1i, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
// the variable is mutable, but not the contents of the box
let mut a = Rc::new([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);
@ -1713,11 +1721,11 @@ not have a destructor.
use std::gc::GC;
// A fixed-size array allocated in a garbage-collected box
let x = box(GC) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let x = box(GC) [1i, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let y = x; // does not perform a move, unlike with `Rc`
let z = x;
assert!(*z == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
assert!(*z == [1i, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
~~~
With shared ownership, mutability cannot be inherited so the boxes are always immutable. However,
@ -3130,7 +3138,7 @@ extern crate num;
fn main() {
// The rational number '1/2':
let one_half = ::num::rational::Ratio::new(1, 2);
let one_half = ::num::rational::Ratio::new(1i, 2);
}
~~~
@ -3165,7 +3173,7 @@ mod farm {
fn main() {
farm::dog();
let a_third = Ratio::new(1, 3);
let a_third = Ratio::new(1i, 3);
}
~~~
@ -3292,13 +3300,13 @@ use iter_range = std::iter::range;
fn main() {
// `range` is imported by default
for _ in range(0, 10) {}
for _ in range(0u, 10) {}
// Doesn't hinder you from importing it under a different name yourself
for _ in iter_range(0, 10) {}
for _ in iter_range(0u, 10) {}
// Or from not using the automatic import.
for _ in ::std::iter::range(0, 10) {}
for _ in ::std::iter::range(0u, 10) {}
}
~~~
@ -3335,7 +3343,7 @@ guides on individual topics.
* [Testing Rust code][testing]
* [The Rust Runtime][runtime]
There is further documentation on the [wiki], however those tend to be even more out of date as this document.
There is further documentation on the [wiki], however those tend to be even more out of date than this document.
[pointers]: guide-pointers.html
[lifetimes]: guide-lifetimes.html

View file

@ -39,7 +39,7 @@ use heap::deallocate;
/// let numbers = Vec::from_fn(100, |i| i as f32);
/// let shared_numbers = Arc::new(numbers);
///
/// for _ in range(0, 10) {
/// for _ in range(0u, 10) {
/// let child_numbers = shared_numbers.clone();
///
/// spawn(proc() {
@ -110,6 +110,7 @@ impl<T: Share + Send> Arc<T> {
}
}
#[unstable]
impl<T: Share + Send> Clone for Arc<T> {
/// Duplicate an atomically reference counted wrapper.
///
@ -236,6 +237,7 @@ impl<T: Share + Send> Weak<T> {
}
}
#[unstable]
impl<T: Share + Send> Clone for Weak<T> {
#[inline]
fn clone(&self) -> Weak<T> {

View file

@ -42,6 +42,7 @@ impl<T: Default> Default for Box<T> {
fn default() -> Box<T> { box Default::default() }
}
#[unstable]
impl<T: Clone> Clone for Box<T> {
/// Return a copy of the owned box.
#[inline]

View file

@ -143,6 +143,7 @@ impl<T> Drop for Rc<T> {
}
}
#[unstable]
impl<T> Clone for Rc<T> {
#[inline]
fn clone(&self) -> Rc<T> {
@ -224,6 +225,7 @@ impl<T> Drop for Weak<T> {
}
}
#[unstable]
impl<T> Clone for Weak<T> {
#[inline]
fn clone(&self) -> Weak<T> {
@ -276,7 +278,7 @@ mod tests {
#[test]
fn test_clone() {
let x = Rc::new(RefCell::new(5));
let x = Rc::new(RefCell::new(5i));
let y = x.clone();
*x.borrow_mut() = 20;
assert_eq!(*y.borrow(), 20);
@ -284,13 +286,13 @@ mod tests {
#[test]
fn test_simple() {
let x = Rc::new(5);
let x = Rc::new(5i);
assert_eq!(*x, 5);
}
#[test]
fn test_simple_clone() {
let x = Rc::new(5);
let x = Rc::new(5i);
let y = x.clone();
assert_eq!(*x, 5);
assert_eq!(*y, 5);
@ -298,20 +300,20 @@ mod tests {
#[test]
fn test_destructor() {
let x = Rc::new(box 5);
let x = Rc::new(box 5i);
assert_eq!(**x, 5);
}
#[test]
fn test_live() {
let x = Rc::new(5);
let x = Rc::new(5i);
let y = x.downgrade();
assert!(y.upgrade().is_some());
}
#[test]
fn test_dead() {
let x = Rc::new(5);
let x = Rc::new(5i);
let y = x.downgrade();
drop(x);
assert!(y.upgrade().is_none());
@ -321,7 +323,7 @@ mod tests {
fn gc_inside() {
// see issue #11532
use std::gc::GC;
let a = Rc::new(RefCell::new(box(GC) 1));
let a = Rc::new(RefCell::new(box(GC) 1i));
assert!(a.try_borrow_mut().is_some());
}

View file

@ -513,7 +513,7 @@ mod tests {
#[test]
pub fn test_copy() {
let arena = TypedArena::new();
for _ in range(0, 100000) {
for _ in range(0u, 100000) {
arena.alloc(Point {
x: 1,
y: 2,
@ -567,7 +567,7 @@ mod tests {
#[test]
pub fn test_noncopy() {
let arena = TypedArena::new();
for _ in range(0, 100000) {
for _ in range(0u, 100000) {
arena.alloc(Noncopy {
string: "hello world".to_string(),
array: vec!( 1, 2, 3, 4, 5 ),

View file

@ -572,7 +572,7 @@ impl ops::Index<uint,bool> for Bitv {
impl fmt::Show for Bitv {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
for bit in self.iter() {
try!(write!(fmt, "{}", if bit { 1 } else { 0 }));
try!(write!(fmt, "{}", if bit { 1u } else { 0u }));
}
Ok(())
}

View file

@ -785,17 +785,17 @@ mod test_btree {
//Tests the functionality of the insert methods (which are unfinished).
#[test]
fn insert_test_one() {
let b = BTree::new(1, "abc".to_string(), 2);
let is_insert = b.insert(2, "xyz".to_string());
let b = BTree::new(1i, "abc".to_string(), 2);
let is_insert = b.insert(2i, "xyz".to_string());
//println!("{}", is_insert.clone().to_str());
assert!(is_insert.root.is_leaf());
}
#[test]
fn insert_test_two() {
let leaf_elt_1 = LeafElt::new(1, "aaa".to_string());
let leaf_elt_2 = LeafElt::new(2, "bbb".to_string());
let leaf_elt_3 = LeafElt::new(3, "ccc".to_string());
let leaf_elt_1 = LeafElt::new(1i, "aaa".to_string());
let leaf_elt_2 = LeafElt::new(2i, "bbb".to_string());
let leaf_elt_3 = LeafElt::new(3i, "ccc".to_string());
let n = Node::new_leaf(vec!(leaf_elt_1, leaf_elt_2, leaf_elt_3));
let b = BTree::new_with_node_len(n, 3, 2);
//println!("{}", b.clone().insert(4, "ddd".to_string()).to_str());
@ -804,10 +804,10 @@ mod test_btree {
#[test]
fn insert_test_three() {
let leaf_elt_1 = LeafElt::new(1, "aaa".to_string());
let leaf_elt_2 = LeafElt::new(2, "bbb".to_string());
let leaf_elt_3 = LeafElt::new(3, "ccc".to_string());
let leaf_elt_4 = LeafElt::new(4, "ddd".to_string());
let leaf_elt_1 = LeafElt::new(1i, "aaa".to_string());
let leaf_elt_2 = LeafElt::new(2i, "bbb".to_string());
let leaf_elt_3 = LeafElt::new(3i, "ccc".to_string());
let leaf_elt_4 = LeafElt::new(4i, "ddd".to_string());
let n = Node::new_leaf(vec!(leaf_elt_1, leaf_elt_2, leaf_elt_3, leaf_elt_4));
let b = BTree::new_with_node_len(n, 3, 2);
//println!("{}", b.clone().insert(5, "eee".to_string()).to_str());
@ -816,10 +816,10 @@ mod test_btree {
#[test]
fn insert_test_four() {
let leaf_elt_1 = LeafElt::new(1, "aaa".to_string());
let leaf_elt_2 = LeafElt::new(2, "bbb".to_string());
let leaf_elt_3 = LeafElt::new(3, "ccc".to_string());
let leaf_elt_4 = LeafElt::new(4, "ddd".to_string());
let leaf_elt_1 = LeafElt::new(1i, "aaa".to_string());
let leaf_elt_2 = LeafElt::new(2i, "bbb".to_string());
let leaf_elt_3 = LeafElt::new(3i, "ccc".to_string());
let leaf_elt_4 = LeafElt::new(4i, "ddd".to_string());
let n = Node::new_leaf(vec!(leaf_elt_1, leaf_elt_2, leaf_elt_3, leaf_elt_4));
let mut b = BTree::new_with_node_len(n, 3, 2);
b = b.clone().insert(5, "eee".to_string());
@ -833,22 +833,22 @@ mod test_btree {
#[test]
fn bsearch_test_one() {
let b = BTree::new(1, "abc".to_string(), 2);
let b = BTree::new(1i, "abc".to_string(), 2u);
assert_eq!(Some(1), b.root.bsearch_node(2));
}
#[test]
fn bsearch_test_two() {
let b = BTree::new(1, "abc".to_string(), 2);
let b = BTree::new(1i, "abc".to_string(), 2u);
assert_eq!(Some(0), b.root.bsearch_node(0));
}
#[test]
fn bsearch_test_three() {
let leaf_elt_1 = LeafElt::new(1, "aaa".to_string());
let leaf_elt_2 = LeafElt::new(2, "bbb".to_string());
let leaf_elt_3 = LeafElt::new(4, "ccc".to_string());
let leaf_elt_4 = LeafElt::new(5, "ddd".to_string());
let leaf_elt_1 = LeafElt::new(1i, "aaa".to_string());
let leaf_elt_2 = LeafElt::new(2i, "bbb".to_string());
let leaf_elt_3 = LeafElt::new(4i, "ccc".to_string());
let leaf_elt_4 = LeafElt::new(5i, "ddd".to_string());
let n = Node::new_leaf(vec!(leaf_elt_1, leaf_elt_2, leaf_elt_3, leaf_elt_4));
let b = BTree::new_with_node_len(n, 3, 2);
assert_eq!(Some(2), b.root.bsearch_node(3));
@ -856,10 +856,10 @@ mod test_btree {
#[test]
fn bsearch_test_four() {
let leaf_elt_1 = LeafElt::new(1, "aaa".to_string());
let leaf_elt_2 = LeafElt::new(2, "bbb".to_string());
let leaf_elt_3 = LeafElt::new(4, "ccc".to_string());
let leaf_elt_4 = LeafElt::new(5, "ddd".to_string());
let leaf_elt_1 = LeafElt::new(1i, "aaa".to_string());
let leaf_elt_2 = LeafElt::new(2i, "bbb".to_string());
let leaf_elt_3 = LeafElt::new(4i, "ccc".to_string());
let leaf_elt_4 = LeafElt::new(5i, "ddd".to_string());
let n = Node::new_leaf(vec!(leaf_elt_1, leaf_elt_2, leaf_elt_3, leaf_elt_4));
let b = BTree::new_with_node_len(n, 3, 2);
assert_eq!(Some(4), b.root.bsearch_node(800));
@ -868,7 +868,7 @@ mod test_btree {
//Tests the functionality of the get method.
#[test]
fn get_test() {
let b = BTree::new(1, "abc".to_string(), 2);
let b = BTree::new(1i, "abc".to_string(), 2);
let val = b.get(1);
assert_eq!(val, Some("abc".to_string()));
}
@ -876,7 +876,7 @@ mod test_btree {
//Tests the BTree's clone() method.
#[test]
fn btree_clone_test() {
let b = BTree::new(1, "abc".to_string(), 2);
let b = BTree::new(1i, "abc".to_string(), 2);
let b2 = b.clone();
assert!(b.root == b2.root)
}
@ -884,31 +884,31 @@ mod test_btree {
//Tests the BTree's cmp() method when one node is "less than" another.
#[test]
fn btree_cmp_test_less() {
let b = BTree::new(1, "abc".to_string(), 2);
let b2 = BTree::new(2, "bcd".to_string(), 2);
let b = BTree::new(1i, "abc".to_string(), 2);
let b2 = BTree::new(2i, "bcd".to_string(), 2);
assert!(&b.cmp(&b2) == &Less)
}
//Tests the BTree's cmp() method when two nodes are equal.
#[test]
fn btree_cmp_test_eq() {
let b = BTree::new(1, "abc".to_string(), 2);
let b2 = BTree::new(1, "bcd".to_string(), 2);
let b = BTree::new(1i, "abc".to_string(), 2);
let b2 = BTree::new(1i, "bcd".to_string(), 2);
assert!(&b.cmp(&b2) == &Equal)
}
//Tests the BTree's cmp() method when one node is "greater than" another.
#[test]
fn btree_cmp_test_greater() {
let b = BTree::new(1, "abc".to_string(), 2);
let b2 = BTree::new(2, "bcd".to_string(), 2);
let b = BTree::new(1i, "abc".to_string(), 2);
let b2 = BTree::new(2i, "bcd".to_string(), 2);
assert!(&b2.cmp(&b) == &Greater)
}
//Tests the BTree's to_str() method.
#[test]
fn btree_tostr_test() {
let b = BTree::new(1, "abc".to_string(), 2);
let b = BTree::new(1i, "abc".to_string(), 2);
assert_eq!(b.to_str(), "Key: 1, value: abc;".to_string())
}

View file

@ -693,7 +693,7 @@ mod tests {
assert_eq!(m.pop_front(), Some(box 1));
let mut n = DList::new();
n.push_front(2);
n.push_front(2i);
n.push_front(3);
{
assert_eq!(n.front().unwrap(), &3);
@ -713,7 +713,7 @@ mod tests {
#[cfg(test)]
fn generate_test() -> DList<int> {
list_from(&[0,1,2,3,4,5,6])
list_from(&[0i,1,2,3,4,5,6])
}
#[cfg(test)]
@ -726,7 +726,7 @@ mod tests {
{
let mut m = DList::new();
let mut n = DList::new();
n.push_back(2);
n.push_back(2i);
m.append(n);
assert_eq!(m.len(), 1);
assert_eq!(m.pop_back(), Some(2));
@ -735,15 +735,15 @@ mod tests {
{
let mut m = DList::new();
let n = DList::new();
m.push_back(2);
m.push_back(2i);
m.append(n);
assert_eq!(m.len(), 1);
assert_eq!(m.pop_back(), Some(2));
check_links(&m);
}
let v = vec![1,2,3,4,5];
let u = vec![9,8,1,2,3,4,5];
let v = vec![1i,2,3,4,5];
let u = vec![9i,8,1,2,3,4,5];
let mut m = list_from(v.as_slice());
m.append(list_from(u.as_slice()));
check_links(&m);
@ -759,15 +759,15 @@ mod tests {
{
let mut m = DList::new();
let mut n = DList::new();
n.push_back(2);
n.push_back(2i);
m.prepend(n);
assert_eq!(m.len(), 1);
assert_eq!(m.pop_back(), Some(2));
check_links(&m);
}
let v = vec![1,2,3,4,5];
let u = vec![9,8,1,2,3,4,5];
let v = vec![1i,2,3,4,5];
let u = vec![9i,8,1,2,3,4,5];
let mut m = list_from(v.as_slice());
m.prepend(list_from(u.as_slice()));
check_links(&m);
@ -786,7 +786,7 @@ mod tests {
n.rotate_forward(); check_links(&n);
assert_eq!(n.len(), 0);
let v = vec![1,2,3,4,5];
let v = vec![1i,2,3,4,5];
let mut m = list_from(v.as_slice());
m.rotate_backward(); check_links(&m);
m.rotate_forward(); check_links(&m);
@ -798,7 +798,7 @@ mod tests {
m.rotate_backward(); check_links(&m);
m.push_front(9); check_links(&m);
m.rotate_forward(); check_links(&m);
assert_eq!(vec![3,9,5,1,2], m.move_iter().collect());
assert_eq!(vec![3i,9,5,1,2], m.move_iter().collect());
}
#[test]
@ -809,7 +809,7 @@ mod tests {
}
let mut n = DList::new();
assert_eq!(n.iter().next(), None);
n.push_front(4);
n.push_front(4i);
let mut it = n.iter();
assert_eq!(it.size_hint(), (1, Some(1)));
assert_eq!(it.next().unwrap(), &4);
@ -820,7 +820,7 @@ mod tests {
#[test]
fn test_iterator_clone() {
let mut n = DList::new();
n.push_back(2);
n.push_back(2i);
n.push_back(3);
n.push_back(4);
let mut it = n.iter();
@ -835,7 +835,7 @@ mod tests {
fn test_iterator_double_end() {
let mut n = DList::new();
assert_eq!(n.iter().next(), None);
n.push_front(4);
n.push_front(4i);
n.push_front(5);
n.push_front(6);
let mut it = n.iter();
@ -857,7 +857,7 @@ mod tests {
}
let mut n = DList::new();
assert_eq!(n.iter().rev().next(), None);
n.push_front(4);
n.push_front(4i);
let mut it = n.iter().rev();
assert_eq!(it.size_hint(), (1, Some(1)));
assert_eq!(it.next().unwrap(), &4);
@ -876,7 +876,7 @@ mod tests {
assert_eq!(len, 0);
let mut n = DList::new();
assert!(n.mut_iter().next().is_none());
n.push_front(4);
n.push_front(4i);
n.push_back(5);
let mut it = n.mut_iter();
assert_eq!(it.size_hint(), (2, Some(2)));
@ -890,7 +890,7 @@ mod tests {
fn test_iterator_mut_double_end() {
let mut n = DList::new();
assert!(n.mut_iter().next_back().is_none());
n.push_front(4);
n.push_front(4i);
n.push_front(5);
n.push_front(6);
let mut it = n.mut_iter();
@ -906,7 +906,7 @@ mod tests {
#[test]
fn test_insert_prev() {
let mut m = list_from(&[0,2,4,6,8]);
let mut m = list_from(&[0i,2,4,6,8]);
let len = m.len();
{
let mut it = m.mut_iter();
@ -933,8 +933,8 @@ mod tests {
#[test]
fn test_merge() {
let mut m = list_from([0, 1, 3, 5, 6, 7, 2]);
let n = list_from([-1, 0, 0, 7, 7, 9]);
let mut m = list_from([0i, 1, 3, 5, 6, 7, 2]);
let n = list_from([-1i, 0, 0, 7, 7, 9]);
let len = m.len() + n.len();
m.merge(n, |a, b| a <= b);
assert_eq!(m.len(), len);
@ -946,12 +946,12 @@ mod tests {
#[test]
fn test_insert_ordered() {
let mut n = DList::new();
n.insert_ordered(1);
n.insert_ordered(1i);
assert_eq!(n.len(), 1);
assert_eq!(n.pop_front(), Some(1));
let mut m = DList::new();
m.push_back(2);
m.push_back(2i);
m.push_back(4);
m.insert_ordered(3);
check_links(&m);
@ -966,7 +966,7 @@ mod tests {
}
let mut n = DList::new();
assert!(n.mut_iter().rev().next().is_none());
n.push_front(4);
n.push_front(4i);
let mut it = n.mut_iter().rev();
assert!(it.next().is_some());
assert!(it.next().is_none());
@ -974,7 +974,7 @@ mod tests {
#[test]
fn test_send() {
let n = list_from([1,2,3]);
let n = list_from([1i,2,3]);
spawn(proc() {
check_links(&n);
assert_eq!(&[&1,&2,&3], n.iter().collect::<Vec<&int>>().as_slice());
@ -991,15 +991,15 @@ mod tests {
m.push_back(1);
assert!(n == m);
let n = list_from([2,3,4]);
let m = list_from([1,2,3]);
let n = list_from([2i,3,4]);
let m = list_from([1i,2,3]);
assert!(n != m);
}
#[test]
fn test_ord() {
let n: DList<int> = list_from([]);
let m = list_from([1,2,3]);
let m = list_from([1i,2,3]);
assert!(n < m);
assert!(m > n);
assert!(n <= n);
@ -1008,7 +1008,7 @@ mod tests {
#[test]
fn test_ord_nan() {
let nan = 0.0/0.0;
let nan = 0.0f64/0.0;
let n = list_from([nan]);
let m = list_from([nan]);
assert!(!(n < m));
@ -1017,21 +1017,21 @@ mod tests {
assert!(!(n >= m));
let n = list_from([nan]);
let one = list_from([1.0]);
let one = list_from([1.0f64]);
assert!(!(n < one));
assert!(!(n > one));
assert!(!(n <= one));
assert!(!(n >= one));
let u = list_from([1.0,2.0,nan]);
let v = list_from([1.0,2.0,3.0]);
let u = list_from([1.0f64,2.0,nan]);
let v = list_from([1.0f64,2.0,3.0]);
assert!(!(u < v));
assert!(!(u > v));
assert!(!(u <= v));
assert!(!(u >= v));
let s = list_from([1.0,2.0,4.0,2.0]);
let t = list_from([1.0,2.0,3.0,2.0]);
let s = list_from([1.0f64,2.0,4.0,2.0]);
let t = list_from([1.0f64,2.0,3.0,2.0]);
assert!(!(s < t));
assert!(s > one);
assert!(!(s <= one));
@ -1040,7 +1040,7 @@ mod tests {
#[test]
fn test_fuzz() {
for _ in range(0, 25) {
for _ in range(0u, 25) {
fuzz_test(3);
fuzz_test(16);
fuzz_test(189);
@ -1049,7 +1049,7 @@ mod tests {
#[test]
fn test_show() {
let list: DList<int> = range(0, 10).collect();
let list: DList<int> = range(0i, 10).collect();
assert!(list.to_str().as_slice() == "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
let list: DList<&str> = vec!["just", "one", "test", "more"].iter()
@ -1097,7 +1097,7 @@ mod tests {
#[bench]
fn bench_collect_into(b: &mut test::Bencher) {
let v = &[0, ..64];
let v = &[0i, ..64];
b.iter(|| {
let _: DList<int> = v.iter().map(|x| *x).collect();
})
@ -1140,7 +1140,7 @@ mod tests {
#[bench]
fn bench_rotate_forward(b: &mut test::Bencher) {
let mut m: DList<int> = DList::new();
m.push_front(0);
m.push_front(0i);
m.push_front(1);
b.iter(|| {
m.rotate_forward();
@ -1150,7 +1150,7 @@ mod tests {
#[bench]
fn bench_rotate_backward(b: &mut test::Bencher) {
let mut m: DList<int> = DList::new();
m.push_front(0);
m.push_front(0i);
m.push_front(1);
b.iter(|| {
m.rotate_backward();
@ -1159,7 +1159,7 @@ mod tests {
#[bench]
fn bench_iter(b: &mut test::Bencher) {
let v = &[0, ..128];
let v = &[0i, ..128];
let m: DList<int> = v.iter().map(|&x|x).collect();
b.iter(|| {
assert!(m.iter().count() == 128);
@ -1167,7 +1167,7 @@ mod tests {
}
#[bench]
fn bench_iter_mut(b: &mut test::Bencher) {
let v = &[0, ..128];
let v = &[0i, ..128];
let mut m: DList<int> = v.iter().map(|&x|x).collect();
b.iter(|| {
assert!(m.mut_iter().count() == 128);
@ -1175,7 +1175,7 @@ mod tests {
}
#[bench]
fn bench_iter_rev(b: &mut test::Bencher) {
let v = &[0, ..128];
let v = &[0i, ..128];
let m: DList<int> = v.iter().map(|&x|x).collect();
b.iter(|| {
assert!(m.iter().rev().count() == 128);
@ -1183,7 +1183,7 @@ mod tests {
}
#[bench]
fn bench_iter_mut_rev(b: &mut test::Bencher) {
let v = &[0, ..128];
let v = &[0i, ..128];
let mut m: DList<int> = v.iter().map(|&x|x).collect();
b.iter(|| {
assert!(m.mut_iter().rev().count() == 128);

View file

@ -255,8 +255,8 @@ mod tests {
#[test]
fn test_iterator() {
let data = vec!(5, 9, 3);
let iterout = [9, 5, 3];
let data = vec!(5i, 9, 3);
let iterout = [9i, 5, 3];
let pq = PriorityQueue::from_vec(data);
let mut i = 0;
for el in pq.iter() {
@ -279,7 +279,7 @@ mod tests {
#[test]
fn test_push() {
let mut heap = PriorityQueue::from_vec(vec!(2, 4, 9));
let mut heap = PriorityQueue::from_vec(vec!(2i, 4, 9));
assert_eq!(heap.len(), 3);
assert!(*heap.top().unwrap() == 9);
heap.push(11);
@ -301,7 +301,7 @@ mod tests {
#[test]
fn test_push_unique() {
let mut heap = PriorityQueue::from_vec(vec!(box 2, box 4, box 9));
let mut heap = PriorityQueue::from_vec(vec!(box 2i, box 4, box 9));
assert_eq!(heap.len(), 3);
assert!(*heap.top().unwrap() == box 9);
heap.push(box 11);
@ -323,7 +323,7 @@ mod tests {
#[test]
fn test_push_pop() {
let mut heap = PriorityQueue::from_vec(vec!(5, 5, 2, 1, 3));
let mut heap = PriorityQueue::from_vec(vec!(5i, 5, 2, 1, 3));
assert_eq!(heap.len(), 5);
assert_eq!(heap.push_pop(6), 6);
assert_eq!(heap.len(), 5);
@ -337,7 +337,7 @@ mod tests {
#[test]
fn test_replace() {
let mut heap = PriorityQueue::from_vec(vec!(5, 5, 2, 1, 3));
let mut heap = PriorityQueue::from_vec(vec!(5i, 5, 2, 1, 3));
assert_eq!(heap.len(), 5);
assert_eq!(heap.replace(6).unwrap(), 5);
assert_eq!(heap.len(), 5);
@ -362,18 +362,18 @@ mod tests {
#[test]
fn test_to_vec() {
check_to_vec(vec!());
check_to_vec(vec!(5));
check_to_vec(vec!(3, 2));
check_to_vec(vec!(2, 3));
check_to_vec(vec!(5, 1, 2));
check_to_vec(vec!(1, 100, 2, 3));
check_to_vec(vec!(1, 3, 5, 7, 9, 2, 4, 6, 8, 0));
check_to_vec(vec!(2, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1));
check_to_vec(vec!(9, 11, 9, 9, 9, 9, 11, 2, 3, 4, 11, 9, 0, 0, 0, 0));
check_to_vec(vec!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
check_to_vec(vec!(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0));
check_to_vec(vec!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 1, 2));
check_to_vec(vec!(5, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1));
check_to_vec(vec!(5i));
check_to_vec(vec!(3i, 2));
check_to_vec(vec!(2i, 3));
check_to_vec(vec!(5i, 1, 2));
check_to_vec(vec!(1i, 100, 2, 3));
check_to_vec(vec!(1i, 3, 5, 7, 9, 2, 4, 6, 8, 0));
check_to_vec(vec!(2i, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1));
check_to_vec(vec!(9i, 11, 9, 9, 9, 9, 11, 2, 3, 4, 11, 9, 0, 0, 0, 0));
check_to_vec(vec!(0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
check_to_vec(vec!(10i, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0));
check_to_vec(vec!(0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 1, 2));
check_to_vec(vec!(5i, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1));
}
#[test]

View file

@ -431,8 +431,8 @@ mod tests {
fn test_simple() {
let mut d = RingBuf::new();
assert_eq!(d.len(), 0u);
d.push_front(17);
d.push_front(42);
d.push_front(17i);
d.push_front(42i);
d.push_back(137);
assert_eq!(d.len(), 3u);
d.push_back(137);
@ -588,7 +588,7 @@ mod tests {
fn bench_grow(b: &mut test::Bencher) {
let mut deq = RingBuf::new();
b.iter(|| {
for _ in range(0, 65) {
for _ in range(0i, 65) {
deq.push_front(1);
}
})
@ -684,7 +684,7 @@ mod tests {
#[test]
fn test_swap() {
let mut d: RingBuf<int> = range(0, 5).collect();
let mut d: RingBuf<int> = range(0i, 5).collect();
d.pop_front();
d.swap(0, 3);
assert_eq!(d.iter().map(|&x|x).collect::<Vec<int>>(), vec!(4, 2, 3, 1));
@ -696,12 +696,12 @@ mod tests {
assert_eq!(d.iter().next(), None);
assert_eq!(d.iter().size_hint(), (0, Some(0)));
for i in range(0, 5) {
for i in range(0i, 5) {
d.push_back(i);
}
assert_eq!(d.iter().collect::<Vec<&int>>().as_slice(), &[&0,&1,&2,&3,&4]);
for i in range(6, 9) {
for i in range(6i, 9) {
d.push_front(i);
}
assert_eq!(d.iter().collect::<Vec<&int>>().as_slice(), &[&8,&7,&6,&0,&1,&2,&3,&4]);
@ -721,12 +721,12 @@ mod tests {
let mut d = RingBuf::new();
assert_eq!(d.iter().rev().next(), None);
for i in range(0, 5) {
for i in range(0i, 5) {
d.push_back(i);
}
assert_eq!(d.iter().rev().collect::<Vec<&int>>().as_slice(), &[&4,&3,&2,&1,&0]);
for i in range(6, 9) {
for i in range(6i, 9) {
d.push_front(i);
}
assert_eq!(d.iter().rev().collect::<Vec<&int>>().as_slice(), &[&4,&3,&2,&1,&0,&6,&7,&8]);
@ -737,7 +737,7 @@ mod tests {
let mut d = RingBuf::with_capacity(3);
assert!(d.mut_iter().rev().next().is_none());
d.push_back(1);
d.push_back(1i);
d.push_back(2);
d.push_back(3);
assert_eq!(d.pop_front(), Some(1));
@ -796,7 +796,7 @@ mod tests {
#[test]
fn test_from_iter() {
use std::iter;
let v = vec!(1,2,3,4,5,6,7);
let v = vec!(1i,2,3,4,5,6,7);
let deq: RingBuf<int> = v.iter().map(|&x| x).collect();
let u: Vec<int> = deq.iter().map(|&x| x).collect();
assert_eq!(u, v);
@ -812,7 +812,7 @@ mod tests {
#[test]
fn test_clone() {
let mut d = RingBuf::new();
d.push_front(17);
d.push_front(17i);
d.push_front(42);
d.push_back(137);
d.push_back(137);
@ -830,7 +830,7 @@ mod tests {
fn test_eq() {
let mut d = RingBuf::new();
assert!(d == RingBuf::with_capacity(0));
d.push_front(137);
d.push_front(137i);
d.push_front(17);
d.push_front(42);
d.push_back(137);
@ -849,7 +849,7 @@ mod tests {
#[test]
fn test_show() {
let ringbuf: RingBuf<int> = range(0, 10).collect();
let ringbuf: RingBuf<int> = range(0i, 10).collect();
assert!(format!("{}", ringbuf).as_slice() == "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
let ringbuf: RingBuf<&str> = vec!["just", "one", "test", "more"].iter()

View file

@ -75,7 +75,7 @@ The iterator yields references to the vector's elements, so if the element
type of the vector is `int`, the element type of the iterator is `&int`.
```rust
let numbers = [0, 1, 2];
let numbers = [0i, 1i, 2i];
for &x in numbers.iter() {
println!("{} is a number!", x);
}
@ -597,10 +597,10 @@ pub trait MutableOrdVector<T> {
/// # Example
///
/// ```rust
/// let mut v = [-5, 4, 1, -3, 2];
/// let mut v = [-5i, 4, 1, -3, 2];
///
/// v.sort();
/// assert!(v == [-5, -3, 1, 2, 4]);
/// assert!(v == [-5i, -3, 1, 2, 4]);
/// ```
fn sort(self);
@ -611,11 +611,11 @@ pub trait MutableOrdVector<T> {
/// # Example
///
/// ```rust
/// let v = &mut [0, 1, 2];
/// let v = &mut [0i, 1, 2];
/// v.next_permutation();
/// assert_eq!(v, &mut [0, 2, 1]);
/// assert_eq!(v, &mut [0i, 2, 1]);
/// v.next_permutation();
/// assert_eq!(v, &mut [1, 0, 2]);
/// assert_eq!(v, &mut [1i, 0, 2]);
/// ```
fn next_permutation(self) -> bool;
@ -626,11 +626,11 @@ pub trait MutableOrdVector<T> {
/// # Example
///
/// ```rust
/// let v = &mut [1, 0, 2];
/// let v = &mut [1i, 0, 2];
/// v.prev_permutation();
/// assert_eq!(v, &mut [0, 2, 1]);
/// assert_eq!(v, &mut [0i, 2, 1]);
/// v.prev_permutation();
/// assert_eq!(v, &mut [0, 1, 2]);
/// assert_eq!(v, &mut [0i, 1, 2]);
/// ```
fn prev_permutation(self) -> bool;
}
@ -796,11 +796,11 @@ mod tests {
#[test]
fn test_get() {
let mut a = vec![11];
let mut a = vec![11i];
assert_eq!(a.as_slice().get(1), None);
a = vec![11, 12];
a = vec![11i, 12];
assert_eq!(a.as_slice().get(1).unwrap(), &12);
a = vec![11, 12, 13];
a = vec![11i, 12, 13];
assert_eq!(a.as_slice().get(1).unwrap(), &12);
}
@ -808,17 +808,17 @@ mod tests {
fn test_head() {
let mut a = vec![];
assert_eq!(a.as_slice().head(), None);
a = vec![11];
a = vec![11i];
assert_eq!(a.as_slice().head().unwrap(), &11);
a = vec![11, 12];
a = vec![11i, 12];
assert_eq!(a.as_slice().head().unwrap(), &11);
}
#[test]
fn test_tail() {
let mut a = vec![11];
let mut a = vec![11i];
assert_eq!(a.tail(), &[]);
a = vec![11, 12];
a = vec![11i, 12];
assert_eq!(a.tail(), &[12]);
}
@ -831,9 +831,9 @@ mod tests {
#[test]
fn test_tailn() {
let mut a = vec![11, 12, 13];
let mut a = vec![11i, 12, 13];
assert_eq!(a.tailn(0), &[11, 12, 13]);
a = vec![11, 12, 13];
a = vec![11i, 12, 13];
assert_eq!(a.tailn(2), &[13]);
}
@ -846,9 +846,9 @@ mod tests {
#[test]
fn test_init() {
let mut a = vec![11];
let mut a = vec![11i];
assert_eq!(a.init(), &[]);
a = vec![11, 12];
a = vec![11i, 12];
assert_eq!(a.init(), &[11]);
}
@ -861,9 +861,9 @@ mod tests {
#[test]
fn test_initn() {
let mut a = vec![11, 12, 13];
let mut a = vec![11i, 12, 13];
assert_eq!(a.as_slice().initn(0), &[11, 12, 13]);
a = vec![11, 12, 13];
a = vec![11i, 12, 13];
assert_eq!(a.as_slice().initn(2), &[11]);
}
@ -878,16 +878,16 @@ mod tests {
fn test_last() {
let mut a = vec![];
assert_eq!(a.as_slice().last(), None);
a = vec![11];
a = vec![11i];
assert_eq!(a.as_slice().last().unwrap(), &11);
a = vec![11, 12];
a = vec![11i, 12];
assert_eq!(a.as_slice().last().unwrap(), &12);
}
#[test]
fn test_slice() {
// Test fixed length vector.
let vec_fixed = [1, 2, 3, 4];
let vec_fixed = [1i, 2, 3, 4];
let v_a = vec_fixed.slice(1u, vec_fixed.len()).to_owned();
assert_eq!(v_a.len(), 3u);
let v_a = v_a.as_slice();
@ -896,7 +896,7 @@ mod tests {
assert_eq!(v_a[2], 4);
// Test on stack.
let vec_stack = &[1, 2, 3];
let vec_stack = &[1i, 2, 3];
let v_b = vec_stack.slice(1u, 3u).to_owned();
assert_eq!(v_b.len(), 2u);
let v_b = v_b.as_slice();
@ -904,7 +904,7 @@ mod tests {
assert_eq!(v_b[1], 3);
// Test `Box<[T]>`
let vec_unique = vec![1, 2, 3, 4, 5, 6];
let vec_unique = vec![1i, 2, 3, 4, 5, 6];
let v_d = vec_unique.slice(1u, 6u).to_owned();
assert_eq!(v_d.len(), 5u);
let v_d = v_d.as_slice();
@ -917,7 +917,7 @@ mod tests {
#[test]
fn test_slice_from() {
let vec = &[1, 2, 3, 4];
let vec = &[1i, 2, 3, 4];
assert_eq!(vec.slice_from(0), vec);
assert_eq!(vec.slice_from(2), &[3, 4]);
assert_eq!(vec.slice_from(4), &[]);
@ -925,7 +925,7 @@ mod tests {
#[test]
fn test_slice_to() {
let vec = &[1, 2, 3, 4];
let vec = &[1i, 2, 3, 4];
assert_eq!(vec.slice_to(4), vec);
assert_eq!(vec.slice_to(2), &[1, 2]);
assert_eq!(vec.slice_to(0), &[]);
@ -934,7 +934,7 @@ mod tests {
#[test]
fn test_pop() {
let mut v = vec![5];
let mut v = vec![5i];
let e = v.pop();
assert_eq!(v.len(), 0);
assert_eq!(e, Some(5));
@ -946,17 +946,17 @@ mod tests {
#[test]
fn test_swap_remove() {
let mut v = vec![1, 2, 3, 4, 5];
let mut v = vec![1i, 2, 3, 4, 5];
let mut e = v.swap_remove(0);
assert_eq!(e, Some(1));
assert_eq!(v, vec![5, 2, 3, 4]);
assert_eq!(v, vec![5i, 2, 3, 4]);
e = v.swap_remove(3);
assert_eq!(e, Some(4));
assert_eq!(v, vec![5, 2, 3]);
assert_eq!(v, vec![5i, 2, 3]);
e = v.swap_remove(3);
assert_eq!(e, None);
assert_eq!(v, vec![5, 2, 3]);
assert_eq!(v, vec![5i, 2, 3]);
}
#[test]
@ -977,12 +977,12 @@ mod tests {
fn test_push() {
// Test on-stack push().
let mut v = vec![];
v.push(1);
v.push(1i);
assert_eq!(v.len(), 1u);
assert_eq!(v.as_slice()[0], 1);
// Test on-heap push().
v.push(2);
v.push(2i);
assert_eq!(v.len(), 2u);
assert_eq!(v.as_slice()[0], 1);
assert_eq!(v.as_slice()[1], 2);
@ -992,7 +992,7 @@ mod tests {
fn test_grow() {
// Test on-stack grow().
let mut v = vec![];
v.grow(2u, &1);
v.grow(2u, &1i);
{
let v = v.as_slice();
assert_eq!(v.len(), 2u);
@ -1001,7 +1001,7 @@ mod tests {
}
// Test on-heap grow().
v.grow(3u, &2);
v.grow(3u, &2i);
{
let v = v.as_slice();
assert_eq!(v.len(), 5u);
@ -1026,7 +1026,7 @@ mod tests {
#[test]
fn test_grow_set() {
let mut v = vec![1, 2, 3];
let mut v = vec![1i, 2, 3];
v.grow_set(4u, &4, 5);
let v = v.as_slice();
assert_eq!(v.len(), 5u);
@ -1039,7 +1039,7 @@ mod tests {
#[test]
fn test_truncate() {
let mut v = vec![box 6,box 5,box 4];
let mut v = vec![box 6i,box 5,box 4];
v.truncate(1);
let v = v.as_slice();
assert_eq!(v.len(), 1);
@ -1049,7 +1049,7 @@ mod tests {
#[test]
fn test_clear() {
let mut v = vec![box 6,box 5,box 4];
let mut v = vec![box 6i,box 5,box 4];
v.clear();
assert_eq!(v.len(), 0);
// If the unsafe block didn't drop things properly, we blow up here.
@ -1063,22 +1063,22 @@ mod tests {
assert_eq!(v, b);
}
case(vec![], vec![]);
case(vec![1], vec![1]);
case(vec![1,1], vec![1]);
case(vec![1,2,3], vec![1,2,3]);
case(vec![1,1,2,3], vec![1,2,3]);
case(vec![1,2,2,3], vec![1,2,3]);
case(vec![1,2,3,3], vec![1,2,3]);
case(vec![1,1,2,2,2,3,3], vec![1,2,3]);
case(vec![1u], vec![1]);
case(vec![1u,1], vec![1]);
case(vec![1u,2,3], vec![1,2,3]);
case(vec![1u,1,2,3], vec![1,2,3]);
case(vec![1u,2,2,3], vec![1,2,3]);
case(vec![1u,2,3,3], vec![1,2,3]);
case(vec![1u,1,2,2,2,3,3], vec![1,2,3]);
}
#[test]
fn test_dedup_unique() {
let mut v0 = vec![box 1, box 1, box 2, box 3];
let mut v0 = vec![box 1i, box 1, box 2, box 3];
v0.dedup();
let mut v1 = vec![box 1, box 2, box 2, box 3];
let mut v1 = vec![box 1i, box 2, box 2, box 3];
v1.dedup();
let mut v2 = vec![box 1, box 2, box 3, box 3];
let mut v2 = vec![box 1i, box 2, box 3, box 3];
v2.dedup();
/*
* If the boxed pointers were leaked or otherwise misused, valgrind
@ -1088,11 +1088,11 @@ mod tests {
#[test]
fn test_dedup_shared() {
let mut v0 = vec![box 1, box 1, box 2, box 3];
let mut v0 = vec![box 1i, box 1, box 2, box 3];
v0.dedup();
let mut v1 = vec![box 1, box 2, box 2, box 3];
let mut v1 = vec![box 1i, box 2, box 2, box 3];
v1.dedup();
let mut v2 = vec![box 1, box 2, box 3, box 3];
let mut v2 = vec![box 1i, box 2, box 3, box 3];
v2.dedup();
/*
* If the pointers were leaked or otherwise misused, valgrind and/or
@ -1102,14 +1102,14 @@ mod tests {
#[test]
fn test_retain() {
let mut v = vec![1, 2, 3, 4, 5];
let mut v = vec![1u, 2, 3, 4, 5];
v.retain(is_odd);
assert_eq!(v, vec![1, 3, 5]);
assert_eq!(v, vec![1u, 3, 5]);
}
#[test]
fn test_element_swaps() {
let mut v = [1, 2, 3];
let mut v = [1i, 2, 3];
for (i, (a, b)) in ElementSwaps::new(v.len()).enumerate() {
v.swap(a, b);
match i {
@ -1145,7 +1145,7 @@ mod tests {
assert_eq!(it.next(), None);
}
{
let v = [1, 2, 3];
let v = [1i, 2, 3];
let mut it = v.permutations();
let (min_size, max_opt) = it.size_hint();
assert_eq!(min_size, 3*2);
@ -1179,7 +1179,7 @@ mod tests {
#[test]
fn test_lexicographic_permutations() {
let v : &mut[int] = &mut[1, 2, 3, 4, 5];
let v : &mut[int] = &mut[1i, 2, 3, 4, 5];
assert!(v.prev_permutation() == false);
assert!(v.next_permutation());
assert_eq!(v, &mut[1, 2, 3, 5, 4]);
@ -1191,7 +1191,7 @@ mod tests {
assert!(v.next_permutation());
assert_eq!(v, &mut[1, 2, 4, 5, 3]);
let v : &mut[int] = &mut[1, 0, 0, 0];
let v : &mut[int] = &mut[1i, 0, 0, 0];
assert!(v.next_permutation() == false);
assert!(v.prev_permutation());
assert_eq!(v, &mut[0, 1, 0, 0]);
@ -1210,13 +1210,13 @@ mod tests {
assert!(empty.prev_permutation() == false);
assert_eq!(empty, &mut[]);
let one_elem : &mut[int] = &mut[4];
let one_elem : &mut[int] = &mut[4i];
assert!(one_elem.prev_permutation() == false);
assert_eq!(one_elem, &mut[4]);
assert!(one_elem.next_permutation() == false);
assert_eq!(one_elem, &mut[4]);
let two_elem : &mut[int] = &mut[1, 2];
let two_elem : &mut[int] = &mut[1i, 2];
assert!(two_elem.prev_permutation() == false);
assert_eq!(two_elem, &mut[1, 2]);
assert!(two_elem.next_permutation());
@ -1231,9 +1231,9 @@ mod tests {
#[test]
fn test_position_elem() {
assert!([].position_elem(&1).is_none());
assert!([].position_elem(&1i).is_none());
let v1 = vec![1, 2, 3, 3, 2, 5];
let v1 = vec![1i, 2, 3, 3, 2, 5];
assert_eq!(v1.as_slice().position_elem(&1), Some(0u));
assert_eq!(v1.as_slice().position_elem(&2), Some(1u));
assert_eq!(v1.as_slice().position_elem(&5), Some(5u));
@ -1242,52 +1242,52 @@ mod tests {
#[test]
fn test_bsearch_elem() {
assert_eq!([1,2,3,4,5].bsearch_elem(&5), Some(4));
assert_eq!([1,2,3,4,5].bsearch_elem(&4), Some(3));
assert_eq!([1,2,3,4,5].bsearch_elem(&3), Some(2));
assert_eq!([1,2,3,4,5].bsearch_elem(&2), Some(1));
assert_eq!([1,2,3,4,5].bsearch_elem(&1), Some(0));
assert_eq!([1i,2,3,4,5].bsearch_elem(&5), Some(4));
assert_eq!([1i,2,3,4,5].bsearch_elem(&4), Some(3));
assert_eq!([1i,2,3,4,5].bsearch_elem(&3), Some(2));
assert_eq!([1i,2,3,4,5].bsearch_elem(&2), Some(1));
assert_eq!([1i,2,3,4,5].bsearch_elem(&1), Some(0));
assert_eq!([2,4,6,8,10].bsearch_elem(&1), None);
assert_eq!([2,4,6,8,10].bsearch_elem(&5), None);
assert_eq!([2,4,6,8,10].bsearch_elem(&4), Some(1));
assert_eq!([2,4,6,8,10].bsearch_elem(&10), Some(4));
assert_eq!([2i,4,6,8,10].bsearch_elem(&1), None);
assert_eq!([2i,4,6,8,10].bsearch_elem(&5), None);
assert_eq!([2i,4,6,8,10].bsearch_elem(&4), Some(1));
assert_eq!([2i,4,6,8,10].bsearch_elem(&10), Some(4));
assert_eq!([2,4,6,8].bsearch_elem(&1), None);
assert_eq!([2,4,6,8].bsearch_elem(&5), None);
assert_eq!([2,4,6,8].bsearch_elem(&4), Some(1));
assert_eq!([2,4,6,8].bsearch_elem(&8), Some(3));
assert_eq!([2i,4,6,8].bsearch_elem(&1), None);
assert_eq!([2i,4,6,8].bsearch_elem(&5), None);
assert_eq!([2i,4,6,8].bsearch_elem(&4), Some(1));
assert_eq!([2i,4,6,8].bsearch_elem(&8), Some(3));
assert_eq!([2,4,6].bsearch_elem(&1), None);
assert_eq!([2,4,6].bsearch_elem(&5), None);
assert_eq!([2,4,6].bsearch_elem(&4), Some(1));
assert_eq!([2,4,6].bsearch_elem(&6), Some(2));
assert_eq!([2i,4,6].bsearch_elem(&1), None);
assert_eq!([2i,4,6].bsearch_elem(&5), None);
assert_eq!([2i,4,6].bsearch_elem(&4), Some(1));
assert_eq!([2i,4,6].bsearch_elem(&6), Some(2));
assert_eq!([2,4].bsearch_elem(&1), None);
assert_eq!([2,4].bsearch_elem(&5), None);
assert_eq!([2,4].bsearch_elem(&2), Some(0));
assert_eq!([2,4].bsearch_elem(&4), Some(1));
assert_eq!([2i,4].bsearch_elem(&1), None);
assert_eq!([2i,4].bsearch_elem(&5), None);
assert_eq!([2i,4].bsearch_elem(&2), Some(0));
assert_eq!([2i,4].bsearch_elem(&4), Some(1));
assert_eq!([2].bsearch_elem(&1), None);
assert_eq!([2].bsearch_elem(&5), None);
assert_eq!([2].bsearch_elem(&2), Some(0));
assert_eq!([2i].bsearch_elem(&1), None);
assert_eq!([2i].bsearch_elem(&5), None);
assert_eq!([2i].bsearch_elem(&2), Some(0));
assert_eq!([].bsearch_elem(&1), None);
assert_eq!([].bsearch_elem(&5), None);
assert_eq!([].bsearch_elem(&1i), None);
assert_eq!([].bsearch_elem(&5i), None);
assert!([1,1,1,1,1].bsearch_elem(&1) != None);
assert!([1,1,1,1,2].bsearch_elem(&1) != None);
assert!([1,1,1,2,2].bsearch_elem(&1) != None);
assert!([1,1,2,2,2].bsearch_elem(&1) != None);
assert_eq!([1,2,2,2,2].bsearch_elem(&1), Some(0));
assert!([1i,1,1,1,1].bsearch_elem(&1) != None);
assert!([1i,1,1,1,2].bsearch_elem(&1) != None);
assert!([1i,1,1,2,2].bsearch_elem(&1) != None);
assert!([1i,1,2,2,2].bsearch_elem(&1) != None);
assert_eq!([1i,2,2,2,2].bsearch_elem(&1), Some(0));
assert_eq!([1,2,3,4,5].bsearch_elem(&6), None);
assert_eq!([1,2,3,4,5].bsearch_elem(&0), None);
assert_eq!([1i,2,3,4,5].bsearch_elem(&6), None);
assert_eq!([1i,2,3,4,5].bsearch_elem(&0), None);
}
#[test]
fn test_reverse() {
let mut v: Vec<int> = vec![10, 20];
let mut v: Vec<int> = vec![10i, 20];
assert_eq!(*v.get(0), 10);
assert_eq!(*v.get(1), 20);
v.reverse();
@ -1302,7 +1302,7 @@ mod tests {
#[test]
fn test_sort() {
for len in range(4u, 25) {
for _ in range(0, 100) {
for _ in range(0i, 100) {
let mut v = task_rng().gen_iter::<uint>().take(len)
.collect::<Vec<uint>>();
let mut v1 = v.clone();
@ -1329,9 +1329,9 @@ mod tests {
#[test]
fn test_sort_stability() {
for len in range(4, 25) {
for _ in range(0 , 10) {
let mut counts = [0, .. 10];
for len in range(4i, 25) {
for _ in range(0u, 10) {
let mut counts = [0i, .. 10];
// create a vector like [(6, 1), (5, 1), (6, 2), ...],
// where the first item of each tuple is random, but
@ -1361,44 +1361,44 @@ mod tests {
#[test]
fn test_partition() {
assert_eq!((vec![]).partition(|x: &int| *x < 3), (vec![], vec![]));
assert_eq!((vec![1, 2, 3]).partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
assert_eq!((vec![1, 2, 3]).partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
assert_eq!((vec![1, 2, 3]).partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
}
#[test]
fn test_partitioned() {
assert_eq!(([]).partitioned(|x: &int| *x < 3), (vec![], vec![]));
assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 2), (vec![1], vec![2, 3]));
assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 2), (vec![1], vec![2, 3]));
assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
}
#[test]
fn test_concat() {
let v: [Vec<int>, ..0] = [];
assert_eq!(v.concat_vec(), vec![]);
assert_eq!([vec![1], vec![2,3]].concat_vec(), vec![1, 2, 3]);
assert_eq!([vec![1i], vec![2i,3i]].concat_vec(), vec![1, 2, 3]);
assert_eq!([&[1], &[2,3]].concat_vec(), vec![1, 2, 3]);
assert_eq!([&[1i], &[2i,3i]].concat_vec(), vec![1, 2, 3]);
}
#[test]
fn test_connect() {
let v: [Vec<int>, ..0] = [];
assert_eq!(v.connect_vec(&0), vec![]);
assert_eq!([vec![1], vec![2, 3]].connect_vec(&0), vec![1, 0, 2, 3]);
assert_eq!([vec![1], vec![2], vec![3]].connect_vec(&0), vec![1, 0, 2, 0, 3]);
assert_eq!([vec![1i], vec![2i, 3]].connect_vec(&0), vec![1, 0, 2, 3]);
assert_eq!([vec![1i], vec![2i], vec![3i]].connect_vec(&0), vec![1, 0, 2, 0, 3]);
assert_eq!([&[1], &[2, 3]].connect_vec(&0), vec![1, 0, 2, 3]);
assert_eq!([&[1], &[2], &[3]].connect_vec(&0), vec![1, 0, 2, 0, 3]);
assert_eq!([&[1i], &[2i, 3]].connect_vec(&0), vec![1, 0, 2, 3]);
assert_eq!([&[1i], &[2i], &[3]].connect_vec(&0), vec![1, 0, 2, 0, 3]);
}
#[test]
fn test_shift() {
let mut x = vec![1, 2, 3];
let mut x = vec![1i, 2, 3];
assert_eq!(x.shift(), Some(1));
assert_eq!(&x, &vec![2, 3]);
assert_eq!(&x, &vec![2i, 3]);
assert_eq!(x.shift(), Some(2));
assert_eq!(x.shift(), Some(3));
assert_eq!(x.shift(), None);
@ -1407,52 +1407,52 @@ mod tests {
#[test]
fn test_unshift() {
let mut x = vec![1, 2, 3];
let mut x = vec![1i, 2, 3];
x.unshift(0);
assert_eq!(x, vec![0, 1, 2, 3]);
}
#[test]
fn test_insert() {
let mut a = vec![1, 2, 4];
let mut a = vec![1i, 2, 4];
a.insert(2, 3);
assert_eq!(a, vec![1, 2, 3, 4]);
let mut a = vec![1, 2, 3];
let mut a = vec![1i, 2, 3];
a.insert(0, 0);
assert_eq!(a, vec![0, 1, 2, 3]);
let mut a = vec![1, 2, 3];
let mut a = vec![1i, 2, 3];
a.insert(3, 4);
assert_eq!(a, vec![1, 2, 3, 4]);
let mut a = vec![];
a.insert(0, 1);
a.insert(0, 1i);
assert_eq!(a, vec![1]);
}
#[test]
#[should_fail]
fn test_insert_oob() {
let mut a = vec![1, 2, 3];
let mut a = vec![1i, 2, 3];
a.insert(4, 5);
}
#[test]
fn test_remove() {
let mut a = vec![1,2,3,4];
let mut a = vec![1i,2,3,4];
assert_eq!(a.remove(2), Some(3));
assert_eq!(a, vec![1,2,4]);
assert_eq!(a, vec![1i,2,4]);
assert_eq!(a.remove(2), Some(4));
assert_eq!(a, vec![1,2]);
assert_eq!(a, vec![1i,2]);
assert_eq!(a.remove(2), None);
assert_eq!(a, vec![1,2]);
assert_eq!(a, vec![1i,2]);
assert_eq!(a.remove(0), Some(1));
assert_eq!(a, vec![2]);
assert_eq!(a, vec![2i]);
assert_eq!(a.remove(0), Some(2));
assert_eq!(a, vec![]);
@ -1473,7 +1473,7 @@ mod tests {
#[test]
fn test_slice_2() {
let v = vec![1, 2, 3, 4, 5];
let v = vec![1i, 2, 3, 4, 5];
let v = v.slice(1u, 3u);
assert_eq!(v.len(), 2u);
assert_eq!(v[0], 2);
@ -1486,7 +1486,7 @@ mod tests {
fn test_from_fn_fail() {
Vec::from_fn(100, |v| {
if v == 50 { fail!() }
box 0
box 0i
});
}
@ -1519,15 +1519,15 @@ mod tests {
if i == 50 {
fail!()
}
(box 0, Rc::new(0))
(box 0i, Rc::new(0i))
})
}
#[test]
#[should_fail]
fn test_permute_fail() {
let v = [(box 0, Rc::new(0)), (box 0, Rc::new(0)),
(box 0, Rc::new(0)), (box 0, Rc::new(0))];
let v = [(box 0i, Rc::new(0i)), (box 0i, Rc::new(0i)),
(box 0i, Rc::new(0i)), (box 0i, Rc::new(0i))];
let mut i = 0;
for _ in v.permutations() {
if i == 2 {
@ -1541,24 +1541,24 @@ mod tests {
#[should_fail]
fn test_copy_memory_oob() {
unsafe {
let mut a = [1, 2, 3, 4];
let b = [1, 2, 3, 4, 5];
let mut a = [1i, 2, 3, 4];
let b = [1i, 2, 3, 4, 5];
a.copy_memory(b);
}
}
#[test]
fn test_total_ord() {
[1, 2, 3, 4].cmp(& &[1, 2, 3]) == Greater;
[1, 2, 3].cmp(& &[1, 2, 3, 4]) == Less;
[1, 2, 3, 4].cmp(& &[1, 2, 3, 4]) == Equal;
[1, 2, 3, 4, 5, 5, 5, 5].cmp(& &[1, 2, 3, 4, 5, 6]) == Less;
[2, 2].cmp(& &[1, 2, 3, 4]) == Greater;
[1i, 2, 3, 4].cmp(& &[1, 2, 3]) == Greater;
[1i, 2, 3].cmp(& &[1, 2, 3, 4]) == Less;
[1i, 2, 3, 4].cmp(& &[1, 2, 3, 4]) == Equal;
[1i, 2, 3, 4, 5, 5, 5, 5].cmp(& &[1, 2, 3, 4, 5, 6]) == Less;
[2i, 2].cmp(& &[1, 2, 3, 4]) == Greater;
}
#[test]
fn test_iterator() {
let xs = [1, 2, 5, 10, 11];
let xs = [1i, 2, 5, 10, 11];
let mut it = xs.iter();
assert_eq!(it.size_hint(), (5, Some(5)));
assert_eq!(it.next().unwrap(), &1);
@ -1576,7 +1576,7 @@ mod tests {
#[test]
fn test_random_access_iterator() {
let xs = [1, 2, 5, 10, 11];
let xs = [1i, 2, 5, 10, 11];
let mut it = xs.iter();
assert_eq!(it.indexable(), 5);
@ -1614,14 +1614,14 @@ mod tests {
#[test]
fn test_iter_size_hints() {
let mut xs = [1, 2, 5, 10, 11];
let mut xs = [1i, 2, 5, 10, 11];
assert_eq!(xs.iter().size_hint(), (5, Some(5)));
assert_eq!(xs.mut_iter().size_hint(), (5, Some(5)));
}
#[test]
fn test_iter_clone() {
let xs = [1, 2, 5];
let xs = [1i, 2, 5];
let mut it = xs.iter();
it.next();
let mut jt = it.clone();
@ -1632,7 +1632,7 @@ mod tests {
#[test]
fn test_mut_iterator() {
let mut xs = [1, 2, 3, 4, 5];
let mut xs = [1i, 2, 3, 4, 5];
for x in xs.mut_iter() {
*x += 1;
}
@ -1642,7 +1642,7 @@ mod tests {
#[test]
fn test_rev_iterator() {
let xs = [1, 2, 5, 10, 11];
let xs = [1i, 2, 5, 10, 11];
let ys = [11, 10, 5, 2, 1];
let mut i = 0;
for &x in xs.iter().rev() {
@ -1781,39 +1781,39 @@ mod tests {
#[test]
fn test_move_from() {
let mut a = [1,2,3,4,5];
let b = vec![6,7,8];
let mut a = [1i,2,3,4,5];
let b = vec![6i,7,8];
assert_eq!(a.move_from(b, 0, 3), 3);
assert!(a == [6,7,8,4,5]);
let mut a = [7,2,8,1];
let b = vec![3,1,4,1,5,9];
assert!(a == [6i,7,8,4,5]);
let mut a = [7i,2,8,1];
let b = vec![3i,1,4,1,5,9];
assert_eq!(a.move_from(b, 0, 6), 4);
assert!(a == [3,1,4,1]);
let mut a = [1,2,3,4];
let b = vec![5,6,7,8,9,0];
assert!(a == [3i,1,4,1]);
let mut a = [1i,2,3,4];
let b = vec![5i,6,7,8,9,0];
assert_eq!(a.move_from(b, 2, 3), 1);
assert!(a == [7,2,3,4]);
let mut a = [1,2,3,4,5];
let b = vec![5,6,7,8,9,0];
assert!(a == [7i,2,3,4]);
let mut a = [1i,2,3,4,5];
let b = vec![5i,6,7,8,9,0];
assert_eq!(a.mut_slice(2,4).move_from(b,1,6), 2);
assert!(a == [1,2,6,7,5]);
assert!(a == [1i,2,6,7,5]);
}
#[test]
fn test_copy_from() {
let mut a = [1,2,3,4,5];
let b = [6,7,8];
let mut a = [1i,2,3,4,5];
let b = [6i,7,8];
assert_eq!(a.copy_from(b), 3);
assert!(a == [6,7,8,4,5]);
let mut c = [7,2,8,1];
let d = [3,1,4,1,5,9];
assert!(a == [6i,7,8,4,5]);
let mut c = [7i,2,8,1];
let d = [3i,1,4,1,5,9];
assert_eq!(c.copy_from(d), 4);
assert!(c == [3,1,4,1]);
assert!(c == [3i,1,4,1]);
}
#[test]
fn test_reverse_part() {
let mut values = [1,2,3,4,5];
let mut values = [1i,2,3,4,5];
values.mut_slice(1, 4).reverse();
assert!(values == [1,4,3,2,5]);
}
@ -1829,15 +1829,15 @@ mod tests {
)
let empty: Vec<int> = vec![];
test_show_vec!(empty, "[]".to_string());
test_show_vec!(vec![1], "[1]".to_string());
test_show_vec!(vec![1, 2, 3], "[1, 2, 3]".to_string());
test_show_vec!(vec![1i], "[1]".to_string());
test_show_vec!(vec![1i, 2, 3], "[1, 2, 3]".to_string());
test_show_vec!(vec![vec![], vec![1u], vec![1u, 1u]],
"[[], [1], [1, 1]]".to_string());
let empty_mut: &mut [int] = &mut[];
test_show_vec!(empty_mut, "[]".to_string());
test_show_vec!(&mut[1], "[1]".to_string());
test_show_vec!(&mut[1, 2, 3], "[1, 2, 3]".to_string());
test_show_vec!(&mut[1i], "[1]".to_string());
test_show_vec!(&mut[1i, 2, 3], "[1, 2, 3]".to_string());
test_show_vec!(&mut[&mut[], &mut[1u], &mut[1u, 1u]],
"[[], [1], [1, 1]]".to_string());
}
@ -1908,7 +1908,7 @@ mod tests {
fn test_iter_zero_sized() {
let mut v = vec![Foo, Foo, Foo];
assert_eq!(v.len(), 3);
let mut cnt = 0;
let mut cnt = 0u;
for f in v.iter() {
assert!(*f == Foo);
@ -1946,13 +1946,13 @@ mod tests {
#[test]
fn test_shrink_to_fit() {
let mut xs = vec![0, 1, 2, 3];
for i in range(4, 100) {
for i in range(4i, 100) {
xs.push(i)
}
assert_eq!(xs.capacity(), 128);
xs.shrink_to_fit();
assert_eq!(xs.capacity(), 100);
assert_eq!(xs, range(0, 100).collect::<Vec<_>>());
assert_eq!(xs, range(0i, 100i).collect::<Vec<_>>());
}
#[test]
@ -2011,14 +2011,14 @@ mod tests {
#[test]
fn test_mut_splitator() {
let mut xs = [0,1,0,2,3,0,0,4,5,0];
let mut xs = [0i,1,0,2,3,0,0,4,5,0];
assert_eq!(xs.mut_split(|x| *x == 0).count(), 6);
for slice in xs.mut_split(|x| *x == 0) {
slice.reverse();
}
assert!(xs == [0,1,0,3,2,0,0,5,4,0]);
let mut xs = [0,1,0,2,3,0,0,4,5,0,6,7];
let mut xs = [0i,1,0,2,3,0,0,4,5,0,6,7];
for slice in xs.mut_split(|x| *x == 0).take(5) {
slice.reverse();
}
@ -2027,7 +2027,7 @@ mod tests {
#[test]
fn test_mut_splitator_rev() {
let mut xs = [1,2,0,3,4,0,0,5,6,0];
let mut xs = [1i,2,0,3,4,0,0,5,6,0];
for slice in xs.mut_split(|x| *x == 0).rev().take(4) {
slice.reverse();
}
@ -2036,7 +2036,7 @@ mod tests {
#[test]
fn test_get_mut() {
let mut v = [0,1,2];
let mut v = [0i,1,2];
assert_eq!(v.get_mut(3), None);
v.get_mut(1).map(|e| *e = 7);
assert_eq!(v[1], 7);
@ -2071,7 +2071,7 @@ mod tests {
#[test]
#[should_fail]
fn test_mut_chunks_0() {
let mut v = [1, 2, 3, 4];
let mut v = [1i, 2, 3, 4];
let _it = v.mut_chunks(0);
}
@ -2103,7 +2103,7 @@ mod tests {
#[test]
fn test_mut_last() {
let mut x = [1, 2, 3, 4, 5];
let mut x = [1i, 2, 3, 4, 5];
let h = x.mut_last();
assert_eq!(*h.unwrap(), 5);
@ -2140,10 +2140,10 @@ mod bench {
#[bench]
fn mut_iterator(b: &mut Bencher) {
let mut v = Vec::from_elem(100, 0);
let mut v = Vec::from_elem(100, 0i);
b.iter(|| {
let mut i = 0;
let mut i = 0i;
for x in v.mut_iter() {
*x = i;
i += 1;
@ -2153,7 +2153,8 @@ mod bench {
#[bench]
fn concat(b: &mut Bencher) {
let xss: Vec<Vec<uint>> = Vec::from_fn(100, |i| range(0, i).collect());
let xss: Vec<Vec<uint>> =
Vec::from_fn(100, |i| range(0u, i).collect());
b.iter(|| {
xss.as_slice().concat_vec()
});
@ -2161,7 +2162,8 @@ mod bench {
#[bench]
fn connect(b: &mut Bencher) {
let xss: Vec<Vec<uint>> = Vec::from_fn(100, |i| range(0, i).collect());
let xss: Vec<Vec<uint>> =
Vec::from_fn(100, |i| range(0u, i).collect());
b.iter(|| {
xss.as_slice().connect_vec(&0)
});
@ -2288,7 +2290,7 @@ mod bench {
let mut rng = weak_rng();
b.iter(|| {
let mut v = Vec::from_elem(30, (0u, 0u));
for _ in range(0, 100) {
for _ in range(0u, 100) {
let l = v.len();
v.insert(rng.gen::<uint>() % (l + 1),
(1, 1));
@ -2300,7 +2302,7 @@ mod bench {
let mut rng = weak_rng();
b.iter(|| {
let mut v = Vec::from_elem(130, (0u, 0u));
for _ in range(0, 100) {
for _ in range(0u, 100) {
let l = v.len();
v.remove(rng.gen::<uint>() % l);
}

View file

@ -277,7 +277,7 @@ mod test_map {
#[test]
fn test_find_mut() {
let mut m = SmallIntMap::new();
assert!(m.insert(1, 12));
assert!(m.insert(1, 12i));
assert!(m.insert(2, 8));
assert!(m.insert(5, 14));
let new = 100;
@ -292,7 +292,7 @@ mod test_map {
let mut map = SmallIntMap::new();
assert_eq!(map.len(), 0);
assert!(map.is_empty());
assert!(map.insert(5, 20));
assert!(map.insert(5, 20i));
assert_eq!(map.len(), 1);
assert!(!map.is_empty());
assert!(map.insert(11, 12));
@ -306,7 +306,7 @@ mod test_map {
#[test]
fn test_clear() {
let mut map = SmallIntMap::new();
assert!(map.insert(5, 20));
assert!(map.insert(5, 20i));
assert!(map.insert(11, 12));
assert!(map.insert(14, 22));
map.clear();
@ -349,15 +349,15 @@ mod test_map {
#[test]
fn test_swap() {
let mut m = SmallIntMap::new();
assert_eq!(m.swap(1, 2), None);
assert_eq!(m.swap(1, 3), Some(2));
assert_eq!(m.swap(1, 4), Some(3));
assert_eq!(m.swap(1, 2i), None);
assert_eq!(m.swap(1, 3i), Some(2));
assert_eq!(m.swap(1, 4i), Some(3));
}
#[test]
fn test_pop() {
let mut m = SmallIntMap::new();
m.insert(1, 2);
m.insert(1, 2i);
assert_eq!(m.pop(&1), Some(2));
assert_eq!(m.pop(&1), None);
}
@ -366,7 +366,7 @@ mod test_map {
fn test_iterator() {
let mut m = SmallIntMap::new();
assert!(m.insert(0, 1));
assert!(m.insert(0, 1i));
assert!(m.insert(1, 2));
assert!(m.insert(3, 5));
assert!(m.insert(6, 10));
@ -391,7 +391,7 @@ mod test_map {
fn test_iterator_size_hints() {
let mut m = SmallIntMap::new();
assert!(m.insert(0, 1));
assert!(m.insert(0, 1i));
assert!(m.insert(1, 2));
assert!(m.insert(3, 5));
assert!(m.insert(6, 10));
@ -407,7 +407,7 @@ mod test_map {
fn test_mut_iterator() {
let mut m = SmallIntMap::new();
assert!(m.insert(0, 1));
assert!(m.insert(0, 1i));
assert!(m.insert(1, 2));
assert!(m.insert(3, 5));
assert!(m.insert(6, 10));
@ -430,7 +430,7 @@ mod test_map {
fn test_rev_iterator() {
let mut m = SmallIntMap::new();
assert!(m.insert(0, 1));
assert!(m.insert(0, 1i));
assert!(m.insert(1, 2));
assert!(m.insert(3, 5));
assert!(m.insert(6, 10));
@ -449,7 +449,7 @@ mod test_map {
fn test_mut_rev_iterator() {
let mut m = SmallIntMap::new();
assert!(m.insert(0, 1));
assert!(m.insert(0, 1i));
assert!(m.insert(1, 2));
assert!(m.insert(3, 5));
assert!(m.insert(6, 10));
@ -471,16 +471,16 @@ mod test_map {
#[test]
fn test_move_iter() {
let mut m = SmallIntMap::new();
m.insert(1, box 2);
m.insert(1, box 2i);
let mut called = false;
for (k, v) in m.move_iter() {
assert!(!called);
called = true;
assert_eq!(k, 1);
assert_eq!(v, box 2);
assert_eq!(v, box 2i);
}
assert!(called);
m.insert(2, box 1);
m.insert(2, box 1i);
}
#[test]
@ -488,8 +488,8 @@ mod test_map {
let mut map = SmallIntMap::new();
let empty = SmallIntMap::<int>::new();
map.insert(1, 2);
map.insert(3, 4);
map.insert(1, 2i);
map.insert(3, 4i);
let map_str = map.to_str();
let map_str = map_str.as_slice();

View file

@ -352,6 +352,14 @@ impl<'a, S: Str> Equiv<S> for String {
}
}
impl<S: Str> Add<S, String> for String {
fn add(&self, other: &S) -> String {
let mut s = self.to_string();
s.push_str(other.as_slice());
return s;
}
}
#[cfg(test)]
mod tests {
use std::prelude::*;
@ -469,4 +477,13 @@ mod tests {
assert_eq!(s.len(), 0);
assert_eq!(s.as_slice(), "");
}
#[test]
fn test_str_add() {
let a = String::from_str("12345");
let b = a + "2";
let b = b + String::from_str("2");
assert_eq!(b.len(), 7);
assert_eq!(b.as_slice(), "1234522");
}
}

View file

@ -1030,16 +1030,16 @@ mod test_treemap {
#[test]
fn find_not_found() {
let mut m = TreeMap::new();
assert!(m.insert(1, 2));
assert!(m.insert(5, 3));
assert!(m.insert(9, 3));
assert!(m.insert(1i, 2i));
assert!(m.insert(5i, 3i));
assert!(m.insert(9i, 3i));
assert_eq!(m.find(&2), None);
}
#[test]
fn test_find_mut() {
let mut m = TreeMap::new();
assert!(m.insert(1, 12));
assert!(m.insert(1i, 12i));
assert!(m.insert(2, 8));
assert!(m.insert(5, 14));
let new = 100;
@ -1052,7 +1052,7 @@ mod test_treemap {
#[test]
fn insert_replace() {
let mut m = TreeMap::new();
assert!(m.insert(5, 2));
assert!(m.insert(5i, 2i));
assert!(m.insert(2, 9));
assert!(!m.insert(2, 11));
assert_eq!(m.find(&2).unwrap(), &11);
@ -1062,7 +1062,7 @@ mod test_treemap {
fn test_clear() {
let mut m = TreeMap::new();
m.clear();
assert!(m.insert(5, 11));
assert!(m.insert(5i, 11i));
assert!(m.insert(12, -3));
assert!(m.insert(19, 2));
m.clear();
@ -1159,8 +1159,8 @@ mod test_treemap {
let mut rng: rand::IsaacRng = rand::SeedableRng::from_seed(&[42]);
for _ in range(0, 3) {
for _ in range(0, 90) {
for _ in range(0u, 3) {
for _ in range(0u, 90) {
let k = rng.gen();
let v = rng.gen();
if !ctrl.iter().any(|x| x == &(k, v)) {
@ -1171,7 +1171,7 @@ mod test_treemap {
}
}
for _ in range(0, 30) {
for _ in range(0u, 30) {
let r = rng.gen_range(0, ctrl.len());
let (key, _) = ctrl.remove(r).unwrap();
assert!(map.remove(&key));
@ -1184,7 +1184,7 @@ mod test_treemap {
#[test]
fn test_len() {
let mut m = TreeMap::new();
assert!(m.insert(3, 6));
assert!(m.insert(3i, 6i));
assert_eq!(m.len(), 1);
assert!(m.insert(0, 0));
assert_eq!(m.len(), 2);
@ -1204,7 +1204,7 @@ mod test_treemap {
fn test_iterator() {
let mut m = TreeMap::new();
assert!(m.insert(3, 6));
assert!(m.insert(3i, 6i));
assert!(m.insert(0, 0));
assert!(m.insert(4, 8));
assert!(m.insert(2, 4));
@ -1222,11 +1222,11 @@ mod test_treemap {
#[test]
fn test_interval_iteration() {
let mut m = TreeMap::new();
for i in range(1, 100) {
for i in range(1i, 100i) {
assert!(m.insert(i * 2, i * 4));
}
for i in range(1, 198) {
for i in range(1i, 198i) {
let mut lb_it = m.lower_bound(&i);
let (&k, &v) = lb_it.next().unwrap();
let lb = i + i % 2;
@ -1247,7 +1247,7 @@ mod test_treemap {
fn test_rev_iter() {
let mut m = TreeMap::new();
assert!(m.insert(3, 6));
assert!(m.insert(3i, 6i));
assert!(m.insert(0, 0));
assert!(m.insert(4, 8));
assert!(m.insert(2, 4));
@ -1296,19 +1296,19 @@ mod test_treemap {
fn test_mut_interval_iter() {
let mut m_lower = TreeMap::new();
let mut m_upper = TreeMap::new();
for i in range(1, 100) {
for i in range(1i, 100i) {
assert!(m_lower.insert(i * 2, i * 4));
assert!(m_upper.insert(i * 2, i * 4));
}
for i in range(1, 199) {
for i in range(1i, 199) {
let mut lb_it = m_lower.mut_lower_bound(&i);
let (&k, v) = lb_it.next().unwrap();
let lb = i + i % 2;
assert_eq!(lb, k);
*v -= k;
}
for i in range(0, 198) {
for i in range(0i, 198) {
let mut ub_it = m_upper.mut_upper_bound(&i);
let (&k, v) = ub_it.next().unwrap();
let ub = i + 2 - i % 2;
@ -1330,7 +1330,7 @@ mod test_treemap {
let mut b = TreeMap::new();
assert!(a == b);
assert!(a.insert(0, 5));
assert!(a.insert(0i, 5i));
assert!(a != b);
assert!(b.insert(0, 4));
assert!(a != b);
@ -1348,7 +1348,7 @@ mod test_treemap {
let mut b = TreeMap::new();
assert!(!(a < b) && !(b < a));
assert!(b.insert(0, 5));
assert!(b.insert(0i, 5i));
assert!(a < b);
assert!(a.insert(0, 7));
assert!(!(a < b) && b < a);
@ -1366,7 +1366,7 @@ mod test_treemap {
let mut b = TreeMap::new();
assert!(a <= b && a >= b);
assert!(a.insert(1, 1));
assert!(a.insert(1i, 1i));
assert!(a > b && a >= b);
assert!(b < a && b <= a);
assert!(b.insert(2, 2));
@ -1391,7 +1391,7 @@ mod test_treemap {
#[test]
fn test_lazy_iterator() {
let mut m = TreeMap::new();
let (x1, y1) = (2, 5);
let (x1, y1) = (2i, 5i);
let (x2, y2) = (9, 12);
let (x3, y3) = (20, -3);
let (x4, y4) = (29, 5);
@ -1437,7 +1437,7 @@ mod test_treemap {
#[test]
fn test_from_iter() {
let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
let xs = [(1i, 1i), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
let map: TreeMap<int, int> = xs.iter().map(|&x| x).collect();
@ -1519,7 +1519,7 @@ mod test_set {
fn test_clear() {
let mut s = TreeSet::new();
s.clear();
assert!(s.insert(5));
assert!(s.insert(5i));
assert!(s.insert(12));
assert!(s.insert(19));
s.clear();
@ -1535,8 +1535,8 @@ mod test_set {
let mut ys = TreeSet::new();
assert!(xs.is_disjoint(&ys));
assert!(ys.is_disjoint(&xs));
assert!(xs.insert(5));
assert!(ys.insert(11));
assert!(xs.insert(5i));
assert!(ys.insert(11i));
assert!(xs.is_disjoint(&ys));
assert!(ys.is_disjoint(&xs));
assert!(xs.insert(7));
@ -1554,13 +1554,13 @@ mod test_set {
#[test]
fn test_subset_and_superset() {
let mut a = TreeSet::new();
assert!(a.insert(0));
assert!(a.insert(0i));
assert!(a.insert(5));
assert!(a.insert(11));
assert!(a.insert(7));
let mut b = TreeSet::new();
assert!(b.insert(0));
assert!(b.insert(0i));
assert!(b.insert(7));
assert!(b.insert(19));
assert!(b.insert(250));
@ -1584,7 +1584,7 @@ mod test_set {
fn test_iterator() {
let mut m = TreeSet::new();
assert!(m.insert(3));
assert!(m.insert(3i));
assert!(m.insert(0));
assert!(m.insert(4));
assert!(m.insert(2));
@ -1601,7 +1601,7 @@ mod test_set {
fn test_rev_iter() {
let mut m = TreeSet::new();
assert!(m.insert(3));
assert!(m.insert(3i));
assert!(m.insert(0));
assert!(m.insert(4));
assert!(m.insert(2));
@ -1616,7 +1616,7 @@ mod test_set {
#[test]
fn test_move_iter() {
let s: TreeSet<int> = range(0, 5).collect();
let s: TreeSet<int> = range(0i, 5).collect();
let mut n = 0;
for x in s.move_iter() {
@ -1627,7 +1627,7 @@ mod test_set {
#[test]
fn test_move_iter_size_hint() {
let s: TreeSet<int> = vec!(0, 1).move_iter().collect();
let s: TreeSet<int> = vec!(0i, 1).move_iter().collect();
let mut it = s.move_iter();
@ -1645,7 +1645,7 @@ mod test_set {
fn test_clone_eq() {
let mut m = TreeSet::new();
m.insert(1);
m.insert(1i);
m.insert(2);
assert!(m.clone() == m);
@ -1762,22 +1762,22 @@ mod test_set {
#[test]
fn test_swap() {
let mut m = TreeMap::new();
assert_eq!(m.swap(1, 2), None);
assert_eq!(m.swap(1, 3), Some(2));
assert_eq!(m.swap(1, 4), Some(3));
assert_eq!(m.swap(1u, 2i), None);
assert_eq!(m.swap(1u, 3i), Some(2));
assert_eq!(m.swap(1u, 4i), Some(3));
}
#[test]
fn test_pop() {
let mut m = TreeMap::new();
m.insert(1, 2);
m.insert(1u, 2i);
assert_eq!(m.pop(&1), Some(2));
assert_eq!(m.pop(&1), None);
}
#[test]
fn test_from_iter() {
let xs = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let xs = [1i, 2, 3, 4, 5, 6, 7, 8, 9];
let set: TreeSet<int> = xs.iter().map(|&x| x).collect();

View file

@ -682,9 +682,9 @@ mod test_map {
#[test]
fn test_find_mut() {
let mut m = TrieMap::new();
assert!(m.insert(1, 12));
assert!(m.insert(2, 8));
assert!(m.insert(5, 14));
assert!(m.insert(1u, 12i));
assert!(m.insert(2u, 8i));
assert!(m.insert(5u, 14i));
let new = 100;
match m.find_mut(&5) {
None => fail!(), Some(x) => *x = new
@ -696,7 +696,7 @@ mod test_map {
fn test_find_mut_missing() {
let mut m = TrieMap::new();
assert!(m.find_mut(&0).is_none());
assert!(m.insert(1, 12));
assert!(m.insert(1u, 12i));
assert!(m.find_mut(&0).is_none());
assert!(m.insert(2, 8));
assert!(m.find_mut(&0).is_none());
@ -781,15 +781,15 @@ mod test_map {
#[test]
fn test_swap() {
let mut m = TrieMap::new();
assert_eq!(m.swap(1, 2), None);
assert_eq!(m.swap(1, 3), Some(2));
assert_eq!(m.swap(1, 4), Some(3));
assert_eq!(m.swap(1u, 2i), None);
assert_eq!(m.swap(1u, 3i), Some(2));
assert_eq!(m.swap(1u, 4i), Some(3));
}
#[test]
fn test_pop() {
let mut m = TrieMap::new();
m.insert(1, 2);
m.insert(1u, 2i);
assert_eq!(m.pop(&1), Some(2));
assert_eq!(m.pop(&1), None);
}
@ -943,7 +943,7 @@ mod bench_map {
fn bench_iter_small(b: &mut Bencher) {
let mut m = TrieMap::<uint>::new();
let mut rng = weak_rng();
for _ in range(0, 20) {
for _ in range(0u, 20) {
m.insert(rng.gen(), rng.gen());
}
@ -954,7 +954,7 @@ mod bench_map {
fn bench_iter_large(b: &mut Bencher) {
let mut m = TrieMap::<uint>::new();
let mut rng = weak_rng();
for _ in range(0, 1000) {
for _ in range(0u, 1000) {
m.insert(rng.gen(), rng.gen());
}
@ -965,12 +965,12 @@ mod bench_map {
fn bench_lower_bound(b: &mut Bencher) {
let mut m = TrieMap::<uint>::new();
let mut rng = weak_rng();
for _ in range(0, 1000) {
for _ in range(0u, 1000) {
m.insert(rng.gen(), rng.gen());
}
b.iter(|| {
for _ in range(0, 10) {
for _ in range(0u, 10) {
m.lower_bound(rng.gen());
}
});
@ -980,12 +980,12 @@ mod bench_map {
fn bench_upper_bound(b: &mut Bencher) {
let mut m = TrieMap::<uint>::new();
let mut rng = weak_rng();
for _ in range(0, 1000) {
for _ in range(0u, 1000) {
m.insert(rng.gen(), rng.gen());
}
b.iter(|| {
for _ in range(0, 10) {
for _ in range(0u, 10) {
m.upper_bound(rng.gen());
}
});
@ -997,7 +997,7 @@ mod bench_map {
let mut rng = weak_rng();
b.iter(|| {
for _ in range(0, 1000) {
for _ in range(0u, 1000) {
m.insert(rng.gen(), [1, .. 10]);
}
})
@ -1008,7 +1008,7 @@ mod bench_map {
let mut rng = weak_rng();
b.iter(|| {
for _ in range(0, 1000) {
for _ in range(0u, 1000) {
// only have the last few bits set.
m.insert(rng.gen::<uint>() & 0xff_ff, [1, .. 10]);
}
@ -1021,7 +1021,7 @@ mod bench_map {
let mut rng = weak_rng();
b.iter(|| {
for _ in range(0, 1000) {
for _ in range(0u, 1000) {
m.insert(rng.gen(), ());
}
})
@ -1032,7 +1032,7 @@ mod bench_map {
let mut rng = weak_rng();
b.iter(|| {
for _ in range(0, 1000) {
for _ in range(0u, 1000) {
// only have the last few bits set.
m.insert(rng.gen::<uint>() & 0xff_ff, ());
}

View file

@ -34,8 +34,8 @@ use slice::{Items, MutItems};
/// ```rust
/// # use std::vec::Vec;
/// let mut vec = Vec::new();
/// vec.push(1);
/// vec.push(2);
/// vec.push(1i);
/// vec.push(2i);
///
/// assert_eq!(vec.len(), 2);
/// assert_eq!(vec.get(0), &1);
@ -47,7 +47,7 @@ use slice::{Items, MutItems};
/// The `vec!` macro is provided to make initialization more convenient:
///
/// ```rust
/// let mut vec = vec!(1, 2, 3);
/// let mut vec = vec!(1i, 2i, 3i);
/// vec.push(4);
/// assert_eq!(vec, vec!(1, 2, 3, 4));
/// ```
@ -147,7 +147,7 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// let vec = vec!(1, 2, 3, 4);
/// let vec = vec!(1i, 2i, 3i, 4i);
/// let (even, odd) = vec.partition(|&n| n % 2 == 0);
/// assert_eq!(even, vec!(2, 4));
/// assert_eq!(odd, vec!(1, 3));
@ -176,8 +176,8 @@ impl<T: Clone> Vec<T> {
/// # Example
///
/// ```rust
/// let vec = vec!(1, 2);
/// let vec = vec.append([3, 4]);
/// let vec = vec!(1i, 2i);
/// let vec = vec.append([3i, 4i]);
/// assert_eq!(vec, vec!(1, 2, 3, 4));
/// ```
#[inline]
@ -192,7 +192,7 @@ impl<T: Clone> Vec<T> {
///
/// ```rust
/// # use std::vec::Vec;
/// let slice = [1, 2, 3];
/// let slice = [1i, 2, 3];
/// let vec = Vec::from_slice(slice);
/// ```
#[inline]
@ -232,8 +232,8 @@ impl<T: Clone> Vec<T> {
/// # Example
///
/// ```rust
/// let mut vec = vec!(1);
/// vec.push_all([2, 3, 4]);
/// let mut vec = vec!(1i);
/// vec.push_all([2i, 3, 4]);
/// assert_eq!(vec, vec!(1, 2, 3, 4));
/// ```
#[inline]
@ -295,10 +295,10 @@ impl<T: Clone> Vec<T> {
/// # Example
///
/// ```rust
/// let vec = vec!(1, 2, 3, 4);
/// let vec = vec!(1i, 2, 3, 4);
/// let (even, odd) = vec.partitioned(|&n| n % 2 == 0);
/// assert_eq!(even, vec!(2, 4));
/// assert_eq!(odd, vec!(1, 3));
/// assert_eq!(even, vec!(2i, 4));
/// assert_eq!(odd, vec!(1i, 3));
/// ```
pub fn partitioned(&self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
let mut lefts = Vec::new();
@ -316,6 +316,7 @@ impl<T: Clone> Vec<T> {
}
}
#[unstable]
impl<T:Clone> Clone for Vec<T> {
fn clone(&self) -> Vec<T> {
let len = self.len;
@ -466,7 +467,7 @@ impl<T> Vec<T> {
///
/// ```rust
/// # use std::vec::Vec;
/// let mut vec: Vec<int> = vec!(1);
/// let mut vec: Vec<int> = vec!(1i);
/// vec.reserve_additional(10);
/// assert!(vec.capacity() >= 11);
/// ```
@ -491,7 +492,7 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// let mut vec = vec!(1, 2, 3);
/// let mut vec = vec!(1i, 2, 3);
/// vec.reserve(10);
/// assert!(vec.capacity() >= 10);
/// ```
@ -533,7 +534,7 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// let mut vec = vec!(1, 2, 3);
/// let mut vec = vec!(1i, 2, 3);
/// vec.shrink_to_fit();
/// ```
pub fn shrink_to_fit(&mut self) {
@ -565,7 +566,7 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// let mut vec = vec!(1, 2, 3);
/// let mut vec = vec!(1i, 2, 3);
/// assert_eq!(vec.pop(), Some(3));
/// assert_eq!(vec, vec!(1, 2));
/// ```
@ -590,7 +591,7 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// let mut vec = vec!(1, 2);
/// let mut vec = vec!(1i, 2);
/// vec.push(3);
/// assert_eq!(vec, vec!(1, 2, 3));
/// ```
@ -626,7 +627,7 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// let vec = vec!(1, 2);
/// let vec = vec!(1i, 2);
/// let vec = vec.append_one(3);
/// assert_eq!(vec, vec!(1, 2, 3));
/// ```
@ -644,7 +645,7 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// let mut vec = vec!(1, 2, 3, 4);
/// let mut vec = vec!(1i, 2, 3, 4);
/// vec.truncate(2);
/// assert_eq!(vec, vec!(1, 2));
/// ```
@ -667,7 +668,7 @@ impl<T> Vec<T> {
/// ```rust
/// fn foo(slice: &mut [int]) {}
///
/// let mut vec = vec!(1, 2);
/// let mut vec = vec!(1i, 2);
/// foo(vec.as_mut_slice());
/// ```
#[inline]
@ -721,7 +722,7 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// let vec = vec!(1, 2, 3);
/// let vec = vec!(1i, 2, 3);
/// assert!(vec.get(1) == &2);
/// ```
#[inline]
@ -738,9 +739,9 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// let mut vec = vec!(1, 2, 3);
/// let mut vec = vec!(1i, 2, 3);
/// *vec.get_mut(1) = 4;
/// assert_eq!(vec, vec!(1, 4, 3));
/// assert_eq!(vec, vec!(1i, 4, 3));
/// ```
#[inline]
pub fn get_mut<'a>(&'a mut self, index: uint) -> &'a mut T {
@ -753,7 +754,7 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// let vec = vec!(1, 2, 3);
/// let vec = vec!(1i, 2, 3);
/// for num in vec.iter() {
/// println!("{}", *num);
/// }
@ -770,7 +771,7 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// let mut vec = vec!(1, 2, 3);
/// let mut vec = vec!(1i, 2, 3);
/// for num in vec.mut_iter() {
/// *num = 0;
/// }
@ -790,11 +791,11 @@ impl<T> Vec<T> {
/// ```rust
/// let mut v = vec!(5i, 4, 1, 3, 2);
/// v.sort_by(|a, b| a.cmp(b));
/// assert_eq!(v, vec!(1, 2, 3, 4, 5));
/// assert_eq!(v, vec!(1i, 2, 3, 4, 5));
///
/// // reverse sorting
/// v.sort_by(|a, b| b.cmp(a));
/// assert_eq!(v, vec!(5, 4, 3, 2, 1));
/// assert_eq!(v, vec!(5i, 4, 3, 2, 1));
/// ```
#[inline]
pub fn sort_by(&mut self, compare: |&T, &T| -> Ordering) {
@ -811,7 +812,7 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// let vec = vec!(1, 2, 3, 4);
/// let vec = vec!(1i, 2, 3, 4);
/// assert!(vec.slice(0, 2) == [1, 2]);
/// ```
#[inline]
@ -828,7 +829,7 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// let vec = vec!(1, 2, 3);
/// let vec = vec!(1i, 2, 3);
/// assert!(vec.tail() == [2, 3]);
/// ```
#[inline]
@ -845,7 +846,7 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// let vec = vec!(1, 2, 3, 4);
/// let vec = vec!(1i, 2, 3, 4);
/// assert!(vec.tailn(2) == [3, 4]);
/// ```
#[inline]
@ -859,7 +860,7 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// let vec = vec!(1, 2, 3);
/// let vec = vec!(1i, 2, 3);
/// assert!(vec.last() == Some(&3));
/// ```
#[inline]
@ -873,9 +874,9 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// let mut vec = vec!(1, 2, 3);
/// let mut vec = vec!(1i, 2, 3);
/// *vec.mut_last().unwrap() = 4;
/// assert_eq!(vec, vec!(1, 2, 4));
/// assert_eq!(vec, vec!(1i, 2, 4));
/// ```
#[inline]
pub fn mut_last<'a>(&'a mut self) -> Option<&'a mut T> {
@ -921,7 +922,7 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// let mut vec = vec!(1, 2, 3);
/// let mut vec = vec!(1i, 2, 3);
/// vec.unshift(4);
/// assert_eq!(vec, vec!(4, 1, 2, 3));
/// ```
@ -941,7 +942,7 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// let mut vec = vec!(1, 2, 3);
/// let mut vec = vec!(1i, 2, 3);
/// assert!(vec.shift() == Some(1));
/// assert_eq!(vec, vec!(2, 3));
/// ```
@ -960,7 +961,7 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// let mut vec = vec!(1, 2, 3);
/// let mut vec = vec!(1i, 2, 3);
/// vec.insert(1, 4);
/// assert_eq!(vec, vec!(1, 4, 2, 3));
/// ```
@ -992,7 +993,7 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// let mut v = vec!(1, 2, 3);
/// let mut v = vec!(1i, 2, 3);
/// assert_eq!(v.remove(1), Some(2));
/// assert_eq!(v, vec!(1, 3));
///
@ -1031,7 +1032,7 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// let mut vec = vec!(box 1);
/// let mut vec = vec!(box 1i);
/// vec.push_all_move(vec!(box 2, box 3, box 4));
/// assert_eq!(vec, vec!(box 1, box 2, box 3, box 4));
/// ```
@ -1050,7 +1051,7 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// let mut vec = vec!(1, 2, 3, 4);
/// let mut vec = vec!(1i, 2, 3, 4);
/// assert!(vec.mut_slice(0, 2) == [1, 2]);
/// ```
#[inline]
@ -1068,7 +1069,7 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// let mut vec = vec!(1, 2, 3, 4);
/// let mut vec = vec!(1i, 2, 3, 4);
/// assert!(vec.mut_slice_from(2) == [3, 4]);
/// ```
#[inline]
@ -1085,7 +1086,7 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// let mut vec = vec!(1, 2, 3, 4);
/// let mut vec = vec!(1i, 2, 3, 4);
/// assert!(vec.mut_slice_to(2) == [1, 2]);
/// ```
#[inline]
@ -1106,7 +1107,7 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// let mut vec = vec!(1, 2, 3, 4, 5, 6);
/// let mut vec = vec!(1i, 2, 3, 4, 5, 6);
///
/// // scoped to restrict the lifetime of the borrows
/// {
@ -1137,9 +1138,9 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// let mut v = vec!(1, 2, 3);
/// let mut v = vec!(1i, 2, 3);
/// v.reverse();
/// assert_eq!(v, vec!(3, 2, 1));
/// assert_eq!(v, vec!(3i, 2, 1));
/// ```
#[inline]
pub fn reverse(&mut self) {
@ -1155,7 +1156,7 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// let vec = vec!(1, 2, 3);
/// let vec = vec!(1i, 2, 3);
/// assert!(vec.slice_from(1) == [2, 3]);
/// ```
#[inline]
@ -1172,7 +1173,7 @@ impl<T> Vec<T> {
/// # Example
///
/// ```rust
/// let vec = vec!(1, 2, 3);
/// let vec = vec!(1i, 2, 3);
/// assert!(vec.slice_to(2) == [1, 2]);
/// ```
#[inline]
@ -1310,7 +1311,7 @@ impl<T:PartialEq> Vec<T> {
/// # Example
///
/// ```rust
/// let vec = vec!(1, 2, 3);
/// let vec = vec!(1i, 2, 3);
/// assert!(vec.contains(&1));
/// ```
#[inline]
@ -1325,9 +1326,9 @@ impl<T:PartialEq> Vec<T> {
/// # Example
///
/// ```rust
/// let mut vec = vec!(1, 2, 2, 3, 2);
/// let mut vec = vec!(1i, 2, 2, 3, 2);
/// vec.dedup();
/// assert_eq!(vec, vec!(1, 2, 3, 2));
/// assert_eq!(vec, vec!(1i, 2, 3, 2));
/// ```
pub fn dedup(&mut self) {
unsafe {
@ -1422,7 +1423,7 @@ impl<T> Vector<T> for Vec<T> {
/// ```rust
/// fn foo(slice: &[int]) {}
///
/// let vec = vec!(1, 2);
/// let vec = vec!(1i, 2);
/// foo(vec.as_slice());
/// ```
#[inline]
@ -1611,7 +1612,7 @@ mod tests {
v.reserve_additional(2);
assert!(v.capacity() >= 2);
for i in range(0, 16) {
for i in range(0i, 16) {
v.push(i);
}
@ -1630,13 +1631,13 @@ mod tests {
let mut v = Vec::new();
let mut w = Vec::new();
v.extend(range(0, 3));
for i in range(0, 3) { w.push(i) }
v.extend(range(0i, 3));
for i in range(0i, 3) { w.push(i) }
assert_eq!(v, w);
v.extend(range(3, 10));
for i in range(3, 10) { w.push(i) }
v.extend(range(3i, 10));
for i in range(3i, 10) { w.push(i) }
assert_eq!(v, w);
}
@ -1691,7 +1692,7 @@ mod tests {
#[test]
fn test_clone() {
let v: Vec<int> = vec!();
let w = vec!(1, 2, 3);
let w = vec!(1i, 2, 3);
assert_eq!(v, v.clone());
@ -1704,8 +1705,8 @@ mod tests {
#[test]
fn test_clone_from() {
let mut v = vec!();
let three = vec!(box 1, box 2, box 3);
let two = vec!(box 4, box 5);
let three = vec!(box 1i, box 2, box 3);
let two = vec!(box 4i, box 5);
// zero, long
v.clone_from(&three);
assert_eq!(v, three);
@ -1771,22 +1772,22 @@ mod tests {
#[test]
fn test_partition() {
assert_eq!(vec![].partition(|x: &int| *x < 3), (vec![], vec![]));
assert_eq!(vec![1, 2, 3].partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
assert_eq!(vec![1, 2, 3].partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
assert_eq!(vec![1, 2, 3].partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
assert_eq!(vec![1i, 2, 3].partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
assert_eq!(vec![1i, 2, 3].partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
assert_eq!(vec![1i, 2, 3].partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
}
#[test]
fn test_partitioned() {
assert_eq!(vec![].partitioned(|x: &int| *x < 3), (vec![], vec![]))
assert_eq!(vec![1, 2, 3].partitioned(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
assert_eq!(vec![1, 2, 3].partitioned(|x: &int| *x < 2), (vec![1], vec![2, 3]));
assert_eq!(vec![1, 2, 3].partitioned(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
assert_eq!(vec![1i, 2, 3].partitioned(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
assert_eq!(vec![1i, 2, 3].partitioned(|x: &int| *x < 2), (vec![1], vec![2, 3]));
assert_eq!(vec![1i, 2, 3].partitioned(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
}
#[test]
fn test_zip_unzip() {
let z1 = vec![(1, 4), (2, 5), (3, 6)];
let z1 = vec![(1i, 4i), (2, 5), (3, 6)];
let (left, right) = unzip(z1.iter().map(|&x| x));
@ -1800,13 +1801,13 @@ mod tests {
fn test_unsafe_ptrs() {
unsafe {
// Test on-stack copy-from-buf.
let a = [1, 2, 3];
let a = [1i, 2, 3];
let ptr = a.as_ptr();
let b = raw::from_buf(ptr, 3u);
assert_eq!(b, vec![1, 2, 3]);
// Test on-heap copy-from-buf.
let c = vec![1, 2, 3, 4, 5];
let c = vec![1i, 2, 3, 4, 5];
let ptr = c.as_ptr();
let d = raw::from_buf(ptr, 5u);
assert_eq!(d, vec![1, 2, 3, 4, 5]);
@ -1912,7 +1913,7 @@ mod tests {
#[bench]
fn bench_from_slice_5(b: &mut Bencher) {
b.iter(|| {
let v: Vec<int> = Vec::from_slice([1, 2, 3, 4, 5]);
let v: Vec<int> = Vec::from_slice([1i, 2, 3, 4, 5]);
assert!(v.as_slice() == [1, 2, 3, 4, 5]);
})
}

View file

@ -284,7 +284,8 @@ mod bench {
#[bench]
fn bench_as_ref(b: &mut Bencher) {
b.iter(|| {
let mut x = 0; let mut y = &mut x as &mut Any;
let mut x = 0i;
let mut y = &mut x as &mut Any;
test::black_box(&mut y);
test::black_box(y.as_ref::<int>() == Some(&0));
});

View file

@ -8,129 +8,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Operations on boolean values (`bool` type)
//!
//! A `to_bit` conversion function.
//! The boolean type
#![doc(primitive = "bool")]
use num::{Int, one, zero};
/////////////////////////////////////////////////////////////////////////////
// Freestanding functions
/////////////////////////////////////////////////////////////////////////////
/// Convert a `bool` to an integer.
///
/// # Examples
///
/// ```rust
/// use std::bool;
///
/// assert_eq!(bool::to_bit::<u8>(true), 1u8);
/// assert_eq!(bool::to_bit::<u8>(false), 0u8);
/// ```
#[inline]
pub fn to_bit<N: Int>(p: bool) -> N {
if p { one() } else { zero() }
}
#[cfg(test)]
mod tests {
use realstd::prelude::*;
use super::to_bit;
#[test]
fn test_to_bit() {
assert_eq!(to_bit::<u8>(true), 1u8);
assert_eq!(to_bit::<u8>(false), 0u8);
}
#[test]
fn test_eq() {
assert_eq!(false.eq(&true), false);
assert_eq!(false == false, true);
assert_eq!(false != true, true);
assert_eq!(false.ne(&false), false);
}
#[test]
fn test_bitand() {
assert_eq!(false.bitand(&false), false);
assert_eq!(true.bitand(&false), false);
assert_eq!(false.bitand(&true), false);
assert_eq!(true.bitand(&true), true);
assert_eq!(false & false, false);
assert_eq!(true & false, false);
assert_eq!(false & true, false);
assert_eq!(true & true, true);
}
#[test]
fn test_bitor() {
assert_eq!(false.bitor(&false), false);
assert_eq!(true.bitor(&false), true);
assert_eq!(false.bitor(&true), true);
assert_eq!(true.bitor(&true), true);
assert_eq!(false | false, false);
assert_eq!(true | false, true);
assert_eq!(false | true, true);
assert_eq!(true | true, true);
}
#[test]
fn test_bitxor() {
assert_eq!(false.bitxor(&false), false);
assert_eq!(true.bitxor(&false), true);
assert_eq!(false.bitxor(&true), true);
assert_eq!(true.bitxor(&true), false);
assert_eq!(false ^ false, false);
assert_eq!(true ^ false, true);
assert_eq!(false ^ true, true);
assert_eq!(true ^ true, false);
}
#[test]
fn test_not() {
assert_eq!(!true, false);
assert_eq!(!false, true);
}
#[test]
fn test_to_str() {
let s = false.to_str();
assert_eq!(s.as_slice(), "false");
let s = true.to_str();
assert_eq!(s.as_slice(), "true");
}
#[test]
fn test_ord() {
assert!(true > false);
assert!(!(false > true));
assert!(false < true);
assert!(!(true < false));
assert!(false <= false);
assert!(false >= false);
assert!(true <= true);
assert!(true >= true);
assert!(false <= true);
assert!(!(false >= true));
assert!(true >= false);
assert!(!(true <= false));
}
#[test]
fn test_totalord() {
assert!(true.cmp(&true) == Equal);
assert!(false.cmp(&false) == Equal);
assert!(true.cmp(&false) == Greater);
assert!(false.cmp(&true) == Less);
}
}

View file

@ -192,6 +192,7 @@ impl<T:Copy> Cell<T> {
}
}
#[unstable]
impl<T:Copy> Clone for Cell<T> {
fn clone(&self) -> Cell<T> {
Cell::new(self.get())
@ -298,6 +299,7 @@ impl<T> RefCell<T> {
}
}
#[unstable]
impl<T: Clone> Clone for RefCell<T> {
fn clone(&self) -> RefCell<T> {
RefCell::new(self.borrow().clone())
@ -389,14 +391,14 @@ mod test {
#[test]
fn smoketest_cell() {
let x = Cell::new(10);
let x = Cell::new(10i);
assert!(x == Cell::new(10));
assert!(x.get() == 10);
x.set(20);
assert!(x == Cell::new(20));
assert!(x.get() == 20);
let y = Cell::new((30, 40));
let y = Cell::new((30i, 40i));
assert!(y == Cell::new((30, 40)));
assert!(y.get() == (30, 40));
}

View file

@ -308,6 +308,7 @@ pub fn escape_unicode(c: char, f: |char|) {
_ => { f('U'); 8 }
};
for offset in range_step::<i32>(4 * (pad - 1), -1, -4) {
let offset = offset as uint;
unsafe {
match ((c as i32) >> offset) & 0xf {
i @ 0 .. 9 => { f(transmute('0' as i32 + i)); }

View file

@ -21,6 +21,8 @@ the `clone` method.
*/
#![unstable]
/// A common trait for cloning an object.
pub trait Clone {
/// Returns a copy of the value. The contents of owned pointers
@ -34,6 +36,7 @@ pub trait Clone {
/// but can be overridden to reuse the resources of `a` to avoid unnecessary
/// allocations.
#[inline(always)]
#[experimental = "this function is mostly unused"]
fn clone_from(&mut self, source: &Self) {
*self = source.clone()
}
@ -88,6 +91,7 @@ clone_impl!(char)
macro_rules! extern_fn_clone(
($($A:ident),*) => (
#[experimental = "this may not be sufficient for fns with region parameters"]
impl<$($A,)* ReturnType> Clone for extern "Rust" fn($($A),*) -> ReturnType {
/// Return a copy of a function pointer
#[inline]
@ -146,8 +150,8 @@ mod test {
#[test]
fn test_clone_from() {
let a = box 5;
let mut b = box 10;
let a = box 5i;
let mut b = box 10i;
realclone_from(&mut b, &a);
assert_eq!(*b, 5);
}

View file

@ -122,7 +122,7 @@ mod test {
#[test]
fn test_success() {
let mut i = 0;
let mut i = 0i;
try_finally(
&mut i, (),
|i, ()| {
@ -139,7 +139,7 @@ mod test {
#[test]
#[should_fail]
fn test_fail() {
let mut i = 0;
let mut i = 0i;
try_finally(
&mut i, (),
|i, ()| {

View file

@ -140,7 +140,7 @@ pub struct RadixFmt<T, R>(T, R);
///
/// ~~~
/// use std::fmt::radix;
/// assert_eq!(format!("{}", radix(55, 36)), "1j".to_string());
/// assert_eq!(format!("{}", radix(55i, 36)), "1j".to_string());
/// ~~~
pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> {
RadixFmt(x, Radix::new(base))
@ -309,11 +309,11 @@ mod tests {
assert!(format!("{:o}", 1u64).as_slice() == "1");
// Test a larger number
assert!(format!("{:t}", 55).as_slice() == "110111");
assert!(format!("{:o}", 55).as_slice() == "67");
assert!(format!("{:d}", 55).as_slice() == "55");
assert!(format!("{:x}", 55).as_slice() == "37");
assert!(format!("{:X}", 55).as_slice() == "37");
assert!(format!("{:t}", 55i).as_slice() == "110111");
assert!(format!("{:o}", 55i).as_slice() == "67");
assert!(format!("{:d}", 55i).as_slice() == "55");
assert!(format!("{:x}", 55i).as_slice() == "37");
assert!(format!("{:X}", 55i).as_slice() == "37");
}
#[test]
@ -335,21 +335,21 @@ mod tests {
#[test]
fn test_format_int_flags() {
assert!(format!("{:3d}", 1).as_slice() == " 1");
assert!(format!("{:>3d}", 1).as_slice() == " 1");
assert!(format!("{:>+3d}", 1).as_slice() == " +1");
assert!(format!("{:<3d}", 1).as_slice() == "1 ");
assert!(format!("{:#d}", 1).as_slice() == "1");
assert!(format!("{:#x}", 10).as_slice() == "0xa");
assert!(format!("{:#X}", 10).as_slice() == "0xA");
assert!(format!("{:#5x}", 10).as_slice() == " 0xa");
assert!(format!("{:#o}", 10).as_slice() == "0o12");
assert!(format!("{:08x}", 10).as_slice() == "0000000a");
assert!(format!("{:8x}", 10).as_slice() == " a");
assert!(format!("{:<8x}", 10).as_slice() == "a ");
assert!(format!("{:>8x}", 10).as_slice() == " a");
assert!(format!("{:#08x}", 10).as_slice() == "0x00000a");
assert!(format!("{:08d}", -10).as_slice() == "-0000010");
assert!(format!("{:3d}", 1i).as_slice() == " 1");
assert!(format!("{:>3d}", 1i).as_slice() == " 1");
assert!(format!("{:>+3d}", 1i).as_slice() == " +1");
assert!(format!("{:<3d}", 1i).as_slice() == "1 ");
assert!(format!("{:#d}", 1i).as_slice() == "1");
assert!(format!("{:#x}", 10i).as_slice() == "0xa");
assert!(format!("{:#X}", 10i).as_slice() == "0xA");
assert!(format!("{:#5x}", 10i).as_slice() == " 0xa");
assert!(format!("{:#o}", 10i).as_slice() == "0o12");
assert!(format!("{:08x}", 10i).as_slice() == "0000000a");
assert!(format!("{:8x}", 10i).as_slice() == " a");
assert!(format!("{:<8x}", 10i).as_slice() == "a ");
assert!(format!("{:>8x}", 10i).as_slice() == " a");
assert!(format!("{:#08x}", 10i).as_slice() == "0x00000a");
assert!(format!("{:08d}", -10i).as_slice() == "-0000010");
assert!(format!("{:x}", -1u8).as_slice() == "ff");
assert!(format!("{:X}", -1u8).as_slice() == "FF");
assert!(format!("{:t}", -1u8).as_slice() == "11111111");
@ -362,12 +362,12 @@ mod tests {
#[test]
fn test_format_int_sign_padding() {
assert!(format!("{:+5d}", 1).as_slice() == " +1");
assert!(format!("{:+5d}", -1).as_slice() == " -1");
assert!(format!("{:05d}", 1).as_slice() == "00001");
assert!(format!("{:05d}", -1).as_slice() == "-0001");
assert!(format!("{:+05d}", 1).as_slice() == "+0001");
assert!(format!("{:+05d}", -1).as_slice() == "-0001");
assert!(format!("{:+5d}", 1i).as_slice() == " +1");
assert!(format!("{:+5d}", -1i).as_slice() == " -1");
assert!(format!("{:05d}", 1i).as_slice() == "00001");
assert!(format!("{:05d}", -1i).as_slice() == "-0001");
assert!(format!("{:+05d}", 1i).as_slice() == "+0001");
assert!(format!("{:+05d}", -1i).as_slice() == "-0001");
}
#[test]
@ -381,8 +381,8 @@ mod tests {
#[test]
fn test_format_radix() {
assert!(format!("{:04}", radix(3, 2)).as_slice() == "0011");
assert!(format!("{}", radix(55, 36)).as_slice() == "1j");
assert!(format!("{:04}", radix(3i, 2)).as_slice() == "0011");
assert!(format!("{}", radix(55i, 36)).as_slice() == "1j");
}
#[test]

View file

@ -35,7 +35,7 @@ into a `loop`, for example, the `for` loop in this example is essentially
translated to the `loop` below.
```rust
let values = vec![1, 2, 3];
let values = vec![1i, 2, 3];
// "Syntactical sugar" taking advantage of an iterator
for &x in values.iter() {
@ -112,8 +112,8 @@ pub trait Iterator<A> {
/// # Example
///
/// ```rust
/// let a = [0];
/// let b = [1];
/// let a = [0i];
/// let b = [1i];
/// let mut it = a.iter().chain(b.iter());
/// assert_eq!(it.next().unwrap(), &0);
/// assert_eq!(it.next().unwrap(), &1);
@ -132,8 +132,8 @@ pub trait Iterator<A> {
/// # Example
///
/// ```rust
/// let a = [0];
/// let b = [1];
/// let a = [0i];
/// let b = [1i];
/// let mut it = a.iter().zip(b.iter());
/// assert_eq!(it.next().unwrap(), (&0, &1));
/// assert!(it.next().is_none());
@ -149,7 +149,7 @@ pub trait Iterator<A> {
/// # Example
///
/// ```rust
/// let a = [1, 2];
/// let a = [1i, 2];
/// let mut it = a.iter().map(|&x| 2 * x);
/// assert_eq!(it.next().unwrap(), 2);
/// assert_eq!(it.next().unwrap(), 4);
@ -167,7 +167,7 @@ pub trait Iterator<A> {
/// # Example
///
/// ```rust
/// let a = [1, 2];
/// let a = [1i, 2];
/// let mut it = a.iter().filter(|&x| *x > 1);
/// assert_eq!(it.next().unwrap(), &2);
/// assert!(it.next().is_none());
@ -184,7 +184,7 @@ pub trait Iterator<A> {
/// # Example
///
/// ```rust
/// let a = [1, 2];
/// let a = [1i, 2];
/// let mut it = a.iter().filter_map(|&x| if x > 1 {Some(2 * x)} else {None});
/// assert_eq!(it.next().unwrap(), 4);
/// assert!(it.next().is_none());
@ -200,7 +200,7 @@ pub trait Iterator<A> {
/// # Example
///
/// ```rust
/// let a = [100, 200];
/// let a = [100i, 200];
/// let mut it = a.iter().enumerate();
/// assert_eq!(it.next().unwrap(), (0, &100));
/// assert_eq!(it.next().unwrap(), (1, &200));
@ -218,7 +218,7 @@ pub trait Iterator<A> {
/// # Example
///
/// ```rust
/// let xs = [100, 200, 300];
/// let xs = [100i, 200, 300];
/// let mut it = xs.iter().map(|x| *x).peekable();
/// assert_eq!(it.peek().unwrap(), &100);
/// assert_eq!(it.next().unwrap(), 100);
@ -241,7 +241,7 @@ pub trait Iterator<A> {
/// # Example
///
/// ```rust
/// let a = [1, 2, 3, 2, 1];
/// let a = [1i, 2, 3, 2, 1];
/// let mut it = a.iter().skip_while(|&a| *a < 3);
/// assert_eq!(it.next().unwrap(), &3);
/// assert_eq!(it.next().unwrap(), &2);
@ -260,7 +260,7 @@ pub trait Iterator<A> {
/// # Example
///
/// ```rust
/// let a = [1, 2, 3, 2, 1];
/// let a = [1i, 2, 3, 2, 1];
/// let mut it = a.iter().take_while(|&a| *a < 3);
/// assert_eq!(it.next().unwrap(), &1);
/// assert_eq!(it.next().unwrap(), &2);
@ -277,7 +277,7 @@ pub trait Iterator<A> {
/// # Example
///
/// ```rust
/// let a = [1, 2, 3, 4, 5];
/// let a = [1i, 2, 3, 4, 5];
/// let mut it = a.iter().skip(3);
/// assert_eq!(it.next().unwrap(), &4);
/// assert_eq!(it.next().unwrap(), &5);
@ -294,7 +294,7 @@ pub trait Iterator<A> {
/// # Example
///
/// ```rust
/// let a = [1, 2, 3, 4, 5];
/// let a = [1i, 2, 3, 4, 5];
/// let mut it = a.iter().take(3);
/// assert_eq!(it.next().unwrap(), &1);
/// assert_eq!(it.next().unwrap(), &2);
@ -314,7 +314,7 @@ pub trait Iterator<A> {
/// # Example
///
/// ```rust
/// let a = [1, 2, 3, 4, 5];
/// let a = [1i, 2, 3, 4, 5];
/// let mut it = a.iter().scan(1, |fac, &x| {
/// *fac = *fac * x;
/// Some(*fac)
@ -378,7 +378,7 @@ pub trait Iterator<A> {
/// }
/// sum
/// }
/// let x = vec![1,2,3,7,8,9];
/// let x = vec![1i,2,3,7,8,9];
/// assert_eq!(process(x.move_iter()), 1006);
/// ```
#[inline]
@ -417,7 +417,7 @@ pub trait Iterator<A> {
/// # Example
///
/// ```rust
/// let mut xs = range(0, 10);
/// let mut xs = range(0u, 10);
/// // sum the first five values
/// let partial_sum = xs.by_ref().take(5).fold(0, |a, b| a + b);
/// assert!(partial_sum == 10);
@ -434,7 +434,7 @@ pub trait Iterator<A> {
/// # Example
///
/// ```rust
/// range(0, 5).advance(|x| {print!("{} ", x); true});
/// range(0u, 5).advance(|x| {print!("{} ", x); true});
/// ```
#[inline]
fn advance(&mut self, f: |A| -> bool) -> bool {
@ -454,7 +454,7 @@ pub trait Iterator<A> {
/// # Example
///
/// ```rust
/// let a = [1, 2, 3, 4, 5];
/// let a = [1i, 2, 3, 4, 5];
/// let b: Vec<int> = a.iter().map(|&x| x).collect();
/// assert!(a.as_slice() == b.as_slice());
/// ```
@ -469,7 +469,7 @@ pub trait Iterator<A> {
/// # Example
///
/// ```rust
/// let a = [1, 2, 3, 4, 5];
/// let a = [1i, 2, 3, 4, 5];
/// let mut it = a.iter();
/// assert!(it.nth(2).unwrap() == &3);
/// assert!(it.nth(2) == None);
@ -491,7 +491,7 @@ pub trait Iterator<A> {
/// # Example
///
/// ```rust
/// let a = [1, 2, 3, 4, 5];
/// let a = [1i, 2, 3, 4, 5];
/// assert!(a.iter().last().unwrap() == &5);
/// ```
#[inline]
@ -507,7 +507,7 @@ pub trait Iterator<A> {
/// # Example
///
/// ```rust
/// let a = [1, 2, 3, 4, 5];
/// let a = [1i, 2, 3, 4, 5];
/// assert!(a.iter().fold(0, |a, &b| a + b) == 15);
/// ```
#[inline]
@ -527,7 +527,7 @@ pub trait Iterator<A> {
/// # Example
///
/// ```rust
/// let a = [1, 2, 3, 4, 5];
/// let a = [1i, 2, 3, 4, 5];
/// let mut it = a.iter();
/// assert!(it.count() == 5);
/// assert!(it.count() == 0);
@ -542,7 +542,7 @@ pub trait Iterator<A> {
/// # Example
///
/// ```rust
/// let a = [1, 2, 3, 4, 5];
/// let a = [1i, 2, 3, 4, 5];
/// assert!(a.iter().all(|x| *x > 0));
/// assert!(!a.iter().all(|x| *x > 2));
/// ```
@ -558,7 +558,7 @@ pub trait Iterator<A> {
/// # Example
///
/// ```rust
/// let a = [1, 2, 3, 4, 5];
/// let a = [1i, 2, 3, 4, 5];
/// let mut it = a.iter();
/// assert!(it.any(|x| *x == 3));
/// assert!(!it.any(|x| *x == 3));
@ -801,7 +801,7 @@ pub trait AdditiveIterator<A> {
/// ```rust
/// use std::iter::AdditiveIterator;
///
/// let a = [1, 2, 3, 4, 5];
/// let a = [1i, 2, 3, 4, 5];
/// let mut it = a.iter().map(|&x| x);
/// assert!(it.sum() == 15);
/// ```
@ -852,7 +852,7 @@ pub trait OrdIterator<A> {
/// # Example
///
/// ```rust
/// let a = [1, 2, 3, 4, 5];
/// let a = [1i, 2, 3, 4, 5];
/// assert!(a.iter().max().unwrap() == &5);
/// ```
fn max(&mut self) -> Option<A>;
@ -862,7 +862,7 @@ pub trait OrdIterator<A> {
/// # Example
///
/// ```rust
/// let a = [1, 2, 3, 4, 5];
/// let a = [1i, 2, 3, 4, 5];
/// assert!(a.iter().min().unwrap() == &1);
/// ```
fn min(&mut self) -> Option<A>;
@ -995,10 +995,10 @@ impl<T: Clone> MinMaxResult<T> {
/// let r: MinMaxResult<int> = NoElements;
/// assert_eq!(r.into_option(), None)
///
/// let r = OneElement(1);
/// let r = OneElement(1i);
/// assert_eq!(r.into_option(), Some((1,1)));
///
/// let r = MinMax(1,2);
/// let r = MinMax(1i,2i);
/// assert_eq!(r.into_option(), Some((1,2)));
/// ```
pub fn into_option(self) -> Option<(T,T)> {
@ -1019,7 +1019,7 @@ pub trait CloneableIterator {
/// ```rust
/// use std::iter::{CloneableIterator, count};
///
/// let a = count(1,1).take(1);
/// let a = count(1i,1i).take(1);
/// let mut cy = a.cycle();
/// assert_eq!(cy.next(), Some(1));
/// assert_eq!(cy.next(), Some(1));
@ -2285,8 +2285,8 @@ pub mod order {
use slice::ImmutableVector;
let empty: [int, ..0] = [];
let xs = [1,2,3];
let ys = [1,2,0];
let xs = [1i,2,3];
let ys = [1i,2,0];
assert!(!lt(xs.iter(), ys.iter()));
assert!(!le(xs.iter(), ys.iter()));
@ -2304,17 +2304,17 @@ pub mod order {
assert!(!ge(empty.iter(), xs.iter()));
// Sequence with NaN
let u = [1.0, 2.0];
let v = [0.0/0.0, 3.0];
let u = [1.0f64, 2.0];
let v = [0.0f64/0.0, 3.0];
assert!(!lt(u.iter(), v.iter()));
assert!(!le(u.iter(), v.iter()));
assert!(!gt(u.iter(), v.iter()));
assert!(!ge(u.iter(), v.iter()));
let a = [0.0/0.0];
let b = [1.0];
let c = [2.0];
let a = [0.0f64/0.0];
let b = [1.0f64];
let c = [2.0f64];
assert!(lt(a.iter(), b.iter()) == (a[0] < b[0]));
assert!(le(a.iter(), b.iter()) == (a[0] <= b[0]));
@ -2380,7 +2380,7 @@ mod tests {
#[test]
fn test_counter_from_iter() {
let it = count(0, 5).take(10);
let it = count(0i, 5).take(10);
let xs: Vec<int> = FromIterator::from_iter(it);
assert!(xs == vec![0, 5, 10, 15, 20, 25, 30, 35, 40, 45]);
}
@ -2577,7 +2577,7 @@ mod tests {
#[test]
fn test_iterator_nth() {
let v = &[0, 1, 2, 3, 4];
let v = &[0i, 1, 2, 3, 4];
for i in range(0u, v.len()) {
assert_eq!(v.iter().nth(i).unwrap(), &v[i]);
}
@ -2585,14 +2585,14 @@ mod tests {
#[test]
fn test_iterator_last() {
let v = &[0, 1, 2, 3, 4];
let v = &[0i, 1, 2, 3, 4];
assert_eq!(v.iter().last().unwrap(), &4);
assert_eq!(v.slice(0, 1).iter().last().unwrap(), &0);
}
#[test]
fn test_iterator_len() {
let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v.slice(0, 4).iter().count(), 4);
assert_eq!(v.slice(0, 10).iter().count(), 10);
assert_eq!(v.slice(0, 0).iter().count(), 0);
@ -2600,7 +2600,7 @@ mod tests {
#[test]
fn test_iterator_sum() {
let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v.slice(0, 4).iter().map(|&x| x).sum(), 6);
assert_eq!(v.iter().map(|&x| x).sum(), 55);
assert_eq!(v.slice(0, 0).iter().map(|&x| x).sum(), 0);
@ -2608,7 +2608,7 @@ mod tests {
#[test]
fn test_iterator_product() {
let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v.slice(0, 4).iter().map(|&x| x).product(), 0);
assert_eq!(v.slice(1, 5).iter().map(|&x| x).product(), 24);
assert_eq!(v.slice(0, 0).iter().map(|&x| x).product(), 1);
@ -2616,7 +2616,7 @@ mod tests {
#[test]
fn test_iterator_max() {
let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v.slice(0, 4).iter().map(|&x| x).max(), Some(3));
assert_eq!(v.iter().map(|&x| x).max(), Some(10));
assert_eq!(v.slice(0, 0).iter().map(|&x| x).max(), None);
@ -2624,7 +2624,7 @@ mod tests {
#[test]
fn test_iterator_min() {
let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(v.slice(0, 4).iter().map(|&x| x).min(), Some(0));
assert_eq!(v.iter().map(|&x| x).min(), Some(0));
assert_eq!(v.slice(0, 0).iter().map(|&x| x).min(), None);
@ -2632,9 +2632,9 @@ mod tests {
#[test]
fn test_iterator_size_hint() {
let c = count(0, 1);
let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let v2 = &[10, 11, 12];
let c = count(0i, 1);
let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let v2 = &[10i, 11, 12];
let vi = v.iter();
assert_eq!(c.size_hint(), (uint::MAX, None));
@ -2669,14 +2669,14 @@ mod tests {
#[test]
fn test_collect() {
let a = vec![1, 2, 3, 4, 5];
let a = vec![1i, 2, 3, 4, 5];
let b: Vec<int> = a.iter().map(|&x| x).collect();
assert!(a == b);
}
#[test]
fn test_all() {
let v: Box<&[int]> = box &[1, 2, 3, 4, 5];
let v: Box<&[int]> = box &[1i, 2, 3, 4, 5];
assert!(v.iter().all(|&x| x < 10));
assert!(!v.iter().all(|&x| x % 2 == 0));
assert!(!v.iter().all(|&x| x > 100));
@ -2685,7 +2685,7 @@ mod tests {
#[test]
fn test_any() {
let v: Box<&[int]> = box &[1, 2, 3, 4, 5];
let v: Box<&[int]> = box &[1i, 2, 3, 4, 5];
assert!(v.iter().any(|&x| x < 10));
assert!(v.iter().any(|&x| x % 2 == 0));
assert!(!v.iter().any(|&x| x > 100));
@ -2694,7 +2694,7 @@ mod tests {
#[test]
fn test_find() {
let v: &[int] = &[1, 3, 9, 27, 103, 14, 11];
let v: &[int] = &[1i, 3, 9, 27, 103, 14, 11];
assert_eq!(*v.iter().find(|x| *x & 1 == 0).unwrap(), 14);
assert_eq!(*v.iter().find(|x| *x % 3 == 0).unwrap(), 3);
assert!(v.iter().find(|x| *x % 12 == 0).is_none());
@ -2702,7 +2702,7 @@ mod tests {
#[test]
fn test_position() {
let v = &[1, 3, 9, 27, 103, 14, 11];
let v = &[1i, 3, 9, 27, 103, 14, 11];
assert_eq!(v.iter().position(|x| *x & 1 == 0).unwrap(), 5);
assert_eq!(v.iter().position(|x| *x % 3 == 0).unwrap(), 1);
assert!(v.iter().position(|x| *x % 12 == 0).is_none());
@ -2710,7 +2710,7 @@ mod tests {
#[test]
fn test_count() {
let xs = &[1, 2, 2, 1, 5, 9, 0, 2];
let xs = &[1i, 2, 2, 1, 5, 9, 0, 2];
assert_eq!(xs.iter().filter(|x| **x == 2).count(), 3);
assert_eq!(xs.iter().filter(|x| **x == 5).count(), 1);
assert_eq!(xs.iter().filter(|x| **x == 95).count(), 0);
@ -2718,19 +2718,19 @@ mod tests {
#[test]
fn test_max_by() {
let xs: &[int] = &[-3, 0, 1, 5, -10];
let xs: &[int] = &[-3i, 0, 1, 5, -10];
assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10);
}
#[test]
fn test_min_by() {
let xs: &[int] = &[-3, 0, 1, 5, -10];
let xs: &[int] = &[-3i, 0, 1, 5, -10];
assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0);
}
#[test]
fn test_by_ref() {
let mut xs = range(0, 10);
let mut xs = range(0i, 10);
// sum the first five values
let partial_sum = xs.by_ref().take(5).fold(0, |a, b| a + b);
assert_eq!(partial_sum, 10);
@ -2739,7 +2739,7 @@ mod tests {
#[test]
fn test_rev() {
let xs = [2, 4, 6, 8, 10, 12, 14, 16];
let xs = [2i, 4, 6, 8, 10, 12, 14, 16];
let mut it = xs.iter();
it.next();
it.next();
@ -2749,7 +2749,7 @@ mod tests {
#[test]
fn test_double_ended_map() {
let xs = [1, 2, 3, 4, 5, 6];
let xs = [1i, 2, 3, 4, 5, 6];
let mut it = xs.iter().map(|&x| x * -1);
assert_eq!(it.next(), Some(-1));
assert_eq!(it.next(), Some(-2));
@ -2762,7 +2762,7 @@ mod tests {
#[test]
fn test_double_ended_enumerate() {
let xs = [1, 2, 3, 4, 5, 6];
let xs = [1i, 2, 3, 4, 5, 6];
let mut it = xs.iter().map(|&x| x).enumerate();
assert_eq!(it.next(), Some((0, 1)));
assert_eq!(it.next(), Some((1, 2)));
@ -2775,8 +2775,8 @@ mod tests {
#[test]
fn test_double_ended_zip() {
let xs = [1, 2, 3, 4, 5, 6];
let ys = [1, 2, 3, 7];
let xs = [1i, 2, 3, 4, 5, 6];
let ys = [1i, 2, 3, 7];
let a = xs.iter().map(|&x| x);
let b = ys.iter().map(|&x| x);
let mut it = a.zip(b);
@ -2789,7 +2789,7 @@ mod tests {
#[test]
fn test_double_ended_filter() {
let xs = [1, 2, 3, 4, 5, 6];
let xs = [1i, 2, 3, 4, 5, 6];
let mut it = xs.iter().filter(|&x| *x & 1 == 0);
assert_eq!(it.next_back().unwrap(), &6);
assert_eq!(it.next_back().unwrap(), &4);
@ -2799,7 +2799,7 @@ mod tests {
#[test]
fn test_double_ended_filter_map() {
let xs = [1, 2, 3, 4, 5, 6];
let xs = [1i, 2, 3, 4, 5, 6];
let mut it = xs.iter().filter_map(|&x| if x & 1 == 0 { Some(x * 2) } else { None });
assert_eq!(it.next_back().unwrap(), 12);
assert_eq!(it.next_back().unwrap(), 8);
@ -2809,8 +2809,8 @@ mod tests {
#[test]
fn test_double_ended_chain() {
let xs = [1, 2, 3, 4, 5];
let ys = [7, 9, 11];
let xs = [1i, 2, 3, 4, 5];
let ys = [7i, 9, 11];
let mut it = xs.iter().chain(ys.iter()).rev();
assert_eq!(it.next().unwrap(), &11)
assert_eq!(it.next().unwrap(), &9)
@ -2827,7 +2827,7 @@ mod tests {
fn test_rposition() {
fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' }
fn g(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'd' }
let v = [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')];
let v = [(0i, 'a'), (1, 'b'), (2, 'c'), (3, 'b')];
assert_eq!(v.iter().rposition(f), Some(3u));
assert!(v.iter().rposition(g).is_none());
@ -2836,9 +2836,9 @@ mod tests {
#[test]
#[should_fail]
fn test_rposition_fail() {
let v = [(box 0, box(GC) 0), (box 0, box(GC) 0),
(box 0, box(GC) 0), (box 0, box(GC) 0)];
let mut i = 0;
let v = [(box 0i, box(GC) 0i), (box 0i, box(GC) 0i),
(box 0i, box(GC) 0i), (box 0i, box(GC) 0i)];
let mut i = 0i;
v.iter().rposition(|_elt| {
if i == 2 {
fail!()
@ -2854,7 +2854,7 @@ mod tests {
{
let mut b = a.clone();
assert_eq!(len, b.indexable());
let mut n = 0;
let mut n = 0u;
for (i, elt) in a.enumerate() {
assert!(Some(elt) == b.idx(i));
n += 1;
@ -2872,7 +2872,7 @@ mod tests {
#[test]
fn test_double_ended_flat_map() {
let u = [0u,1];
let v = [5,6,7,8];
let v = [5u,6,7,8];
let mut it = u.iter().flat_map(|x| v.slice(*x, v.len()).iter());
assert_eq!(it.next_back().unwrap(), &8);
assert_eq!(it.next().unwrap(), &5);
@ -2888,8 +2888,8 @@ mod tests {
#[test]
fn test_random_access_chain() {
let xs = [1, 2, 3, 4, 5];
let ys = [7, 9, 11];
let xs = [1i, 2, 3, 4, 5];
let ys = [7i, 9, 11];
let mut it = xs.iter().chain(ys.iter());
assert_eq!(it.idx(0).unwrap(), &1);
assert_eq!(it.idx(5).unwrap(), &7);
@ -2909,13 +2909,13 @@ mod tests {
#[test]
fn test_random_access_enumerate() {
let xs = [1, 2, 3, 4, 5];
let xs = [1i, 2, 3, 4, 5];
check_randacc_iter(xs.iter().enumerate(), xs.len());
}
#[test]
fn test_random_access_rev() {
let xs = [1, 2, 3, 4, 5];
let xs = [1i, 2, 3, 4, 5];
check_randacc_iter(xs.iter().rev(), xs.len());
let mut it = xs.iter().rev();
it.next();
@ -2926,14 +2926,14 @@ mod tests {
#[test]
fn test_random_access_zip() {
let xs = [1, 2, 3, 4, 5];
let ys = [7, 9, 11];
let xs = [1i, 2, 3, 4, 5];
let ys = [7i, 9, 11];
check_randacc_iter(xs.iter().zip(ys.iter()), cmp::min(xs.len(), ys.len()));
}
#[test]
fn test_random_access_take() {
let xs = [1, 2, 3, 4, 5];
let xs = [1i, 2, 3, 4, 5];
let empty: &[int] = [];
check_randacc_iter(xs.iter().take(3), 3);
check_randacc_iter(xs.iter().take(20), xs.len());
@ -2943,7 +2943,7 @@ mod tests {
#[test]
fn test_random_access_skip() {
let xs = [1, 2, 3, 4, 5];
let xs = [1i, 2, 3, 4, 5];
let empty: &[int] = [];
check_randacc_iter(xs.iter().skip(2), xs.len() - 2);
check_randacc_iter(empty.iter().skip(2), 0);
@ -2951,7 +2951,7 @@ mod tests {
#[test]
fn test_random_access_inspect() {
let xs = [1, 2, 3, 4, 5];
let xs = [1i, 2, 3, 4, 5];
// test .map and .inspect that don't implement Clone
let mut it = xs.iter().inspect(|_| {});
@ -2964,7 +2964,7 @@ mod tests {
#[test]
fn test_random_access_map() {
let xs = [1, 2, 3, 4, 5];
let xs = [1i, 2, 3, 4, 5];
let mut it = xs.iter().map(|x| *x);
assert_eq!(xs.len(), it.indexable());
@ -2975,7 +2975,7 @@ mod tests {
#[test]
fn test_random_access_cycle() {
let xs = [1, 2, 3, 4, 5];
let xs = [1i, 2, 3, 4, 5];
let empty: &[int] = [];
check_randacc_iter(xs.iter().cycle().take(27), 27);
check_randacc_iter(empty.iter().cycle(), 0);
@ -3044,10 +3044,10 @@ mod tests {
assert!(range(-10i, -1).collect::<Vec<int>>() ==
vec![-10, -9, -8, -7, -6, -5, -4, -3, -2]);
assert!(range(0i, 5).rev().collect::<Vec<int>>() == vec![4, 3, 2, 1, 0]);
assert_eq!(range(200, -5).count(), 0);
assert_eq!(range(200, -5).rev().count(), 0);
assert_eq!(range(200, 200).count(), 0);
assert_eq!(range(200, 200).rev().count(), 0);
assert_eq!(range(200i, -5).count(), 0);
assert_eq!(range(200i, -5).rev().count(), 0);
assert_eq!(range(200i, 200).count(), 0);
assert_eq!(range(200i, 200).rev().count(), 0);
assert_eq!(range(0i, 100).size_hint(), (100, Some(100)));
// this test is only meaningful when sizeof uint < sizeof u64
@ -3062,10 +3062,10 @@ mod tests {
vec![0i, 1, 2, 3, 4, 5]);
assert!(range_inclusive(0i, 5).rev().collect::<Vec<int>>() ==
vec![5i, 4, 3, 2, 1, 0]);
assert_eq!(range_inclusive(200, -5).count(), 0);
assert_eq!(range_inclusive(200, -5).rev().count(), 0);
assert!(range_inclusive(200, 200).collect::<Vec<int>>() == vec![200]);
assert!(range_inclusive(200, 200).rev().collect::<Vec<int>>() == vec![200]);
assert_eq!(range_inclusive(200i, -5).count(), 0);
assert_eq!(range_inclusive(200i, -5).rev().count(), 0);
assert!(range_inclusive(200i, 200).collect::<Vec<int>>() == vec![200]);
assert!(range_inclusive(200i, 200).rev().collect::<Vec<int>>() == vec![200]);
}
#[test]
@ -3078,8 +3078,8 @@ mod tests {
vec![20, 14, 8, 2]);
assert!(range_step(200u8, 255, 50).collect::<Vec<u8>>() ==
vec![200u8, 250]);
assert!(range_step(200, -5, 1).collect::<Vec<int>>() == vec![]);
assert!(range_step(200, 200, 1).collect::<Vec<int>>() == vec![]);
assert!(range_step(200i, -5, 1).collect::<Vec<int>>() == vec![]);
assert!(range_step(200i, 200, 1).collect::<Vec<int>>() == vec![]);
}
#[test]
@ -3092,22 +3092,22 @@ mod tests {
vec![20, 14, 8, 2]);
assert!(range_step_inclusive(200u8, 255, 50).collect::<Vec<u8>>() ==
vec![200u8, 250]);
assert!(range_step_inclusive(200, -5, 1).collect::<Vec<int>>() ==
assert!(range_step_inclusive(200i, -5, 1).collect::<Vec<int>>() ==
vec![]);
assert!(range_step_inclusive(200, 200, 1).collect::<Vec<int>>() ==
assert!(range_step_inclusive(200i, 200, 1).collect::<Vec<int>>() ==
vec![200]);
}
#[test]
fn test_reverse() {
let mut ys = [1, 2, 3, 4, 5];
let mut ys = [1i, 2, 3, 4, 5];
ys.mut_iter().reverse_();
assert!(ys == [5, 4, 3, 2, 1]);
}
#[test]
fn test_peekable_is_empty() {
let a = [1];
let a = [1i];
let mut it = a.iter().peekable();
assert!( !it.is_empty() );
it.next();
@ -3137,10 +3137,10 @@ mod tests {
let r: MinMaxResult<int> = NoElements;
assert_eq!(r.into_option(), None)
let r = OneElement(1);
let r = OneElement(1i);
assert_eq!(r.into_option(), Some((1,1)));
let r = MinMax(1,2);
let r = MinMax(1i,2);
assert_eq!(r.into_option(), Some((1,2)));
}
}

View file

@ -324,7 +324,7 @@ pub fn replace<T>(dest: &mut T, mut src: T) -> T {
/// ```
/// use std::cell::RefCell;
///
/// let x = RefCell::new(1);
/// let x = RefCell::new(1i);
///
/// let mut mutable_borrow = x.borrow_mut();
/// *mutable_borrow = 1;
@ -458,8 +458,8 @@ mod tests {
#[test]
fn test_swap() {
let mut x = 31337;
let mut y = 42;
let mut x = 31337i;
let mut y = 42i;
swap(&mut x, &mut y);
assert_eq!(x, 42);
assert_eq!(y, 31337);
@ -483,7 +483,7 @@ mod tests {
trait Foo {}
impl Foo for int {}
let a = box 100 as Box<Foo>;
let a = box 100i as Box<Foo>;
unsafe {
let x: raw::TraitObject = transmute(a);
assert!(*(x.data as *int) == 100);

View file

@ -10,6 +10,7 @@
//! Operations and constants for signed 16-bits integers (`i16` type)
#![unstable]
#![doc(primitive = "i16")]
int_module!(i16, 16)

View file

@ -10,6 +10,7 @@
//! Operations and constants for signed 32-bits integers (`i32` type)
#![unstable]
#![doc(primitive = "i32")]
int_module!(i32, 32)

View file

@ -10,6 +10,7 @@
//! Operations and constants for signed 64-bits integers (`i64` type)
#![unstable]
#![doc(primitive = "i64")]
int_module!(i64, 64)

View file

@ -10,6 +10,7 @@
//! Operations and constants for signed 8-bits integers (`i8` type)
#![unstable]
#![doc(primitive = "i8")]
int_module!(i8, 8)

View file

@ -10,6 +10,7 @@
//! Operations and constants for architecture-sized signed integers (`int` type)
#![unstable]
#![doc(primitive = "int")]
#[cfg(target_word_size = "32")] int_module!(int, 32)

View file

@ -15,17 +15,21 @@ macro_rules! int_module (($T:ty, $bits:expr) => (
// FIXME(#11621): Should be deprecated once CTFE is implemented in favour of
// calling the `mem::size_of` function.
#[unstable]
pub static BITS : uint = $bits;
// FIXME(#11621): Should be deprecated once CTFE is implemented in favour of
// calling the `mem::size_of` function.
#[unstable]
pub static BYTES : uint = ($bits / 8);
// FIXME(#11621): Should be deprecated once CTFE is implemented in favour of
// calling the `Bounded::min_value` function.
#[unstable]
pub static MIN: $T = (-1 as $T) << (BITS - 1);
// FIXME(#9837): Compute MIN like this so the high bits that shouldn't exist are 0.
// FIXME(#11621): Should be deprecated once CTFE is implemented in favour of
// calling the `Bounded::max_value` function.
#[unstable]
pub static MAX: $T = !MIN;
#[cfg(test)]

View file

@ -322,7 +322,7 @@ trait_impl!(Unsigned for uint u8 u16 u32 u64)
/// ```rust
/// use std::num;
///
/// assert_eq!(num::pow(2, 4), 16);
/// assert_eq!(num::pow(2i, 4), 16);
/// ```
#[inline]
pub fn pow<T: One + Mul<T, T>>(mut base: T, mut exp: uint) -> T {
@ -1144,7 +1144,7 @@ impl_from_primitive!(f64, n.to_f64())
/// ```
/// use std::num;
///
/// let twenty: f32 = num::cast(0x14).unwrap();
/// let twenty: f32 = num::cast(0x14i).unwrap();
/// assert_eq!(twenty, 20f32);
/// ```
///
@ -1378,11 +1378,11 @@ checkeddiv_uint_impl!(uint u8 u16 u32 u64)
/// Helper function for testing numeric operations
#[cfg(test)]
pub fn test_num<T:Num + NumCast + ::std::fmt::Show>(ten: T, two: T) {
assert_eq!(ten.add(&two), cast(12).unwrap());
assert_eq!(ten.sub(&two), cast(8).unwrap());
assert_eq!(ten.mul(&two), cast(20).unwrap());
assert_eq!(ten.div(&two), cast(5).unwrap());
assert_eq!(ten.rem(&two), cast(0).unwrap());
assert_eq!(ten.add(&two), cast(12i).unwrap());
assert_eq!(ten.sub(&two), cast(8i).unwrap());
assert_eq!(ten.mul(&two), cast(20i).unwrap());
assert_eq!(ten.div(&two), cast(5i).unwrap());
assert_eq!(ten.rem(&two), cast(0i).unwrap());
assert_eq!(ten.add(&two), ten + two);
assert_eq!(ten.sub(&two), ten - two);

View file

@ -10,6 +10,7 @@
//! Operations and constants for unsigned 16-bits integers (`u16` type)
#![unstable]
#![doc(primitive = "u16")]
uint_module!(u16, i16, 16)

View file

@ -10,6 +10,7 @@
//! Operations and constants for unsigned 32-bits integers (`u32` type)
#![unstable]
#![doc(primitive = "u32")]
uint_module!(u32, i32, 32)

View file

@ -10,6 +10,7 @@
//! Operations and constants for unsigned 64-bits integer (`u64` type)
#![unstable]
#![doc(primitive = "u64")]
uint_module!(u64, i64, 64)

View file

@ -10,6 +10,7 @@
//! Operations and constants for unsigned 8-bits integers (`u8` type)
#![unstable]
#![doc(primitive = "u8")]
uint_module!(u8, i8, 8)

View file

@ -10,6 +10,7 @@
//! Operations and constants for architecture-sized unsigned integers (`uint` type)
#![unstable]
#![doc(primitive = "uint")]
uint_module!(uint, int, ::int::BITS)

View file

@ -13,10 +13,14 @@
macro_rules! uint_module (($T:ty, $T_SIGNED:ty, $bits:expr) => (
#[unstable]
pub static BITS : uint = $bits;
#[unstable]
pub static BYTES : uint = ($bits / 8);
#[unstable]
pub static MIN: $T = 0 as $T;
#[unstable]
pub static MAX: $T = 0 as $T - 1 as $T;
#[cfg(test)]

View file

@ -570,11 +570,18 @@ pub trait Shl<RHS,Result> {
macro_rules! shl_impl(
($($t:ty)*) => ($(
#[cfg(not(test))]
#[cfg(stage0)]
impl Shl<$t, $t> for $t {
#[inline]
fn shl(&self, other: &$t) -> $t { (*self) << (*other) }
}
#[cfg(not(stage0), not(test))]
impl Shl<$t, $t> for $t {
#[inline]
fn shl(&self, other: &$t) -> $t {
(*self) << (*other as uint)
}
}
)*)
)
@ -612,11 +619,16 @@ pub trait Shr<RHS,Result> {
macro_rules! shr_impl(
($($t:ty)*) => ($(
#[cfg(not(test))]
#[cfg(stage0, not(test))]
impl Shr<$t, $t> for $t {
#[inline]
fn shr(&self, other: &$t) -> $t { (*self) >> (*other) }
}
#[cfg(not(stage0), not(test))]
impl Shr<$t, $t> for $t {
#[inline]
fn shr(&self, other: &$t) -> $t { (*self) >> (*other as uint) }
}
)*)
)

View file

@ -505,8 +505,8 @@ impl<T: Default> Option<T> {
/// let good_year = from_str(good_year_from_input).unwrap_or_default();
/// let bad_year = from_str(bad_year_from_input).unwrap_or_default();
///
/// assert_eq!(1909, good_year);
/// assert_eq!(0, bad_year);
/// assert_eq!(1909i, good_year);
/// assert_eq!(0i, bad_year);
/// ```
#[inline]
pub fn unwrap_or_default(self) -> T {
@ -675,7 +675,7 @@ mod tests {
t.clone()
}
let i = Rc::new(RefCell::new(0));
let i = Rc::new(RefCell::new(0i));
{
let x = r(realclone(&i));
let opt = Some(x);
@ -687,7 +687,7 @@ mod tests {
#[test]
fn test_option_dance() {
let x = Some(());
let mut y = Some(5);
let mut y = Some(5i);
let mut y2 = 0;
for _x in x.iter() {
y2 = y.take_unwrap();
@ -705,12 +705,12 @@ mod tests {
#[test]
fn test_and() {
let x: Option<int> = Some(1);
assert_eq!(x.and(Some(2)), Some(2));
let x: Option<int> = Some(1i);
assert_eq!(x.and(Some(2i)), Some(2));
assert_eq!(x.and(None::<int>), None);
let x: Option<int> = None;
assert_eq!(x.and(Some(2)), None);
assert_eq!(x.and(Some(2i)), None);
assert_eq!(x.and(None::<int>), None);
}
@ -749,7 +749,7 @@ mod tests {
#[test]
fn test_option_while_some() {
let mut i = 0;
let mut i = 0i;
Some(10).while_some(|j| {
i += 1;
if j > 0 {
@ -763,7 +763,7 @@ mod tests {
#[test]
fn test_unwrap() {
assert_eq!(Some(1).unwrap(), 1);
assert_eq!(Some(1i).unwrap(), 1);
let s = Some("hello".to_string()).unwrap();
assert_eq!(s.as_slice(), "hello");
}
@ -802,7 +802,7 @@ mod tests {
#[test]
fn test_filtered() {
let some_stuff = Some(42);
let some_stuff = Some(42i);
let modified_stuff = some_stuff.filtered(|&x| {x < 10});
assert_eq!(some_stuff.unwrap(), 42);
assert!(modified_stuff.is_none());
@ -810,7 +810,7 @@ mod tests {
#[test]
fn test_iter() {
let val = 5;
let val = 5i;
let x = Some(val);
let mut it = x.iter();
@ -823,8 +823,8 @@ mod tests {
#[test]
fn test_mut_iter() {
let val = 5;
let new_val = 11;
let val = 5i;
let new_val = 11i;
let mut x = Some(val);
{
@ -848,9 +848,9 @@ mod tests {
#[test]
fn test_ord() {
let small = Some(1.0);
let big = Some(5.0);
let nan = Some(0.0/0.0);
let small = Some(1.0f64);
let big = Some(5.0f64);
let nan = Some(0.0f64/0.0);
assert!(!(nan < big));
assert!(!(nan > big));
assert!(small < big);
@ -874,15 +874,15 @@ mod tests {
#[test]
fn test_collect() {
let v: Option<Vec<int>> = collect(range(0, 0)
.map(|_| Some(0)));
let v: Option<Vec<int>> = collect(range(0i, 0)
.map(|_| Some(0i)));
assert!(v == Some(vec![]));
let v: Option<Vec<int>> = collect(range(0, 3)
let v: Option<Vec<int>> = collect(range(0i, 3)
.map(|x| Some(x)));
assert!(v == Some(vec![0, 1, 2]));
let v: Option<Vec<int>> = collect(range(0, 3)
let v: Option<Vec<int>> = collect(range(0i, 3)
.map(|x| if x > 1 { None } else { Some(x) }));
assert!(v == None);

View file

@ -624,7 +624,7 @@ pub mod test {
#[test]
fn test_ptr_addition() {
unsafe {
let xs = Vec::from_elem(16, 5);
let xs = Vec::from_elem(16, 5i);
let mut ptr = xs.as_ptr();
let end = ptr.offset(16);
@ -642,7 +642,7 @@ pub mod test {
m_ptr = m_ptr.offset(1);
}
assert!(xs_mut == Vec::from_elem(16, 10));
assert!(xs_mut == Vec::from_elem(16, 10i));
}
}
@ -719,8 +719,8 @@ pub mod test {
];
let arr_ptr = arr.as_ptr();
let mut ctr = 0;
let mut iteration_count = 0;
let mut ctr = 0u;
let mut iteration_count = 0u;
array_each(arr_ptr, |e| {
let actual = str::raw::from_c_str(e);
let expected = expected_arr[ctr].with_ref(|buf| {

View file

@ -654,11 +654,11 @@ mod tests {
#[test]
pub fn test_and() {
assert_eq!(op1().and(Ok(667)).unwrap(), 667);
assert_eq!(op1().and(Ok(667i)).unwrap(), 667);
assert_eq!(op1().and(Err::<(), &'static str>("bad")).unwrap_err(),
"bad");
assert_eq!(op2().and(Ok(667)).unwrap_err(), "sadface");
assert_eq!(op2().and(Ok(667i)).unwrap_err(), "sadface");
assert_eq!(op2().and(Err::<(),&'static str>("bad")).unwrap_err(),
"sadface");
}
@ -708,18 +708,18 @@ mod tests {
#[test]
fn test_collect() {
let v: Result<Vec<int>, ()> = collect(range(0, 0).map(|_| Ok::<int, ()>(0)));
let v: Result<Vec<int>, ()> = collect(range(0i, 0).map(|_| Ok::<int, ()>(0)));
assert!(v == Ok(vec![]));
let v: Result<Vec<int>, ()> = collect(range(0, 3).map(|x| Ok::<int, ()>(x)));
let v: Result<Vec<int>, ()> = collect(range(0i, 3).map(|x| Ok::<int, ()>(x)));
assert!(v == Ok(vec![0, 1, 2]));
let v: Result<Vec<int>, int> = collect(range(0, 3)
let v: Result<Vec<int>, int> = collect(range(0i, 3)
.map(|x| if x > 1 { Err(x) } else { Ok(x) }));
assert!(v == Err(2));
// test that it does not take more elements than it needs
let mut functions = [|| Ok(()), || Err(1), || fail!()];
let mut functions = [|| Ok(()), || Err(1i), || fail!()];
let v: Result<Vec<()>, int> = collect(functions.mut_iter().map(|f| (*f)()));
assert!(v == Err(1));
@ -727,19 +727,19 @@ mod tests {
#[test]
fn test_fold() {
assert_eq!(fold_(range(0, 0)
assert_eq!(fold_(range(0i, 0)
.map(|_| Ok::<(), ()>(()))),
Ok(()));
assert_eq!(fold(range(0, 3)
assert_eq!(fold(range(0i, 3)
.map(|x| Ok::<int, ()>(x)),
0, |a, b| a + b),
Ok(3));
assert_eq!(fold_(range(0, 3)
assert_eq!(fold_(range(0i, 3)
.map(|x| if x > 1 { Err(x) } else { Ok(()) })),
Err(2));
// test that it does not take more elements than it needs
let mut functions = [|| Ok(()), || Err(1), || fail!()];
let mut functions = [|| Ok(()), || Err(1i), || fail!()];
assert_eq!(fold_(functions.mut_iter()
.map(|f| (*f)())),
@ -759,7 +759,7 @@ mod tests {
#[test]
pub fn test_unwrap_or() {
let ok: Result<int, &'static str> = Ok(100);
let ok: Result<int, &'static str> = Ok(100i);
let ok_err: Result<int, &'static str> = Err("Err");
assert_eq!(ok.unwrap_or(50), 100);
@ -770,7 +770,7 @@ mod tests {
pub fn test_unwrap_or_else() {
fn handler(msg: &'static str) -> int {
if msg == "I got this." {
50
50i
} else {
fail!("BadBad")
}
@ -788,7 +788,7 @@ mod tests {
pub fn test_unwrap_or_else_failure() {
fn handler(msg: &'static str) -> int {
if msg == "I got this." {
50
50i
} else {
fail!("BadBad")
}

View file

@ -376,7 +376,7 @@ pub trait ImmutableVector<'a, T> {
* `[3,4]`):
*
* ```rust
* let v = &[1,2,3,4];
* let v = &[1i, 2, 3, 4];
* for win in v.windows(2) {
* println!("{}", win);
* }
@ -401,7 +401,7 @@ pub trait ImmutableVector<'a, T> {
* `[3,4]`, `[5]`):
*
* ```rust
* let v = &[1,2,3,4,5];
* let v = &[1i, 2, 3, 4, 5];
* for win in v.chunks(2) {
* println!("{}", win);
* }
@ -830,24 +830,24 @@ pub trait MutableVector<'a, T> {
/// # Example
///
/// ```rust
/// let mut v = [1, 2, 3, 4, 5, 6];
/// let mut v = [1i, 2, 3, 4, 5, 6];
///
/// // scoped to restrict the lifetime of the borrows
/// {
/// let (left, right) = v.mut_split_at(0);
/// assert!(left == &mut []);
/// assert!(right == &mut [1, 2, 3, 4, 5, 6]);
/// assert!(right == &mut [1i, 2, 3, 4, 5, 6]);
/// }
///
/// {
/// let (left, right) = v.mut_split_at(2);
/// assert!(left == &mut [1, 2]);
/// assert!(right == &mut [3, 4, 5, 6]);
/// assert!(left == &mut [1i, 2]);
/// assert!(right == &mut [3i, 4, 5, 6]);
/// }
///
/// {
/// let (left, right) = v.mut_split_at(6);
/// assert!(left == &mut [1, 2, 3, 4, 5, 6]);
/// assert!(left == &mut [1i, 2, 3, 4, 5, 6]);
/// assert!(right == &mut []);
/// }
/// ```
@ -858,9 +858,9 @@ pub trait MutableVector<'a, T> {
/// # Example
///
/// ```rust
/// let mut v = [1, 2, 3];
/// let mut v = [1i, 2, 3];
/// v.reverse();
/// assert!(v == [3, 2, 1]);
/// assert!(v == [3i, 2, 1]);
/// ```
fn reverse(self);
@ -1080,15 +1080,15 @@ pub trait MutableCloneableVector<T> {
/// ```rust
/// use std::slice::MutableCloneableVector;
///
/// let mut dst = [0, 0, 0];
/// let src = [1, 2];
/// let mut dst = [0i, 0, 0];
/// let src = [1i, 2];
///
/// assert!(dst.copy_from(src) == 2);
/// assert!(dst == [1, 2, 0]);
///
/// let src2 = [3, 4, 5, 6];
/// let src2 = [3i, 4, 5, 6];
/// assert!(dst.copy_from(src2) == 3);
/// assert!(dst == [3, 4, 5]);
/// assert!(dst == [3i, 4, 5]);
/// ```
fn copy_from(self, &[T]) -> uint;
}

View file

@ -364,7 +364,8 @@ impl TwoWaySearcher {
period = period2;
}
let byteset = needle.iter().fold(0, |a, &b| (1 << (b & 0x3f)) | a);
let byteset = needle.iter()
.fold(0, |a, &b| (1 << ((b & 0x3f) as uint)) | a);
if needle.slice_to(critPos) == needle.slice_from(needle.len() - critPos) {
TwoWaySearcher {
@ -396,7 +397,9 @@ impl TwoWaySearcher {
}
// Quickly skip by large portions unrelated to our substring
if (self.byteset >> (haystack[self.position + needle.len() - 1] & 0x3f)) & 1 == 0 {
if (self.byteset >>
((haystack[self.position + needle.len() - 1] & 0x3f)
as uint)) & 1 == 0 {
self.position += needle.len();
continue 'search;
}

View file

@ -38,9 +38,9 @@
//! Using methods:
//!
//! ```
//! let pair = ("pi", 3.14);
//! let pair = ("pi", 3.14f64);
//! assert_eq!(pair.val0(), "pi");
//! assert_eq!(pair.val1(), 3.14);
//! assert_eq!(pair.val1(), 3.14f64);
//! ```
//!
//! Using traits implemented for tuples:
@ -48,8 +48,8 @@
//! ```
//! use std::default::Default;
//!
//! let a = (1, 2);
//! let b = (3, 4);
//! let a = (1i, 2i);
//! let b = (3i, 4i);
//! assert!(a != b);
//!
//! let c = b.clone();
@ -104,6 +104,7 @@ macro_rules! tuple_impls {
)+
}
#[unstable]
impl<$($T:Clone),+> Clone for ($($T,)+) {
fn clone(&self) -> ($($T,)+) {
($(self.$refN().clone(),)+)
@ -300,7 +301,7 @@ mod tests {
#[test]
fn test_clone() {
let a = (1, "2");
let a = (1i, "2");
let b = a.clone();
assert_eq!(a, b);
}
@ -335,7 +336,7 @@ mod tests {
fn test_tuple_cmp() {
let (small, big) = ((1u, 2u, 3u), (3u, 2u, 1u));
let nan = 0.0/0.0;
let nan = 0.0f64/0.0;
// PartialEq
assert_eq!(small, small);
@ -357,12 +358,12 @@ mod tests {
assert!(big >= small);
assert!(big >= big);
assert!(!((1.0, 2.0) < (nan, 3.0)));
assert!(!((1.0, 2.0) <= (nan, 3.0)));
assert!(!((1.0, 2.0) > (nan, 3.0)));
assert!(!((1.0, 2.0) >= (nan, 3.0)));
assert!(((1.0, 2.0) < (2.0, nan)));
assert!(!((2.0, 2.0) < (2.0, nan)));
assert!(!((1.0f64, 2.0f64) < (nan, 3.0)));
assert!(!((1.0f64, 2.0f64) <= (nan, 3.0)));
assert!(!((1.0f64, 2.0f64) > (nan, 3.0)));
assert!(!((1.0f64, 2.0f64) >= (nan, 3.0)));
assert!(((1.0f64, 2.0f64) < (2.0, nan)));
assert!(!((2.0f64, 2.0f64) < (2.0, nan)));
// Ord
assert!(small.cmp(&small) == Equal);
@ -373,11 +374,11 @@ mod tests {
#[test]
fn test_show() {
let s = format!("{}", (1,));
let s = format!("{}", (1i,));
assert_eq!(s.as_slice(), "(1,)");
let s = format!("{}", (1, true));
let s = format!("{}", (1i, true));
assert_eq!(s.as_slice(), "(1, true)");
let s = format!("{}", (1, "hi", true));
let s = format!("{}", (1i, "hi", true));
assert_eq!(s.as_slice(), "(1, hi, true)");
}
}

View file

@ -116,14 +116,14 @@ mod tests {
fn test_flate_round_trip() {
let mut r = rand::task_rng();
let mut words = vec!();
for _ in range(0, 20) {
for _ in range(0u, 20) {
let range = r.gen_range(1u, 10);
let v = r.gen_iter::<u8>().take(range).collect::<Vec<u8>>();
words.push(v);
}
for _ in range(0, 20) {
for _ in range(0u, 20) {
let mut input = vec![];
for _ in range(0, 2000) {
for _ in range(0u, 2000) {
input.push_all(r.choose(words.as_slice()).unwrap().as_slice());
}
debug!("de/inflate of {} bytes of random word-sequences",

View file

@ -686,13 +686,13 @@ mod test {
fn test_range_pattern() {
let pat = Pattern::new("a[0-9]b");
for i in range(0, 10) {
for i in range(0u, 10) {
assert!(pat.matches(format!("a{}b", i).as_slice()));
}
assert!(!pat.matches("a_b"));
let pat = Pattern::new("a[!0-9]b");
for i in range(0, 10) {
for i in range(0u, 10) {
assert!(!pat.matches(format!("a{}b", i).as_slice()));
}
assert!(pat.matches("a_b"));

View file

@ -245,7 +245,7 @@ mod test {
event_loop_factory: basic::event_loop,
});
for _ in range(0, 20) {
for _ in range(0u, 20) {
pool.spawn(TaskOpts::new(), proc() {
let (tx, rx) = channel();
spawn(proc() {

View file

@ -1336,7 +1336,7 @@ mod test {
fn multithreading() {
run(proc() {
let mut rxs = vec![];
for _ in range(0, 10) {
for _ in range(0u, 10) {
let (tx, rx) = channel();
spawn(proc() {
tx.send(());
@ -1469,7 +1469,7 @@ mod test {
fn single_threaded_yield() {
use std::task::deschedule;
run(proc() {
for _ in range(0, 5) { deschedule(); }
for _ in range(0u, 5) { deschedule(); }
});
}
@ -1480,7 +1480,7 @@ mod test {
// Testing that a task in one scheduler can block in foreign code
// without affecting other schedulers
for _ in range(0, 20) {
for _ in range(0u, 20) {
let mut pool = pool();
let (start_tx, start_rx) = channel();
let (fin_tx, fin_rx) = channel();

View file

@ -536,7 +536,7 @@ mod tests {
fn yield_test() {
let (tx, rx) = channel();
spawn_opts(TaskOpts::new(), proc() {
for _ in range(0, 10) { task::deschedule(); }
for _ in range(0u, 10) { task::deschedule(); }
tx.send(());
});
rx.recv();

View file

@ -23,7 +23,7 @@ fn main() {
error!("this is printed by default");
if log_enabled!(log::INFO) {
let x = 3 * 4; // expensive computation
let x = 3i * 4i; // expensive computation
info!("the answer was: {}", x);
}
}

View file

@ -27,7 +27,7 @@
/// # fn main() {
/// log!(log::DEBUG, "this is a debug message");
/// log!(log::WARN, "this is a warning {}", "message");
/// log!(6, "this is a custom logging level: {level}", level=6);
/// log!(6, "this is a custom logging level: {level}", level=6u);
/// # }
/// ```
#[macro_export]
@ -54,7 +54,7 @@ macro_rules! log(
/// #[phase(plugin, link)] extern crate log;
///
/// # fn main() {
/// # let error = 3;
/// # let error = 3u;
/// error!("the build has failed with error code: {}", error);
/// # }
/// ```
@ -72,7 +72,7 @@ macro_rules! error(
/// #[phase(plugin, link)] extern crate log;
///
/// # fn main() {
/// # let code = 3;
/// # let code = 3u;
/// warn!("you may like to know that a process exited with: {}", code);
/// # }
/// ```
@ -90,7 +90,7 @@ macro_rules! warn(
/// #[phase(plugin, link)] extern crate log;
///
/// # fn main() {
/// # let ret = 3;
/// # let ret = 3i;
/// info!("this function is about to return: {}", ret);
/// # }
/// ```
@ -110,7 +110,7 @@ macro_rules! info(
/// #[phase(plugin, link)] extern crate log;
///
/// # fn main() {
/// debug!("x = {x}, y = {y}", x=10, y=20);
/// debug!("x = {x}, y = {y}", x=10i, y=20i);
/// # }
/// ```
#[macro_export]

View file

@ -93,7 +93,7 @@ mod select {
}
pub fn fd_set(set: &mut fd_set, fd: i32) {
set.fds_bits[(fd / 32) as uint] |= 1 << (fd % 32);
set.fds_bits[(fd / 32) as uint] |= 1 << ((fd % 32) as uint);
}
}

View file

@ -328,7 +328,7 @@ mod tests {
fn yield_test() {
let (tx, rx) = channel();
spawn(proc() {
for _ in range(0, 10) { task::deschedule(); }
for _ in range(0u, 10) { task::deschedule(); }
tx.send(());
});
rx.recv();

View file

@ -2172,7 +2172,7 @@ mod biguint_tests {
fn test_rand_range() {
let mut rng = task_rng();
for _ in range(0, 10) {
for _ in range(0u, 10) {
assert_eq!(rng.gen_bigint_range(&FromPrimitive::from_uint(236).unwrap(),
&FromPrimitive::from_uint(237).unwrap()),
FromPrimitive::from_uint(236).unwrap());
@ -2180,7 +2180,7 @@ mod biguint_tests {
let l = FromPrimitive::from_uint(403469000 + 2352).unwrap();
let u = FromPrimitive::from_uint(403469000 + 3513).unwrap();
for _ in range(0, 1000) {
for _ in range(0u, 1000) {
let n: BigUint = rng.gen_biguint_below(&u);
assert!(n < u);
@ -2761,7 +2761,7 @@ mod bigint_tests {
fn test_rand_range() {
let mut rng = task_rng();
for _ in range(0, 10) {
for _ in range(0u, 10) {
assert_eq!(rng.gen_bigint_range(&FromPrimitive::from_uint(236).unwrap(),
&FromPrimitive::from_uint(237).unwrap()),
FromPrimitive::from_uint(236).unwrap());
@ -2769,7 +2769,7 @@ mod bigint_tests {
fn check(l: BigInt, u: BigInt) {
let mut rng = task_rng();
for _ in range(0, 1000) {
for _ in range(0u, 1000) {
let n: BigInt = rng.gen_bigint_range(&l, &u);
assert!(n >= l);
assert!(n < u);
@ -2858,7 +2858,7 @@ mod bench {
let n = { let one : BigUint = One::one(); one << 1000 };
b.iter(|| {
let mut m = n.clone();
for _ in range(0, 10) {
for _ in range(0u, 10) {
m = m >> 1;
}
})

View file

@ -54,6 +54,8 @@
html_root_url = "http://doc.rust-lang.org/",
html_playground_url = "http://play.rust-lang.org/")]
#![allow(deprecated)] // from_str_radix
extern crate rand;
pub use bigint::{BigInt, BigUint};

View file

@ -353,10 +353,10 @@ mod test {
// check our constants are what Ratio::new etc. would make.
assert_eq!(_0, Zero::zero());
assert_eq!(_1, One::one());
assert_eq!(_2, Ratio::from_integer(2));
assert_eq!(_1_2, Ratio::new(1,2));
assert_eq!(_3_2, Ratio::new(3,2));
assert_eq!(_neg1_2, Ratio::new(-1,2));
assert_eq!(_2, Ratio::from_integer(2i));
assert_eq!(_1_2, Ratio::new(1i,2i));
assert_eq!(_3_2, Ratio::new(3i,2i));
assert_eq!(_neg1_2, Ratio::new(-1i,2i));
}
#[test]
@ -368,7 +368,7 @@ mod test {
#[test]
#[should_fail]
fn test_new_zero() {
let _a = Ratio::new(1,0);
let _a = Ratio::new(1i,0);
}
@ -466,8 +466,8 @@ mod test {
}
test(_1, _1_2, _1_2);
test(_1_2, _3_2, Ratio::new(3,4));
test(_1_2, _neg1_2, Ratio::new(-1, 4));
test(_1_2, _3_2, Ratio::new(3i,4i));
test(_1_2, _neg1_2, Ratio::new(-1i, 4i));
}
#[test]
@ -606,7 +606,7 @@ mod test {
test16(_2, "2/1".to_string());
test16(_neg1_2, "-1/2".to_string());
test16(_neg1_2 / _2, "-1/4".to_string());
test16(Ratio::new(13,15), "d/f".to_string());
test16(Ratio::new(13i,15i), "d/f".to_string());
test16(_1_2*_1_2*_1_2*_1_2, "1/10".to_string());
}
@ -645,7 +645,7 @@ mod test {
test(2f64.powf(100.), ("1267650600228229401496703205376", "1"));
test(-2f64.powf(100.), ("-1267650600228229401496703205376", "1"));
test(684729.48391f64, ("367611342500051", "536870912"));
test(-8573.5918555, ("-4713381968463931", "549755813888"));
test(-8573.5918555f64, ("-4713381968463931", "549755813888"));
test(1.0 / 2f64.powf(100.), ("1", "1267650600228229401496703205376"));
}

View file

@ -101,7 +101,7 @@ mod test {
fn test_exp() {
let mut exp = Exp::new(10.0);
let mut rng = ::test::rng();
for _ in range(0, 1000) {
for _ in range(0u, 1000) {
assert!(exp.sample(&mut rng) >= 0.0);
assert!(exp.ind_sample(&mut rng) >= 0.0);
}

View file

@ -327,7 +327,7 @@ mod test {
fn test_chi_squared_one() {
let mut chi = ChiSquared::new(1.0);
let mut rng = ::test::rng();
for _ in range(0, 1000) {
for _ in range(0u, 1000) {
chi.sample(&mut rng);
chi.ind_sample(&mut rng);
}
@ -336,7 +336,7 @@ mod test {
fn test_chi_squared_small() {
let mut chi = ChiSquared::new(0.5);
let mut rng = ::test::rng();
for _ in range(0, 1000) {
for _ in range(0u, 1000) {
chi.sample(&mut rng);
chi.ind_sample(&mut rng);
}
@ -345,7 +345,7 @@ mod test {
fn test_chi_squared_large() {
let mut chi = ChiSquared::new(30.0);
let mut rng = ::test::rng();
for _ in range(0, 1000) {
for _ in range(0u, 1000) {
chi.sample(&mut rng);
chi.ind_sample(&mut rng);
}
@ -360,7 +360,7 @@ mod test {
fn test_f() {
let mut f = FisherF::new(2.0, 32.0);
let mut rng = ::test::rng();
for _ in range(0, 1000) {
for _ in range(0u, 1000) {
f.sample(&mut rng);
f.ind_sample(&mut rng);
}
@ -370,7 +370,7 @@ mod test {
fn test_t() {
let mut t = StudentT::new(11.0);
let mut rng = ::test::rng();
for _ in range(0, 1000) {
for _ in range(0u, 1000) {
t.sample(&mut rng);
t.ind_sample(&mut rng);
}

View file

@ -101,7 +101,7 @@ pub struct Weighted<T> {
/// Weighted { weight: 1, item: 'c' });
/// let wc = WeightedChoice::new(items.as_mut_slice());
/// let mut rng = rand::task_rng();
/// for _ in range(0, 16) {
/// for _ in range(0u, 16) {
/// // on average prints 'a' 4 times, 'b' 8 and 'c' twice.
/// println!("{}", wc.ind_sample(&mut rng));
/// }
@ -308,36 +308,36 @@ mod tests {
}}
);
t!(vec!(Weighted { weight: 1, item: 10}), [10]);
t!(vec!(Weighted { weight: 1, item: 10i}), [10]);
// skip some
t!(vec!(Weighted { weight: 0, item: 20},
Weighted { weight: 2, item: 21},
Weighted { weight: 0, item: 22},
Weighted { weight: 1, item: 23}),
t!(vec!(Weighted { weight: 0, item: 20i},
Weighted { weight: 2, item: 21i},
Weighted { weight: 0, item: 22i},
Weighted { weight: 1, item: 23i}),
[21,21, 23]);
// different weights
t!(vec!(Weighted { weight: 4, item: 30},
Weighted { weight: 3, item: 31}),
t!(vec!(Weighted { weight: 4, item: 30i},
Weighted { weight: 3, item: 31i}),
[30,30,30,30, 31,31,31]);
// check that we're binary searching
// correctly with some vectors of odd
// length.
t!(vec!(Weighted { weight: 1, item: 40},
Weighted { weight: 1, item: 41},
Weighted { weight: 1, item: 42},
Weighted { weight: 1, item: 43},
Weighted { weight: 1, item: 44}),
t!(vec!(Weighted { weight: 1, item: 40i},
Weighted { weight: 1, item: 41i},
Weighted { weight: 1, item: 42i},
Weighted { weight: 1, item: 43i},
Weighted { weight: 1, item: 44i}),
[40, 41, 42, 43, 44]);
t!(vec!(Weighted { weight: 1, item: 50},
Weighted { weight: 1, item: 51},
Weighted { weight: 1, item: 52},
Weighted { weight: 1, item: 53},
Weighted { weight: 1, item: 54},
Weighted { weight: 1, item: 55},
Weighted { weight: 1, item: 56}),
t!(vec!(Weighted { weight: 1, item: 50i},
Weighted { weight: 1, item: 51i},
Weighted { weight: 1, item: 52i},
Weighted { weight: 1, item: 53i},
Weighted { weight: 1, item: 54i},
Weighted { weight: 1, item: 55i},
Weighted { weight: 1, item: 56i}),
[50, 51, 52, 53, 54, 55, 56]);
}
@ -347,15 +347,15 @@ mod tests {
}
#[test] #[should_fail]
fn test_weighted_choice_zero_weight() {
WeightedChoice::new(&mut [Weighted { weight: 0, item: 0},
Weighted { weight: 0, item: 1}]);
WeightedChoice::new(&mut [Weighted { weight: 0, item: 0i},
Weighted { weight: 0, item: 1i}]);
}
#[test] #[should_fail]
fn test_weighted_choice_weight_overflows() {
let x = (-1) as uint / 2; // x + x + 2 is the overflow
WeightedChoice::new(&mut [Weighted { weight: x, item: 0 },
Weighted { weight: 1, item: 1 },
Weighted { weight: x, item: 2 },
Weighted { weight: 1, item: 3 }]);
WeightedChoice::new(&mut [Weighted { weight: x, item: 0i },
Weighted { weight: 1, item: 1i },
Weighted { weight: x, item: 2i },
Weighted { weight: 1, item: 3i }]);
}
}

View file

@ -158,7 +158,7 @@ mod tests {
fn test_normal() {
let mut norm = Normal::new(10.0, 10.0);
let mut rng = ::test::rng();
for _ in range(0, 1000) {
for _ in range(0u, 1000) {
norm.sample(&mut rng);
norm.ind_sample(&mut rng);
}
@ -174,7 +174,7 @@ mod tests {
fn test_log_normal() {
let mut lnorm = LogNormal::new(10.0, 10.0);
let mut rng = ::test::rng();
for _ in range(0, 1000) {
for _ in range(0u, 1000) {
lnorm.sample(&mut rng);
lnorm.ind_sample(&mut rng);
}

View file

@ -42,7 +42,7 @@ use distributions::{Sample, IndependentSample};
/// let between = Range::new(10u, 10000u);
/// let mut rng = rand::task_rng();
/// let mut sum = 0;
/// for _ in range(0, 1000) {
/// for _ in range(0u, 1000) {
/// sum += between.ind_sample(&mut rng);
/// }
/// println!("{}", sum);
@ -172,12 +172,12 @@ mod tests {
#[should_fail]
#[test]
fn test_range_bad_limits_equal() {
Range::new(10, 10);
Range::new(10i, 10i);
}
#[should_fail]
#[test]
fn test_range_bad_limits_flipped() {
Range::new(10, 5);
Range::new(10i, 5i);
}
#[test]
@ -191,7 +191,7 @@ mod tests {
(Bounded::min_value(), Bounded::max_value())];
for &(low, high) in v.iter() {
let mut sampler: Range<$ty> = Range::new(low, high);
for _ in range(0, 1000) {
for _ in range(0u, 1000) {
let v = sampler.sample(&mut rng);
assert!(low <= v && v < high);
let v = sampler.ind_sample(&mut rng);
@ -217,7 +217,7 @@ mod tests {
(-1e35, 1e35)];
for &(low, high) in v.iter() {
let mut sampler: Range<$ty> = Range::new(low, high);
for _ in range(0, 1000) {
for _ in range(0u, 1000) {
let v = sampler.sample(&mut rng);
assert!(low <= v && v < high);
let v = sampler.ind_sample(&mut rng);

View file

@ -18,7 +18,8 @@ use core::mem;
use {Rng, SeedableRng, Rand};
static RAND_SIZE_LEN: u32 = 8;
static RAND_SIZE: u32 = 1 << RAND_SIZE_LEN;
static RAND_SIZE: u32 = 1 << (RAND_SIZE_LEN as uint);
static RAND_SIZE_UINT: uint = 1 << (RAND_SIZE_LEN as uint);
/// A random number generator that uses the ISAAC algorithm[1].
///
@ -31,16 +32,16 @@ static RAND_SIZE: u32 = 1 << RAND_SIZE_LEN;
/// generator*](http://www.burtleburtle.net/bob/rand/isaacafa.html)
pub struct IsaacRng {
cnt: u32,
rsl: [u32, .. RAND_SIZE],
mem: [u32, .. RAND_SIZE],
rsl: [u32, ..RAND_SIZE_UINT],
mem: [u32, ..RAND_SIZE_UINT],
a: u32,
b: u32,
c: u32
}
static EMPTY: IsaacRng = IsaacRng {
cnt: 0,
rsl: [0, .. RAND_SIZE],
mem: [0, .. RAND_SIZE],
rsl: [0, ..RAND_SIZE_UINT],
mem: [0, ..RAND_SIZE_UINT],
a: 0, b: 0, c: 0
};
@ -79,7 +80,9 @@ impl IsaacRng {
}}
);
for _ in range(0, 4) { mix!(); }
for _ in range(0u, 4) {
mix!();
}
if use_rsl {
macro_rules! memloop (
@ -115,32 +118,43 @@ impl IsaacRng {
/// Refills the output buffer (`self.rsl`)
#[inline]
#[allow(unsigned_negate)]
fn isaac(&mut self) {
self.c += 1;
// abbreviations
let mut a = self.a;
let mut b = self.b + self.c;
static MIDPOINT: uint = RAND_SIZE as uint / 2;
static MIDPOINT: uint = (RAND_SIZE / 2) as uint;
macro_rules! ind (($x:expr) => {
self.mem[(($x >> 2) & (RAND_SIZE - 1)) as uint]
self.mem[(($x >> 2) as uint & ((RAND_SIZE - 1) as uint))]
});
macro_rules! rngstep(
macro_rules! rngstepp(
($j:expr, $shift:expr) => {{
let base = $j;
let mix = if $shift < 0 {
a >> -$shift as uint
} else {
a << $shift as uint
};
let mix = a << $shift as uint;
let x = self.mem[base + mr_offset];
a = (a ^ mix) + self.mem[base + m2_offset];
let y = ind!(x) + a + b;
self.mem[base + mr_offset] = y;
b = ind!(y >> RAND_SIZE_LEN) + x;
b = ind!(y >> RAND_SIZE_LEN as uint) + x;
self.rsl[base + mr_offset] = b;
}}
);
macro_rules! rngstepn(
($j:expr, $shift:expr) => {{
let base = $j;
let mix = a >> $shift as uint;
let x = self.mem[base + mr_offset];
a = (a ^ mix) + self.mem[base + m2_offset];
let y = ind!(x) + a + b;
self.mem[base + mr_offset] = y;
b = ind!(y >> RAND_SIZE_LEN as uint) + x;
self.rsl[base + mr_offset] = b;
}}
);
@ -148,10 +162,10 @@ impl IsaacRng {
let r = [(0, MIDPOINT), (MIDPOINT, 0)];
for &(mr_offset, m2_offset) in r.iter() {
for i in range_step(0u, MIDPOINT, 4) {
rngstep!(i + 0, 13);
rngstep!(i + 1, -6);
rngstep!(i + 2, 2);
rngstep!(i + 3, -16);
rngstepp!(i + 0, 13);
rngstepn!(i + 1, 6);
rngstepp!(i + 2, 2);
rngstepn!(i + 3, 16);
}
}
@ -286,7 +300,10 @@ impl Isaac64Rng {
}}
);
for _ in range(0, 4) { mix!(); }
for _ in range(0u, 4) {
mix!();
}
if use_rsl {
macro_rules! memloop (
($arr:expr) => {{
@ -332,14 +349,27 @@ impl Isaac64Rng {
*self.mem.unsafe_ref(($x as uint >> 3) & (RAND_SIZE_64 - 1))
}
);
macro_rules! rngstep(
macro_rules! rngstepp(
($j:expr, $shift:expr) => {{
let base = base + $j;
let mix = a ^ (if $shift < 0 {
a >> -$shift as uint
} else {
a << $shift as uint
});
let mix = a ^ (a << $shift as uint);
let mix = if $j == 0 {!mix} else {mix};
unsafe {
let x = *self.mem.unsafe_ref(base + mr_offset);
a = mix + *self.mem.unsafe_ref(base + m2_offset);
let y = ind!(x) + a + b;
self.mem.unsafe_set(base + mr_offset, y);
b = ind!(y >> RAND_SIZE_64_LEN) + x;
self.rsl.unsafe_set(base + mr_offset, b);
}
}}
);
macro_rules! rngstepn(
($j:expr, $shift:expr) => {{
let base = base + $j;
let mix = a ^ (a >> $shift as uint);
let mix = if $j == 0 {!mix} else {mix};
unsafe {
@ -356,10 +386,10 @@ impl Isaac64Rng {
for &(mr_offset, m2_offset) in MP_VEC.iter() {
for base in range(0, MIDPOINT / 4).map(|i| i * 4) {
rngstep!(0, 21);
rngstep!(1, -5);
rngstep!(2, 12);
rngstep!(3, -33);
rngstepp!(0, 21);
rngstepn!(1, 5);
rngstepp!(2, 12);
rngstepn!(3, 33);
}
}
@ -515,7 +545,7 @@ mod test {
let seed = &[12345, 67890, 54321, 9876];
let mut rb: IsaacRng = SeedableRng::from_seed(seed);
// skip forward to the 10000th number
for _ in range(0, 10000) { rb.next_u32(); }
for _ in range(0u, 10000) { rb.next_u32(); }
let v = Vec::from_fn(10, |_| rb.next_u32());
assert_eq!(v,
@ -537,7 +567,7 @@ mod test {
let seed = &[12345, 67890, 54321, 9876];
let mut rb: Isaac64Rng = SeedableRng::from_seed(seed);
// skip forward to the 10000th number
for _ in range(0, 10000) { rb.next_u64(); }
for _ in range(0u, 10000) { rb.next_u64(); }
let v = Vec::from_fn(10, |_| rb.next_u64());
assert_eq!(v,

View file

@ -180,7 +180,7 @@ pub trait Rng {
/// let mut rng = task_rng();
/// let n: uint = rng.gen_range(0u, 10);
/// println!("{}", n);
/// let m: f64 = rng.gen_range(-40.0, 1.3e5);
/// let m: f64 = rng.gen_range(-40.0f64, 1.3e5f64);
/// println!("{}", m);
/// ```
fn gen_range<T: PartialOrd + SampleRange>(&mut self, low: T, high: T) -> T {
@ -225,7 +225,7 @@ pub trait Rng {
/// ```
/// use std::rand::{task_rng, Rng};
///
/// let choices = [1, 2, 4, 8, 16, 32];
/// let choices = [1i, 2, 4, 8, 16, 32];
/// let mut rng = task_rng();
/// println!("{}", rng.choose(choices));
/// assert_eq!(rng.choose(choices.slice_to(0)), None);
@ -252,7 +252,7 @@ pub trait Rng {
/// use std::rand::{task_rng, Rng};
///
/// let mut rng = task_rng();
/// let mut y = [1,2,3];
/// let mut y = [1i, 2, 3];
/// rng.shuffle(y);
/// println!("{}", y.as_slice());
/// rng.shuffle(y);

View file

@ -244,7 +244,7 @@ mod tests {
// this is unlikely to catch an incorrect implementation that
// generates exactly 0 or 1, but it keeps it sane.
let mut rng = task_rng();
for _ in range(0, 1_000) {
for _ in range(0u, 1_000) {
// strict inequalities
let Open01(f) = rng.gen::<Open01<f64>>();
assert!(0.0 < f && f < 1.0);
@ -257,7 +257,7 @@ mod tests {
#[test]
fn rand_closed() {
let mut rng = task_rng();
for _ in range(0, 1_000) {
for _ in range(0u, 1_000) {
// strict inequalities
let Closed01(f) = rng.gen::<Closed01<f64>>();
assert!(0.0 <= f && f <= 1.0);

View file

@ -184,7 +184,7 @@ mod test {
let mut rs = ReseedingRng::new(Counter {i:0}, 400, ReseedWithDefault);
let mut i = 0;
for _ in range(0, 1000) {
for _ in range(0u, 1000) {
assert_eq!(rs.next_u32(), i % 100);
i += 1;
}

View file

@ -1170,26 +1170,39 @@ fn link_args(cmd: &mut Command,
// The default library location, we need this to find the runtime.
// The location of crates will be determined as needed.
let lib_path = sess.target_filesearch().get_lib_path();
cmd.arg("-L").arg(lib_path);
cmd.arg("-L").arg(&lib_path);
cmd.arg("-o").arg(out_filename).arg(obj_filename);
// Stack growth requires statically linking a __morestack function. Note
// that this is listed *before* all other libraries, even though it may be
// used to resolve symbols in other libraries. The only case that this
// wouldn't be pulled in by the object file is if the object file had no
// functions.
// that this is listed *before* all other libraries. Due to the usage of the
// --as-needed flag below, the standard library may only be useful for its
// rust_stack_exhausted function. In this case, we must ensure that the
// libmorestack.a file appears *before* the standard library (so we put it
// at the very front).
//
// If we're building an executable, there must be at least one function (the
// main function), and if we're building a dylib then we don't need it for
// later libraries because they're all dylibs (not rlibs).
// Most of the time this is sufficient, except for when LLVM gets super
// clever. If, for example, we have a main function `fn main() {}`, LLVM
// will optimize out calls to `__morestack` entirely because the function
// doesn't need any stack at all!
//
// I'm honestly not entirely sure why this needs to come first. Apparently
// the --as-needed flag above sometimes strips out libstd from the command
// line, but inserting this farther to the left makes the
// "rust_stack_exhausted" symbol an outstanding undefined symbol, which
// flags libstd as a required library (or whatever provides the symbol).
cmd.arg("-lmorestack");
// To get around this snag, we specially tell the linker to always include
// all contents of this library. This way we're guaranteed that the linker
// will include the __morestack symbol 100% of the time, always resolving
// references to it even if the object above didn't use it.
match sess.targ_cfg.os {
abi::OsMacos | abi::OsiOS => {
let morestack = lib_path.join("libmorestack.a");
let mut v = "-Wl,-force_load,".as_bytes().to_owned();
v.push_all(morestack.as_vec());
cmd.arg(v.as_slice());
}
_ => {
cmd.args(["-Wl,--whole-archive", "-lmorestack",
"-Wl,--no-whole-archive"]);
}
}
// When linking a dynamic library, we put the metadata into a section of the
// executable. This metadata is in a separate object file from the main

View file

@ -100,7 +100,7 @@ impl Svh {
let hash = state.result();
return Svh {
hash: range_step(0, 64, 4).map(|i| hex(hash >> i)).collect()
hash: range_step(0u, 64u, 4u).map(|i| hex(hash >> i)).collect()
};
fn hex(b: u64) -> char {

View file

@ -544,7 +544,7 @@ pub fn optgroups() -> Vec<getopts::OptGroup> {
optmulti("F", "forbid", "Set lint forbidden", "OPT"),
optmulti("C", "codegen", "Set a codegen option", "OPT[=VALUE]"),
optmulti("Z", "", "Set internal debugging options", "FLAG"),
optflag("v", "version", "Print version info and exit"),
optflagopt("v", "version", "Print version info and exit", "verbose"),
optopt("", "color", "Configure coloring of output:
auto = colorize, if output goes to a tty (default);
always = always colorize output;

View file

@ -112,13 +112,24 @@ fn run_compiler(args: &[String]) {
driver::compile_input(sess, cfg, &input, &odir, &ofile);
}
pub fn version(command: &str) {
let vers = match option_env!("CFG_VERSION") {
Some(vers) => vers,
None => "unknown version"
/// Prints version information and returns None on success or an error
/// message on failure.
pub fn version(binary: &str, matches: &getopts::Matches) -> Option<String> {
let verbose = match matches.opt_str("version").as_ref().map(|s| s.as_slice()) {
None => false,
Some("verbose") => true,
Some(s) => return Some(format!("Unrecognized argument: {}", s))
};
println!("{} {}", command, vers);
println!("host: {}", driver::host_triple());
println!("{} {}", binary, env!("CFG_VERSION"));
if verbose {
println!("binary: {}", binary);
println!("commit-hash: {}", option_env!("CFG_VER_HASH").unwrap_or("unknown"));
println!("commit-date: {}", option_env!("CFG_VER_DATE").unwrap_or("unknown"));
println!("host: {}", driver::host_triple());
println!("release: {}", env!("CFG_RELEASE"));
}
None
}
fn usage() {
@ -268,9 +279,11 @@ pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
return None;
}
if matches.opt_present("v") || matches.opt_present("version") {
version("rustc");
return None;
if matches.opt_present("version") {
match version("rustc", &matches) {
Some(err) => early_error(err.as_slice()),
None => return None
}
}
Some(matches)

View file

@ -448,7 +448,7 @@ impl<'a> PluginMetadataReader<'a> {
macros: macros.move_iter().map(|x| x.to_string()).collect(),
registrar_symbol: registrar,
};
if should_link {
if should_link && existing_match(&self.env, &info.crate_id, None).is_none() {
// register crate now to avoid double-reading metadata
register_crate(&mut self.env, &None, info.ident.as_slice(),
&info.crate_id, krate.span, library);

View file

@ -347,7 +347,7 @@ impl<'a> Context<'a> {
fn extract_one(&mut self, m: HashSet<Path>, flavor: &str,
slot: &mut Option<MetadataBlob>) -> Option<Path> {
let mut ret = None::<Path>;
let mut error = 0;
let mut error = 0u;
if slot.is_some() {
// FIXME(#10786): for an optimization, we only read one of the

View file

@ -10,7 +10,7 @@
#![allow(non_camel_case_types)]
use middle::const_eval::{compare_const_vals, const_bool, const_float, const_val};
use middle::const_eval::{compare_const_vals, const_bool, const_float, const_nil, const_val};
use middle::const_eval::{eval_const_expr, lookup_const_by_id};
use middle::def::*;
use middle::pat_util::*;
@ -203,6 +203,7 @@ enum ctor {
fn const_val_to_expr(value: &const_val) -> Gc<Expr> {
let node = match value {
&const_bool(b) => LitBool(b),
&const_nil => LitNil,
_ => unreachable!()
};
box(GC) Expr {
@ -309,6 +310,9 @@ fn all_constructors(cx: &MatchCheckCtxt, m: &Matrix, left_ty: ty::t) -> Vec<ctor
ty::ty_bool =>
[true, false].iter().map(|b| val(const_bool(*b))).collect(),
ty::ty_nil =>
vec!(val(const_nil)),
ty::ty_rptr(_, ty::mt { ty: ty, .. }) => match ty::get(ty).sty {
ty::ty_vec(_, None) => vec_constructors(m),
_ => vec!(single)
@ -326,9 +330,6 @@ fn all_constructors(cx: &MatchCheckCtxt, m: &Matrix, left_ty: ty::t) -> Vec<ctor
ty::ty_vec(_, Some(n)) =>
vec!(vec(n)),
ty::ty_nil if !m.iter().all(|r| is_wild(cx, *r.get(0))) =>
vec!(),
_ =>
vec!(single)
}
@ -734,6 +735,7 @@ fn check_fn(cx: &mut MatchCheckCtxt,
},
None => ()
}
check_legality_of_move_bindings(cx, false, [input.pat]);
}
}

View file

@ -299,7 +299,8 @@ pub enum const_val {
const_uint(u64),
const_str(InternedString),
const_binary(Rc<Vec<u8> >),
const_bool(bool)
const_bool(bool),
const_nil
}
pub fn eval_const_expr(tcx: &ty::ctxt, e: &Expr) -> const_val {
@ -367,8 +368,8 @@ pub fn eval_const_expr_partial<T: ty::ExprTyProvider>(tcx: &T, e: &Expr)
BiAnd | BiBitAnd => Ok(const_int(a & b)),
BiOr | BiBitOr => Ok(const_int(a | b)),
BiBitXor => Ok(const_int(a ^ b)),
BiShl => Ok(const_int(a << b)),
BiShr => Ok(const_int(a >> b)),
BiShl => Ok(const_int(a << b as uint)),
BiShr => Ok(const_int(a >> b as uint)),
BiEq => fromb(a == b),
BiLt => fromb(a < b),
BiLe => fromb(a <= b),
@ -394,8 +395,8 @@ pub fn eval_const_expr_partial<T: ty::ExprTyProvider>(tcx: &T, e: &Expr)
BiAnd | BiBitAnd => Ok(const_uint(a & b)),
BiOr | BiBitOr => Ok(const_uint(a | b)),
BiBitXor => Ok(const_uint(a ^ b)),
BiShl => Ok(const_uint(a << b)),
BiShr => Ok(const_uint(a >> b)),
BiShl => Ok(const_uint(a << b as uint)),
BiShr => Ok(const_uint(a >> b as uint)),
BiEq => fromb(a == b),
BiLt => fromb(a < b),
BiLe => fromb(a <= b),
@ -407,15 +408,15 @@ pub fn eval_const_expr_partial<T: ty::ExprTyProvider>(tcx: &T, e: &Expr)
// shifts can have any integral type as their rhs
(Ok(const_int(a)), Ok(const_uint(b))) => {
match op {
BiShl => Ok(const_int(a << b)),
BiShr => Ok(const_int(a >> b)),
BiShl => Ok(const_int(a << b as uint)),
BiShr => Ok(const_int(a >> b as uint)),
_ => Err("can't do this op on an int and uint".to_string())
}
}
(Ok(const_uint(a)), Ok(const_int(b))) => {
match op {
BiShl => Ok(const_uint(a << b)),
BiShr => Ok(const_uint(a >> b)),
BiShl => Ok(const_uint(a << b as uint)),
BiShr => Ok(const_uint(a >> b as uint)),
_ => Err("can't do this op on a uint and int".to_string())
}
}
@ -514,7 +515,7 @@ pub fn lit_to_const(lit: &Lit) -> const_val {
LitFloat(ref n, _) | LitFloatUnsuffixed(ref n) => {
const_float(from_str::<f64>(n.get()).unwrap() as f64)
}
LitNil => const_int(0i64),
LitNil => const_nil,
LitBool(b) => const_bool(b)
}
}
@ -530,6 +531,7 @@ pub fn compare_const_vals(a: &const_val, b: &const_val) -> Option<int> {
(&const_str(ref a), &const_str(ref b)) => compare_vals(a, b),
(&const_bool(a), &const_bool(b)) => compare_vals(a, b),
(&const_binary(ref a), &const_binary(ref b)) => compare_vals(a, b),
(&const_nil, &const_nil) => compare_vals((), ()),
_ => None
}
}

View file

@ -595,7 +595,7 @@ fn set_bit(words: &mut [uint], bit: uint) -> bool {
fn bit_str(bit: uint) -> String {
let byte = bit >> 8;
let lobits = 1 << (bit & 0xFF);
let lobits = 1u << (bit & 0xFF);
format!("[{}:{}-{:02x}]", bit, byte, lobits)
}

View file

@ -1966,7 +1966,7 @@ impl<'a> Resolver<'a> {
/// Resolves all imports for the crate. This method performs the fixed-
/// point iteration.
fn resolve_imports(&mut self) {
let mut i = 0;
let mut i = 0u;
let mut prev_unresolved_imports = 0;
loop {
debug!("(resolving imports) iteration {}, {} imports left",

View file

@ -256,7 +256,7 @@ impl<'a> FmtStrs<'a> {
self.check_and_record(Variable,
span,
sub_span,
svec!(id, name, qualname, value, typ, 0));
svec!(id, name, qualname, value, typ, 0u));
}
// formal parameters
@ -271,7 +271,7 @@ impl<'a> FmtStrs<'a> {
self.check_and_record(Variable,
span,
sub_span,
svec!(id, name, qualname, "", typ, 0));
svec!(id, name, qualname, "", typ, 0u));
}
// value is the initialising expression of the static if it is not mut, otherwise "".
@ -474,7 +474,10 @@ impl<'a> FmtStrs<'a> {
self.check_and_record(Inheritance,
span,
sub_span,
svec!(base_id.node, base_id.krate, deriv_id, 0));
svec!(base_id.node,
base_id.krate,
deriv_id,
0u));
}
pub fn fn_call_str(&mut self,
@ -516,7 +519,7 @@ impl<'a> FmtStrs<'a> {
self.record_with_span(ModRef,
span,
sub_span,
svec!(0, 0, qualname, parent));
svec!(0u, 0u, qualname, parent));
}
pub fn typedef_str(&mut self,
@ -557,7 +560,7 @@ impl<'a> FmtStrs<'a> {
self.record_with_span(TypeRef,
span,
sub_span,
svec!(0, 0, qualname, 0));
svec!(0u, 0u, qualname, 0u));
}
// A slightly generic function for a reference to an item of any kind.

View file

@ -578,6 +578,7 @@ fn load_discr(bcx: &Block, ity: IntType, ptr: ValueRef, min: Disr, max: Disr)
assert_eq!(val_ty(ptr), llty.ptr_to());
let bits = machine::llbitsize_of_real(bcx.ccx(), llty);
assert!(bits <= 64);
let bits = bits as uint;
let mask = (-1u64 >> (64 - bits)) as Disr;
if (max + 1) & mask == min & mask {
// i.e., if the range is everything. The lo==hi case would be

View file

@ -2095,7 +2095,9 @@ impl EnumMemberDescriptionFactory {
let null_variant_index = (1 - non_null_variant_index) as uint;
let null_variant_ident = self.variants.get(null_variant_index).name;
let null_variant_name = token::get_ident(null_variant_ident);
let union_member_name = format!("RUST$ENCODED$ENUM${}${}", 0, null_variant_name);
let union_member_name = format!("RUST$ENCODED$ENUM${}${}",
0u,
null_variant_name);
// Finally create the (singleton) list of descriptions of union
// members.
@ -3150,7 +3152,7 @@ fn set_debug_location(cx: &CrateContext, debug_location: DebugLocation) {
match debug_location {
KnownLocation { scope, line, .. } => {
let col = 0; // Always set the column to zero like Clang and GCC
let col = 0u; // Always set the column to zero like Clang and GCC
debug!("setting debug location to {} {}", line, col);
let elements = [C_i32(cx, line as i32), C_i32(cx, col as i32), scope, ptr::null()];
unsafe {

View file

@ -610,7 +610,6 @@ fn trans_rvalue_stmt_unadjusted<'a>(bcx: &'a Block<'a>,
controlflow::trans_loop(bcx, expr.id, &**body)
}
ast::ExprAssign(ref dst, ref src) => {
let src_datum = unpack_datum!(bcx, trans(bcx, &**src));
let dst_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &**dst, "assign"));
if ty::type_needs_drop(bcx.tcx(), dst_datum.ty) {
@ -630,12 +629,13 @@ fn trans_rvalue_stmt_unadjusted<'a>(bcx: &'a Block<'a>,
//
// We could avoid this intermediary with some analysis
// to determine whether `dst` may possibly own `src`.
let src_datum = unpack_datum!(bcx, trans(bcx, &**src));
let src_datum = unpack_datum!(
bcx, src_datum.to_rvalue_datum(bcx, "ExprAssign"));
bcx = glue::drop_ty(bcx, dst_datum.val, dst_datum.ty);
src_datum.store_to(bcx, dst_datum.val)
} else {
src_datum.store_to(bcx, dst_datum.val)
trans_into(bcx, &**src, SaveIn(dst_datum.to_llref()))
}
}
ast::ExprAssignOp(op, ref dst, ref src) => {

View file

@ -4184,6 +4184,12 @@ pub fn eval_repeat_count<T: ExprTyProvider>(tcx: &T, count_expr: &ast::Expr) ->
repeat count but found binary array");
return 0;
}
const_eval::const_nil => {
tcx.ty_ctxt().sess.span_err(count_expr.span,
"expected positive integer for \
repeat count but found ()");
return 0;
}
},
Err(..) => {
tcx.ty_ctxt().sess.span_err(count_expr.span,

View file

@ -65,7 +65,9 @@ pub fn coerce(fcx: &FnCtxt, sp: Span, expected: ty::t, expr: &ast::Expr) {
expected.repr(fcx.ccx.tcx),
expr_ty.repr(fcx.ccx.tcx));
let expected = if ty::type_needs_infer(expected) {
resolve_type(fcx.infcx(), expected,
resolve_type(fcx.infcx(),
None,
expected,
try_resolve_tvar_shallow).unwrap_or(expected)
} else { expected };
match fcx.mk_assignty(expr, expr_ty, expected) {

View file

@ -169,6 +169,19 @@ pub struct Inherited<'a> {
upvar_borrow_map: RefCell<ty::UpvarBorrowMap>,
}
/// When type-checking an expression, we propagate downward
/// whatever type hint we are able in the form of an `Expectation`.
enum Expectation {
/// We know nothing about what type this expression should have.
NoExpectation,
/// This expression should have the type given (or some subtype)
ExpectHasType(ty::t),
/// This expression will be cast to the `ty::t`
ExpectCastableToType(ty::t),
}
#[deriving(Clone)]
pub struct FnStyleState {
pub def: ast::NodeId,
@ -492,7 +505,7 @@ fn check_fn<'a>(ccx: &'a CrateCtxt<'a>,
visit.visit_block(body, ());
}
check_block_with_expected(&fcx, body, Some(ret_ty));
check_block_with_expected(&fcx, body, ExpectHasType(ret_ty));
// We unify the tail expr's type with the
// function result type, if there is a tail expr.
@ -1708,7 +1721,11 @@ fn write_call(fcx: &FnCtxt, call_expr: &ast::Expr, output: ty::t) {
}
// AST fragment checking
pub fn check_lit(fcx: &FnCtxt, lit: &ast::Lit) -> ty::t {
fn check_lit(fcx: &FnCtxt,
lit: &ast::Lit,
expected: Expectation)
-> ty::t
{
let tcx = fcx.ccx.tcx;
match lit.node {
@ -1721,15 +1738,29 @@ pub fn check_lit(fcx: &FnCtxt, lit: &ast::Lit) -> ty::t {
ast::LitInt(_, t) => ty::mk_mach_int(t),
ast::LitUint(_, t) => ty::mk_mach_uint(t),
ast::LitIntUnsuffixed(_) => {
// An unsuffixed integer literal could have any integral type,
// so we create an integral type variable for it.
ty::mk_int_var(tcx, fcx.infcx().next_int_var_id())
let opt_ty = expected.map_to_option(fcx, |sty| {
match *sty {
ty::ty_int(i) => Some(ty::mk_mach_int(i)),
ty::ty_uint(i) => Some(ty::mk_mach_uint(i)),
ty::ty_char => Some(ty::mk_mach_uint(ast::TyU8)),
ty::ty_ptr(..) => Some(ty::mk_mach_uint(ast::TyU)),
ty::ty_bare_fn(..) => Some(ty::mk_mach_uint(ast::TyU)),
_ => None
}
});
opt_ty.unwrap_or_else(
|| ty::mk_int_var(tcx, fcx.infcx().next_int_var_id()))
}
ast::LitFloat(_, t) => ty::mk_mach_float(t),
ast::LitFloatUnsuffixed(_) => {
// An unsuffixed floating point literal could have any floating point
// type, so we create a floating point type variable for it.
ty::mk_float_var(tcx, fcx.infcx().next_float_var_id())
let opt_ty = expected.map_to_option(fcx, |sty| {
match *sty {
ty::ty_float(i) => Some(ty::mk_mach_float(i)),
_ => None
}
});
opt_ty.unwrap_or_else(
|| ty::mk_float_var(tcx, fcx.infcx().next_float_var_id()))
}
ast::LitNil => ty::mk_nil(),
ast::LitBool(_) => ty::mk_bool()
@ -1746,43 +1777,51 @@ pub fn valid_range_bounds(ccx: &CrateCtxt,
}
}
pub fn check_expr_has_type(
fcx: &FnCtxt, expr: &ast::Expr,
expected: ty::t) {
check_expr_with_unifier(fcx, expr, Some(expected), NoPreference, || {
demand::suptype(fcx, expr.span, expected, fcx.expr_ty(expr));
});
pub fn check_expr_has_type(fcx: &FnCtxt,
expr: &ast::Expr,
expected: ty::t) {
check_expr_with_unifier(
fcx, expr, ExpectHasType(expected), NoPreference,
|| demand::suptype(fcx, expr.span, expected, fcx.expr_ty(expr)));
}
fn check_expr_coercable_to_type(fcx: &FnCtxt, expr: &ast::Expr, expected: ty::t) {
check_expr_with_unifier(fcx, expr, Some(expected), NoPreference, || {
demand::coerce(fcx, expr.span, expected, expr)
});
fn check_expr_coercable_to_type(fcx: &FnCtxt,
expr: &ast::Expr,
expected: ty::t) {
check_expr_with_unifier(
fcx, expr, ExpectHasType(expected), NoPreference,
|| demand::coerce(fcx, expr.span, expected, expr));
}
fn check_expr_with_hint(fcx: &FnCtxt, expr: &ast::Expr, expected: ty::t) {
check_expr_with_unifier(fcx, expr, Some(expected), NoPreference, || ())
check_expr_with_unifier(
fcx, expr, ExpectHasType(expected), NoPreference,
|| ())
}
fn check_expr_with_opt_hint(fcx: &FnCtxt, expr: &ast::Expr,
expected: Option<ty::t>) {
check_expr_with_unifier(fcx, expr, expected, NoPreference, || ())
fn check_expr_with_expectation(fcx: &FnCtxt,
expr: &ast::Expr,
expected: Expectation) {
check_expr_with_unifier(
fcx, expr, expected, NoPreference,
|| ())
}
fn check_expr_with_opt_hint_and_lvalue_pref(fcx: &FnCtxt,
fn check_expr_with_expectation_and_lvalue_pref(fcx: &FnCtxt,
expr: &ast::Expr,
expected: Option<ty::t>,
lvalue_pref: LvaluePreference) {
expected: Expectation,
lvalue_pref: LvaluePreference)
{
check_expr_with_unifier(fcx, expr, expected, lvalue_pref, || ())
}
fn check_expr(fcx: &FnCtxt, expr: &ast::Expr) {
check_expr_with_unifier(fcx, expr, None, NoPreference, || ())
check_expr_with_unifier(fcx, expr, NoExpectation, NoPreference, || ())
}
fn check_expr_with_lvalue_pref(fcx: &FnCtxt, expr: &ast::Expr,
lvalue_pref: LvaluePreference) {
check_expr_with_unifier(fcx, expr, None, lvalue_pref, || ())
check_expr_with_unifier(fcx, expr, NoExpectation, lvalue_pref, || ())
}
@ -1863,9 +1902,10 @@ enum TupleArgumentsFlag {
/// `ty_bot`, so avoid that when err and bot need to be handled differently.
fn check_expr_with_unifier(fcx: &FnCtxt,
expr: &ast::Expr,
expected: Option<ty::t>,
expected: Expectation,
lvalue_pref: LvaluePreference,
unifier: ||) {
unifier: ||)
{
debug!(">> typechecking");
// A generic function for doing all of the checking for call expressions
@ -2001,14 +2041,27 @@ fn check_expr_with_unifier(fcx: &FnCtxt,
opt_else_expr: Option<Gc<ast::Expr>>,
id: ast::NodeId,
sp: Span,
expected: Option<ty::t>) {
expected: Expectation) {
check_expr_has_type(fcx, cond_expr, ty::mk_bool());
let branches_ty = match opt_else_expr {
Some(ref else_expr) => {
// Disregard "castable to" expectations because they
// can lead us astray. Consider for example `if cond
// {22} else {c} as u8` -- if we propagate the
// "castable to u8" constraint to 22, it will pick the
// type 22u8, which is overly constrained (c might not
// be a u8). In effect, the problem is that the
// "castable to" expectation is not the tightest thing
// we can say, so we want to drop it in this case.
// The tightest thing we can say is "must unify with
// else branch". Note that in the case of a "has type"
// constraint, this limitation does not hold.
let expected = expected.only_has_type();
check_block_with_expected(fcx, then_blk, expected);
let then_ty = fcx.node_ty(then_blk.id);
check_expr_with_opt_hint(fcx, &**else_expr, expected);
check_expr_with_expectation(fcx, &**else_expr, expected);
let else_ty = fcx.expr_ty(&**else_expr);
infer::common_supertype(fcx.infcx(),
infer::IfExpression(sp),
@ -2101,10 +2154,8 @@ fn check_expr_with_unifier(fcx: &FnCtxt,
fcx.expr_ty(&*lhs));
if ty::type_is_integral(lhs_t) && ast_util::is_shift_binop(op) {
// Shift is a special case: rhs can be any integral type
check_expr(fcx, &*rhs);
let rhs_t = fcx.expr_ty(&*rhs);
require_integral(fcx, rhs.span, rhs_t);
// Shift is a special case: rhs must be uint, no matter what lhs is
check_expr_has_type(fcx, rhs, ty::mk_uint());
fcx.write_ty(expr.id, lhs_t);
return;
}
@ -2243,40 +2294,18 @@ fn check_expr_with_unifier(fcx: &FnCtxt,
})
}
// Resolves `expected` by a single level if it is a variable and passes it
// through the `unpack` function. It there is no expected type or
// resolution is not possible (e.g., no constraints yet present), just
// returns `none`.
fn unpack_expected<O>(
fcx: &FnCtxt,
expected: Option<ty::t>,
unpack: |&ty::sty| -> Option<O>)
-> Option<O> {
match expected {
Some(t) => {
match resolve_type(fcx.infcx(), t, force_tvar) {
Ok(t) => unpack(&ty::get(t).sty),
_ => None
}
}
_ => None
}
}
fn check_expr_fn(fcx: &FnCtxt,
expr: &ast::Expr,
store: ty::TraitStore,
decl: &ast::FnDecl,
body: ast::P<ast::Block>,
expected: Option<ty::t>) {
expected: Expectation) {
let tcx = fcx.ccx.tcx;
// Find the expected input/output types (if any). Substitute
// fresh bound regions for any bound regions we find in the
// expected types so as to avoid capture.
let expected_sty = unpack_expected(fcx,
expected,
|x| Some((*x).clone()));
let expected_sty = expected.map_to_option(fcx, |x| Some((*x).clone()));
let (expected_sig,
expected_onceness,
expected_bounds) = {
@ -2696,8 +2725,8 @@ fn check_expr_with_unifier(fcx: &FnCtxt,
}
}
ast::ExprLit(ref lit) => {
let typ = check_lit(fcx, &**lit);
ast::ExprLit(lit) => {
let typ = check_lit(fcx, lit, expected);
fcx.write_ty(id, typ);
}
ast::ExprBinary(op, ref lhs, ref rhs) => {
@ -2735,21 +2764,31 @@ fn check_expr_with_unifier(fcx: &FnCtxt,
}
}
ast::ExprUnary(unop, ref oprnd) => {
let exp_inner = unpack_expected(fcx, expected, |sty| {
let expected = expected.only_has_type();
let expected_inner = expected.map(fcx, |sty| {
match unop {
ast::UnBox | ast::UnUniq => match *sty {
ty::ty_box(ty) | ty::ty_uniq(ty) => Some(ty),
_ => None
ty::ty_box(ty) | ty::ty_uniq(ty) => {
ExpectHasType(ty)
}
_ => {
NoExpectation
}
},
ast::UnNot | ast::UnNeg => expected,
ast::UnDeref => None
ast::UnNot | ast::UnNeg => {
expected
}
ast::UnDeref => {
NoExpectation
}
}
});
let lvalue_pref = match unop {
ast::UnDeref => lvalue_pref,
_ => NoPreference
};
check_expr_with_opt_hint_and_lvalue_pref(fcx, &**oprnd, exp_inner, lvalue_pref);
check_expr_with_expectation_and_lvalue_pref(
fcx, &**oprnd, expected_inner, lvalue_pref);
let mut oprnd_t = fcx.expr_ty(&**oprnd);
if !ty::type_is_error(oprnd_t) && !ty::type_is_bot(oprnd_t) {
match unop {
@ -2818,15 +2857,19 @@ fn check_expr_with_unifier(fcx: &FnCtxt,
fcx.write_ty(id, oprnd_t);
}
ast::ExprAddrOf(mutbl, ref oprnd) => {
let hint = unpack_expected(
fcx, expected,
|sty| match *sty { ty::ty_rptr(_, ref mt) => Some(mt.ty),
_ => None });
let expected = expected.only_has_type();
let hint = expected.map(fcx, |sty| {
match *sty { ty::ty_rptr(_, ref mt) => ExpectHasType(mt.ty),
_ => NoExpectation }
});
let lvalue_pref = match mutbl {
ast::MutMutable => PreferMutLvalue,
ast::MutImmutable => NoPreference
};
check_expr_with_opt_hint_and_lvalue_pref(fcx, &**oprnd, hint, lvalue_pref);
check_expr_with_expectation_and_lvalue_pref(fcx,
&**oprnd,
hint,
lvalue_pref);
// Note: at this point, we cannot say what the best lifetime
// is to use for resulting pointer. We want to use the
@ -2890,9 +2933,9 @@ fn check_expr_with_unifier(fcx: &FnCtxt,
}
fcx.write_bot(id);
}
ast::ExprParen(ref a) => {
check_expr_with_opt_hint_and_lvalue_pref(fcx, &**a, expected, lvalue_pref);
fcx.write_ty(id, fcx.expr_ty(&**a));
ast::ExprParen(a) => {
check_expr_with_expectation_and_lvalue_pref(fcx, a, expected, lvalue_pref);
fcx.write_ty(id, fcx.expr_ty(a));
}
ast::ExprAssign(ref lhs, ref rhs) => {
check_expr_with_lvalue_pref(fcx, &**lhs, PreferMutLvalue);
@ -3006,133 +3049,11 @@ fn check_expr_with_unifier(fcx: &FnCtxt,
fcx.write_bot(id);
}
}
ast::ExprCast(ref e, ref t) => {
check_expr(fcx, &**e);
let t_1 = fcx.to_ty(&**t);
let t_e = fcx.expr_ty(&**e);
debug!("t_1={}", fcx.infcx().ty_to_str(t_1));
debug!("t_e={}", fcx.infcx().ty_to_str(t_e));
if ty::type_is_error(t_e) {
fcx.write_error(id);
}
else if ty::type_is_bot(t_e) {
fcx.write_bot(id);
}
else {
match ty::get(t_1).sty {
// This will be looked up later on
_ if ty::type_is_trait(t_1) => {},
_ => {
let t_1 = structurally_resolved_type(fcx, e.span, t_1);
let t_e = structurally_resolved_type(fcx, e.span, t_e);
if ty::type_is_nil(t_e) {
fcx.type_error_message(expr.span, |actual| {
format!("cast from nil: `{}` as `{}`",
actual,
fcx.infcx().ty_to_str(t_1))
}, t_e, None);
} else if ty::type_is_nil(t_1) {
fcx.type_error_message(expr.span, |actual| {
format!("cast to nil: `{}` as `{}`",
actual,
fcx.infcx().ty_to_str(t_1))
}, t_e, None);
}
let t_1_is_scalar = ty::type_is_scalar(t_1);
let t_1_is_char = ty::type_is_char(t_1);
let t_1_is_bare_fn = ty::type_is_bare_fn(t_1);
let t_1_is_float = ty::type_is_floating_point(t_1);
// casts to scalars other than `char` and `bare fn` are trivial
let t_1_is_trivial = t_1_is_scalar && !t_1_is_char && !t_1_is_bare_fn;
if ty::type_is_c_like_enum(fcx.tcx(), t_e) && t_1_is_trivial {
if t_1_is_float {
fcx.type_error_message(expr.span, |actual| {
format!("illegal cast; cast through an \
integer first: `{}` as `{}`",
actual,
fcx.infcx().ty_to_str(t_1))
}, t_e, None);
}
// casts from C-like enums are allowed
} else if t_1_is_char {
let t_e = fcx.infcx().resolve_type_vars_if_possible(t_e);
if ty::get(t_e).sty != ty::ty_uint(ast::TyU8) {
fcx.type_error_message(expr.span, |actual| {
format!("only `u8` can be cast as \
`char`, not `{}`", actual)
}, t_e, None);
}
} else if ty::get(t_1).sty == ty::ty_bool {
fcx.tcx()
.sess
.span_err(expr.span,
"cannot cast as `bool`, compare with \
zero instead");
} else if ty::type_is_region_ptr(t_e) && ty::type_is_unsafe_ptr(t_1) {
fn is_vec(t: ty::t) -> bool {
match ty::get(t).sty {
ty::ty_vec(..) => true,
ty::ty_ptr(ty::mt{ty: t, ..}) | ty::ty_rptr(_, ty::mt{ty: t, ..}) |
ty::ty_box(t) | ty::ty_uniq(t) => match ty::get(t).sty {
ty::ty_vec(_, None) => true,
_ => false,
},
_ => false
}
}
fn types_compatible(fcx: &FnCtxt, sp: Span,
t1: ty::t, t2: ty::t) -> bool {
if !is_vec(t1) {
false
} else {
let el = ty::sequence_element_type(fcx.tcx(),
t1);
infer::mk_eqty(fcx.infcx(), false,
infer::Misc(sp), el, t2).is_ok()
}
}
// Due to the limitations of LLVM global constants,
// region pointers end up pointing at copies of
// vector elements instead of the original values.
// To allow unsafe pointers to work correctly, we
// need to special-case obtaining an unsafe pointer
// from a region pointer to a vector.
/* this cast is only allowed from &[T] to *T or
&T to *T. */
match (&ty::get(t_e).sty, &ty::get(t_1).sty) {
(&ty::ty_rptr(_, ty::mt { ty: mt1, mutbl: ast::MutImmutable }),
&ty::ty_ptr(ty::mt { ty: mt2, mutbl: ast::MutImmutable }))
if types_compatible(fcx, e.span, mt1, mt2) => {
/* this case is allowed */
}
_ => {
demand::coerce(fcx, e.span, t_1, &**e);
}
}
} else if !(ty::type_is_scalar(t_e) && t_1_is_trivial) {
/*
If more type combinations should be supported than are
supported here, then file an enhancement issue and
record the issue number in this comment.
*/
fcx.type_error_message(expr.span, |actual| {
format!("non-scalar cast: `{}` as `{}`",
actual,
fcx.infcx().ty_to_str(t_1))
}, t_e, None);
}
}
}
fcx.write_ty(id, t_1);
}
ast::ExprCast(expr_from, t) => {
let ty_to = fcx.to_ty(t);
debug!("ExprCast ty_to={}", fcx.infcx().ty_to_str(ty_to));
check_cast(fcx, expr_from, ty_to);
fcx.write_ty(id, ty_to);
}
ast::ExprVec(ref args) => {
let t: ty::t = fcx.infcx().next_ty_var();
@ -3144,7 +3065,7 @@ fn check_expr_with_unifier(fcx: &FnCtxt,
fcx.write_ty(id, typ);
}
ast::ExprRepeat(ref element, ref count_expr) => {
check_expr_with_hint(fcx, &**count_expr, ty::mk_uint());
check_expr_has_type(fcx, &**count_expr, ty::mk_uint());
let count = ty::eval_repeat_count(fcx, &**count_expr);
let t: ty::t = fcx.infcx().next_ty_var();
check_expr_has_type(fcx, &**element, t);
@ -3162,7 +3083,8 @@ fn check_expr_with_unifier(fcx: &FnCtxt,
}
}
ast::ExprTup(ref elts) => {
let flds = unpack_expected(fcx, expected, |sty| {
let expected = expected.only_has_type();
let flds = expected.map_to_option(fcx, |sty| {
match *sty {
ty::ty_tup(ref flds) => Some((*flds).clone()),
_ => None
@ -3173,11 +3095,11 @@ fn check_expr_with_unifier(fcx: &FnCtxt,
let elt_ts = elts.iter().enumerate().map(|(i, e)| {
let opt_hint = match flds {
Some(ref fs) if i < fs.len() => Some(*fs.get(i)),
_ => None
Some(ref fs) if i < fs.len() => ExpectHasType(*fs.get(i)),
_ => NoExpectation
};
check_expr_with_opt_hint(fcx, &**e, opt_hint);
let t = fcx.expr_ty(&**e);
check_expr_with_expectation(fcx, *e, opt_hint);
let t = fcx.expr_ty(*e);
err_field = err_field || ty::type_is_error(t);
bot_field = bot_field || ty::type_is_bot(t);
t
@ -3263,14 +3185,193 @@ fn check_expr_with_unifier(fcx: &FnCtxt,
syntax::print::pprust::expr_to_str(expr));
debug!("... {}, expected is {}",
ppaux::ty_to_str(tcx, fcx.expr_ty(expr)),
match expected {
Some(t) => ppaux::ty_to_str(tcx, t),
_ => "empty".to_string()
});
expected.repr(tcx))
unifier();
}
impl Expectation {
fn only_has_type(self) -> Expectation {
match self {
NoExpectation | ExpectCastableToType(..) => NoExpectation,
ExpectHasType(t) => ExpectHasType(t)
}
}
// Resolves `expected` by a single level if it is a variable. If
// there is no expected type or resolution is not possible (e.g.,
// no constraints yet present), just returns `None`.
fn resolve(self, fcx: &FnCtxt) -> Expectation {
match self {
NoExpectation => {
NoExpectation
}
ExpectCastableToType(t) => {
ExpectCastableToType(
fcx.infcx().resolve_type_vars_if_possible(t))
}
ExpectHasType(t) => {
ExpectHasType(
fcx.infcx().resolve_type_vars_if_possible(t))
}
}
}
fn map(self, fcx: &FnCtxt, unpack: |&ty::sty| -> Expectation) -> Expectation {
match self.resolve(fcx) {
NoExpectation => NoExpectation,
ExpectCastableToType(t) | ExpectHasType(t) => unpack(&ty::get(t).sty),
}
}
fn map_to_option<O>(self,
fcx: &FnCtxt,
unpack: |&ty::sty| -> Option<O>)
-> Option<O>
{
match self.resolve(fcx) {
NoExpectation => None,
ExpectCastableToType(t) | ExpectHasType(t) => unpack(&ty::get(t).sty),
}
}
}
impl Repr for Expectation {
fn repr(&self, tcx: &ty::ctxt) -> String {
match *self {
NoExpectation => format!("NoExpectation"),
ExpectHasType(t) => format!("ExpectHasType({})",
t.repr(tcx)),
ExpectCastableToType(t) => format!("ExpectCastableToType({})",
t.repr(tcx)),
}
}
}
fn check_cast(fcx: &FnCtxt, expr_from: Gc<ast::Expr>, ty_to: ty::t) {
// Find the type of `expr_from`. Supply hints based on the type
// we are casting to, if appropriate.
let ty_to = structurally_resolved_type(fcx, expr_from.span, ty_to);
if ty::type_is_scalar(ty_to) {
// Supply the type as a hint so as to influence integer
// literals and other things that might care.
check_expr_with_hint(fcx, expr_from, ty_to)
} else {
check_expr(fcx, expr_from)
}
let ty_from = fcx.expr_ty(expr_from);
// Object creation is checked during the vtable phase.
if ty::type_is_trait(ty_to) {
check_expr(fcx, expr_from);
return;
}
let ty_from = fcx.infcx().resolve_type_vars_if_possible(ty_from);
if ty::type_is_nil(ty_from) {
fcx.type_error_message(expr_from.span, |actual| {
format!("cast from nil: `{}` as `{}`", actual,
fcx.infcx().ty_to_str(ty_to))
}, ty_from, None);
return;
}
if ty::type_is_nil(ty_to) {
fcx.type_error_message(expr_from.span, |actual| {
format!("cast to nil: `{}` as `{}`", actual,
fcx.infcx().ty_to_str(ty_to))
}, ty_from, None);
return;
}
let t_e = structurally_resolved_type(fcx, expr_from.span, ty_from);
let t_1 = structurally_resolved_type(fcx, expr_from.span, ty_to);
let to_is_scalar = ty::type_is_scalar(t_1);
let to_is_float = ty::type_is_floating_point(t_1);
let to_is_char = ty::type_is_char(t_1);
let to_is_bare_fn = ty::type_is_bare_fn(t_1);
// casts to scalars other than `char` and `bare fn` are trivial
let to_is_trivial = to_is_scalar &&
!to_is_char && !to_is_bare_fn;
if ty::type_is_c_like_enum(fcx.tcx(), t_e) && to_is_trivial {
if to_is_float {
fcx.type_error_message(expr_from.span, |actual| {
format!("illegal cast; cast through an integer first: `{}` \
as `{}`",
actual,
fcx.infcx().ty_to_str(t_1))
}, ty_from, None);
}
// casts from C-like enums are allowed
} else if to_is_char {
if ty::get(ty_from).sty != ty::ty_uint(ast::TyU8) {
fcx.type_error_message(expr_from.span, |actual| {
format!("only `u8` can be cast as `char`, not `{}`", actual)
}, ty_from, None);
}
} else if ty::type_is_bool(t_1) {
fcx.tcx().sess.span_err(expr_from.span,
"cannot cast as `bool`, compare with zero instead");
} else if ty::type_is_region_ptr(t_e) && ty::type_is_unsafe_ptr(t_1) {
fn is_vec(t: ty::t) -> bool {
match ty::get(t).sty {
ty::ty_vec(..) => true,
ty::ty_ptr(ty::mt{ty: t, ..}) |
ty::ty_rptr(_, ty::mt{ty: t, ..}) |
ty::ty_box(t) |
ty::ty_uniq(t) => match ty::get(t).sty {
ty::ty_vec(_, None) => true,
_ => false,
},
_ => false
}
}
fn types_compatible(fcx: &FnCtxt, sp: Span,
t1: ty::t, t2: ty::t) -> bool {
if !is_vec(t1) {
false
} else {
let el = ty::sequence_element_type(fcx.tcx(),
t1);
infer::mk_eqty(fcx.infcx(), false,
infer::Misc(sp), el, t2).is_ok()
}
}
// Due to the limitations of LLVM global constants,
// region pointers end up pointing at copies of
// vector elements instead of the original values.
// To allow unsafe pointers to work correctly, we
// need to special-case obtaining an unsafe pointer
// from a region pointer to a vector.
/* this cast is only allowed from &[T] to *T or
&T to *T. */
match (&ty::get(t_e).sty, &ty::get(t_1).sty) {
(&ty::ty_rptr(_, ty::mt { ty: mt1, mutbl: ast::MutImmutable }),
&ty::ty_ptr(ty::mt { ty: mt2, mutbl: ast::MutImmutable }))
if types_compatible(fcx, expr_from.span, mt1, mt2) => {
/* this case is allowed */
}
_ => {
demand::coerce(fcx, expr_from.span, ty_to, expr_from);
}
}
} else if !(ty::type_is_scalar(t_e) && to_is_trivial) {
// If more type combinations should be supported than are
// supported here, then file an enhancement issue and
// record the issue number in this comment.
fcx.type_error_message(expr_from.span, |actual| {
format!("non-scalar cast: `{}` as `{}`", actual,
fcx.infcx().ty_to_str(ty_to))
}, ty_from, None);
}
}
pub fn require_uint(fcx: &FnCtxt, sp: Span, t: ty::t) {
if !type_is_uint(fcx, sp, t) {
fcx.type_error_message(sp, |actual| {
@ -3371,7 +3472,7 @@ pub fn check_stmt(fcx: &FnCtxt, stmt: &ast::Stmt) {
}
pub fn check_block_no_value(fcx: &FnCtxt, blk: &ast::Block) {
check_block_with_expected(fcx, blk, Some(ty::mk_nil()));
check_block_with_expected(fcx, blk, ExpectHasType(ty::mk_nil()));
let blkty = fcx.node_ty(blk.id);
if ty::type_is_error(blkty) {
fcx.write_error(blk.id);
@ -3385,9 +3486,9 @@ pub fn check_block_no_value(fcx: &FnCtxt, blk: &ast::Block) {
}
}
pub fn check_block_with_expected(fcx: &FnCtxt,
blk: &ast::Block,
expected: Option<ty::t>) {
fn check_block_with_expected(fcx: &FnCtxt,
blk: &ast::Block,
expected: Expectation) {
let prev = {
let mut fcx_ps = fcx.ps.borrow_mut();
let fn_style_state = fcx_ps.recurse(blk);
@ -3448,8 +3549,8 @@ pub fn check_block_with_expected(fcx: &FnCtxt,
e.span,
"unreachable expression".to_string());
}
check_expr_with_opt_hint(fcx, &*e, expected);
let ety = fcx.expr_ty(&*e);
check_expr_with_expectation(fcx, e, expected);
let ety = fcx.expr_ty(e);
fcx.write_ty(blk.id, ety);
if any_err {
fcx.write_error(blk.id);
@ -4170,7 +4271,7 @@ pub fn instantiate_path(fcx: &FnCtxt,
// Resolves `typ` by a single level if `typ` is a type variable. If no
// resolution is possible, then an error is reported.
pub fn structurally_resolved_type(fcx: &FnCtxt, sp: Span, tp: ty::t) -> ty::t {
match infer::resolve_type(fcx.infcx(), tp, force_tvar) {
match infer::resolve_type(fcx.infcx(), Some(sp), tp, force_tvar) {
Ok(t_s) if !ty::type_is_ty_var(t_s) => t_s,
_ => {
fcx.type_error_message(sp, |_actual| {

View file

@ -228,7 +228,7 @@ impl<'a> Rcx<'a> {
* bigger than the let and the `*b` expression, so we will
* effectively resolve `<R0>` to be the block B.
*/
match resolve_type(self.fcx.infcx(), unresolved_ty,
match resolve_type(self.fcx.infcx(), None, unresolved_ty,
resolve_and_force_all_but_regions) {
Ok(t) => t,
Err(_) => ty::mk_err()

View file

@ -481,7 +481,7 @@ fn fixup_ty(vcx: &VtableContext,
is_early: bool)
-> Option<ty::t> {
let tcx = vcx.tcx();
match resolve_type(vcx.infcx, ty, resolve_and_force_all_but_regions) {
match resolve_type(vcx.infcx, Some(span), ty, resolve_and_force_all_but_regions) {
Ok(new_type) => Some(new_type),
Err(e) if !is_early => {
tcx.sess.span_fatal(span,

View file

@ -456,7 +456,7 @@ impl<'cx> TypeFolder for Resolver<'cx> {
return t;
}
match resolve_type(self.infcx, t, resolve_all | force_all) {
match resolve_type(self.infcx, None, t, resolve_all | force_all) {
Ok(t) => t,
Err(e) => {
self.report_error(e);

View file

@ -61,6 +61,7 @@ fn get_base_type(inference_context: &InferCtxt,
-> Option<t> {
let resolved_type;
match resolve_type(inference_context,
Some(span),
original_type,
resolve_ivar) {
Ok(resulting_type) if !type_is_ty_var(resulting_type) => {

View file

@ -213,7 +213,8 @@ impl<'f> Coerce<'f> {
pub fn unpack_actual_value(&self, a: ty::t, f: |&ty::sty| -> CoerceResult)
-> CoerceResult {
match resolve_type(self.get_ref().infcx, a, try_resolve_tvar_shallow) {
match resolve_type(self.get_ref().infcx, None,
a, try_resolve_tvar_shallow) {
Ok(t) => {
f(&ty::get(t).sty)
}

Some files were not shown because too many files have changed in this diff Show more