diff options
| author | bors <bors@rust-lang.org> | 2014-12-13 22:57:21 +0000 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2014-12-13 22:57:21 +0000 |
| commit | 444fa1b7cffcd99ca5b8abb51acf979f06a25899 (patch) | |
| tree | 51a8beea4fd983ce8cb46879a2fdbaf72916c13e /src/libcore/fmt | |
| parent | 567b90ff095076054c98fa2f08d6c552ae60968d (diff) | |
| parent | b8e0b81dd57621af28d7b2b5551a3217f7bd4cec (diff) | |
| download | rust-444fa1b7cffcd99ca5b8abb51acf979f06a25899.tar.gz rust-444fa1b7cffcd99ca5b8abb51acf979f06a25899.zip | |
auto merge of #19467 : japaric/rust/uc, r=alexcrichton
This PR moves almost all our current uses of closures, both in public API and internal uses, to the new "unboxed" closures system.
In most cases, downstream code that *only uses* closures will continue to work as it is. The reason is that the `|| {}` syntax can be inferred either as a boxed or an "unboxed" closure according to the context. For example the following code will continue to work:
``` rust
some_option.map(|x| x.transform_with(upvar))
```
And will get silently upgraded to an "unboxed" closure.
In some other cases, it may be necessary to "annotate" which `Fn*` trait the closure implements:
```
// Change this
|x| { /* body */}
// to either of these
|: x| { /* body */} // closure implements the FnOnce trait
|&mut : x| { /* body */} // FnMut
|&: x| { /* body */} // Fn
```
This mainly occurs when the closure is assigned to a variable first, and then passed to a function/method.
``` rust
let closure = |: x| x.transform_with(upvar);
some.option.map(closure)
```
(It's very likely that in the future, an improved inference engine will make this annotation unnecessary)
Other cases that require annotation are closures that implement some trait via a blanket `impl`, for example:
- `std::finally::Finally`
- `regex::Replacer`
- `std::str::CharEq`
``` rust
string.trim_left_chars(|c: char| c.is_whitespace())
//~^ ERROR: the trait `Fn<(char,), bool>` is not implemented for the type `|char| -> bool`
string.trim_left_chars(|&: c: char| c.is_whitespace()) // OK
```
Finally, all implementations of traits that contain boxed closures in the arguments of their methods are now broken. And will need to be updated to use unboxed closures. These are the main affected traits:
- `serialize::Decoder`
- `serialize::DecoderHelpers`
- `serialize::Encoder`
- `serialize::EncoderHelpers`
- `rustrt::ToCStr`
For example, change this:
``` rust
// libserialize/json.rs
impl<'a> Encoder<io::IoError> for Encoder<'a> {
fn emit_enum(&mut self,
_name: &str,
f: |&mut Encoder<'a>| -> EncodeResult) -> EncodeResult {
f(self)
}
}
```
to:
``` rust
// libserialize/json.rs
impl<'a> Encoder<io::IoError> for Encoder<'a> {
fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult
{
f(self)
}
}
```
[breaking-change]
---
### How the `Fn*` bound has been selected
I've chosen the bounds to make the functions/structs as "generic as possible", i.e. to let them allow the maximum amount of input.
- An `F: FnOnce` bound accepts the three kinds of closures: `|:|`, `|&mut:|` and `|&:|`.
- An `F: FnMut` bound only accepts "non-consuming" closures: `|&mut:|` and `|&:|`.
- An `F: Fn` bound only accept the "immutable environment" closures: `|&:|`.
This means that whenever possible the `FnOnce` bound has been used, if the `FnOnce` bound couldn't be used, then the `FnMut` was used. The `Fn` bound was never used in the whole repository.
The `FnMut` bound was the most used, because it resembles the semantics of the current boxed closures: the closure can modify its environment, and the closure may be called several times.
The `FnOnce` bound allows new semantics: you can move out the upvars when the closure is called. This can be effectively paired with the `move || {}` syntax to transfer ownership from the environment to the closure caller.
In the case of trait methods, is hard to select the "right" bound since we can't control how the trait may be implemented by downstream users. In these cases, I have selected the bound based on how we use these traits in the repository. For this reason the selected bounds may not be ideal, and may require tweaking before stabilization.
r? @aturon
Diffstat (limited to 'src/libcore/fmt')
| -rw-r--r-- | src/libcore/fmt/float.rs | 9 | ||||
| -rw-r--r-- | src/libcore/fmt/mod.rs | 9 |
2 files changed, 10 insertions, 8 deletions
diff --git a/src/libcore/fmt/float.rs b/src/libcore/fmt/float.rs index 400ce76baa0..fb4d91e912a 100644 --- a/src/libcore/fmt/float.rs +++ b/src/libcore/fmt/float.rs @@ -20,6 +20,7 @@ use fmt; use iter::{range, DoubleEndedIteratorExt}; use num::{Float, FPNaN, FPInfinite, ToPrimitive}; use num::cast; +use ops::FnOnce; use result::Result::Ok; use slice::{mod, SlicePrelude}; use str::StrPrelude; @@ -84,7 +85,7 @@ static DIGIT_E_RADIX: uint = ('e' as uint) - ('a' as uint) + 11u; /// between digit and exponent sign `'e'`. /// - Panics if `radix` > 25 and `exp_format` is `ExpBin` due to conflict /// between digit and exponent sign `'p'`. -pub fn float_to_str_bytes_common<T: Float, U>( +pub fn float_to_str_bytes_common<T: Float, U, F>( num: T, radix: uint, negative_zero: bool, @@ -92,8 +93,10 @@ pub fn float_to_str_bytes_common<T: Float, U>( digits: SignificantDigits, exp_format: ExponentFormat, exp_upper: bool, - f: |&[u8]| -> U -) -> U { + f: F +) -> U where + F: FnOnce(&[u8]) -> U, +{ assert!(2 <= radix && radix <= 36); match exp_format { ExpDec if radix >= DIGIT_E_RADIX // decimal exponent 'e' diff --git a/src/libcore/fmt/mod.rs b/src/libcore/fmt/mod.rs index 88ea811cfd6..37a1d4d564d 100644 --- a/src/libcore/fmt/mod.rs +++ b/src/libcore/fmt/mod.rs @@ -19,7 +19,7 @@ use kinds::{Copy, Sized}; use mem; use option::Option; use option::Option::{Some, None}; -use ops::Deref; +use ops::{Deref, FnOnce}; use result::Result::{Ok, Err}; use result; use slice::SlicePrelude; @@ -491,10 +491,9 @@ impl<'a> Formatter<'a> { /// Runs a callback, emitting the correct padding either before or /// afterwards depending on whether right or left alignment is requested. - fn with_padding(&mut self, - padding: uint, - default: rt::Alignment, - f: |&mut Formatter| -> Result) -> Result { + fn with_padding<F>(&mut self, padding: uint, default: rt::Alignment, f: F) -> Result where + F: FnOnce(&mut Formatter) -> Result, + { use char::Char; let align = match self.align { rt::AlignUnknown => default, |
