]> git.lizzy.rs Git - rust.git/commit
Add `core::num::wrapping` and fix overflow errors.
authorJames Miller <james@aatch.net>
Fri, 9 Jan 2015 03:10:57 +0000 (16:10 +1300)
committerFelix S. Klock II <pnkfelix@pnkfx.org>
Tue, 3 Mar 2015 11:10:19 +0000 (12:10 +0100)
commit1246d4067fdc034d064dfb78f88c2c3c079c3f4f
treea126ed9a0c48d2b6a486f311aa6d0924bbbb69aa
parentcdfff9db35d037c51dfd5c2bac2174f651294adb
Add `core::num::wrapping` and fix overflow errors.

Many of the core rust libraries have places that rely on integer
wrapping behaviour. These places have been altered to use the wrapping_*
methods:

 * core::hash::sip - A number of macros
 * core::str - The `maximal_suffix` method in `TwoWaySearcher`
 * rustc::util::nodemap - Implementation of FnvHash
 * rustc_back::sha2 - A number of macros and other places
 * rand::isaac - Isaac64Rng, changed to use the Wrapping helper type

Some places had "benign" underflow. This is when underflow or overflow
occurs, but the unspecified value is not used due to other conditions.

 * collections::bit::Bitv - underflow when `self.nbits` is zero.
 * collections::hash::{map,table} - Underflow when searching an empty
   table. Did cause undefined behaviour in this case due to an
   out-of-bounds ptr::offset based on the underflowed index. However the
   resulting pointers would never be read from.
 * syntax::ext::deriving::encodable - Underflow when calculating the
   index of the last field in a variant with no fields.

These cases were altered to avoid the underflow, often by moving the
underflowing operation to a place where underflow could not happen.

There was one case that relied on the fact that unsigned arithmetic and
two's complement arithmetic are identical with wrapping semantics. This
was changed to use the wrapping_* methods.

Finally, the calculation of variant discriminants could overflow if the
preceeding discriminant was `U64_MAX`. The logic in `rustc::middle::ty`
for this was altered to avoid the overflow completely, while the
remaining places were changed to use wrapping methods. This is because
`rustc::middle::ty::enum_variants` now throws an error when the
calculated discriminant value overflows a `u64`.

This behaviour can be triggered by the following code:

```
enum Foo {
  A = U64_MAX,
  B
}
```

This commit also implements the remaining integer operators for
Wrapped<T>.
19 files changed:
src/libcollections/bit.rs
src/libcore/hash/sip.rs
src/libcore/num/mod.rs
src/libcore/num/wrapping.rs [new file with mode: 0644]
src/libcore/str/mod.rs
src/librand/distributions/range.rs
src/librand/isaac.rs
src/librustc/metadata/decoder.rs
src/librustc/metadata/encoder.rs
src/librustc/middle/astencode.rs
src/librustc/middle/ty.rs
src/librustc/util/nodemap.rs
src/librustc_back/sha2.rs
src/librustc_typeck/check/mod.rs
src/libstd/collections/hash/map.rs
src/libstd/collections/hash/table.rs
src/libstd/num/mod.rs
src/libstd/prelude/v1.rs
src/libsyntax/ext/deriving/encodable.rs