As it says in the title. I've added an `expect` method to `Result` that allows printing both an error message (e.g. what operation was attempted), and the error value. This is separate from the `unwrap` and `ok().expect("message")` behaviours.
This is a direct port of my prior work on the float formatting. The detailed description is available [here](https://github.com/lifthrasiir/rust-strconv#flt2dec). In brief,
* This adds a new hidden module `core::num::flt2dec` for testing from `libcoretest`. Why is it in `core::num` instead of `core::fmt`? Because I envision that the table used by `flt2dec` is directly applicable to `dec2flt` (cf. #24557) as well, which exceeds the realm of "formatting".
* This contains both Dragon4 algorithm (exact, complete but slow) and Grisu3 algorithm (exact, fast but incomplete).
* The code is accompanied with a large amount of self-tests and some exhaustive tests. In particular, `libcoretest` gets a new dependency on `librand`. For the external interface it relies on the existing test suite.
* It is known that, in the best case, the entire formatting code has about 30 KBs of binary overhead (judged from strconv experiments). Not too bad but there might be a potential room for improvements.
This is rather large code. I did my best to comment and annotate the code, but you have been warned.
For the maximal availability the original code was licensed in CC0, but I've also dual-licensed it in MIT/Apache as well so there should be no licensing concern.
This is [breaking-change] as it changes the float output slightly (and it also affects the casing of `inf` and `nan`). I hope this is not a big deal though :)
Fixes#7030, #18038 and #24556. Also related to #6220 and #20870.
## Known Issues
- [x] I've yet to finish `make check-stage1`. It does pass main test suites including `run-pass` but there might be some unknown edges on the doctests.
- [ ] Figure out how this PR affects rustc.
- [ ] Determine which internal routine is mapped to the formatting specifier. Depending on the decision, some internal routine can be safely removed (for instance, currently `to_shortest_str` is unused).
For the shortest mode the IEEE 754 decoder already provides
an exact rounding range accounting for banker's rounding,
but it was not the case for the exact mode. This commit alters
the exact mode algorithm for Dragon so that any number ending at
`...x5000...` with even `x` and infinite zeroes will round to
`...x` instead of `...(x+1)` as it was. Grisu is not affected
by this change because this halfway case always results in
the failure for Grisu.
The bug involves the incorrect logic for `core::num::flt2dec::decoder`.
This makes some numbers in the form of 2^n missing one final digits,
which breaks the bijectivity criterion. The regression tests have been
added, and f32 exhaustive test is rerun to get the updated result.
This is a fork of the flt2dec portion of rust-strconv [1] with
a necessary relicensing (the original code was licensed CC0-1.0).
Each module is accompanied with large unit tests, integrated
in this commit as coretest::num::flt2dec. This module is added
in order to replace the existing core::fmt::float method.
The forked revision of rust-strconv is from 2015-04-20, with a commit ID
9adf6d3571c6764a6f240a740c823024f70dc1c7.
[1] https://github.com/lifthrasiir/rust-strconv/
Specifically, make count, nth, and last call the corresponding methods
on the underlying iterator where possible. This way, if the underlying
iterator has an optimized count, nth, or last implementations (e.g.
slice::Iter), these methods will propagate these optimizations.
Additionally, change Skip::next to take advantage of a potentially
optimized nth method on the underlying iterator.
These implementations were intended to be unstable, but currently the stability
attributes cannot handle a stable trait with an unstable `impl` block. This
commit also audits the rest of the standard library for explicitly-`#[unstable]`
impl blocks. No others were removed but some annotations were changed to
`#[stable]` as they're defacto stable anyway.
One particularly interesting `impl` marked `#[stable]` as part of this commit
is the `Add<&[T]>` impl for `Vec<T>`, which uses `push_all` and implicitly
clones all elements of the vector provided.
Closes#24791
[breaking-change]
These implementations were intended to be unstable, but currently the stability
attributes cannot handle a stable trait with an unstable `impl` block. This
commit also audits the rest of the standard library for explicitly-`#[unstable]`
impl blocks. No others were removed but some annotations were changed to
`#[stable]` as they're defacto stable anyway.
One particularly interesting `impl` marked `#[stable]` as part of this commit
is the `Add<&[T]>` impl for `Vec<T>`, which uses `push_all` and implicitly
clones all elements of the vector provided.
Closes#24791
core: Fix size_hint for signed integer `Range<T>` iterators
There was an overflow bug in .size_hint() for signed iterators, which
produced an hilariously incorrect size or an overflow panic.
Incorrect size is a serious bug since the iterators are marked
ExactSizeIterator. (And leads to abort() on (-1i8..127).collect() when
the collection tries to preallocate too much).
> (-1i8..127).size_hint()
(18446744073709551488, Some(18446744073709551488))
Bug found using quickcheck.
Fixes#24851
Instead of using the O(n) defaults, define O(1) shortcuts. I also copied (and slightly modified) the relevant tests from the iter tests into the slice tests just in case someone comes along and changes them in the future.
Partially implements #24214.
There was an overflow bug in .size_hint() for signed iterators, which
produced an hilariously incorrect size or an overflow panic.
Incorrect size is a serious bug since the iterators are marked
ExactSizeIterator. (And leads to abort() on (-1i8..127).collect() when
the collection tries to preallocate too much).
All signed range iterators were affected.
> (-1i8..127).size_hint()
(18446744073709551488, Some(18446744073709551488))
Bug found using quickcheck.
Fixes#24851
Changes the style guidelines regarding unit tests to recommend using a
sub-module named "tests" instead of "test" for unit tests as "test"
might clash with imports of libtest.
This patch
1. renames libunicode to librustc_unicode,
2. deprecates several pieces of libunicode (see below), and
3. removes references to deprecated functions from
librustc_driver and libsyntax. This may change pretty-printed
output from these modules in cases involving wide or combining
characters used in filenames, identifiers, etc.
The following functions are marked deprecated:
1. char.width() and str.width():
--> use unicode-width crate
2. str.graphemes() and str.grapheme_indices():
--> use unicode-segmentation crate
3. str.nfd_chars(), str.nfkd_chars(), str.nfc_chars(), str.nfkc_chars(),
char.compose(), char.decompose_canonical(), char.decompose_compatible(),
char.canonical_combining_class():
--> use unicode-normalization crate
The main change in this patch is removing the use of `Option` inside the
inner loops of those functions to avoid comparisons where one branch
will only trigger on the first pass through the loop.
The included benchmarks go from:
test bench_max ... bench: 372 ns/iter (+/- 118)
test bench_max_by ... bench: 428 ns/iter (+/- 33)
test bench_max_by2 ... bench: 7128 ns/iter (+/- 326)
to:
test bench_max ... bench: 317 ns/iter (+/- 64)
test bench_max_by ... bench: 356 ns/iter (+/- 270)
test bench_max_by2 ... bench: 1387 ns/iter (+/- 183)
Problem noticed in http://www.reddit.com/r/rust/comments/31syce/using_iterators_to_find_the_index_of_the_min_or/
The main change in this patch is removing the use of `Option` inside the
inner loops of those functions to avoid comparisons where one branch
will only trigger on the first pass through the loop.
The included benchmarks go from:
test bench_max ... bench: 372 ns/iter (+/- 118)
test bench_max_by ... bench: 428 ns/iter (+/- 33)
test bench_max_by2 ... bench: 7128 ns/iter (+/- 326)
to:
test bench_max ... bench: 317 ns/iter (+/- 64)
test bench_max_by ... bench: 356 ns/iter (+/- 270)
test bench_max_by2 ... bench: 1387 ns/iter (+/- 183)
Problem noticed in http://www.reddit.com/r/rust/comments/31syce/using_iterators_to_find_the_index_of_the_min_or/
In addition to being nicer, this also allows you to use `sum` and `product` for
iterators yielding custom types aside from the standard integers.
Due to removing the `AdditiveIterator` and `MultiplicativeIterator` trait, this
is a breaking change.
[breaking-change]
This adds the missing methods and turns `str::pattern` in a user facing module, as per RFC.
This also contains some big internal refactorings:
- string iterator pairs are implemented with a central macro to reduce redundancy
- Moved all tests from `coretest::str` into `collectionstest::str` and left a note to prevent the two sets of tests drifting apart further.
See https://github.com/rust-lang/rust/issues/22477
These constants are small and can fit even in `u8`, but semantically they have type `usize` because they denote sizes and are almost always used in `usize` context. The change of their type to `u32` during the integer audit led only to the large amount of `as usize` noise (see the second commit, which removes this noise).
This is a minor [breaking-change] to an unstable interface.
r? @aturon
This commit is an implementation of [RFC 979][rfc] which changes the meaning of
the count parameter to the `splitn` function on strings and slices. The
parameter now means the number of items that are returned from the iterator, not
the number of splits that are made.
[rfc]: https://github.com/rust-lang/rfcs/pull/979Closes#23911
[breaking-change]
const_eval : add overflow-checking for {`+`, `-`, `*`, `/`, `<<`, `>>`}.
One tricky detail here: There is some duplication of labor between `rustc::middle::const_eval` and `rustc_trans::trans::consts`. It might be good to explore ways to try to factor out the common structure to the two passes (by abstracting over the particular value-representation used in the compile-time interpreter).
----
Update: Rebased atop #23841Fix#22531Fix#23030Fix#23221Fix#23235
This is a deprecated attribute that is slated for removal, and it also affects
all implementors of the trait. This commit removes the attribute and fixes up
implementors accordingly. The primary implementation which was lost was the
ability to compare `&[T]` and `Vec<T>` (in that order).
This change also modifies the `assert_eq!` macro to not consider both directions
of equality, only the one given in the left/right forms to the macro. This
modification is motivated due to the fact that `&[T] == Vec<T>` no longer
compiles, causing hundreds of errors in unit tests in the standard library (and
likely throughout the community as well).
Closes#19470
[breaking-change]
This commit cleans out a large amount of deprecated APIs from the standard
library and some of the facade crates as well, updating all users in the
compiler and in tests as it goes along.
This is a deprecated attribute that is slated for removal, and it also affects
all implementors of the trait. This commit removes the attribute and fixes up
implementors accordingly. The primary implementation which was lost was the
ability to compare `&[T]` and `Vec<T>` (in that order).
This change also modifies the `assert_eq!` macro to not consider both directions
of equality, only the one given in the left/right forms to the macro. This
modification is motivated due to the fact that `&[T] == Vec<T>` no longer
compiles, causing hundreds of errors in unit tests in the standard library (and
likely throughout the community as well).
cc #19470
[breaking-change]
This functions swaps the order of arguments to a few functions that previously
took (output, input) parameters, but now take (input, output) parameters (in
that order).
The affected functions are:
* ptr::copy
* ptr::copy_nonoverlapping
* slice::bytes::copy_memory
* intrinsics::copy
* intrinsics::copy_nonoverlapping
Closes#22890
[breaking-change]
The collections debug helpers no longer prefix output with the
collection name, in line with the current conventions for Debug
implementations. Implementations that want to preserve the current
behavior can simply add a `try!(write!(fmt, "TypeName "));` at the
beginning of the `fmt` method.
[breaking-change]
This permits all coercions to be performed in casts, but adds lints to warn in those cases.
Part of this patch moves cast checking to a later stage of type checking. We acquire obligations to check casts as part of type checking where we previously checked them. Once we have type checked a function or module, then we check any cast obligations which have been acquired. That means we have more type information available to check casts (this was crucial to making coercions work properly in place of some casts), but it means that casts cannot feed input into type inference.
[breaking change]
* Adds two new lints for trivial casts and trivial numeric casts, these are warn by default, but can cause errors if you build with warnings as errors. Previously, trivial numeric casts and casts to trait objects were allowed.
* The unused casts lint has gone.
* Interactions between casting and type inference have changed in subtle ways. Two ways this might manifest are:
- You may need to 'direct' casts more with extra type information, for example, in some cases where `foo as _ as T` succeeded, you may now need to specify the type for `_`
- Casts do not influence inference of integer types. E.g., the following used to type check:
```
let x = 42;
let y = &x as *const u32;
```
Because the cast would inform inference that `x` must have type `u32`. This no longer applies and the compiler will fallback to `i32` for `x` and thus there will be a type error in the cast. The solution is to add more type information:
```
let x: u32 = 42;
let y = &x as *const u32;
```
The method with which backwards compatibility was retained ended up leading to
documentation that rustdoc didn't handle well and largely ended up confusing.
possible blanket impls and also triggers internal overflow. Add some
special cases for common uses (&&str, &String) for now; bounds-targeting
deref coercions are probably the right longer term answer.
The method with which backwards compatibility was retained ended up leading to
documentation that rustdoc didn't handle well and largely ended up confusing.
This commit removes the reexports of `old_io` traits as well as `old_path` types
and traits from the prelude. This functionality is now all deprecated and needs
to be removed to make way for other functionality like `Seek` in the `std::io`
module (currently reexported as `NewSeek` in the io prelude).
Closes#23377Closes#23378
This commit deprecates the `count`, `range` and `range_step` functions
in `iter`, in favor of range notation. To recover all existing
functionality, a new `step_by` adapter is provided directly on `ops::Range`
and `ops::RangeFrom`.
[breaking-change]
I've made some minor changes from the implementation attached to the RFC to try to minimize codegen. The methods now take `&Debug` trait objects rather than being parameterized and there are inlined stub methods that call to non-inlined methods to do the work.
r? @alexcrichton
cc @huonw for the `derive(Debug)` changes.
This commit performs another pass over the `std::char` module for stabilization.
Some minor cleanup is performed such as migrating documentation from libcore to
libunicode (where the `std`-facing trait resides) as well as a slight
reorganiation in libunicode itself. Otherwise, the stability modifications made
are:
* `char::from_digit` is now stable
* `CharExt::is_digit` is now stable
* `CharExt::to_digit` is now stable
* `CharExt::to_{lower,upper}case` are now stable after being modified to return
an iterator over characters. While the implementation today has not changed
this should allow us to implement the full set of case conversions in unicode
where some characters can map to multiple when doing an upper or lower case
mapping.
* `StrExt::to_{lower,upper}case` was added as unstable for a convenience of not
having to worry about characters expanding to more characters when you just
want the whole string to get into upper or lower case.
This is a breaking change due to the change in the signatures of the
`CharExt::to_{upper,lower}case` methods. Code can be updated to use functions
like `flat_map` or `collect` to handle the difference.
[breaking-change]
Closes#20333
This commit performs another pass over the `std::char` module for stabilization.
Some minor cleanup is performed such as migrating documentation from libcore to
libunicode (where the `std`-facing trait resides) as well as a slight
reorganiation in libunicode itself. Otherwise, the stability modifications made
are:
* `char::from_digit` is now stable
* `CharExt::is_digit` is now stable
* `CharExt::to_digit` is now stable
* `CharExt::to_{lower,upper}case` are now stable after being modified to return
an iterator over characters. While the implementation today has not changed
this should allow us to implement the full set of case conversions in unicode
where some characters can map to multiple when doing an upper or lower case
mapping.
* `StrExt::to_{lower,upper}case` was added as unstable for a convenience of not
having to worry about characters expanding to more characters when you just
want the whole string to get into upper or lower case.
This is a breaking change due to the change in the signatures of the
`CharExt::to_{upper,lower}case` methods. Code can be updated to use functions
like `flat_map` or `collect` to handle the difference.
[breaking-change]
Many of the modifications putting in `Box::new` calls also include a
pointer to Issue 22405, which tracks going back to `box <expr>` if
possible in the future.
(Still tried to use `Box<_>` where it sufficed; thus some tests still
have `box_syntax` enabled, as they use a mix of `box` and `Box::new`.)
Precursor for overloaded-`box` and placement-`in`; see Issue 22181.
This is the kind of change that one is expected to need to make to
accommodate overloaded-`box`.
----
Note that this is not *all* of the changes necessary to accommodate
Issue 22181. It is merely the subset of those cases where there was
already a let-binding in place that made it easy to add the necesasry
type ascription.
(For unnamed intermediate `Box` values, one must go down a different
route; `Box::new` is the option that maximizes portability, but has
potential inefficiency depending on whether the call is inlined.)
----
There is one place worth note, `run-pass/coerce-match.rs`, where I
used an ugly form of `Box<_>` type ascription where I would have
preferred to use `Box::new` to accommodate overloaded-`box`. I
deliberately did not use `Box::new` here, because that is already done
in coerce-match-calls.rs.
----
Precursor for overloaded-`box` and placement-`in`; see Issue 22181.
Rebase and follow-through on work done by @cmr and @aatch.
Implements most of rust-lang/rfcs#560. Errors encountered from the checks during building were fixed.
The checks for division, remainder and bit-shifting have not been implemented yet.
See also PR #20795
cc @Aatch ; cc @nikomatsakis
* `core::num`: adjust `UnsignedInt::is_power_of_two`,
`UnsignedInt::next_power_of_two`, `Int::pow`.
In particular for `Int::pow`: (1.) do not panic when `base`
overflows if `acc` never observes the overflowed `base`, and (2.)
if `acc` does observe the overflowed `base`, make sure we only
panic if we would have otherwise (e.g. during a computation of
`base * base`).
* also in `core::num`: avoid underflow during computation of `uint::MAX`.
* `std::num`: adjust tests `uint::test_uint_from_str_overflow`,
`uint::test_uint_to_str_overflow`, `strconv`
* `coretest::num`: adjust `test::test_int_from_str_overflow`.
This changes the type of some public constants/statics in libunicode.
Notably some `&'static &'static [(char, char)]` have changed
to `&'static [(char, char)]`. The regexp crate seems to be the
sole user of these, yet this is technically a [breaking-change]
Changes .or() so that it can return a Result with a different E type
than the one it is called on.
Essentially:
fn or(self, res: Result<T, E>) -> Result<T, E>
becomes
fn or<F>(self, res: Result<T, F>) -> Result<T, F>
This brings `or` in line with the existing `and` & `or_else`
This is a
[breaking-change]
Due to some code needing additional type annotations.
Changes .or() so that it can return a Result with a different E type
than the one it is called on.
Essentially:
fn or(self, res: Result<T, E>) -> Result<T, E>
becomes
fn or<F>(self, res: Result<T, F>) -> Result<T, F>
This brings `or` in line with the existing `and` and `or_else` member
types.
This is a
[breaking-change]
Due to some code needing additional type annotations.
This is not a complete implementation of the RFC:
- only existing methods got updated, no new ones added
- doc comments are not extensive enough yet
- optimizations got lost and need to be reimplemented
See https://github.com/rust-lang/rfcs/pull/528
Technically a
[breaking-change]
This commit is an implementation of [RFC 823][rfc] which is another pass over
the `std::hash` module for stabilization. The contents of the module were not
entirely marked stable, but some portions which remained quite similar to the
previous incarnation are now marked `#[stable]`. Specifically:
[rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0823-hash-simplification.md
* `std::hash` is now stable (the name)
* `Hash` is now stable
* `Hash::hash` is now stable
* `Hasher` is now stable
* `SipHasher` is now stable
* `SipHasher::new` and `new_with_keys` are now stable
* `Hasher for SipHasher` is now stable
* Many `Hash` implementations are now stable
All other portions of the `hash` module remain `#[unstable]` as they are less
commonly used and were recently redesigned.
This commit is a breaking change due to the modifications to the `std::hash` API
and more details can be found on the [RFC][rfc].
Closes#22467
[breaking-change]
This overlaps with #22276 (I left make check running overnight) but covers a number of additional cases and has a few rewrites where the clones are not even necessary.
This also implements `RandomAccessIterator` for `iter::Cloned`
cc @steveklabnik, you may want to glance at this before #22281 gets the bors treatment
This commit is an implementation of [RFC 823][rfc] which is another pass over
the `std::hash` module for stabilization. The contents of the module were not
entirely marked stable, but some portions which remained quite similar to the
previous incarnation are now marked `#[stable]`. Specifically:
[rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0823-hash-simplification.md
* `std::hash` is now stable (the name)
* `Hash` is now stable
* `Hash::hash` is now stable
* `Hasher` is now stable
* `SipHasher` is now stable
* `SipHasher::new` and `new_with_keys` are now stable
* `Hasher for SipHasher` is now stable
* Many `Hash` implementations are now stable
All other portions of the `hash` module remain `#[unstable]` as they are less
commonly used and were recently redesigned.
This commit is a breaking change due to the modifications to the `std::hash` API
and more details can be found on the [RFC][rfc].
Closes#22467
[breaking-change]
Port `core::ptr::Unique` to have `PhantomData`. Add `PhantomData` to
`TypedArena` and `Vec` as well.
As a drive-by, switch `ptr::Unique` from a tuple-struct to a struct
with fields.
When self.start > self.end, these iterators simply return None,
so we adjust the size_hint to just return zero in this case.
Certain optimizations can be implemented in and outside libstd if we
know we can trust the size_hint for all inputs to for example
Range<usize>.
This corrects the ExactSizeIterator implementations, which IMO were
unsound and incorrect previously, since they allowed a range like (2..1)
to return a size_hint of -1us in when debug assertions are turned off.
Use the crates.io crate `rand` (version 0.1 should be a drop in
replacement for `std::rand`) and `rand_macros` (`#[derive_Rand]` should
be a drop-in replacement).
[breaking-change]
The existence of these two functions is at odds with our current [error
conventions][conventions] which recommend that panicking and `Result`-like
variants should not be provided together.
[conventions]: https://github.com/rust-lang/rfcs/blob/master/text/0236-error-conventions.md#do-not-provide-both-result-and-fail-variants
This commit adds a new `borrow_state` function returning a `BorrowState` enum to
`RefCell` which serves as a replacemnt for the `try_borrow` and `try_borrow_mut`
functions.
The existence of these two functions is at odds with our current [error
conventions][conventions] which recommend that panicking and `Result`-like
variants should not be provided together.
[conventions]: https://github.com/rust-lang/rfcs/blob/master/text/0236-error-conventions.md#do-not-provide-both-result-and-fail-variants
This commit adds a new `borrow_state` function returning a `BorrowState` enum to
`RefCell` which serves as a replacemnt for the `try_borrow` and `try_borrow_mut`
functions.
This commits adds an associated type to the `FromStr` trait representing an
error payload for parses which do not succeed. The previous return value,
`Option<Self>` did not allow for this form of payload. After the associated type
was added, the following attributes were applied:
* `FromStr` is now stable
* `FromStr::Err` is now stable
* `FromStr::from_str` is now stable
* `StrExt::parse` is now stable
* `FromStr for bool` is now stable
* `FromStr for $float` is now stable
* `FromStr for $integral` is now stable
* Errors returned from stable `FromStr` implementations are stable
* Errors implement `Display` and `Error` (both impl blocks being `#[stable]`)
Closes#15138
This commits adds an associated type to the `FromStr` trait representing an
error payload for parses which do not succeed. The previous return value,
`Option<Self>` did not allow for this form of payload. After the associated type
was added, the following attributes were applied:
* `FromStr` is now stable
* `FromStr::Err` is now stable
* `FromStr::from_str` is now stable
* `StrExt::parse` is now stable
* `FromStr for bool` is now stable
* `FromStr for $float` is now stable
* `FromStr for $integral` is now stable
* Errors returned from stable `FromStr` implementations are stable
* Errors implement `Display` and `Error` (both impl blocks being `#[stable]`)
Closes#15138