diff options
| author | bors <bors@rust-lang.org> | 2015-07-22 16:58:56 +0000 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2015-07-22 16:58:56 +0000 |
| commit | 55428306657c5b42a26183c90fcd06e1ee7b94f5 (patch) | |
| tree | 73fa8e52bdc282916ff8836ec93d7f65229042c2 | |
| parent | d4d4206e5604b86fc4a9b28a8b51d99121cc3a5d (diff) | |
| parent | 5f04b1b384204bfad1e1e582b36ef99c78c5cc19 (diff) | |
Auto merge of #27219 - steveklabnik:rollup, r=steveklabnik
- Successful merges: #27084, #27127, #27131, #27140, #27146, #27147, #27151, #27154, #27155, #27156, #27157, #27158, #27163, #27164, #27166, #27167, #27170, #27175, #27183, #27201, #27202 - Failed merges: #26778
| -rw-r--r-- | src/doc/trpl/ffi.md | 8 | ||||
| -rw-r--r-- | src/doc/trpl/installing-rust.md | 15 | ||||
| -rw-r--r-- | src/doc/trpl/release-channels.md | 23 | ||||
| -rw-r--r-- | src/doc/trpl/unsafe.md | 10 | ||||
| -rw-r--r-- | src/libcore/iter.rs | 8 | ||||
| -rw-r--r-- | src/librustc/middle/intrinsicck.rs | 2 | ||||
| -rw-r--r-- | src/librustc_resolve/diagnostics.rs | 164 | ||||
| -rw-r--r-- | src/librustc_typeck/diagnostics.rs | 28 | ||||
| -rw-r--r-- | src/libstd/io/buffered.rs | 299 | ||||
| -rw-r--r-- | src/libstd/io/cursor.rs | 149 | ||||
| -rw-r--r-- | src/libstd/io/mod.rs | 49 | ||||
| -rw-r--r-- | src/libstd/io/util.rs | 17 | ||||
| -rw-r--r-- | src/test/compile-fail/issue-20162.rs | 17 | ||||
| -rw-r--r-- | src/test/compile-fail/issue-21174.rs | 2 | ||||
| -rw-r--r-- | src/test/run-pass/issue-10436.rs | 20 | ||||
| -rw-r--r-- | src/test/run-pass/issue-14229.rs | 30 | ||||
| -rw-r--r-- | src/test/run-pass/issue-14382.rs | 24 | ||||
| -rw-r--r-- | src/test/run-pass/issue-19404.rs | 47 | ||||
| -rw-r--r-- | src/test/run-pass/issue-26468.rs | 38 |
19 files changed, 893 insertions, 57 deletions
diff --git a/src/doc/trpl/ffi.md b/src/doc/trpl/ffi.md index cbedf863714..753a5a32e8a 100644 --- a/src/doc/trpl/ffi.md +++ b/src/doc/trpl/ffi.md @@ -340,7 +340,7 @@ libraries: Note that frameworks are only available on OSX targets. The different `kind` values are meant to differentiate how the native library -participates in linkage. From a linkage perspective, the rust compiler creates +participates in linkage. From a linkage perspective, the Rust compiler creates two flavors of artifacts: partial (rlib/staticlib) and final (dylib/binary). Native dynamic library and framework dependencies are propagated to the final artifact boundary, while static library dependencies are not propagated at @@ -350,9 +350,9 @@ artifact. A few examples of how this model can be used are: * A native build dependency. Sometimes some C/C++ glue is needed when writing - some rust code, but distribution of the C/C++ code in a library format is just + some Rust code, but distribution of the C/C++ code in a library format is just a burden. In this case, the code will be archived into `libfoo.a` and then the - rust crate would declare a dependency via `#[link(name = "foo", kind = + Rust crate would declare a dependency via `#[link(name = "foo", kind = "static")]`. Regardless of the flavor of output for the crate, the native static library @@ -361,7 +361,7 @@ A few examples of how this model can be used are: * A normal dynamic dependency. Common system libraries (like `readline`) are available on a large number of systems, and often a static copy of these - libraries cannot be found. When this dependency is included in a rust crate, + libraries cannot be found. When this dependency is included in a Rust crate, partial targets (like rlibs) will not link to the library, but when the rlib is included in a final target (like a binary), the native library will be linked in. diff --git a/src/doc/trpl/installing-rust.md b/src/doc/trpl/installing-rust.md index 39e8ea6cbd3..83750ec3b01 100644 --- a/src/doc/trpl/installing-rust.md +++ b/src/doc/trpl/installing-rust.md @@ -2,7 +2,7 @@ The first step to using Rust is to install it! There are a number of ways to install Rust, but the easiest is to use the `rustup` script. If you're on Linux -or a Mac, all you need to do is this: +or a Mac, all you need to do is this: > Note: you don't need to type in the `$`s, they just indicate the start of > each command. You’ll see many tutorials and examples around the web that @@ -25,6 +25,12 @@ $ sh rustup.sh [insecurity]: http://curlpipesh.tumblr.com If you're on Windows, please download the appropriate [installer][install-page]. +**NOTE:** By default, the Windows installer will not add Rust to the %PATH% +system variable. If this is the only version of Rust you are installing and you +want to be able to run it from the command line, click on "Advanced" on the +install dialog and on the "Product Features" page ensure "Add to PATH" is +installed on the local hard drive. + [install-page]: http://www.rust-lang.org/install.html @@ -87,6 +93,11 @@ rustc 1.0.0 (a59de37e9 2015-05-13) If you did, Rust has been installed successfully! Congrats! +If you didn't and you're on Windows, check that Rust is in your %PATH% system +variable. If it isn't, run the installer again, select "Change" on the "Change, +repair, or remove installation" page and ensure "Add to PATH" is installed on +the local hard drive. + This installer also installs a copy of the documentation locally, so you can read it offline. On UNIX systems, `/usr/local/share/doc/rust` is the location. On Windows, it's in a `share/doc` directory, inside wherever you installed Rust @@ -101,5 +112,5 @@ resources include [the user’s forum][users], and [irc]: irc://irc.mozilla.org/#rust [mibbit]: http://chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust -[users]: http://users.rust-lang.org/ +[users]: http://users.rust-lang.org/ [stackoverflow]: http://stackoverflow.com/questions/tagged/rust diff --git a/src/doc/trpl/release-channels.md b/src/doc/trpl/release-channels.md index 03e65539a20..1e203c6553e 100644 --- a/src/doc/trpl/release-channels.md +++ b/src/doc/trpl/release-channels.md @@ -43,3 +43,26 @@ This will help alert the team in case there’s an accidental regression. Additionally, testing against nightly can catch regressions even sooner, and so if you don’t mind a third build, we’d appreciate testing against all channels. +As an example, many Rust programmers use [Travis](https://travis-ci.org/) to +test their crates, which is free for open source projects. Travis [supports +Rust directly][travis], and you can use a `.travis.yml` file like this to +test on all channels: + +```yaml +language: rust +rust: + - nightly + - beta + - stable + +matrix: + allow_failures: + - rust: nightly +``` + +[travis]: http://docs.travis-ci.com/user/languages/rust/ + +With this configuration, Travis will test all three channels, but if something +breaks on nightly, it won’t fail your build. A similar configuration is +recommended for any CI system, check the documentation of the one you’re +using for more details. diff --git a/src/doc/trpl/unsafe.md b/src/doc/trpl/unsafe.md index 80b0c87473f..1b223365bd6 100644 --- a/src/doc/trpl/unsafe.md +++ b/src/doc/trpl/unsafe.md @@ -100,10 +100,14 @@ that you normally can not do. Just three. Here they are: That’s it. It’s important that `unsafe` does not, for example, ‘turn off the borrow checker’. Adding `unsafe` to some random Rust code doesn’t change its -semantics, it won’t just start accepting anything. +semantics, it won’t just start accepting anything. But it will let you write +things that _do_ break some of the rules. -But it will let you write things that _do_ break some of the rules. Let’s go -over these three abilities in order. +You will also encounter the `unsafe` keyword when writing bindings to foreign +(non-Rust) interfaces. You're encouraged to write a safe, native Rust interface +around the methods provided by the library. + +Let’s go over the basic three abilities listed, in order. ## Access or update a `static mut` diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs index 4c8511eb190..415326a8a61 100644 --- a/src/libcore/iter.rs +++ b/src/libcore/iter.rs @@ -2555,7 +2555,7 @@ impl<I: RandomAccessIterator, F> RandomAccessIterator for Inspect<I, F> #[unstable(feature = "iter_unfold")] #[derive(Clone)] #[deprecated(since = "1.2.0", - reason = "has gained enough traction to retain its position \ + reason = "has not gained enough traction to retain its position \ in the standard library")] #[allow(deprecated)] pub struct Unfold<St, F> { @@ -2567,7 +2567,7 @@ pub struct Unfold<St, F> { #[unstable(feature = "iter_unfold")] #[deprecated(since = "1.2.0", - reason = "has gained enough traction to retain its position \ + reason = "has not gained enough traction to retain its position \ in the standard library")] #[allow(deprecated)] impl<A, St, F> Unfold<St, F> where F: FnMut(&mut St) -> Option<A> { @@ -3018,7 +3018,7 @@ type IterateState<T, F> = (F, Option<T>, bool); /// from a given seed value. #[unstable(feature = "iter_iterate")] #[deprecated(since = "1.2.0", - reason = "has gained enough traction to retain its position \ + reason = "has not gained enough traction to retain its position \ in the standard library")] #[allow(deprecated)] pub type Iterate<T, F> = Unfold<IterateState<T, F>, fn(&mut IterateState<T, F>) -> Option<T>>; @@ -3027,7 +3027,7 @@ pub type Iterate<T, F> = Unfold<IterateState<T, F>, fn(&mut IterateState<T, F>) /// repeated applications of the given function `f`. #[unstable(feature = "iter_iterate")] #[deprecated(since = "1.2.0", - reason = "has gained enough traction to retain its position \ + reason = "has not gained enough traction to retain its position \ in the standard library")] #[allow(deprecated)] pub fn iterate<T, F>(seed: T, f: F) -> Iterate<T, F> where diff --git a/src/librustc/middle/intrinsicck.rs b/src/librustc/middle/intrinsicck.rs index c5f6f0126de..a10e0b8dfc2 100644 --- a/src/librustc/middle/intrinsicck.rs +++ b/src/librustc/middle/intrinsicck.rs @@ -165,7 +165,7 @@ impl<'a, 'tcx> IntrinsicCheckingVisitor<'a, 'tcx> { if from_tc.interior_param() || to_tc.interior_param() { span_err!(self.tcx.sess, span, E0139, "cannot transmute to or from a type that contains \ - type parameters in its interior"); + unsubstituted type parameters"); return; } diff --git a/src/librustc_resolve/diagnostics.rs b/src/librustc_resolve/diagnostics.rs index a0d06e5e124..5a941c757fc 100644 --- a/src/librustc_resolve/diagnostics.rs +++ b/src/librustc_resolve/diagnostics.rs @@ -106,8 +106,7 @@ mod foo { use foo::MyTrait::do_something; ``` -In general, it's not legal to directly import methods belonging to a -trait or concrete type. +It's illegal to directly import methods belonging to a trait or concrete type. "##, E0255: r##" @@ -272,7 +271,160 @@ See the 'Use Declarations' section of the reference for more information on this topic: http://doc.rust-lang.org/reference.html#use-declarations -"## +"##, + +E0403: r##" +Some type parameters have the same name. Example of erroneous code: + +``` +fn foo<T, T>(s: T, u: T) {} // error: the name `T` is already used for a type + // parameter in this type parameter list +``` + +Please verify that none of the type parameterss are misspelled, and rename any +clashing parameters. Example: + +``` +fn foo<T, Y>(s: T, u: Y) {} // ok! +``` +"##, + +E0404: r##" +You tried to implement something which was not a trait on an object. Example of +erroneous code: + +``` +struct Foo; +struct Bar; + +impl Foo for Bar {} // error: `Foo` is not a trait +``` + +Please verify that you didn't misspell the trait's name or otherwise use the +wrong identifier. Example: + +``` +trait Foo { + // some functions +} +struct Bar; + +impl Foo for Bar { // ok! + // functions implementation +} +``` +"##, + +E0405: r##" +An unknown trait was implemented. Example of erroneous code: + +``` +struct Foo; + +impl SomeTrait for Foo {} // error: use of undeclared trait name `SomeTrait` +``` + +Please verify that the name of the trait wasn't misspelled and ensure that it +was imported. Example: + +``` +// solution 1: +use some_file::SomeTrait; + +// solution 2: +trait SomeTrait { + // some functions +} + +struct Foo; + +impl SomeTrait for Foo { // ok! + // implements functions +} +``` +"##, + +E0407: r##" +A definition of a method not in the implemented trait was given in a trait +implementation. Example of erroneous code: + +``` +trait Foo { + fn a(); +} + +struct Bar; + +impl Foo for Bar { + fn a() {} + fn b() {} // error: method `b` is not a member of trait `Foo` +} +``` + +Please verify you didn't misspell the method name and you used the correct +trait. First example: + +``` +trait Foo { + fn a(); + fn b(); +} + +struct Bar; + +impl Foo for Bar { + fn a() {} + fn b() {} // ok! +} +``` + +Second example: + +``` +trait Foo { + fn a(); +} + +struct Bar; + +impl Foo for Bar { + fn a() {} +} + +impl Bar { + fn b() {} +} +``` +"##, + +E0428: r##" +A type or module has been defined more than once. Example of erroneous +code: + +``` +struct Bar; +struct Bar; // error: duplicate definition of value `Bar` +``` + +Please verify you didn't misspell the type/module's name or remove/rename the +duplicated one. Example: + +``` +struct Bar; +struct Bar2; // ok! +``` +"##, + +E0433: r##" +Invalid import. Example of erroneous code: + +``` +use something_which_doesnt_exist; +// error: unresolved import `something_which_doesnt_exist` +``` + +Please verify you didn't misspell the import's name. +"##, } @@ -284,11 +436,7 @@ register_diagnostics! { E0258, E0401, // can't use type parameters from outer function E0402, // cannot use an outer type parameter in this context - E0403, // the name `{}` is already used - E0404, // is not a trait - E0405, // use of undeclared trait name E0406, // undeclared associated type - E0407, // method is not a member of trait E0408, // variable from pattern #1 is not bound in pattern # E0409, // variable is bound with different mode in pattern # than in // pattern #1 @@ -313,13 +461,11 @@ register_diagnostics! { E0425, // unresolved name E0426, // use of undeclared label E0427, // cannot use `ref` binding mode with ... - E0428, // duplicate definition of ... E0429, // `self` imports are only allowed within a { } list E0430, // `self` import can only appear once in the list E0431, // `self` import can only appear in an import list with a non-empty // prefix E0432, // unresolved import - E0433, // failed to resolve E0434, // can't capture dynamic environment in a fn item E0435, // attempt to use a non-constant value in a constant E0437, // type is not a member of trait diff --git a/src/librustc_typeck/diagnostics.rs b/src/librustc_typeck/diagnostics.rs index f22da25c010..f865de522b2 100644 --- a/src/librustc_typeck/diagnostics.rs +++ b/src/librustc_typeck/diagnostics.rs @@ -1458,6 +1458,33 @@ return, for example with a `loop` that never breaks or a call to another diverging function (such as `panic!()`). "##, +E0172: r##" +This error means that an attempt was made to specify the type of a variable with +a combination of a concrete type and a trait. Consider the following example: + +``` +fn foo(bar: i32+std::fmt::Display) {} +``` + +The code is trying to specify that we want to receive a signed 32-bit integer +which also implements `Display`. This doesn't make sense: when we pass `i32`, a +concrete type, it implicitly includes all of the traits that it implements. +This includes `Display`, `Debug`, `Clone`, and a host of others. + +If `i32` implements the trait we desire, there's no need to specify the trait +separately. If it does not, then we need to `impl` the trait for `i32` before +passing it into `foo`. Either way, a fixed definition for `foo` will look like +the following: + +``` +fn foo(bar: i32) {} +``` + +To learn more about traits, take a look at the Book: + +https://doc.rust-lang.org/book/traits.html +"##, + E0178: r##" In types, the `+` type operator has low precedence, so it is often necessary to use parentheses. @@ -2178,7 +2205,6 @@ register_diagnostics! { E0164, E0167, E0168, - E0172, E0173, // manual implementations of unboxed closure traits are experimental E0174, // explicit use of unboxed closure methods are experimental E0182, diff --git a/src/libstd/io/buffered.rs b/src/libstd/io/buffered.rs index d6561ebb489..c25aa35ffbe 100644 --- a/src/libstd/io/buffered.rs +++ b/src/libstd/io/buffered.rs @@ -252,14 +252,49 @@ impl<R: Seek> Seek for BufReader<R> { } } -/// Wraps a Writer and buffers output to it. +/// Wraps a writer and buffers its output. /// -/// It can be excessively inefficient to work directly with a `Write`. For -/// example, every call to `write` on `TcpStream` results in a system call. A -/// `BufWriter` keeps an in memory buffer of data and writes it to the -/// underlying `Write` in large, infrequent batches. +/// It can be excessively inefficient to work directly with something that +/// implements `Write`. For example, every call to `write` on `TcpStream` +/// results in a system call. A `BufWriter` keeps an in-memory buffer of data +/// and writes it to an underlying writer in large, infrequent batches. /// /// The buffer will be written out when the writer is dropped. +/// +/// # Examples +/// +/// Let's write the numbers one through ten to a `TcpStream`: +/// +/// ```no_run +/// use std::io::prelude::*; +/// use std::net::TcpStream; +/// +/// let mut stream = TcpStream::connect("127.0.0.1:34254").unwrap(); +/// +/// for i in 1..10 { +/// stream.write(&[i]).unwrap(); +/// } +/// ``` +/// +/// Because we're not buffering, we write each one in turn, incurring the +/// overhead of a system call per byte written. We can fix this with a +/// `BufWriter`: +/// +/// ```no_run +/// use std::io::prelude::*; +/// use std::io::BufWriter; +/// use std::net::TcpStream; +/// +/// let mut stream = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap()); +/// +/// for i in 1..10 { +/// stream.write(&[i]).unwrap(); +/// } +/// ``` +/// +/// By wrapping the stream with a `BufWriter`, these ten writes are all grouped +/// together by the buffer, and will all be written out in one system call when +/// the `stream` is dropped. #[stable(feature = "rust1", since = "1.0.0")] pub struct BufWriter<W: Write> { inner: Option<W>, @@ -269,18 +304,60 @@ pub struct BufWriter<W: Write> { /// An error returned by `into_inner` which combines an error that /// happened while writing out the buffer, and the buffered writer object /// which may be used to recover from the condition. +/// +/// # Examples +/// +/// ```no_run +/// use std::io::BufWriter; +/// use std::net::TcpStream; +/// +/// let mut stream = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap()); +/// +/// // do stuff with the stream +/// +/// // we want to get our `TcpStream` back, so let's try: +/// +/// let stream = match stream.into_inner() { +/// Ok(s) => s, +/// Err(e) => { +/// // Here, e is an IntoInnerError +/// panic!("An error occurred"); +/// } +/// }; +/// ``` #[derive(Debug)] #[stable(feature = "rust1", since = "1.0.0")] pub struct IntoInnerError<W>(W, Error); impl<W: Write> BufWriter<W> { /// Creates a new `BufWriter` with a default buffer capacity. + /// + /// # Examples + /// + /// ```no_run + /// use std::io::BufWriter; + /// use std::net::TcpStream; + /// + /// let mut buffer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap()); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn new(inner: W) -> BufWriter<W> { BufWriter::with_capacity(DEFAULT_BUF_SIZE, inner) } /// Creates a new `BufWriter` with the specified buffer capacity. + /// + /// # Examples + /// + /// Creating a buffer with a buffer of a hundred bytes. + /// + /// ```no_run + /// use std::io::BufWriter; + /// use std::net::TcpStream; + /// + /// let stream = TcpStream::connect("127.0.0.1:34254").unwrap(); + /// let mut buffer = BufWriter::with_capacity(100, stream); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn with_capacity(cap: usize, inner: W) -> BufWriter<W> { BufWriter { @@ -313,6 +390,18 @@ impl<W: Write> BufWriter<W> { } /// Gets a reference to the underlying writer. + /// + /// # Examples + /// + /// ```no_run + /// use std::io::BufWriter; + /// use std::net::TcpStream; + /// + /// let mut buffer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap()); + /// + /// // we can use reference just like buffer + /// let reference = buffer.get_ref(); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn get_ref(&self) -> &W { self.inner.as_ref().unwrap() } @@ -321,12 +410,36 @@ impl<W: Write> BufWriter<W> { /// # Warning /// /// It is inadvisable to directly write to the underlying writer. + /// + /// # Examples + /// + /// ```no_run + /// use std::io::BufWriter; + /// use std::net::TcpStream; + /// + /// let mut buffer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap()); + /// + /// // we can use reference just like buffer + /// let reference = buffer.get_mut(); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn get_mut(&mut self) -> &mut W { self.inner.as_mut().unwrap() } /// Unwraps this `BufWriter`, returning the underlying writer. /// /// The buffer is written out before returning the writer. + /// + /// # Examples + /// + /// ```no_run + /// use std::io::BufWriter; + /// use std::net::TcpStream; + /// + /// let mut buffer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap()); + /// + /// // unwrap the TcpStream and flush the buffer + /// let stream = buffer.into_inner().unwrap(); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn into_inner(mut self) -> Result<W, IntoInnerError<BufWriter<W>>> { match self.flush_buf() { @@ -384,9 +497,34 @@ impl<W: Write> Drop for BufWriter<W> { } impl<W> IntoInnerError<W> { - /// Returns the error which caused the call to `into_inner` to fail. + /// Returns the error which caused the call to `into_inner()` to fail. /// /// This error was returned when attempting to write the internal buffer. + /// + /// # Examples + /// + /// ```no_run + /// use std::io::BufWriter; + /// use std::net::TcpStream; + /// + /// let mut stream = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap()); + /// + /// // do stuff with the stream + /// + /// // we want to get our `TcpStream` back, so let's try: + /// + /// let stream = match stream.into_inner() { + /// Ok(s) => s, + /// Err(e) => { + /// // Here, e is an IntoInnerError, let's log the inner error. + /// // + /// // We'll just 'log' to stdout for this example. + /// println!("{}", e.error()); + /// + /// panic!("An unexpected error occurred."); + /// } + /// }; + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn error(&self) -> &Error { &self.1 } @@ -394,6 +532,32 @@ impl<W> IntoInnerError<W> { /// /// The returned object can be used for error recovery, such as /// re-inspecting the buffer. + /// + /// # Examples + /// + /// ```no_run + /// use std::io::BufWriter; + /// use std::net::TcpStream; + /// + /// let mut stream = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap()); + /// + /// // do stuff with the stream + /// + /// // we want to get our `TcpStream` back, so let's try: + /// + /// let stream = match stream.into_inner() { + /// Ok(s) => s, + /// Err(e) => { + /// // Here, e is a IntoInnerError, let's re-examine the buffer: + /// let buffer = e.into_inner(); + /// + /// // do stuff to try to recover + /// + /// // afterwards, let's just return the stream + /// buffer.into_inner().unwrap() + /// } + /// }; + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn into_inner(self) -> W { self.0 } } @@ -417,17 +581,74 @@ impl<W> fmt::Display for IntoInnerError<W> { } } -/// Wraps a Writer and buffers output to it, flushing whenever a newline +/// Wraps a writer and buffers output to it, flushing whenever a newline /// (`0x0a`, `'\n'`) is detected. /// -/// The buffer will be written out when the writer is dropped. +/// The [`BufWriter`][bufwriter] struct wraps a writer and buffers its output. +/// But it only does this batched write when it goes out of scope, or when the +/// internal buffer is full. Sometimes, you'd prefer to write each line as it's +/// completed, rather than the entire buffer at once. Enter `LineWriter`. It +/// does exactly that. +/// +/// [bufwriter]: struct.BufWriter.html +/// +/// If there's still a partial line in the buffer when the `LineWriter` is +/// dropped, it will flush those contents. +/// +/// # Examples +/// +/// We can use `LineWriter` to write one line at a time, significantly +/// reducing the number of actual writes to the file. +/// +/// ``` +/// use std::fs::File; +/// use std::io::prelude::*; +/// use std::io::LineWriter; +/// +/// # fn foo() -> std::io::Result<()> { +/// let road_not_taken = b"I shall be telling this with a sigh +/// Somewhere ages and ages hence: +/// Two roads diverged in a wood, and I - +/// I took the one less traveled by, +/// And that has made all the difference."; +/// +/// let file = try!(File::create("poem.txt")); +/// let mut file = LineWriter::new(file); +/// +/// for &byte in road_not_taken.iter() { +/// file.write(&[byte]).unwrap(); +/// } +/// +/// // let's check we did the right thing. +/// let mut file = try!(File::open("poem.txt")); +/// let mut contents = String::new(); +/// +/// try!(file.read_to_string(&mut contents)); +/// +/// assert_eq!(contents.as_bytes(), &road_not_taken[..]); +/// # Ok(()) +/// # } +/// ``` #[stable(feature = "rust1", since = "1.0.0")] pub struct LineWriter<W: Write> { inner: BufWriter<W>, } impl<W: Write> LineWriter<W> { - /// Creates a new `LineWriter` + /// Creates a new `LineWriter`. + /// + /// # Examples + /// + /// ``` + /// use std::fs::File; + /// use std::io::LineWriter; + /// + /// # fn foo() -> std::io::Result<()> { + /// let file = try!(File::create("poem.txt")); + /// let file = LineWriter::new(file); + /// # Ok(()) + /// # } + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn new(inner: W) -> LineWriter<W> { // Lines typically aren't that long, don't use a giant buffer @@ -436,12 +657,40 @@ impl<W: Write> LineWriter<W> { /// Creates a new `LineWriter` with a specified capacity for the internal /// buffer. + /// + /// # Examples + /// + /// ``` + /// use std::fs::File; + /// use std::io::LineWriter; + /// + /// # fn foo() -> std::io::Result<()> { + /// let file = try!(File::create("poem.txt")); + /// let file = LineWriter::with_capacity(100, file); + /// # Ok(()) + /// # } + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn with_capacity(cap: usize, inner: W) -> LineWriter<W> { LineWriter { inner: BufWriter::with_capacity(cap, inner) } } /// Gets a reference to the underlying writer. + /// + /// # Examples + /// + /// ``` + /// use std::fs::File; + /// use std::io::LineWriter; + /// + /// # fn foo() -> std::io::Result<()> { + /// let file = try!(File::create("poem.txt")); + /// let file = LineWriter::new(file); + /// + /// let reference = file.get_ref(); + /// # Ok(()) + /// # } + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn get_ref(&self) -> &W { self.inner.get_ref() } @@ -449,12 +698,44 @@ impl<W: Write> LineWriter<W> { /// /// Caution must be taken when calling methods on the mutable reference /// returned as extra writes could corrupt the output stream. + /// + /// # Examples + /// + /// ``` + /// use std::fs::File; + /// use std::io::LineWriter; + /// + /// # fn foo() -> std::io::Result<()> { + /// let file = try!(File::create("poem.txt")); + /// let mut file = LineWriter::new(file); + /// + /// // we can use reference just like file + /// let reference = file.get_mut(); + /// # Ok(()) + /// # } + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn get_mut(&mut self) -> &mut W { self.inner.get_mut() } /// Unwraps this `LineWriter`, returning the underlying writer. /// /// The internal buffer is written out before returning the writer. + /// + /// # Examples + /// + /// ``` + /// use std::fs::File; + /// use std::io::LineWriter; + /// + /// # fn foo() -> std::io::Result<()> { + /// let file = try!(File::create("poem.txt")); + /// + /// let writer: LineWriter<File> = LineWriter::new(file); + /// + /// let file: File = try!(writer.into_inner()); + /// # Ok(()) + /// # } + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn into_inner(self) -> Result<W, IntoInnerError<LineWriter<W>>> { self.inner.into_inner().map_err(|IntoInnerError(buf, e)| { diff --git a/src/libstd/io/cursor.rs b/src/libstd/io/cursor.rs index f059b24baf6..4bb7d2ebd19 100644 --- a/src/libstd/io/cursor.rs +++ b/src/libstd/io/cursor.rs @@ -15,16 +15,67 @@ use cmp; use io::{self, SeekFrom, Error, ErrorKind}; use slice; -/// A `Cursor` is a type which wraps a non-I/O object to provide a `Seek` +/// A `Cursor` wraps another type and provides it with a [`Seek`][seek] /// implementation. /// -/// Cursors are typically used with memory buffer objects in order to allow -/// `Seek`, `Read`, and `Write` implementations. For example, common cursor types -/// include `Cursor<Vec<u8>>` and `Cursor<&[u8]>`. +/// [seek]: trait.Seek.html /// -/// Implementations of the I/O traits for `Cursor<T>` are currently not generic -/// over `T` itself. Instead, specific implementations are provided for various -/// in-memory buffer types like `Vec<u8>` and `&[u8]`. +/// Cursors are typically used with in-memory buffers to allow them to +/// implement `Read` and/or `Write`, allowing these buffers to be used +/// anywhere you might use a reader or writer that does actual I/O. +/// +/// The standard library implements some I/O traits on various types which +/// are commonly used as a buffer, like `Cursor<Vec<u8>>` and `Cursor<&[u8]>`. +/// +/// # Examples +/// +/// We may want to write bytes to a [`File`][file] in our production +/// code, but use an in-memory buffer in our tests. We can do this with +/// `Cursor`: +/// +/// [file]: ../fs/struct.File.html +/// +/// ```no_run +/// use std::io::prelude::*; +/// use std::io::{self, SeekFrom}; +/// use std::fs::File; +/// +/// // a library function we've written +/// fn write_ten_bytes_at_end<W: Write + Seek>(writer: &mut W) -> io::Result<()> { +/// try!(writer.seek(SeekFrom::End(-10))); +/// +/// for i in 0..10 { +/// try!(writer.write(&[i])); +/// } +/// +/// // all went well +/// Ok(()) +/// } +/// +/// # fn foo() -> io::Result<()> { +/// // Here's some code that uses this library function. +/// // +/// // We might want to use a BufReader here for efficiency, but let's +/// // keep this example focused. +/// let mut file = try!(File::create("foo.txt")); +/// +/// try!(write_ten_bytes_at_end(&mut file)); +/// # Ok(()) +/// # } +/// +/// // now let's write a test +/// #[test] +/// fn test_writes_bytes() { +/// // setting up a real File is much more slow than an in-memory buffer, +/// // let's use a cursor instead +/// use std::io::Cursor; +/// let mut buff = Cursor::new(vec![0; 15]); +/// +/// write_ten_bytes(&mut buff).unwrap(); +/// +/// assert_eq!(&buff.get_ref()[5..15], &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); +/// } +/// ``` #[stable(feature = "rust1", since = "1.0.0")] #[derive(Clone, Debug)] pub struct Cursor<T> { @@ -34,16 +85,50 @@ pub struct Cursor<T> { impl<T> Cursor<T> { /// Creates a new cursor wrapping the provided underlying I/O object. + /// + /// # Examples + /// + /// ``` + /// use std::io::Cursor; + /// + /// let buff = Cursor::new(Vec::new()); + /// # fn force_inference(_: &Cursor<Vec<u8>>) {} + /// # force_inference(&buff); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn new(inner: T) -> Cursor<T> { Cursor { pos: 0, inner: inner } } /// Consumes this cursor, returning the underlying value. + /// + /// # Examples + /// + /// ``` + /// use std::io::Cursor; + /// + /// let buff = Cursor::new(Vec::new()); + /// # fn force_inference(_: &Cursor<Vec<u8>>) {} + /// # force_inference(&buff); + /// + /// let vec = buff.into_inner(); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn into_inner(self) -> T { self.inner } /// Gets a reference to the underlying value in this cursor. + /// + /// # Examples + /// + /// ``` + /// use std::io::Cursor; + /// + /// let buff = Cursor::new(Vec::new()); + /// # fn force_inference(_: &Cursor<Vec<u8>>) {} + /// # force_inference(&buff); + /// + /// let reference = buff.get_ref(); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn get_ref(&self) -> &T { &self.inner } @@ -51,14 +136,60 @@ impl<T> Cursor<T> { /// /// Care should be taken to avoid modifying the internal I/O state of the /// underlying value as it may corrupt this cursor's position. + /// + /// # Examples + /// + /// ``` + /// use std::io::Cursor; + /// + /// let mut buff = Cursor::new(Vec::new()); + /// # fn force_inference(_: &Cursor<Vec<u8>>) {} + /// # force_inference(&buff); + /// + /// let reference = buff.get_mut(); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn get_mut(&mut self) -> &mut T { &mut self.inner } - /// Returns the current value of this cursor + /// Returns the current position of this cursor. + /// + /// # Examples + /// + /// ``` + /// use std::io::Cursor; + /// use std::io::prelude::*; + /// use std::io::SeekFrom; + /// + /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]); + /// + /// assert_eq!(buff.position(), 0); + /// + /// buff.seek(SeekFrom::Current(2)).unwrap(); + /// assert_eq!(buff.position(), 2); + /// + /// buff.seek(SeekFrom::Current(-1)).unwrap(); + /// assert_eq!(buff.position(), 1); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn position(&self) -> u64 { self.pos } - /// Sets the value of this cursor + /// Sets the position of this cursor. + /// + /// # Examples + /// + /// ``` + /// use std::io::Cursor; + /// + /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]); + /// + /// assert_eq!(buff.position(), 0); + /// + /// buff.set_position(2); + /// assert_eq!(buff.position(), 2); + /// + /// buff.set_position(4); + /// assert_eq!(buff.position(), 4); + /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn set_position(&mut self, pos: u64) { self.pos = pos; } } diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index 3016cfa8fe5..fbdfdeaaef4 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -1396,7 +1396,10 @@ pub trait BufRead: Read { /// A `Write` adaptor which will write data to multiple locations. /// -/// For more information, see `Write::broadcast`. +/// This struct is generally created by calling [`broadcast()`][broadcast] on a +/// writer. Please see the documentation of `broadcast()` for more details. +/// +/// [broadcast]: trait.Write.html#method.broadcast #[unstable(feature = "io", reason = "awaiting stability of Write::broadcast")] pub struct Broadcast<T, U> { first: T, @@ -1417,9 +1420,12 @@ impl<T: Write, U: Write> Write for Broadcast<T, U> { } } -/// Adaptor to chain together two instances of `Read`. +/// Adaptor to chain together two readers. +/// +/// This struct is generally created by calling [`chain()`][chain] on a reader. +/// Please see the documentation of `chain()` for more details. /// -/// For more information, see `Read::chain`. +/// [chain]: trait.Read.html#method.chain #[stable(feature = "rust1", since = "1.0.0")] pub struct Chain<T, U> { first: T, @@ -1442,7 +1448,10 @@ impl<T: Read, U: Read> Read for Chain<T, U> { /// Reader adaptor which limits the bytes read from an underlying reader. /// -/// For more information, see `Read::take`. +/// This struct is generally created by calling [`take()`][take] on a reader. +/// Please see the documentation of `take()` for more details. +/// +/// [take]: trait.Read.html#method.take #[stable(feature = "rust1", since = "1.0.0")] pub struct Take<T> { inner: T, @@ -1495,7 +1504,10 @@ impl<T: BufRead> BufRead for Take<T> { /// An adaptor which will emit all read data to a specified writer as well. /// -/// For more information see `Read::tee` +/// This struct is generally created by calling [`tee()`][tee] on a reader. +/// Please see the documentation of `tee()` for more details. +/// +/// [tee]: trait.Read.html#method.tee #[unstable(feature = "io", reason = "awaiting stability of Read::tee")] pub struct Tee<R, W> { reader: R, @@ -1512,9 +1524,12 @@ impl<R: Read, W: Write> Read for Tee<R, W> { } } -/// A bridge from implementations of `Read` to an `Iterator` of `u8`. +/// An iterator over `u8` values of a reader. /// -/// See `Read::bytes` for more information. +/// This struct is generally created by calling [`bytes()`][bytes] on a reader. +/// Please see the documentation of `bytes()` for more details. +/// +/// [bytes]: trait.Read.html#method.bytes #[stable(feature = "rust1", since = "1.0.0")] pub struct Bytes<R> { inner: R, @@ -1534,9 +1549,12 @@ impl<R: Read> Iterator for Bytes<R> { } } -/// A bridge from implementations of `Read` to an `Iterator` of `char`. +/// An iterator over the `char`s of a reader. +/// +/// This struct is generally created by calling [`chars()`][chars] on a reader. +/// Please see the documentation of `chars()` for more details. /// -/// See `Read::chars` for more information. +/// [chars]: trait.Read.html#method.chars #[unstable(feature = "io", reason = "awaiting stability of Read::chars")] pub struct Chars<R> { inner: R, @@ -1618,7 +1636,10 @@ impl fmt::Display for CharsError { /// An iterator over the contents of an instance of `BufRead` split on a /// particular byte. /// -/// See `BufRead::split` for more information. +/// This struct is generally created by calling [`split()`][split] on a +/// `BufRead`. Please see the documentation of `split()` for more details. +/// +/// [split]: trait.BufRead.html#method.split #[stable(feature = "rust1", since = "1.0.0")] pub struct Split<B> { buf: B, @@ -1644,10 +1665,12 @@ impl<B: BufRead> Iterator for Split<B> { } } -/// An iterator over the lines of an instance of `BufRead` split on a newline -/// byte. +/// An iterator over the lines of an instance of `BufRead`. +/// +/// This struct is generally created by calling [`lines()`][lines] on a +/// `BufRead`. Please see the documentation of `lines()` for more details. /// -/// See `BufRead::lines` for more information. +/// [lines]: trait.BufRead.html#method.lines #[stable(feature = "rust1", since = "1.0.0")] pub struct Lines<B> { buf: B, diff --git a/src/libstd/io/util.rs b/src/libstd/io/util.rs index c0bced26bef..dc29811ed5b 100644 --- a/src/libstd/io/util.rs +++ b/src/libstd/io/util.rs @@ -61,6 +61,11 @@ pub fn copy<R: Read, W: Write>(reader: &mut R, writer: &mut W) -> io::Result<u64 } /// A reader which is always at EOF. +/// +/// This struct is generally created by calling [`empty()`][empty]. Please see +/// the documentation of `empty()` for more details. +/// +/// [empty]: fn.empty.html #[stable(feature = "rust1", since = "1.0.0")] pub struct Empty { _priv: () } @@ -95,7 +100,12 @@ impl BufRead for Empty { fn consume(&mut self, _n: usize) {} } -/// A reader which infinitely yields one byte. +/// A reader which yields one byte over and over and over and over and over and... +/// +/// This struct is generally created by calling [`repeat()`][repeat]. Please +/// see the documentation of `repeat()` for more details. +/// +/// [empty]: fn.repeat.html #[stable(feature = "rust1", since = "1.0.0")] pub struct Repeat { byte: u8 } @@ -117,6 +127,11 @@ impl Read for Repeat { } /// A writer which will move data into the void. +/// +/// This struct is generally created by calling [`sink()`][sink]. Please +/// see the documentation of `sink()` for more details. +/// +/// [empty]: fn.sink.html #[stable(feature = "rust1", since = "1.0.0")] pub struct Sink { _priv: () } diff --git a/src/test/compile-fail/issue-20162.rs b/src/test/compile-fail/issue-20162.rs new file mode 100644 index 00000000000..d3a87689ac5 --- /dev/null +++ b/src/test/compile-fail/issue-20162.rs @@ -0,0 +1,17 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +struct X { x: i32 } + +fn main() { + let mut b: Vec<X> = vec![]; + b.sort(); + //~^ ERROR the trait `core::cmp::Ord` is not implemented for the type `X` +} diff --git a/src/test/compile-fail/issue-21174.rs b/src/test/compile-fail/issue-21174.rs index ec258449cb1..30fd2eb4d2f 100644 --- a/src/test/compile-fail/issue-21174.rs +++ b/src/test/compile-fail/issue-21174.rs @@ -15,7 +15,7 @@ trait Trait<'a> { fn foo<'a, T: Trait<'a>>(value: T::A) { let new: T::B = unsafe { std::mem::transmute(value) }; -//~^ ERROR: cannot transmute to or from a type that contains type parameters in its interior [E0139] +//~^ ERROR: cannot transmute to or from a type that contains unsubstituted type parameters [E0139] } fn main() { } diff --git a/src/test/run-pass/issue-10436.rs b/src/test/run-pass/issue-10436.rs new file mode 100644 index 00000000000..81a955b0f22 --- /dev/null +++ b/src/test/run-pass/issue-10436.rs @@ -0,0 +1,20 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +fn works<T>(x: T) -> Vec<T> { vec![x] } + +fn also_works<T: Clone>(x: T) -> Vec<T> { vec![x] } + +fn main() { + let _: Vec<usize> = works(0); + let _: Vec<usize> = also_works(0); + let _ = works(0); + let _ = also_works(0); +} diff --git a/src/test/run-pass/issue-14229.rs b/src/test/run-pass/issue-14229.rs new file mode 100644 index 00000000000..ee2bbe63750 --- /dev/null +++ b/src/test/run-pass/issue-14229.rs @@ -0,0 +1,30 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +trait Foo: Sized { + fn foo(self) {} +} + +trait Bar: Sized { + fn bar(self) {} +} + +struct S; + +impl<'l> Foo for &'l S {} + +impl<T: Foo> Bar for T {} + +fn main() { + let s = S; + s.foo(); + (&s).bar(); + s.bar(); +} diff --git a/src/test/run-pass/issue-14382.rs b/src/test/run-pass/issue-14382.rs new file mode 100644 index 00000000000..cdb44f6a606 --- /dev/null +++ b/src/test/run-pass/issue-14382.rs @@ -0,0 +1,24 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#[derive(Debug)] +struct Matrix4<S>(S); +trait POrd<S> {} + +fn translate<S: POrd<S>>(s: S) -> Matrix4<S> { Matrix4(s) } + +impl POrd<f32> for f32 {} +impl POrd<f64> for f64 {} + +fn main() { + let x = 1.0; + let m : Matrix4<f32> = translate(x); + println!("m: {:?}", m); +} diff --git a/src/test/run-pass/issue-19404.rs b/src/test/run-pass/issue-19404.rs new file mode 100644 index 00000000000..0eea6ba22ca --- /dev/null +++ b/src/test/run-pass/issue-19404.rs @@ -0,0 +1,47 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![feature(reflect_marker)] + +use std::any::TypeId; +use std::marker::Reflect; +use std::rc::Rc; + +type Fp<T> = Rc<T>; + +struct Engine; + +trait Component: 'static + Reflect {} +impl Component for Engine {} + +trait Env { + fn get_component_type_id(&self, type_id: TypeId) -> Option<Fp<Component>>; +} + +impl<'a> Env+'a { + fn get_component<T: Component>(&self) -> Option<Fp<T>> { + let x = self.get_component_type_id(TypeId::of::<T>()); + None + } +} + +trait Figment { + fn init(&mut self, env: &Env); +} + +struct MyFigment; + +impl Figment for MyFigment { + fn init(&mut self, env: &Env) { + let engine = env.get_component::<Engine>(); + } +} + +fn main() {} diff --git a/src/test/run-pass/issue-26468.rs b/src/test/run-pass/issue-26468.rs new file mode 100644 index 00000000000..9fb8675e84e --- /dev/null +++ b/src/test/run-pass/issue-26468.rs @@ -0,0 +1,38 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![allow(dead_code)] + +enum FooMode { + Check = 0x1001, +} + +enum BarMode { + Check = 0x2001, +} + +enum Mode { + Foo(FooMode), + Bar(BarMode), +} + +#[inline(never)] +fn broken(mode: &Mode) -> u32 { + for _ in 0..1 { + if let Mode::Foo(FooMode::Check) = *mode { return 17 } + if let Mode::Bar(BarMode::Check) = *mode { return 19 } + } + return 42; +} + +fn main() { + let mode = Mode::Bar(BarMode::Check); + assert_eq!(broken(&mode), 19); +} |
