From d84eb506e29bfc8eddb57e84b25cf548bb8e3f5a Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Tue, 3 Dec 2019 22:52:45 +0100 Subject: [PATCH 01/18] Fix TypedArena. --- src/libarena/lib.rs | 59 +++++++++------------------------------------ 1 file changed, 12 insertions(+), 47 deletions(-) diff --git a/src/libarena/lib.rs b/src/libarena/lib.rs index 66d27a275192e..854942dad3ded 100644 --- a/src/libarena/lib.rs +++ b/src/libarena/lib.rs @@ -202,53 +202,18 @@ impl TypedArena { #[inline] pub fn alloc_from_iter>(&self, iter: I) -> &mut [T] { assert!(mem::size_of::() != 0); - let mut iter = iter.into_iter(); - let size_hint = iter.size_hint(); - - match size_hint { - (min, Some(max)) if min == max => { - // We know the exact number of elements the iterator will produce here - let len = min; - - if len == 0 { - return &mut []; - } - - self.ensure_capacity(len); - - let slice = self.ptr.get(); - - unsafe { - let mut ptr = self.ptr.get(); - for _ in 0..len { - // Write into uninitialized memory. - ptr::write(ptr, iter.next().unwrap()); - // Advance the pointer. - ptr = ptr.offset(1); - // Update the pointer per iteration so if `iter.next()` panics - // we destroy the correct amount - self.ptr.set(ptr); - } - slice::from_raw_parts_mut(slice, len) - } - } - _ => { - cold_path(move || -> &mut [T] { - let mut vec: SmallVec<[_; 8]> = iter.collect(); - if vec.is_empty() { - return &mut []; - } - // Move the content to the arena by copying it and then forgetting - // the content of the SmallVec - unsafe { - let len = vec.len(); - let start_ptr = self.alloc_raw_slice(len); - vec.as_ptr().copy_to_nonoverlapping(start_ptr, len); - vec.set_len(0); - slice::from_raw_parts_mut(start_ptr, len) - } - }) - } + let mut vec: SmallVec<[_; 8]> = iter.into_iter().collect(); + if vec.is_empty() { + return &mut []; + } + // Move the content to the arena by copying it and then forgetting + // the content of the SmallVec + unsafe { + let len = vec.len(); + let start_ptr = self.alloc_raw_slice(len); + vec.as_ptr().copy_to_nonoverlapping(start_ptr, len); + vec.set_len(0); + slice::from_raw_parts_mut(start_ptr, len) } } From d358b246b4fb5bd637b009a34d82c904a97d0344 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Miku=C5=82a?= Date: Wed, 4 Dec 2019 18:40:16 +0100 Subject: [PATCH 02/18] Update tokio crates to latest versions --- Cargo.lock | 130 +++++++++++++++++++---------------------------------- 1 file changed, 47 insertions(+), 83 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5e83513af5b37..789206501df2e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -734,16 +734,6 @@ dependencies = [ "crossbeam-utils 0.2.2", ] -[[package]] -name = "crossbeam-deque" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05e44b8cf3e1a625844d1750e1f7820da46044ff6d28f4d43e455ba3e5bb2c13" -dependencies = [ - "crossbeam-epoch 0.7.2", - "crossbeam-utils 0.6.5", -] - [[package]] name = "crossbeam-deque" version = "0.7.1" @@ -1760,7 +1750,7 @@ dependencies = [ "jsonrpc-server-utils", "log", "parity-tokio-ipc", - "parking_lot 0.9.0", + "parking_lot", "tokio-service", ] @@ -1772,7 +1762,7 @@ checksum = "e2c08b444cc0ed70263798834343d0ac875e664257df8079160f23ac1ea79446" dependencies = [ "jsonrpc-core", "log", - "parking_lot 0.9.0", + "parking_lot", "serde", ] @@ -1884,16 +1874,6 @@ dependencies = [ name = "linkchecker" version = "0.1.0" -[[package]] -name = "lock_api" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "949826a5ccf18c1b3a7c3d57692778d21768b79e46eb9dd07bfc4c2160036c54" -dependencies = [ - "owning_ref", - "scopeguard 0.3.3", -] - [[package]] name = "lock_api" version = "0.3.1" @@ -2358,15 +2338,6 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd20eec3dbe4376829cb7d80ae6ac45e0a766831dca50202ff2d40db46a8a024" -[[package]] -name = "owning_ref" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdf84f41639e037b484f93433aa3897863b561ed65c6e59c7073d7c561710f37" -dependencies = [ - "stable_deref_trait", -] - [[package]] name = "packed_simd" version = "0.3.1" @@ -2415,40 +2386,17 @@ dependencies = [ "winapi 0.3.8", ] -[[package]] -name = "parking_lot" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab41b4aed082705d1056416ae4468b6ea99d52599ecf3169b00088d43113e337" -dependencies = [ - "lock_api 0.1.3", - "parking_lot_core 0.4.0", -] - [[package]] name = "parking_lot" version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f842b1982eb6c2fe34036a4fbfb06dd185a3f5c8edfaacdf7d1ea10b07de6252" dependencies = [ - "lock_api 0.3.1", - "parking_lot_core 0.6.2", + "lock_api", + "parking_lot_core", "rustc_version", ] -[[package]] -name = "parking_lot_core" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94c8c7923936b28d546dfd14d4472eaf34c99b14e1c973a32b3e6d4eb04298c9" -dependencies = [ - "libc", - "rand 0.6.1", - "rustc_version", - "smallvec 0.6.10", - "winapi 0.3.8", -] - [[package]] name = "parking_lot_core" version = "0.6.2" @@ -3193,7 +3141,7 @@ dependencies = [ "log", "measureme", "num_cpus", - "parking_lot 0.9.0", + "parking_lot", "polonius-engine", "rustc-rayon 0.3.0", "rustc-rayon-core 0.3.0", @@ -3243,7 +3191,7 @@ dependencies = [ "jobserver", "lazy_static 1.3.0", "log", - "parking_lot 0.9.0", + "parking_lot", "rustc-ap-graphviz", "rustc-ap-rustc_index", "rustc-ap-serialize", @@ -3556,7 +3504,7 @@ dependencies = [ "lazy_static 1.3.0", "log", "measureme", - "parking_lot 0.9.0", + "parking_lot", "rustc-hash", "rustc-rayon 0.3.0", "rustc-rayon-core 0.3.0", @@ -4693,9 +4641,9 @@ dependencies = [ [[package]] name = "tokio" -version = "0.1.14" +version = "0.1.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4790d0be6f4ba6ae4f48190efa2ed7780c9e3567796abdb285003cf39840d9c5" +checksum = "5a09c0b5bb588872ab2f09afa13ee6e9dac11e10a0ec9e8e3ba39a5a5d530af6" dependencies = [ "bytes", "futures", @@ -4707,6 +4655,7 @@ dependencies = [ "tokio-fs", "tokio-io", "tokio-reactor", + "tokio-sync", "tokio-tcp", "tokio-threadpool", "tokio-timer", @@ -4738,9 +4687,9 @@ dependencies = [ [[package]] name = "tokio-current-thread" -version = "0.1.4" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "331c8acc267855ec06eb0c94618dcbbfea45bed2d20b77252940095273fb58f6" +checksum = "d16217cad7f1b840c5a97dfb3c43b0c871fef423a6e8d2118c604e843662a443" dependencies = [ "futures", "tokio-executor", @@ -4748,9 +4697,9 @@ dependencies = [ [[package]] name = "tokio-executor" -version = "0.1.6" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30c6dbf2d1ad1de300b393910e8a3aa272b724a400b6531da03eed99e329fbf0" +checksum = "ca6df436c42b0c3330a82d855d2ef017cd793090ad550a6bc2184f4b933532ab" dependencies = [ "crossbeam-utils 0.6.5", "futures", @@ -4758,9 +4707,9 @@ dependencies = [ [[package]] name = "tokio-fs" -version = "0.1.5" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e9cbbc8a3698b7ab652340f46633364f9eaa928ddaaee79d8b8f356dd79a09d" +checksum = "3fe6dc22b08d6993916647d108a1a7d15b9cd29c4f4496c62b92c45b5041b7af" dependencies = [ "futures", "tokio-io", @@ -4769,9 +4718,9 @@ dependencies = [ [[package]] name = "tokio-io" -version = "0.1.11" +version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b53aeb9d3f5ccf2ebb29e19788f96987fa1355f8fe45ea193928eaaaf3ae820f" +checksum = "5090db468dad16e1a7a54c8c67280c5e4b544f3d3e018f0b913b400261f85926" dependencies = [ "bytes", "futures", @@ -4793,12 +4742,15 @@ dependencies = [ [[package]] name = "tokio-process" -version = "0.2.3" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88e1281e412013f1ff5787def044a9577a0bed059f451e835f1643201f8b777d" +checksum = "afbd6ef1b8cc2bd2c2b580d882774d443ebb1c6ceefe35ba9ea4ab586c89dbe8" dependencies = [ + "crossbeam-queue", "futures", + "lazy_static 1.3.0", "libc", + "log", "mio", "mio-named-pipes", "tokio-io", @@ -4809,9 +4761,9 @@ dependencies = [ [[package]] name = "tokio-reactor" -version = "0.1.8" +version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afbcdb0f0d2a1e4c440af82d7bbf0bf91a8a8c0575bcd20c05d15be7e9d3a02f" +checksum = "6732fe6b53c8d11178dcb77ac6d9682af27fc6d4cb87789449152e5377377146" dependencies = [ "crossbeam-utils 0.6.5", "futures", @@ -4819,10 +4771,11 @@ dependencies = [ "log", "mio", "num_cpus", - "parking_lot 0.7.1", + "parking_lot", "slab", "tokio-executor", "tokio-io", + "tokio-sync", ] [[package]] @@ -4851,6 +4804,16 @@ dependencies = [ "winapi 0.3.8", ] +[[package]] +name = "tokio-sync" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d06554cce1ae4a50f42fba8023918afa931413aded705b560e29600ccf7c6d76" +dependencies = [ + "fnv", + "futures", +] + [[package]] name = "tokio-tcp" version = "0.1.3" @@ -4867,25 +4830,26 @@ dependencies = [ [[package]] name = "tokio-threadpool" -version = "0.1.10" +version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17465013014410310f9f61fa10bf4724803c149ea1d51efece131c38efca93aa" +checksum = "2bd2c6a3885302581f4401c82af70d792bb9df1700e7437b0aeb4ada94d5388c" dependencies = [ - "crossbeam-channel", - "crossbeam-deque 0.6.3", + "crossbeam-deque 0.7.1", + "crossbeam-queue", "crossbeam-utils 0.6.5", "futures", + "lazy_static 1.3.0", "log", "num_cpus", - "rand 0.6.1", + "slab", "tokio-executor", ] [[package]] name = "tokio-timer" -version = "0.2.8" +version = "0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f37f0111d76cc5da132fe9bc0590b9b9cfd079bc7e75ac3846278430a299ff8" +checksum = "1739638e364e558128461fc1ad84d997702c8e31c2e6b18fb99842268199e827" dependencies = [ "crossbeam-utils 0.6.5", "futures", @@ -4895,9 +4859,9 @@ dependencies = [ [[package]] name = "tokio-udp" -version = "0.1.3" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66268575b80f4a4a710ef83d087fdfeeabdce9b74c797535fbac18a2cb906e92" +checksum = "f02298505547f73e60f568359ef0d016d5acd6e830ab9bc7c4a5b3403440121b" dependencies = [ "bytes", "futures", From 479cc7ae9ab02700516829221291865944e2c6cb Mon Sep 17 00:00:00 2001 From: lqd Date: Mon, 18 Nov 2019 13:45:41 +0100 Subject: [PATCH 03/18] update to polonius 0.11 to compute subset errors - adapt to the new polonius `FactTypes` API - reorganize the type aliases referring to polonius to avoid referencing the inner atom or fact types multiple times: only one input and output types should be enough for everyone. They could equally be in `borrow_check` as `nll` though. --- Cargo.lock | 4 ++-- src/librustc/Cargo.toml | 2 +- src/librustc_mir/Cargo.toml | 2 +- src/librustc_mir/borrow_check/flows.rs | 9 +++------ src/librustc_mir/borrow_check/nll/facts.rs | 15 +++++++++++++-- src/librustc_mir/borrow_check/nll/mod.rs | 11 ++++++----- 6 files changed, 26 insertions(+), 17 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 26727c5c1db60..65e58b798df67 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2575,9 +2575,9 @@ checksum = "676e8eb2b1b4c9043511a9b7bea0915320d7e502b0a079fb03f9635a5252b18c" [[package]] name = "polonius-engine" -version = "0.10.0" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50fa9dbfd0d3d60594da338cfe6f94028433eecae4b11b7e83fd99759227bbfe" +checksum = "1e478d7c38eb785c6416cbe58df12aa55d7aefa3759b6d3e044b2ed03f423cec" dependencies = [ "datafrog", "log", diff --git a/src/librustc/Cargo.toml b/src/librustc/Cargo.toml index f8ad6f8f30edb..fb5387ffd018e 100644 --- a/src/librustc/Cargo.toml +++ b/src/librustc/Cargo.toml @@ -20,7 +20,7 @@ scoped-tls = "1.0" log = { version = "0.4", features = ["release_max_level_info", "std"] } rustc-rayon = "0.3.0" rustc-rayon-core = "0.3.0" -polonius-engine = "0.10.0" +polonius-engine = "0.11.0" rustc_apfloat = { path = "../librustc_apfloat" } rustc_feature = { path = "../librustc_feature" } rustc_target = { path = "../librustc_target" } diff --git a/src/librustc_mir/Cargo.toml b/src/librustc_mir/Cargo.toml index 4afbb4d85d025..7e3bd98176e6a 100644 --- a/src/librustc_mir/Cargo.toml +++ b/src/librustc_mir/Cargo.toml @@ -16,7 +16,7 @@ dot = { path = "../libgraphviz", package = "graphviz" } itertools = "0.8" log = "0.4" log_settings = "0.1.1" -polonius-engine = "0.10.0" +polonius-engine = "0.11.0" rustc = { path = "../librustc" } rustc_target = { path = "../librustc_target" } rustc_data_structures = { path = "../librustc_data_structures" } diff --git a/src/librustc_mir/borrow_check/flows.rs b/src/librustc_mir/borrow_check/flows.rs index ce5d2a14bd122..57c544fda0c54 100644 --- a/src/librustc_mir/borrow_check/flows.rs +++ b/src/librustc_mir/borrow_check/flows.rs @@ -3,16 +3,15 @@ //! FIXME: this might be better as a "generic" fixed-point combinator, //! but is not as ugly as it is right now. -use rustc::mir::{BasicBlock, Local, Location}; -use rustc::ty::RegionVid; +use rustc::mir::{BasicBlock, Location}; use rustc_index::bit_set::BitIter; use crate::borrow_check::location::LocationIndex; -use polonius_engine::Output; +use crate::borrow_check::nll::PoloniusOutput; use crate::dataflow::indexes::BorrowIndex; -use crate::dataflow::move_paths::{HasMoveData, MovePathIndex}; +use crate::dataflow::move_paths::HasMoveData; use crate::dataflow::Borrows; use crate::dataflow::EverInitializedPlaces; use crate::dataflow::MaybeUninitializedPlaces; @@ -21,8 +20,6 @@ use either::Either; use std::fmt; use std::rc::Rc; -crate type PoloniusOutput = Output; - crate struct Flows<'b, 'tcx> { borrows: FlowAtLocation<'tcx, Borrows<'b, 'tcx>>, pub uninits: FlowAtLocation<'tcx, MaybeUninitializedPlaces<'b, 'tcx>>, diff --git a/src/librustc_mir/borrow_check/nll/facts.rs b/src/librustc_mir/borrow_check/nll/facts.rs index 13e5769c5bea8..eabb11acab91e 100644 --- a/src/librustc_mir/borrow_check/nll/facts.rs +++ b/src/librustc_mir/borrow_check/nll/facts.rs @@ -1,6 +1,6 @@ use crate::borrow_check::location::{LocationIndex, LocationTable}; use crate::dataflow::indexes::{BorrowIndex, MovePathIndex}; -use polonius_engine::AllFacts as PoloniusAllFacts; +use polonius_engine::AllFacts as PoloniusFacts; use polonius_engine::Atom; use rustc::mir::Local; use rustc::ty::{RegionVid, TyCtxt}; @@ -11,7 +11,18 @@ use std::fs::{self, File}; use std::io::Write; use std::path::Path; -crate type AllFacts = PoloniusAllFacts; +#[derive(Copy, Clone, Debug)] +crate struct RustcFacts; + +impl polonius_engine::FactTypes for RustcFacts { + type Origin = RegionVid; + type Loan = BorrowIndex; + type Point = LocationIndex; + type Variable = Local; + type Path = MovePathIndex; +} + +crate type AllFacts = PoloniusFacts; crate trait AllFactsExt { /// Returns `true` if there is a need to gather `AllFacts` given the diff --git a/src/librustc_mir/borrow_check/nll/mod.rs b/src/librustc_mir/borrow_check/nll/mod.rs index b9363200cdf28..337f612f7cea9 100644 --- a/src/librustc_mir/borrow_check/nll/mod.rs +++ b/src/librustc_mir/borrow_check/nll/mod.rs @@ -1,10 +1,9 @@ use crate::borrow_check::borrow_set::BorrowSet; -use crate::borrow_check::location::{LocationIndex, LocationTable}; +use crate::borrow_check::location::LocationTable; use crate::borrow_check::nll::facts::AllFactsExt; use crate::borrow_check::nll::type_check::{MirTypeckResults, MirTypeckRegionConstraints}; use crate::borrow_check::nll::region_infer::values::RegionValueElements; -use crate::dataflow::indexes::BorrowIndex; -use crate::dataflow::move_paths::{InitLocation, MoveData, MovePathIndex, InitKind}; +use crate::dataflow::move_paths::{InitLocation, MoveData, InitKind}; use crate::dataflow::FlowAtLocation; use crate::dataflow::MaybeInitializedPlaces; use crate::transform::MirSource; @@ -43,10 +42,12 @@ crate mod universal_regions; crate mod type_check; crate mod region_infer; -use self::facts::AllFacts; +use self::facts::{AllFacts, RustcFacts}; use self::region_infer::RegionInferenceContext; use self::universal_regions::UniversalRegions; +crate type PoloniusOutput = Output; + /// Rewrites the regions in the MIR to use NLL variables, also /// scraping out the set of universal regions (e.g., region parameters) /// declared on the function. That set will need to be given to @@ -170,7 +171,7 @@ pub(in crate::borrow_check) fn compute_regions<'cx, 'tcx>( errors_buffer: &mut Vec, ) -> ( RegionInferenceContext<'tcx>, - Option>>, + Option>, Option>, ) { let mut all_facts = if AllFacts::enabled(infcx.tcx) { From 4b16ae1609c65d337d4f22e2f4ddea0c4c467b3b Mon Sep 17 00:00:00 2001 From: Remy Rakic Date: Tue, 19 Nov 2019 16:53:52 +0100 Subject: [PATCH 04/18] Add a way to list the base non-transitive edges in `TransitiveRelation` --- src/librustc_data_structures/transitive_relation.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/librustc_data_structures/transitive_relation.rs b/src/librustc_data_structures/transitive_relation.rs index a3926c1555172..bbf6999b98375 100644 --- a/src/librustc_data_structures/transitive_relation.rs +++ b/src/librustc_data_structures/transitive_relation.rs @@ -373,6 +373,14 @@ impl TransitiveRelation { } matrix } + + /// Lists all the base edges in the graph: the initial _non-transitive_ set of element + /// relations, which will be later used as the basis for the transitive closure computation. + pub fn base_edges(&self) -> impl Iterator { + self.edges + .iter() + .map(move |edge| (&self.elements[edge.source.0], &self.elements[edge.target.0])) + } } /// Pare down is used as a step in the LUB computation. It edits the From 4dd6292c3c563e53732672d878930a9c26d512fc Mon Sep 17 00:00:00 2001 From: Remy Rakic Date: Tue, 19 Nov 2019 16:55:58 +0100 Subject: [PATCH 05/18] UniversalRegionRelations: add a way to list the base non-transitive `outlives` constraints --- .../borrow_check/nll/type_check/free_region_relations.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/librustc_mir/borrow_check/nll/type_check/free_region_relations.rs b/src/librustc_mir/borrow_check/nll/type_check/free_region_relations.rs index d18a8e87453a5..8bb68383a49ba 100644 --- a/src/librustc_mir/borrow_check/nll/type_check/free_region_relations.rs +++ b/src/librustc_mir/borrow_check/nll/type_check/free_region_relations.rs @@ -217,6 +217,11 @@ impl UniversalRegionRelations<'tcx> { crate fn regions_outlived_by(&self, fr1: RegionVid) -> Vec<&RegionVid> { self.outlives.reachable_from(&fr1) } + + /// Returns the _non-transitive_ set of known `outlives` constraints between free regions. + crate fn known_outlives(&self) -> impl Iterator { + self.outlives.base_edges() + } } struct UniversalRegionRelationsBuilder<'this, 'tcx> { From 7a3dca69bb706a015cf220a80ca35234dd2aeee6 Mon Sep 17 00:00:00 2001 From: Remy Rakic Date: Tue, 19 Nov 2019 16:58:09 +0100 Subject: [PATCH 06/18] Polonius: emit `placeholder` and `known_subset` facts, as inputs to the subset error computation --- src/librustc_mir/borrow_check/nll/facts.rs | 2 ++ src/librustc_mir/borrow_check/nll/mod.rs | 30 ++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/src/librustc_mir/borrow_check/nll/facts.rs b/src/librustc_mir/borrow_check/nll/facts.rs index eabb11acab91e..a16c36d749f0d 100644 --- a/src/librustc_mir/borrow_check/nll/facts.rs +++ b/src/librustc_mir/borrow_check/nll/facts.rs @@ -66,6 +66,7 @@ impl AllFactsExt for AllFacts { wr.write_facts_to_path(self.[ borrow_region, universal_region, + placeholder, cfg_edge, killed, outlives, @@ -80,6 +81,7 @@ impl AllFactsExt for AllFacts { initialized_at, moved_out_at, path_accessed_at, + known_subset, ]) } Ok(()) diff --git a/src/librustc_mir/borrow_check/nll/mod.rs b/src/librustc_mir/borrow_check/nll/mod.rs index 337f612f7cea9..ffd9c011717df 100644 --- a/src/librustc_mir/borrow_check/nll/mod.rs +++ b/src/librustc_mir/borrow_check/nll/mod.rs @@ -209,6 +209,36 @@ pub(in crate::borrow_check) fn compute_regions<'cx, 'tcx>( .universal_region .extend(universal_regions.universal_regions()); populate_polonius_move_facts(all_facts, move_data, location_table, &body); + + // Emit universal regions facts, and their relations, for Polonius. + // + // 1: universal regions are modeled in Polonius as a pair: + // - the universal region vid itself. + // - a "placeholder loan" associated to this universal region. Since they don't exist in + // the `borrow_set`, their `BorrowIndex` are synthesized as the universal region index + // added to the existing number of loans, as if they succeeded them in the set. + // + let borrow_count = borrow_set.borrows.len(); + debug!( + "compute_regions: polonius placeholders, num_universals={}, borrow_count={}", + universal_regions.len(), + borrow_count + ); + + for universal_region in universal_regions.universal_regions() { + let universal_region_idx = universal_region.index(); + let placeholder_loan_idx = borrow_count + universal_region_idx; + all_facts.placeholder.push((universal_region, placeholder_loan_idx.into())); + } + + // 2: the universal region relations `outlives` constraints are emitted as + // `known_subset` facts. + for (fr1, fr2) in universal_region_relations.known_outlives() { + if fr1 != fr2 { + debug!("compute_regions: emitting polonius `known_subset` fr1={:?}, fr2={:?}", fr1, fr2); + all_facts.known_subset.push((*fr1, *fr2)); + } + } } // Create the region inference context, taking ownership of the From 02a6662e2feec6ecf49d497c78ecf17599223e03 Mon Sep 17 00:00:00 2001 From: Remy Rakic Date: Wed, 20 Nov 2019 11:13:03 +0100 Subject: [PATCH 07/18] Implement subset errors using Polonius - switches to using the Naive variant by default - emits subset errors or propagates unsatisfied obligations to the caller --- src/librustc_mir/borrow_check/nll/mod.rs | 4 +- .../borrow_check/nll/region_infer/mod.rs | 186 ++++++++++++++++-- 2 files changed, 172 insertions(+), 18 deletions(-) diff --git a/src/librustc_mir/borrow_check/nll/mod.rs b/src/librustc_mir/borrow_check/nll/mod.rs index ffd9c011717df..5be299f2a9440 100644 --- a/src/librustc_mir/borrow_check/nll/mod.rs +++ b/src/librustc_mir/borrow_check/nll/mod.rs @@ -300,7 +300,7 @@ pub(in crate::borrow_check) fn compute_regions<'cx, 'tcx>( if infcx.tcx.sess.opts.debugging_opts.polonius { let algorithm = env::var("POLONIUS_ALGORITHM") - .unwrap_or_else(|_| String::from("Hybrid")); + .unwrap_or_else(|_| String::from("Naive")); let algorithm = Algorithm::from_str(&algorithm).unwrap(); debug!("compute_regions: using polonius algorithm {:?}", algorithm); Some(Rc::new(Output::compute( @@ -315,7 +315,7 @@ pub(in crate::borrow_check) fn compute_regions<'cx, 'tcx>( // Solve the region constraints. let closure_region_requirements = - regioncx.solve(infcx, &body, local_names, upvars, def_id, errors_buffer); + regioncx.solve(infcx, &body, local_names, upvars, def_id, errors_buffer, polonius_output.clone()); // Dump MIR results into a file, if that is enabled. This let us // write unit-tests, as well as helping with debugging. diff --git a/src/librustc_mir/borrow_check/nll/region_infer/mod.rs b/src/librustc_mir/borrow_check/nll/region_infer/mod.rs index 85031d6210a4d..574c64aa571cb 100644 --- a/src/librustc_mir/borrow_check/nll/region_infer/mod.rs +++ b/src/librustc_mir/borrow_check/nll/region_infer/mod.rs @@ -44,7 +44,7 @@ use crate::borrow_check::{ use self::values::{LivenessValues, RegionValueElements, RegionValues}; use super::universal_regions::UniversalRegions; -use super::ToRegionVid; +use super::{PoloniusOutput, ToRegionVid}; mod dump_mir; mod graphviz; @@ -484,6 +484,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { upvars: &[Upvar], mir_def_id: DefId, errors_buffer: &mut Vec, + polonius_output: Option>, ) -> Option> { self.propagate_constraints(body); @@ -509,16 +510,33 @@ impl<'tcx> RegionInferenceContext<'tcx> { // multiple problems. let mut region_naming = RegionErrorNamingCtx::new(); - self.check_universal_regions( - infcx, - body, - local_names, - upvars, - mir_def_id, - outlives_requirements.as_mut(), - errors_buffer, - &mut region_naming, - ); + // In Polonius mode, the errors about missing universal region relations are in the output + // and need to be emitted or propagated. Otherwise, we need to check whether the + // constraints were too strong, and if so, emit or propagate those errors. + if infcx.tcx.sess.opts.debugging_opts.polonius { + self.check_polonius_subset_errors( + infcx, + body, + local_names, + upvars, + mir_def_id, + outlives_requirements.as_mut(), + errors_buffer, + &mut region_naming, + polonius_output.expect("Polonius output is unavailable despite `-Z polonius`"), + ); + } else { + self.check_universal_regions( + infcx, + body, + local_names, + upvars, + mir_def_id, + outlives_requirements.as_mut(), + errors_buffer, + &mut region_naming, + ); + } self.check_member_constraints(infcx, mir_def_id, errors_buffer); @@ -1375,6 +1393,111 @@ impl<'tcx> RegionInferenceContext<'tcx> { outlives_suggestion.add_suggestion(body, self, infcx, errors_buffer, region_naming); } + /// Checks if Polonius has found any unexpected free region relations. + /// + /// In Polonius terms, a "subset error" (or "illegal subset relation error") is the equivalent + /// of NLL's "checking if any region constraints were too strong": a placeholder origin `'a` + /// was unexpectedly found to be a subset of another placeholder origin `'b`, and means in NLL + /// terms that the "longer free region" `'a` outlived the "shorter free region" `'b`. + /// + /// More details can be found in this blog post by Niko: + /// http://smallcultfollowing.com/babysteps/blog/2019/01/17/polonius-and-region-errors/ + /// + /// In the canonical example + /// + /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x } + /// + /// returning `x` requires `&'a u32 <: &'b u32` and hence we establish (transitively) a + /// constraint that `'a: 'b`. It is an error that we have no evidence that this + /// constraint holds. + /// + /// If `propagated_outlives_requirements` is `Some`, then we will + /// push unsatisfied obligations into there. Otherwise, we'll + /// report them as errors. + fn check_polonius_subset_errors( + &self, + infcx: &InferCtxt<'_, 'tcx>, + body: &Body<'tcx>, + local_names: &IndexVec>, + upvars: &[Upvar], + mir_def_id: DefId, + mut propagated_outlives_requirements: Option<&mut Vec>>, + errors_buffer: &mut Vec, + region_naming: &mut RegionErrorNamingCtx, + polonius_output: Rc, + ) { + debug!("check_polonius_subset_errors: {} subset_errors", polonius_output.subset_errors.len()); + + let mut outlives_suggestion = OutlivesSuggestionBuilder::new(mir_def_id, local_names); + + // Similarly to `check_universal_regions`: a free region relation, which was not explicitly + // declared ("known") was found by Polonius, so emit an error, or propagate the + // requirements for our caller into the `propagated_outlives_requirements` vector. + // + // Polonius doesn't model regions ("origins") as CFG-subsets or durations, but the + // `longer_fr` and `shorter_fr` terminology will still be used here, for consistency with + // the rest of the NLL infrastructure. The "subset origin" is the "longer free region", + // and the "superset origin" is the outlived "shorter free region". + // + // Note: Polonius will produce a subset error at every point where the unexpected + // `longer_fr`'s "placeholder loan" is contained in the `shorter_fr`. This can be helpful + // for diagnostics in the future, e.g. to point more precisely at the key locations + // requiring this constraint to hold. However, the error and diagnostics code downstream + // expects that these errors are not duplicated (and that they are in a certain order). + // Otherwise, diagnostics messages such as the ones giving names like `'1` to elided or + // anonymous lifetimes for example, could give these names differently, while others like + // the outlives suggestions or the debug output from `#[rustc_regions]` would be + // duplicated. The polonius subset errors are deduplicated here, while keeping the + // CFG-location ordering. + let mut subset_errors: Vec<_> = polonius_output + .subset_errors + .iter() + .flat_map(|(_location, subset_errors)| subset_errors.iter()) + .collect(); + subset_errors.sort(); + subset_errors.dedup(); + + for (longer_fr, shorter_fr) in subset_errors.into_iter() { + debug!("check_polonius_subset_errors: subset_error longer_fr={:?},\ + shorter_fr={:?}", longer_fr, shorter_fr); + + self.report_or_propagate_universal_region_error( + *longer_fr, + *shorter_fr, + infcx, + body, + local_names, + upvars, + mir_def_id, + &mut propagated_outlives_requirements, + &mut outlives_suggestion, + errors_buffer, + region_naming, + ); + } + + // Handle the placeholder errors as usual, until the chalk-rustc-polonius triumvirate has + // a more complete picture on how to separate this responsibility. + for (fr, fr_definition) in self.definitions.iter_enumerated() { + match fr_definition.origin { + NLLRegionVariableOrigin::FreeRegion => { + // handled by polonius above + } + + NLLRegionVariableOrigin::Placeholder(placeholder) => { + self.check_bound_universal_region(infcx, body, mir_def_id, fr, placeholder); + } + + NLLRegionVariableOrigin::Existential { .. } => { + // nothing to check here + } + } + } + + // Emit outlives suggestions + outlives_suggestion.add_suggestion(body, self, infcx, errors_buffer, region_naming); + } + /// Checks the final value for the free region `fr` to see if it /// grew too large. In particular, examine what `end(X)` points /// wound up in `fr`'s final value; for each `end(X)` where `X != @@ -1474,8 +1597,37 @@ impl<'tcx> RegionInferenceContext<'tcx> { return None; } + self.report_or_propagate_universal_region_error( + longer_fr, + shorter_fr, + infcx, + body, + local_names, + upvars, + mir_def_id, + propagated_outlives_requirements, + outlives_suggestion, + errors_buffer, + region_naming, + ) + } + + fn report_or_propagate_universal_region_error( + &self, + longer_fr: RegionVid, + shorter_fr: RegionVid, + infcx: &InferCtxt<'_, 'tcx>, + body: &Body<'tcx>, + local_names: &IndexVec>, + upvars: &[Upvar], + mir_def_id: DefId, + propagated_outlives_requirements: &mut Option<&mut Vec>>, + outlives_suggestion: &mut OutlivesSuggestionBuilder<'_>, + errors_buffer: &mut Vec, + region_naming: &mut RegionErrorNamingCtx, + ) -> Option { debug!( - "check_universal_region_relation: fr={:?} does not outlive shorter_fr={:?}", + "report_or_propagate_universal_region_error: fr={:?} does not outlive shorter_fr={:?}", longer_fr, shorter_fr, ); @@ -1484,9 +1636,9 @@ impl<'tcx> RegionInferenceContext<'tcx> { // We'll call it `fr-` -- it's ever so slightly smaller than // `longer_fr`. - if let Some(fr_minus) = self.universal_region_relations.non_local_lower_bound(longer_fr) - { - debug!("check_universal_region: fr_minus={:?}", fr_minus); + if let Some(fr_minus) = + self.universal_region_relations.non_local_lower_bound(longer_fr) { + debug!("report_or_propagate_universal_region_error: fr_minus={:?}", fr_minus); let blame_span_category = self.find_outlives_blame_span(body, longer_fr, @@ -1497,7 +1649,9 @@ impl<'tcx> RegionInferenceContext<'tcx> { // so slightly larger than `shorter_fr`. let shorter_fr_plus = self.universal_region_relations.non_local_upper_bounds(&shorter_fr); - debug!("check_universal_region: shorter_fr_plus={:?}", shorter_fr_plus); + debug!( + "report_or_propagate_universal_region_error: shorter_fr_plus={:?}", shorter_fr_plus + ); for &&fr in &shorter_fr_plus { // Push the constraint `fr-: shorter_fr+` propagated_outlives_requirements.push(ClosureOutlivesRequirement { From 67b04d5f641efe6bc0dd989d0a2747c210c134eb Mon Sep 17 00:00:00 2001 From: Remy Rakic Date: Mon, 2 Dec 2019 18:38:05 +0100 Subject: [PATCH 08/18] bless polonius output of test hrtb-perfect-forwarding.rs The plan is to use chalk and not have polonius deal with this. --- .../hrtb-perfect-forwarding.polonius.stderr | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 src/test/ui/hrtb/hrtb-perfect-forwarding.polonius.stderr diff --git a/src/test/ui/hrtb/hrtb-perfect-forwarding.polonius.stderr b/src/test/ui/hrtb/hrtb-perfect-forwarding.polonius.stderr new file mode 100644 index 0000000000000..558d643cde895 --- /dev/null +++ b/src/test/ui/hrtb/hrtb-perfect-forwarding.polonius.stderr @@ -0,0 +1,68 @@ +warning: function cannot return without recursing + --> $DIR/hrtb-perfect-forwarding.rs:22:1 + | +LL | / fn no_hrtb<'b,T>(mut t: T) +LL | | where T : Bar<&'b isize> +LL | | { +LL | | // OK -- `T : Bar<&'b isize>`, and thus the impl above ensures that +LL | | // `&mut T : Bar<&'b isize>`. +LL | | no_hrtb(&mut t); + | | --------------- recursive call site +LL | | } + | |_^ cannot return without recursing + | + = note: `#[warn(unconditional_recursion)]` on by default + = help: a `loop` may express intention better if this is on purpose + +warning: function cannot return without recursing + --> $DIR/hrtb-perfect-forwarding.rs:30:1 + | +LL | / fn bar_hrtb(mut t: T) +LL | | where T : for<'b> Bar<&'b isize> +LL | | { +LL | | // OK -- `T : for<'b> Bar<&'b isize>`, and thus the impl above +... | +LL | | bar_hrtb(&mut t); + | | ---------------- recursive call site +LL | | } + | |_^ cannot return without recursing + | + = help: a `loop` may express intention better if this is on purpose + +warning: function cannot return without recursing + --> $DIR/hrtb-perfect-forwarding.rs:39:1 + | +LL | / fn foo_hrtb_bar_not<'b,T>(mut t: T) +LL | | where T : for<'a> Foo<&'a isize> + Bar<&'b isize> +LL | | { +LL | | // Not OK -- The forwarding impl for `Foo` requires that `Bar` also +... | +LL | | foo_hrtb_bar_not(&mut t); + | | ------------------------ recursive call site +LL | | } + | |_^ cannot return without recursing + | + = help: a `loop` may express intention better if this is on purpose + +error: higher-ranked subtype error + --> $DIR/hrtb-perfect-forwarding.rs:46:5 + | +LL | foo_hrtb_bar_not(&mut t); + | ^^^^^^^^^^^^^^^^^^^^^^^^ + +warning: function cannot return without recursing + --> $DIR/hrtb-perfect-forwarding.rs:49:1 + | +LL | / fn foo_hrtb_bar_hrtb(mut t: T) +LL | | where T : for<'a> Foo<&'a isize> + for<'b> Bar<&'b isize> +LL | | { +LL | | // OK -- now we have `T : for<'b> Bar&'b isize>`. +LL | | foo_hrtb_bar_hrtb(&mut t); + | | ------------------------- recursive call site +LL | | } + | |_^ cannot return without recursing + | + = help: a `loop` may express intention better if this is on purpose + +error: aborting due to previous error + From 695640816a48098efaddc83d1abaa9edcc4fd109 Mon Sep 17 00:00:00 2001 From: Remy Rakic Date: Mon, 2 Dec 2019 18:44:23 +0100 Subject: [PATCH 09/18] bless polonius output of test ui/nll/outlives-suggestion-simple.rs The polonius output has one more error which should be displayed in the regular case, but error reporting in the regular case stopped at the first error. Admittedly it would be nice to combine suggestions for the same source lifetime so that `'a: 'b` and `'a: 'c` are not bothsuggested, but instead a single `'a: 'b + 'c` is. --- ...outlives-suggestion-simple.polonius.stderr | 121 ++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 src/test/ui/nll/outlives-suggestion-simple.polonius.stderr diff --git a/src/test/ui/nll/outlives-suggestion-simple.polonius.stderr b/src/test/ui/nll/outlives-suggestion-simple.polonius.stderr new file mode 100644 index 0000000000000..815744618f62c --- /dev/null +++ b/src/test/ui/nll/outlives-suggestion-simple.polonius.stderr @@ -0,0 +1,121 @@ +error: lifetime may not live long enough + --> $DIR/outlives-suggestion-simple.rs:6:5 + | +LL | fn foo1<'a, 'b>(x: &'a usize) -> &'b usize { + | -- -- lifetime `'b` defined here + | | + | lifetime `'a` defined here +LL | x + | ^ returning this value requires that `'a` must outlive `'b` + | + = help: consider adding the following bound: `'a: 'b` + +error: lifetime may not live long enough + --> $DIR/outlives-suggestion-simple.rs:10:5 + | +LL | fn foo2<'a>(x: &'a usize) -> &'static usize { + | -- lifetime `'a` defined here +LL | x + | ^ returning this value requires that `'a` must outlive `'static` + | + = help: consider replacing `'a` with `'static` + +error: lifetime may not live long enough + --> $DIR/outlives-suggestion-simple.rs:14:5 + | +LL | fn foo3<'a, 'b>(x: &'a usize, y: &'b usize) -> (&'b usize, &'a usize) { + | -- -- lifetime `'b` defined here + | | + | lifetime `'a` defined here +LL | (x, y) + | ^^^^^^ function was supposed to return data with lifetime `'b` but it is returning data with lifetime `'a` + | + = help: consider adding the following bound: `'a: 'b` + +error: lifetime may not live long enough + --> $DIR/outlives-suggestion-simple.rs:14:5 + | +LL | fn foo3<'a, 'b>(x: &'a usize, y: &'b usize) -> (&'b usize, &'a usize) { + | -- -- lifetime `'b` defined here + | | + | lifetime `'a` defined here +LL | (x, y) + | ^^^^^^ function was supposed to return data with lifetime `'a` but it is returning data with lifetime `'b` + | + = help: consider adding the following bound: `'b: 'a` + +help: `'a` and `'b` must be the same: replace one with the other + +error: lifetime may not live long enough + --> $DIR/outlives-suggestion-simple.rs:22:5 + | +LL | fn foo4<'a, 'b, 'c>(x: &'a usize) -> (&'b usize, &'c usize) { + | -- -- lifetime `'b` defined here + | | + | lifetime `'a` defined here +... +LL | (x, x) + | ^^^^^^ returning this value requires that `'a` must outlive `'b` + | + = help: consider adding the following bound: `'a: 'b` + +error: lifetime may not live long enough + --> $DIR/outlives-suggestion-simple.rs:22:5 + | +LL | fn foo4<'a, 'b, 'c>(x: &'a usize) -> (&'b usize, &'c usize) { + | -- -- lifetime `'c` defined here + | | + | lifetime `'a` defined here +... +LL | (x, x) + | ^^^^^^ returning this value requires that `'a` must outlive `'c` + | + = help: consider adding the following bound: `'a: 'c` + +error: lifetime may not live long enough + --> $DIR/outlives-suggestion-simple.rs:31:9 + | +LL | pub fn foo<'a>(x: &'a usize) -> Self { + | -- lifetime `'a` defined here +LL | Foo { x } + | ^^^^^^^^^ returning this value requires that `'a` must outlive `'static` + | + = help: consider replacing `'a` with `'static` + +error: lifetime may not live long enough + --> $DIR/outlives-suggestion-simple.rs:41:9 + | +LL | impl<'a> Bar<'a> { + | -- lifetime `'a` defined here +LL | pub fn get<'b>(&self) -> &'b usize { + | -- lifetime `'b` defined here +LL | self.x + | ^^^^^^ returning this value requires that `'a` must outlive `'b` + | + = help: consider adding the following bound: `'a: 'b` + +error: lifetime may not live long enough + --> $DIR/outlives-suggestion-simple.rs:52:9 + | +LL | impl<'a> Baz<'a> { + | -- lifetime `'a` defined here +LL | fn get<'b>(&'b self) -> &'a i32 { + | -- lifetime `'b` defined here +LL | self.x + | ^^^^^^ returning this value requires that `'b` must outlive `'a` + | + = help: consider adding the following bound: `'b: 'a` + +error[E0521]: borrowed data escapes outside of function + --> $DIR/outlives-suggestion-simple.rs:73:9 + | +LL | fn get_bar(&self) -> Bar2 { + | ----- + | | + | `self` is declared here, outside of the function body + | `self` is a reference that is only valid in the function body +LL | Bar2::new(&self) + | ^^^^^^^^^^^^^^^^ `self` escapes the function body here + +error: aborting due to 10 previous errors + From 720716f9d08094e66581ce069caaa500ee4e04e6 Mon Sep 17 00:00:00 2001 From: Remy Rakic Date: Mon, 2 Dec 2019 18:54:42 +0100 Subject: [PATCH 10/18] bless polonius output due to lacking the 'static special-casing --- ...xpect-region-supply-region.polonius.stderr | 56 +++++++++++++++++ .../error-handling.polonius.stderr | 12 ++++ .../closure-substs.polonius.stderr | 60 +++++++++++++++++++ 3 files changed, 128 insertions(+) create mode 100644 src/test/ui/closures/closure-expected-type/expect-region-supply-region.polonius.stderr create mode 100644 src/test/ui/impl-trait/multiple-lifetimes/error-handling.polonius.stderr create mode 100644 src/test/ui/nll/user-annotations/closure-substs.polonius.stderr diff --git a/src/test/ui/closures/closure-expected-type/expect-region-supply-region.polonius.stderr b/src/test/ui/closures/closure-expected-type/expect-region-supply-region.polonius.stderr new file mode 100644 index 0000000000000..2a7461fb469b2 --- /dev/null +++ b/src/test/ui/closures/closure-expected-type/expect-region-supply-region.polonius.stderr @@ -0,0 +1,56 @@ +error[E0521]: borrowed data escapes outside of closure + --> $DIR/expect-region-supply-region.rs:18:9 + | +LL | let mut f: Option<&u32> = None; + | ----- `f` is declared here, outside of the closure body +LL | closure_expecting_bound(|x| { + | - `x` is a reference that is only valid in the closure body +LL | f = Some(x); + | ^^^^^^^^^^^ `x` escapes the closure body here + +error[E0521]: borrowed data escapes outside of closure + --> $DIR/expect-region-supply-region.rs:28:9 + | +LL | let mut f: Option<&u32> = None; + | ----- `f` is declared here, outside of the closure body +LL | closure_expecting_bound(|x: &u32| { + | - `x` is a reference that is only valid in the closure body +LL | f = Some(x); + | ^^^^^^^^^^^ `x` escapes the closure body here + +error: lifetime may not live long enough + --> $DIR/expect-region-supply-region.rs:37:30 + | +LL | fn expect_bound_supply_named<'x>() { + | -- lifetime `'x` defined here +... +LL | closure_expecting_bound(|x: &'x u32| { + | ^ - let's call the lifetime of this reference `'1` + | | + | requires that `'1` must outlive `'x` + +error[E0521]: borrowed data escapes outside of closure + --> $DIR/expect-region-supply-region.rs:42:9 + | +LL | let mut f: Option<&u32> = None; + | ----- `f` is declared here, outside of the closure body +... +LL | closure_expecting_bound(|x: &'x u32| { + | - `x` is a reference that is only valid in the closure body +... +LL | f = Some(x); + | ^^^^^^^^^^^ `x` escapes the closure body here + +error: lifetime may not live long enough + --> $DIR/expect-region-supply-region.rs:37:30 + | +LL | fn expect_bound_supply_named<'x>() { + | -- lifetime `'x` defined here +... +LL | closure_expecting_bound(|x: &'x u32| { + | ^ requires that `'x` must outlive `'static` + | + = help: consider replacing `'x` with `'static` + +error: aborting due to 5 previous errors + diff --git a/src/test/ui/impl-trait/multiple-lifetimes/error-handling.polonius.stderr b/src/test/ui/impl-trait/multiple-lifetimes/error-handling.polonius.stderr new file mode 100644 index 0000000000000..72e8fa33d7b4d --- /dev/null +++ b/src/test/ui/impl-trait/multiple-lifetimes/error-handling.polonius.stderr @@ -0,0 +1,12 @@ +error: lifetime may not live long enough + --> $DIR/error-handling.rs:13:56 + | +LL | fn foo<'a, 'b, 'c>(x: &'static i32, mut y: &'a i32) -> E<'b, 'c> { + | -- -- lifetime `'b` defined here ^^^^^^^^^ opaque type requires that `'a` must outlive `'b` + | | + | lifetime `'a` defined here + | + = help: consider adding the following bound: `'a: 'b` + +error: aborting due to previous error + diff --git a/src/test/ui/nll/user-annotations/closure-substs.polonius.stderr b/src/test/ui/nll/user-annotations/closure-substs.polonius.stderr new file mode 100644 index 0000000000000..d5bcdf6444171 --- /dev/null +++ b/src/test/ui/nll/user-annotations/closure-substs.polonius.stderr @@ -0,0 +1,60 @@ +error: lifetime may not live long enough + --> $DIR/closure-substs.rs:8:16 + | +LL | fn foo<'a>() { + | -- lifetime `'a` defined here +... +LL | return x; + | ^ returning this value requires that `'a` must outlive `'static` + | + = help: consider replacing `'a` with `'static` + +error: lifetime may not live long enough + --> $DIR/closure-substs.rs:15:16 + | +LL | |x: &i32| -> &'static i32 { + | - let's call the lifetime of this reference `'1` +LL | return x; + | ^ returning this value requires that `'1` must outlive `'static` + +error: lifetime may not live long enough + --> $DIR/closure-substs.rs:15:16 + | +LL | |x: &i32| -> &'static i32 { + | - ------------ return type of closure is &'2 i32 + | | + | let's call the lifetime of this reference `'1` +LL | return x; + | ^ returning this value requires that `'1` must outlive `'2` + +error: lifetime may not live long enough + --> $DIR/closure-substs.rs:22:9 + | +LL | fn bar<'a>() { + | -- lifetime `'a` defined here +... +LL | b(x); + | ^^^^ argument requires that `'a` must outlive `'static` + | + = help: consider replacing `'a` with `'static` + +error[E0521]: borrowed data escapes outside of closure + --> $DIR/closure-substs.rs:29:9 + | +LL | |x: &i32, b: fn(&'static i32)| { + | - `x` is a reference that is only valid in the closure body +LL | b(x); + | ^^^^ `x` escapes the closure body here + +error[E0521]: borrowed data escapes outside of closure + --> $DIR/closure-substs.rs:29:9 + | +LL | |x: &i32, b: fn(&'static i32)| { + | - - `b` is declared here, outside of the closure body + | | + | `x` is a reference that is only valid in the closure body +LL | b(x); + | ^^^^ `x` escapes the closure body here + +error: aborting due to 6 previous errors + From e2230a4366dc7854f766e4f79e964f719671fa0c Mon Sep 17 00:00:00 2001 From: Remy Rakic Date: Mon, 2 Dec 2019 19:37:24 +0100 Subject: [PATCH 11/18] appease the vociferous tidy --- src/librustc_mir/borrow_check/nll/mod.rs | 16 +++++++++++++--- .../borrow_check/nll/region_infer/mod.rs | 13 +++++++++---- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/src/librustc_mir/borrow_check/nll/mod.rs b/src/librustc_mir/borrow_check/nll/mod.rs index 5be299f2a9440..0c2e2320bf984 100644 --- a/src/librustc_mir/borrow_check/nll/mod.rs +++ b/src/librustc_mir/borrow_check/nll/mod.rs @@ -235,7 +235,10 @@ pub(in crate::borrow_check) fn compute_regions<'cx, 'tcx>( // `known_subset` facts. for (fr1, fr2) in universal_region_relations.known_outlives() { if fr1 != fr2 { - debug!("compute_regions: emitting polonius `known_subset` fr1={:?}, fr2={:?}", fr1, fr2); + debug!( + "compute_regions: emitting polonius `known_subset` fr1={:?}, fr2={:?}", + fr1, fr2 + ); all_facts.known_subset.push((*fr1, *fr2)); } } @@ -314,8 +317,15 @@ pub(in crate::borrow_check) fn compute_regions<'cx, 'tcx>( }); // Solve the region constraints. - let closure_region_requirements = - regioncx.solve(infcx, &body, local_names, upvars, def_id, errors_buffer, polonius_output.clone()); + let closure_region_requirements = regioncx.solve( + infcx, + &body, + local_names, + upvars, + def_id, + errors_buffer, + polonius_output.clone(), + ); // Dump MIR results into a file, if that is enabled. This let us // write unit-tests, as well as helping with debugging. diff --git a/src/librustc_mir/borrow_check/nll/region_infer/mod.rs b/src/librustc_mir/borrow_check/nll/region_infer/mod.rs index 574c64aa571cb..8d0f1b8e24a6b 100644 --- a/src/librustc_mir/borrow_check/nll/region_infer/mod.rs +++ b/src/librustc_mir/borrow_check/nll/region_infer/mod.rs @@ -1426,7 +1426,10 @@ impl<'tcx> RegionInferenceContext<'tcx> { region_naming: &mut RegionErrorNamingCtx, polonius_output: Rc, ) { - debug!("check_polonius_subset_errors: {} subset_errors", polonius_output.subset_errors.len()); + debug!( + "check_polonius_subset_errors: {} subset_errors", + polonius_output.subset_errors.len() + ); let mut outlives_suggestion = OutlivesSuggestionBuilder::new(mir_def_id, local_names); @@ -1647,10 +1650,12 @@ impl<'tcx> RegionInferenceContext<'tcx> { // Grow `shorter_fr` until we find some non-local regions. (We // always will.) We'll call them `shorter_fr+` -- they're ever // so slightly larger than `shorter_fr`. - let shorter_fr_plus = - self.universal_region_relations.non_local_upper_bounds(&shorter_fr); + let shorter_fr_plus = self + .universal_region_relations + .non_local_upper_bounds(&shorter_fr); debug!( - "report_or_propagate_universal_region_error: shorter_fr_plus={:?}", shorter_fr_plus + "report_or_propagate_universal_region_error: shorter_fr_plus={:?}", + shorter_fr_plus ); for &&fr in &shorter_fr_plus { // Push the constraint `fr-: shorter_fr+` From 1314ba323b6612d5109344c1d8bf9ae16e1e421f Mon Sep 17 00:00:00 2001 From: Remy Rakic Date: Tue, 3 Dec 2019 14:07:41 +0100 Subject: [PATCH 12/18] add subset relations test using polonius It's a relatively simple smoke-test for subset errors, executed outside of the polonius compare-mode. --- src/test/ui/nll/polonius/subset-relations.rs | 30 +++++++++++++++++++ .../ui/nll/polonius/subset-relations.stderr | 14 +++++++++ 2 files changed, 44 insertions(+) create mode 100644 src/test/ui/nll/polonius/subset-relations.rs create mode 100644 src/test/ui/nll/polonius/subset-relations.stderr diff --git a/src/test/ui/nll/polonius/subset-relations.rs b/src/test/ui/nll/polonius/subset-relations.rs new file mode 100644 index 0000000000000..3f6f67ebf4030 --- /dev/null +++ b/src/test/ui/nll/polonius/subset-relations.rs @@ -0,0 +1,30 @@ +// Checks that Polonius can compute cases of universal regions errors: +// "illegal subset relation errors", cases where analysis finds that +// two free regions outlive each other, without any evidence that this +// relation holds. + +// ignore-compare-mode-nll +// compile-flags: -Z borrowck=mir -Zpolonius + +// returning `y` requires that `'b: 'a`, but it's not known to be true +fn missing_subset<'a, 'b>(x: &'a u32, y: &'b u32) -> &'a u32 { + y //~ ERROR +} + +// `'b: 'a` is explicitly declared +fn valid_subset<'a, 'b: 'a>(x: &'a u32, y: &'b u32) -> &'a u32 { + y +} + +// because of `x`, it is implied that `'b: 'a` holds +fn implied_bounds_subset<'a, 'b>(x: &'a &'b mut u32) -> &'a u32 { + x +} + +// `'b: 'a` is declared, and `'a: 'c` is known via implied bounds: +// `'b: 'c` is therefore known to hold transitively +fn transitively_valid_subset<'a, 'b: 'a, 'c>(x: &'c &'a u32, y: &'b u32) -> &'c u32 { + y +} + +fn main() {} diff --git a/src/test/ui/nll/polonius/subset-relations.stderr b/src/test/ui/nll/polonius/subset-relations.stderr new file mode 100644 index 0000000000000..63645106f82c1 --- /dev/null +++ b/src/test/ui/nll/polonius/subset-relations.stderr @@ -0,0 +1,14 @@ +error: lifetime may not live long enough + --> $DIR/subset-relations.rs:11:5 + | +LL | fn missing_subset<'a, 'b>(x: &'a u32, y: &'b u32) -> &'a u32 { + | -- -- lifetime `'b` defined here + | | + | lifetime `'a` defined here +LL | y + | ^ function was supposed to return data with lifetime `'a` but it is returning data with lifetime `'b` + | + = help: consider adding the following bound: `'b: 'a` + +error: aborting due to previous error + From 0f306a7db431f335b5a3d94c31222a8b008d5437 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Tue, 3 Dec 2019 15:02:27 -0800 Subject: [PATCH 13/18] Do not ICE on async fn with non-Copy infered type arg Fix #66958. --- .../diagnostics/conflict_errors.rs | 19 ++++++++++--------- src/test/ui/issues/issue-66958.rs | 15 +++++++++++++++ src/test/ui/issues/issue-66958.stderr | 13 +++++++++++++ 3 files changed, 38 insertions(+), 9 deletions(-) create mode 100644 src/test/ui/issues/issue-66958.rs create mode 100644 src/test/ui/issues/issue-66958.stderr diff --git a/src/librustc_mir/borrow_check/diagnostics/conflict_errors.rs b/src/librustc_mir/borrow_check/diagnostics/conflict_errors.rs index d14957b9017da..a0f126fb2cb30 100644 --- a/src/librustc_mir/borrow_check/diagnostics/conflict_errors.rs +++ b/src/librustc_mir/borrow_check/diagnostics/conflict_errors.rs @@ -240,15 +240,16 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { let tcx = self.infcx.tcx; let generics = tcx.generics_of(self.mir_def_id); let param = generics.type_param(¶m_ty, tcx); - let generics = tcx.hir().get_generics(self.mir_def_id).unwrap(); - suggest_constraining_type_param( - generics, - &mut err, - ¶m.name.as_str(), - "Copy", - tcx.sess.source_map(), - span, - ); + if let Some(generics) = tcx.hir().get_generics(self.mir_def_id) { + suggest_constraining_type_param( + generics, + &mut err, + ¶m.name.as_str(), + "Copy", + tcx.sess.source_map(), + span, + ); + } } let span = if let Some(local) = place.as_local() { let decl = &self.body.local_decls[local]; diff --git a/src/test/ui/issues/issue-66958.rs b/src/test/ui/issues/issue-66958.rs new file mode 100644 index 0000000000000..a4c48ab05c020 --- /dev/null +++ b/src/test/ui/issues/issue-66958.rs @@ -0,0 +1,15 @@ +// edition:2018 + +struct Ia(u32, S); + +impl Ia { + fn partial(_: S) {} + fn full(self) {} + + async fn crash(self) { + Self::partial(self.1); + Self::full(self); //~ ERROR use of moved value: `self` + } +} + +fn main() {} diff --git a/src/test/ui/issues/issue-66958.stderr b/src/test/ui/issues/issue-66958.stderr new file mode 100644 index 0000000000000..79a80168a5e59 --- /dev/null +++ b/src/test/ui/issues/issue-66958.stderr @@ -0,0 +1,13 @@ +error[E0382]: use of moved value: `self` + --> $DIR/issue-66958.rs:11:20 + | +LL | Self::partial(self.1); + | ------ value moved here +LL | Self::full(self); + | ^^^^ value used here after partial move + | + = note: move occurs because `self.1` has type `S`, which does not implement the `Copy` trait + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0382`. From 7ed90667664a910ae4327415fc4a33eb580dd2ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Thu, 5 Dec 2019 06:57:34 -0800 Subject: [PATCH 14/18] review comments --- .../issues/issue-66958-non-copy-infered-type-arg.rs} | 4 ++-- .../issues/issue-66958-non-copy-infered-type-arg.stderr} | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) rename src/test/ui/{issues/issue-66958.rs => async-await/issues/issue-66958-non-copy-infered-type-arg.rs} (78%) rename src/test/ui/{issues/issue-66958.stderr => async-await/issues/issue-66958-non-copy-infered-type-arg.stderr} (68%) diff --git a/src/test/ui/issues/issue-66958.rs b/src/test/ui/async-await/issues/issue-66958-non-copy-infered-type-arg.rs similarity index 78% rename from src/test/ui/issues/issue-66958.rs rename to src/test/ui/async-await/issues/issue-66958-non-copy-infered-type-arg.rs index a4c48ab05c020..c8c2702ec447e 100644 --- a/src/test/ui/issues/issue-66958.rs +++ b/src/test/ui/async-await/issues/issue-66958-non-copy-infered-type-arg.rs @@ -1,13 +1,13 @@ // edition:2018 -struct Ia(u32, S); +struct Ia(S); impl Ia { fn partial(_: S) {} fn full(self) {} async fn crash(self) { - Self::partial(self.1); + Self::partial(self.0); Self::full(self); //~ ERROR use of moved value: `self` } } diff --git a/src/test/ui/issues/issue-66958.stderr b/src/test/ui/async-await/issues/issue-66958-non-copy-infered-type-arg.stderr similarity index 68% rename from src/test/ui/issues/issue-66958.stderr rename to src/test/ui/async-await/issues/issue-66958-non-copy-infered-type-arg.stderr index 79a80168a5e59..9177b83dd48d7 100644 --- a/src/test/ui/issues/issue-66958.stderr +++ b/src/test/ui/async-await/issues/issue-66958-non-copy-infered-type-arg.stderr @@ -1,12 +1,12 @@ error[E0382]: use of moved value: `self` - --> $DIR/issue-66958.rs:11:20 + --> $DIR/issue-66958-non-copy-infered-type-arg.rs:11:20 | -LL | Self::partial(self.1); +LL | Self::partial(self.0); | ------ value moved here LL | Self::full(self); | ^^^^ value used here after partial move | - = note: move occurs because `self.1` has type `S`, which does not implement the `Copy` trait + = note: move occurs because `self.0` has type `S`, which does not implement the `Copy` trait error: aborting due to previous error From 3f1e3913697f8395896036d3f6beec422055acb9 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Fri, 29 Nov 2019 20:36:28 -0800 Subject: [PATCH 15/18] Exclude manually arranged ascii tables from rustfmt --- src/libcore/benches/ascii.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/libcore/benches/ascii.rs b/src/libcore/benches/ascii.rs index e921dd1ba0636..f28bc4ca72bb8 100644 --- a/src/libcore/benches/ascii.rs +++ b/src/libcore/benches/ascii.rs @@ -277,6 +277,7 @@ const LONG: &'static str = repeat!(r#" The Manlet (1903)[106] "#); +#[rustfmt::skip] const ASCII_UPPERCASE_MAP: [u8; 256] = [ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, @@ -330,6 +331,7 @@ enum AsciiCharacterClass { } use self::AsciiCharacterClass::*; +#[rustfmt::skip] static ASCII_CHARACTER_CLASS: [AsciiCharacterClass; 256] = [ // _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _a _b _c _d _e _f C, C, C, C, C, C, C, C, C, Cw,Cw,C, Cw,Cw,C, C, // 0_ From 24d7f72c6291030d5a3906c74f9a40d1af2944b0 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Fri, 29 Nov 2019 20:41:53 -0800 Subject: [PATCH 16/18] Suppress libcore/ptr/mod.rs filelength lint --- src/libcore/ptr/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/libcore/ptr/mod.rs b/src/libcore/ptr/mod.rs index 1e051dbebcaf8..a8cc440c239af 100644 --- a/src/libcore/ptr/mod.rs +++ b/src/libcore/ptr/mod.rs @@ -65,6 +65,7 @@ //! [`write_volatile`]: ./fn.write_volatile.html //! [`NonNull::dangling`]: ./struct.NonNull.html#method.dangling +// ignore-tidy-filelength // ignore-tidy-undocumented-unsafe #![stable(feature = "rust1", since = "1.0.0")] From c737169fe579327bd42bf04134a375ae8d8d0d7b Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Fri, 6 Dec 2019 20:18:12 -0800 Subject: [PATCH 17/18] Format libcore with rustfmt (including tests and benches) --- src/libcore/benches/any.rs | 2 +- src/libcore/benches/ascii.rs | 20 +- src/libcore/benches/char/methods.rs | 13 +- src/libcore/benches/fmt.rs | 2 +- src/libcore/benches/hash/sip.rs | 48 +- src/libcore/benches/iter.rs | 65 +-- src/libcore/benches/lib.rs | 2 +- src/libcore/benches/num/flt2dec/mod.rs | 6 +- .../benches/num/flt2dec/strategy/dragon.rs | 2 +- .../benches/num/flt2dec/strategy/grisu.rs | 4 +- src/libcore/benches/num/mod.rs | 12 +- src/libcore/benches/ops.rs | 7 +- src/libcore/benches/slice.rs | 7 +- src/libcore/bool.rs | 12 +- src/libcore/convert/num.rs | 1 - src/libcore/hint.rs | 28 +- src/libcore/iter/traits/collect.rs | 12 +- src/libcore/num/f64.rs | 5 +- src/libcore/ops/try.rs | 36 +- src/libcore/panicking.rs | 20 +- src/libcore/ptr/mod.rs | 234 +++++---- src/libcore/tests/any.rs | 23 +- src/libcore/tests/array.rs | 8 +- src/libcore/tests/ascii.rs | 130 +++-- src/libcore/tests/atomic.rs | 6 +- src/libcore/tests/cell.rs | 10 +- src/libcore/tests/char.rs | 26 +- src/libcore/tests/hash/mod.rs | 37 +- src/libcore/tests/hash/sip.rs | 291 ++++++----- src/libcore/tests/intrinsics.rs | 6 +- src/libcore/tests/manually_drop.rs | 2 +- src/libcore/tests/mem.rs | 10 +- src/libcore/tests/nonzero.rs | 31 +- src/libcore/tests/num/bignum.rs | 16 +- src/libcore/tests/num/dec2flt/mod.rs | 6 +- src/libcore/tests/num/dec2flt/parse.rs | 4 +- src/libcore/tests/num/dec2flt/rawfp.rs | 23 +- src/libcore/tests/num/flt2dec/estimator.rs | 22 +- src/libcore/tests/num/flt2dec/random.rs | 121 +++-- .../tests/num/flt2dec/strategy/grisu.rs | 13 +- src/libcore/tests/num/int_macros.rs | 477 +++++++++--------- src/libcore/tests/num/uint_macros.rs | 320 ++++++------ src/libcore/tests/ops.rs | 31 +- src/libcore/tests/option.rs | 27 +- src/libcore/tests/ptr.rs | 59 ++- src/libcore/tests/slice.rs | 111 ++-- src/libcore/tests/str_lossy.rs | 78 +-- src/libcore/tests/time.rs | 51 +- src/libcore/tests/tuple.rs | 2 +- 49 files changed, 1308 insertions(+), 1171 deletions(-) diff --git a/src/libcore/benches/any.rs b/src/libcore/benches/any.rs index ceb507aad38f4..53099b78266f8 100644 --- a/src/libcore/benches/any.rs +++ b/src/libcore/benches/any.rs @@ -1,5 +1,5 @@ use core::any::*; -use test::{Bencher, black_box}; +use test::{black_box, Bencher}; #[bench] fn bench_downcast_ref(b: &mut Bencher) { diff --git a/src/libcore/benches/ascii.rs b/src/libcore/benches/ascii.rs index f28bc4ca72bb8..76ccd3ddb6fd8 100644 --- a/src/libcore/benches/ascii.rs +++ b/src/libcore/benches/ascii.rs @@ -22,17 +22,9 @@ // // Therefore: fn branchless_to_ascii_upper_case(byte: u8) -> u8 { - byte & - !( - ( - byte.wrapping_add(0x1f) & - !byte.wrapping_add(0x05) & - 0x80 - ) >> 2 - ) + byte & !((byte.wrapping_add(0x1f) & !byte.wrapping_add(0x05) & 0x80) >> 2) } - macro_rules! benches { ($( fn $name: ident($arg: ident: &mut [u8]) $body: block )+ @iter $( $is_: ident, )+) => { benches! {@ @@ -254,12 +246,15 @@ benches! { } macro_rules! repeat { - ($s: expr) => { concat!($s, $s, $s, $s, $s, $s, $s, $s, $s, $s) } + ($s: expr) => { + concat!($s, $s, $s, $s, $s, $s, $s, $s, $s, $s) + }; } const SHORT: &'static str = "Alice's"; const MEDIUM: &'static str = "Alice's Adventures in Wonderland"; -const LONG: &'static str = repeat!(r#" +const LONG: &'static str = repeat!( + r#" La Guida di Bragia, a Ballad Opera for the Marionette Theatre (around 1850) Alice's Adventures in Wonderland (1865) Phantasmagoria and Other Poems (1869) @@ -275,7 +270,8 @@ const LONG: &'static str = repeat!(r#" What the Tortoise Said to Achilles (1895) Three Sunsets and Other Poems (1898) The Manlet (1903)[106] -"#); +"# +); #[rustfmt::skip] const ASCII_UPPERCASE_MAP: [u8; 256] = [ diff --git a/src/libcore/benches/char/methods.rs b/src/libcore/benches/char/methods.rs index af934c1171577..a9a08a4d76200 100644 --- a/src/libcore/benches/char/methods.rs +++ b/src/libcore/benches/char/methods.rs @@ -25,8 +25,13 @@ fn bench_to_digit_radix_36(b: &mut Bencher) { #[bench] fn bench_to_digit_radix_var(b: &mut Bencher) { - b.iter(|| CHARS.iter().cycle() - .zip(RADIX.iter().cycle()) - .take(10_000) - .map(|(c, radix)| c.to_digit(*radix)).min()) + b.iter(|| { + CHARS + .iter() + .cycle() + .zip(RADIX.iter().cycle()) + .take(10_000) + .map(|(c, radix)| c.to_digit(*radix)) + .min() + }) } diff --git a/src/libcore/benches/fmt.rs b/src/libcore/benches/fmt.rs index 92f10c760c6d2..dd72a33996f17 100644 --- a/src/libcore/benches/fmt.rs +++ b/src/libcore/benches/fmt.rs @@ -1,5 +1,5 @@ -use std::io::{self, Write as IoWrite}; use std::fmt::{self, Write as FmtWrite}; +use std::io::{self, Write as IoWrite}; use test::Bencher; #[bench] diff --git a/src/libcore/benches/hash/sip.rs b/src/libcore/benches/hash/sip.rs index 5baba42763e10..725c864dce9f1 100644 --- a/src/libcore/benches/hash/sip.rs +++ b/src/libcore/benches/hash/sip.rs @@ -1,7 +1,7 @@ #![allow(deprecated)] use core::hash::*; -use test::{Bencher, black_box}; +use test::{black_box, Bencher}; fn hash_bytes(mut s: H, x: &[u8]) -> u64 { Hasher::write(&mut s, x); @@ -44,11 +44,11 @@ fn bench_str_over_8_bytes(b: &mut Bencher) { #[bench] fn bench_long_str(b: &mut Bencher) { let s = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor \ -incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud \ -exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute \ -irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla \ -pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui \ -officia deserunt mollit anim id est laborum."; + incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud \ + exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute \ + irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla \ + pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui \ + officia deserunt mollit anim id est laborum."; b.iter(|| { assert_eq!(hash(&s), 17717065544121360093); }) @@ -58,9 +58,7 @@ officia deserunt mollit anim id est laborum."; fn bench_u32(b: &mut Bencher) { let u = 162629500u32; let u = black_box(u); - b.iter(|| { - hash(&u) - }); + b.iter(|| hash(&u)); b.bytes = 8; } @@ -70,9 +68,7 @@ fn bench_u32_keyed(b: &mut Bencher) { let u = black_box(u); let k1 = black_box(0x1); let k2 = black_box(0x2); - b.iter(|| { - hash_with(SipHasher::new_with_keys(k1, k2), &u) - }); + b.iter(|| hash_with(SipHasher::new_with_keys(k1, k2), &u)); b.bytes = 8; } @@ -80,62 +76,48 @@ fn bench_u32_keyed(b: &mut Bencher) { fn bench_u64(b: &mut Bencher) { let u = 16262950014981195938u64; let u = black_box(u); - b.iter(|| { - hash(&u) - }); + b.iter(|| hash(&u)); b.bytes = 8; } #[bench] fn bench_bytes_4(b: &mut Bencher) { let data = black_box([b' '; 4]); - b.iter(|| { - hash_bytes(SipHasher::default(), &data) - }); + b.iter(|| hash_bytes(SipHasher::default(), &data)); b.bytes = 4; } #[bench] fn bench_bytes_7(b: &mut Bencher) { let data = black_box([b' '; 7]); - b.iter(|| { - hash_bytes(SipHasher::default(), &data) - }); + b.iter(|| hash_bytes(SipHasher::default(), &data)); b.bytes = 7; } #[bench] fn bench_bytes_8(b: &mut Bencher) { let data = black_box([b' '; 8]); - b.iter(|| { - hash_bytes(SipHasher::default(), &data) - }); + b.iter(|| hash_bytes(SipHasher::default(), &data)); b.bytes = 8; } #[bench] fn bench_bytes_a_16(b: &mut Bencher) { let data = black_box([b' '; 16]); - b.iter(|| { - hash_bytes(SipHasher::default(), &data) - }); + b.iter(|| hash_bytes(SipHasher::default(), &data)); b.bytes = 16; } #[bench] fn bench_bytes_b_32(b: &mut Bencher) { let data = black_box([b' '; 32]); - b.iter(|| { - hash_bytes(SipHasher::default(), &data) - }); + b.iter(|| hash_bytes(SipHasher::default(), &data)); b.bytes = 32; } #[bench] fn bench_bytes_c_128(b: &mut Bencher) { let data = black_box([b' '; 128]); - b.iter(|| { - hash_bytes(SipHasher::default(), &data) - }); + b.iter(|| hash_bytes(SipHasher::default(), &data)); b.bytes = 128; } diff --git a/src/libcore/benches/iter.rs b/src/libcore/benches/iter.rs index 7dcfad8306fce..fb6b4b7837941 100644 --- a/src/libcore/benches/iter.rs +++ b/src/libcore/benches/iter.rs @@ -1,5 +1,5 @@ use core::iter::*; -use test::{Bencher, black_box}; +use test::{black_box, Bencher}; #[bench] fn bench_rposition(b: &mut Bencher) { @@ -14,7 +14,11 @@ fn bench_skip_while(b: &mut Bencher) { b.iter(|| { let it = 0..100; let mut sum = 0; - it.skip_while(|&x| { sum += x; sum < 4000 }).all(|_| true); + it.skip_while(|&x| { + sum += x; + sum < 4000 + }) + .all(|_| true); }); } @@ -29,7 +33,9 @@ fn bench_multiple_take(b: &mut Bencher) { }); } -fn scatter(x: i32) -> i32 { (x * 31) % 127 } +fn scatter(x: i32) -> i32 { + (x * 31) % 127 +} #[bench] fn bench_max_by_key(b: &mut Bencher) { @@ -76,23 +82,21 @@ pub fn add_zip(xs: &[f32], ys: &mut [f32]) { fn bench_zip_copy(b: &mut Bencher) { let source = vec![0u8; 16 * 1024]; let mut dst = black_box(vec![0u8; 16 * 1024]); - b.iter(|| { - copy_zip(&source, &mut dst) - }) + b.iter(|| copy_zip(&source, &mut dst)) } #[bench] fn bench_zip_add(b: &mut Bencher) { let source = vec![1.; 16 * 1024]; let mut dst = vec![0.; 16 * 1024]; - b.iter(|| { - add_zip(&source, &mut dst) - }); + b.iter(|| add_zip(&source, &mut dst)); } /// `Iterator::for_each` implemented as a plain loop. -fn for_each_loop(iter: I, mut f: F) where - I: Iterator, F: FnMut(I::Item) +fn for_each_loop(iter: I, mut f: F) +where + I: Iterator, + F: FnMut(I::Item), { for item in iter { f(item); @@ -101,8 +105,10 @@ fn for_each_loop(iter: I, mut f: F) where /// `Iterator::for_each` implemented with `fold` for internal iteration. /// (except when `by_ref()` effectively disables that optimization.) -fn for_each_fold(iter: I, mut f: F) where - I: Iterator, F: FnMut(I::Item) +fn for_each_fold(iter: I, mut f: F) +where + I: Iterator, + F: FnMut(I::Item), { iter.fold((), move |(), item| f(item)); } @@ -137,25 +143,20 @@ fn bench_for_each_chain_ref_fold(b: &mut Bencher) { }); } - /// Helper to benchmark `sum` for iterators taken by value which /// can optimize `fold`, and by reference which cannot. macro_rules! bench_sums { ($bench_sum:ident, $bench_ref_sum:ident, $iter:expr) => { #[bench] fn $bench_sum(b: &mut Bencher) { - b.iter(|| -> i64 { - $iter.map(black_box).sum() - }); + b.iter(|| -> i64 { $iter.map(black_box).sum() }); } #[bench] fn $bench_ref_sum(b: &mut Bencher) { - b.iter(|| -> i64 { - $iter.map(black_box).by_ref().sum() - }); + b.iter(|| -> i64 { $iter.map(black_box).by_ref().sum() }); } - } + }; } bench_sums! { @@ -286,7 +287,10 @@ fn bench_zip_then_skip(b: &mut Bencher) { let t: Vec<_> = (0..100_000).collect(); b.iter(|| { - let s = v.iter().zip(t.iter()).skip(10000) + let s = v + .iter() + .zip(t.iter()) + .skip(10000) .take_while(|t| *t.0 < 10100) .map(|(a, b)| *a + *b) .sum::(); @@ -299,7 +303,10 @@ fn bench_skip_then_zip(b: &mut Bencher) { let t: Vec<_> = (0..100_000).collect(); b.iter(|| { - let s = v.iter().skip(10000).zip(t.iter().skip(10000)) + let s = v + .iter() + .skip(10000) + .zip(t.iter().skip(10000)) .take_while(|t| *t.0 < 10100) .map(|(a, b)| *a + *b) .sum::(); @@ -309,23 +316,17 @@ fn bench_skip_then_zip(b: &mut Bencher) { #[bench] fn bench_filter_count(b: &mut Bencher) { - b.iter(|| { - (0i64..1000000).map(black_box).filter(|x| x % 3 == 0).count() - }) + b.iter(|| (0i64..1000000).map(black_box).filter(|x| x % 3 == 0).count()) } #[bench] fn bench_filter_ref_count(b: &mut Bencher) { - b.iter(|| { - (0i64..1000000).map(black_box).by_ref().filter(|x| x % 3 == 0).count() - }) + b.iter(|| (0i64..1000000).map(black_box).by_ref().filter(|x| x % 3 == 0).count()) } #[bench] fn bench_filter_chain_count(b: &mut Bencher) { - b.iter(|| { - (0i64..1000000).chain(0..1000000).map(black_box).filter(|x| x % 3 == 0).count() - }) + b.iter(|| (0i64..1000000).chain(0..1000000).map(black_box).filter(|x| x % 3 == 0).count()) } #[bench] diff --git a/src/libcore/benches/lib.rs b/src/libcore/benches/lib.rs index dea2963d9ac83..6932c7fe221d0 100644 --- a/src/libcore/benches/lib.rs +++ b/src/libcore/benches/lib.rs @@ -6,9 +6,9 @@ extern crate test; mod any; mod ascii; mod char; +mod fmt; mod hash; mod iter; mod num; mod ops; mod slice; -mod fmt; diff --git a/src/libcore/benches/num/flt2dec/mod.rs b/src/libcore/benches/num/flt2dec/mod.rs index 4153745d0424a..b810dd12ab61b 100644 --- a/src/libcore/benches/num/flt2dec/mod.rs +++ b/src/libcore/benches/num/flt2dec/mod.rs @@ -3,17 +3,17 @@ mod strategy { mod grisu; } +use core::num::flt2dec::MAX_SIG_DIGITS; +use core::num::flt2dec::{decode, DecodableFloat, Decoded, FullDecoded}; use std::f64; use std::io::Write; use std::vec::Vec; use test::Bencher; -use core::num::flt2dec::{decode, DecodableFloat, FullDecoded, Decoded}; -use core::num::flt2dec::MAX_SIG_DIGITS; pub fn decode_finite(v: T) -> Decoded { match decode(v).1 { FullDecoded::Finite(decoded) => decoded, - full_decoded => panic!("expected finite, got {:?} instead", full_decoded) + full_decoded => panic!("expected finite, got {:?} instead", full_decoded), } } diff --git a/src/libcore/benches/num/flt2dec/strategy/dragon.rs b/src/libcore/benches/num/flt2dec/strategy/dragon.rs index 60660b1da1118..4052fec33813c 100644 --- a/src/libcore/benches/num/flt2dec/strategy/dragon.rs +++ b/src/libcore/benches/num/flt2dec/strategy/dragon.rs @@ -1,6 +1,6 @@ -use std::{i16, f64}; use super::super::*; use core::num::flt2dec::strategy::dragon::*; +use std::{f64, i16}; use test::Bencher; #[bench] diff --git a/src/libcore/benches/num/flt2dec/strategy/grisu.rs b/src/libcore/benches/num/flt2dec/strategy/grisu.rs index 841feba50dd5b..495074747c283 100644 --- a/src/libcore/benches/num/flt2dec/strategy/grisu.rs +++ b/src/libcore/benches/num/flt2dec/strategy/grisu.rs @@ -1,12 +1,12 @@ -use std::{i16, f64}; use super::super::*; use core::num::flt2dec::strategy::grisu::*; +use std::{f64, i16}; use test::Bencher; pub fn decode_finite(v: T) -> Decoded { match decode(v).1 { FullDecoded::Finite(decoded) => decoded, - full_decoded => panic!("expected finite, got {:?} instead", full_decoded) + full_decoded => panic!("expected finite, got {:?} instead", full_decoded), } } diff --git a/src/libcore/benches/num/mod.rs b/src/libcore/benches/num/mod.rs index 2dcdf2b6fe9f7..852d4e481e20d 100644 --- a/src/libcore/benches/num/mod.rs +++ b/src/libcore/benches/num/mod.rs @@ -1,8 +1,8 @@ -mod flt2dec; mod dec2flt; +mod flt2dec; -use test::Bencher; use std::str::FromStr; +use test::Bencher; const ASCII_NUMBERS: [&str; 19] = [ "0", @@ -27,7 +27,7 @@ const ASCII_NUMBERS: [&str; 19] = [ ]; macro_rules! from_str_bench { - ($mac:ident, $t:ty) => ( + ($mac:ident, $t:ty) => { #[bench] fn $mac(b: &mut Bencher) { b.iter(|| { @@ -39,11 +39,11 @@ macro_rules! from_str_bench { .max() }) } - ) + }; } macro_rules! from_str_radix_bench { - ($mac:ident, $t:ty, $radix:expr) => ( + ($mac:ident, $t:ty, $radix:expr) => { #[bench] fn $mac(b: &mut Bencher) { b.iter(|| { @@ -55,7 +55,7 @@ macro_rules! from_str_radix_bench { .max() }) } - ) + }; } from_str_bench!(bench_u8_from_str, u8); diff --git a/src/libcore/benches/ops.rs b/src/libcore/benches/ops.rs index 80649f33562f2..0a2be8a28819f 100644 --- a/src/libcore/benches/ops.rs +++ b/src/libcore/benches/ops.rs @@ -4,17 +4,16 @@ use test::Bencher; // Overhead of dtors struct HasDtor { - _x: isize + _x: isize, } impl Drop for HasDtor { - fn drop(&mut self) { - } + fn drop(&mut self) {} } #[bench] fn alloc_obj_with_dtor(b: &mut Bencher) { b.iter(|| { - HasDtor { _x : 10 }; + HasDtor { _x: 10 }; }) } diff --git a/src/libcore/benches/slice.rs b/src/libcore/benches/slice.rs index 711a8dff2c0b5..06b37cb08448c 100644 --- a/src/libcore/benches/slice.rs +++ b/src/libcore/benches/slice.rs @@ -8,11 +8,12 @@ enum Cache { } fn binary_search(b: &mut Bencher, cache: Cache, mapper: F) - where F: Fn(usize) -> usize +where + F: Fn(usize) -> usize, { let size = match cache { - Cache::L1 => 1000, // 8kb - Cache::L2 => 10_000, // 80kb + Cache::L1 => 1000, // 8kb + Cache::L2 => 10_000, // 80kb Cache::L3 => 1_000_000, // 8Mb }; let v = (0..size).map(&mapper).collect::>(); diff --git a/src/libcore/bool.rs b/src/libcore/bool.rs index 1b3c254a05f98..6e0865e8653b7 100644 --- a/src/libcore/bool.rs +++ b/src/libcore/bool.rs @@ -15,11 +15,7 @@ impl bool { #[unstable(feature = "bool_to_option", issue = "64260")] #[inline] pub fn then_some(self, t: T) -> Option { - if self { - Some(t) - } else { - None - } + if self { Some(t) } else { None } } /// Returns `Some(f())` if the `bool` is `true`, or `None` otherwise. @@ -35,10 +31,6 @@ impl bool { #[unstable(feature = "bool_to_option", issue = "64260")] #[inline] pub fn then T>(self, f: F) -> Option { - if self { - Some(f()) - } else { - None - } + if self { Some(f()) } else { None } } } diff --git a/src/libcore/convert/num.rs b/src/libcore/convert/num.rs index 0877dacb38dd2..d976c8b7f4361 100644 --- a/src/libcore/convert/num.rs +++ b/src/libcore/convert/num.rs @@ -146,7 +146,6 @@ impl_from! { i16, isize, #[stable(feature = "lossless_iusize_conv", since = "1.2 // https://www.cl.cam.ac.uk/research/security/ctsrd/pdfs/20171017a-cheri-poster.pdf // http://www.csl.sri.com/users/neumann/2012resolve-cheri.pdf - // Note: integers can only be represented with full precision in a float if // they fit in the significand, which is 24 bits in f32 and 53 bits in f64. // Lossy float conversions are not implemented at this time. diff --git a/src/libcore/hint.rs b/src/libcore/hint.rs index a295e65bb5511..f4fb9ab1757cd 100644 --- a/src/libcore/hint.rs +++ b/src/libcore/hint.rs @@ -64,31 +64,27 @@ pub unsafe fn unreachable_unchecked() -> ! { #[inline] #[unstable(feature = "renamed_spin_loop", issue = "55002")] pub fn spin_loop() { - #[cfg( - all( - any(target_arch = "x86", target_arch = "x86_64"), - target_feature = "sse2" - ) - )] { - #[cfg(target_arch = "x86")] { + #[cfg(all(any(target_arch = "x86", target_arch = "x86_64"), target_feature = "sse2"))] + { + #[cfg(target_arch = "x86")] + { unsafe { crate::arch::x86::_mm_pause() }; } - #[cfg(target_arch = "x86_64")] { + #[cfg(target_arch = "x86_64")] + { unsafe { crate::arch::x86_64::_mm_pause() }; } } - #[cfg( - any( - target_arch = "aarch64", - all(target_arch = "arm", target_feature = "v6") - ) - )] { - #[cfg(target_arch = "aarch64")] { + #[cfg(any(target_arch = "aarch64", all(target_arch = "arm", target_feature = "v6")))] + { + #[cfg(target_arch = "aarch64")] + { unsafe { crate::arch::aarch64::__yield() }; } - #[cfg(target_arch = "arm")] { + #[cfg(target_arch = "arm")] + { unsafe { crate::arch::arm::__yield() }; } } diff --git a/src/libcore/iter/traits/collect.rs b/src/libcore/iter/traits/collect.rs index d6ae5cfe9e00e..f21ab8dbc3737 100644 --- a/src/libcore/iter/traits/collect.rs +++ b/src/libcore/iter/traits/collect.rs @@ -91,9 +91,9 @@ /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[rustc_on_unimplemented( - message="a value of type `{Self}` cannot be built from an iterator \ - over elements of type `{A}`", - label="value of type `{Self}` cannot be built from `std::iter::Iterator`", + message = "a value of type `{Self}` cannot be built from an iterator \ + over elements of type `{A}`", + label = "value of type `{Self}` cannot be built from `std::iter::Iterator`" )] pub trait FromIterator: Sized { /// Creates a value from an iterator. @@ -116,7 +116,7 @@ pub trait FromIterator: Sized { /// assert_eq!(v, vec![5, 5, 5, 5, 5]); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - fn from_iter>(iter: T) -> Self; + fn from_iter>(iter: T) -> Self; } /// Conversion into an `Iterator`. @@ -214,7 +214,7 @@ pub trait IntoIterator { /// Which kind of iterator are we turning this into? #[stable(feature = "rust1", since = "1.0.0")] - type IntoIter: Iterator; + type IntoIter: Iterator; /// Creates an iterator from a value. /// @@ -340,7 +340,7 @@ pub trait Extend { /// assert_eq!("abcdef", &message); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - fn extend>(&mut self, iter: T); + fn extend>(&mut self, iter: T); } #[stable(feature = "extend_for_unit", since = "1.28.0")] diff --git a/src/libcore/num/f64.rs b/src/libcore/num/f64.rs index 794f77fcfc1be..5446ce3e3b3e9 100644 --- a/src/libcore/num/f64.rs +++ b/src/libcore/num/f64.rs @@ -439,7 +439,10 @@ impl f64 { #[cfg(not(bootstrap))] #[unstable(feature = "float_approx_unchecked_to", issue = "67058")] #[inline] - pub unsafe fn approx_unchecked_to(self) -> Int where Self: FloatToInt { + pub unsafe fn approx_unchecked_to(self) -> Int + where + Self: FloatToInt, + { FloatToInt::::approx_unchecked(self) } diff --git a/src/libcore/ops/try.rs b/src/libcore/ops/try.rs index a748ee87ef99a..22ba97b91df12 100644 --- a/src/libcore/ops/try.rs +++ b/src/libcore/ops/try.rs @@ -5,20 +5,28 @@ /// extracting those success or failure values from an existing instance and /// creating a new instance from a success or failure value. #[unstable(feature = "try_trait", issue = "42327")] -#[cfg_attr(not(bootstrap), rustc_on_unimplemented( -on(all( -any(from_method="from_error", from_method="from_ok"), -from_desugaring="QuestionMark"), -message="the `?` operator can only be used in {ItemContext} \ - that returns `Result` or `Option` \ - (or another type that implements `{Try}`)", -label="cannot use the `?` operator in {ItemContext} that returns `{Self}`", -enclosing_scope="this function should return `Result` or `Option` to accept `?`"), -on(all(from_method="into_result", from_desugaring="QuestionMark"), -message="the `?` operator can only be applied to values \ - that implement `{Try}`", -label="the `?` operator cannot be applied to type `{Self}`") -))] +#[cfg_attr( + not(bootstrap), + rustc_on_unimplemented( + on( + all( + any(from_method = "from_error", from_method = "from_ok"), + from_desugaring = "QuestionMark" + ), + message = "the `?` operator can only be used in {ItemContext} \ + that returns `Result` or `Option` \ + (or another type that implements `{Try}`)", + label = "cannot use the `?` operator in {ItemContext} that returns `{Self}`", + enclosing_scope = "this function should return `Result` or `Option` to accept `?`" + ), + on( + all(from_method = "into_result", from_desugaring = "QuestionMark"), + message = "the `?` operator can only be applied to values \ + that implement `{Try}`", + label = "the `?` operator cannot be applied to type `{Self}`" + ) + ) +)] #[doc(alias = "?")] pub trait Try { /// The type of this value when viewed as successful. diff --git a/src/libcore/panicking.rs b/src/libcore/panicking.rs index 5a8d647396dda..4857b1145952d 100644 --- a/src/libcore/panicking.rs +++ b/src/libcore/panicking.rs @@ -22,10 +22,12 @@ // ignore-tidy-undocumented-unsafe #![allow(dead_code, missing_docs)] -#![unstable(feature = "core_panic", - reason = "internal details of the implementation of the `panic!` \ - and related macros", - issue = "0")] +#![unstable( + feature = "core_panic", + reason = "internal details of the implementation of the `panic!` \ + and related macros", + issue = "0" +)] use crate::fmt; use crate::panic::{Location, PanicInfo}; @@ -33,7 +35,7 @@ use crate::panic::{Location, PanicInfo}; #[cold] // never inline unless panic_immediate_abort to avoid code // bloat at the call sites as much as possible -#[cfg_attr(not(feature="panic_immediate_abort"),inline(never))] +#[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))] #[lang = "panic"] // needed by codegen for panic on overflow and other `Assert` MIR terminators pub fn panic(expr: &str, location: &Location<'_>) -> ! { if cfg!(feature = "panic_immediate_abort") { @@ -50,7 +52,7 @@ pub fn panic(expr: &str, location: &Location<'_>) -> ! { } #[cold] -#[cfg_attr(not(feature="panic_immediate_abort"),inline(never))] +#[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))] #[lang = "panic_bounds_check"] // needed by codegen for panic on OOB array/slice access fn panic_bounds_check(location: &Location<'_>, index: usize, len: usize) -> ! { if cfg!(feature = "panic_immediate_abort") { @@ -59,13 +61,13 @@ fn panic_bounds_check(location: &Location<'_>, index: usize, len: usize) -> ! { panic_fmt( format_args!("index out of bounds: the len is {} but the index is {}", len, index), - location + location, ) } #[cold] -#[cfg_attr(not(feature="panic_immediate_abort"),inline(never))] -#[cfg_attr( feature="panic_immediate_abort" ,inline)] +#[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))] +#[cfg_attr(feature = "panic_immediate_abort", inline)] pub fn panic_fmt(fmt: fmt::Arguments<'_>, location: &Location<'_>) -> ! { if cfg!(feature = "panic_immediate_abort") { unsafe { super::intrinsics::abort() } diff --git a/src/libcore/ptr/mod.rs b/src/libcore/ptr/mod.rs index a8cc440c239af..24ffa3483298b 100644 --- a/src/libcore/ptr/mod.rs +++ b/src/libcore/ptr/mod.rs @@ -70,11 +70,11 @@ #![stable(feature = "rust1", since = "1.0.0")] -use crate::intrinsics; +use crate::cmp::Ordering::{self, Equal, Greater, Less}; use crate::fmt; use crate::hash; +use crate::intrinsics; use crate::mem::{self, MaybeUninit}; -use crate::cmp::Ordering::{self, Less, Equal, Greater}; #[stable(feature = "rust1", since = "1.0.0")] pub use crate::intrinsics::copy_nonoverlapping; @@ -198,7 +198,9 @@ unsafe fn real_drop_in_place(to_drop: &mut T) { #[inline(always)] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_promotable] -pub const fn null() -> *const T { 0 as *const T } +pub const fn null() -> *const T { + 0 as *const T +} /// Creates a null mutable raw pointer. /// @@ -213,7 +215,9 @@ pub const fn null() -> *const T { 0 as *const T } #[inline(always)] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_promotable] -pub const fn null_mut() -> *mut T { 0 as *mut T } +pub const fn null_mut() -> *mut T { + 0 as *mut T +} #[repr(C)] pub(crate) union Repr { @@ -705,9 +709,7 @@ pub unsafe fn read(src: *const T) -> T { #[stable(feature = "ptr_unaligned", since = "1.17.0")] pub unsafe fn read_unaligned(src: *const T) -> T { let mut tmp = MaybeUninit::::uninit(); - copy_nonoverlapping(src as *const u8, - tmp.as_mut_ptr() as *mut u8, - mem::size_of::()); + copy_nonoverlapping(src as *const u8, tmp.as_mut_ptr() as *mut u8, mem::size_of::()); tmp.assume_init() } @@ -890,9 +892,7 @@ pub unsafe fn write(dst: *mut T, src: T) { #[inline] #[stable(feature = "ptr_unaligned", since = "1.17.0")] pub unsafe fn write_unaligned(dst: *mut T, src: T) { - copy_nonoverlapping(&src as *const T as *const u8, - dst as *mut u8, - mem::size_of::()); + copy_nonoverlapping(&src as *const T as *const u8, dst as *mut u8, mem::size_of::()); mem::forget(src); } @@ -1123,11 +1123,7 @@ impl *const T { #[stable(feature = "ptr_as_ref", since = "1.9.0")] #[inline] pub unsafe fn as_ref<'a>(self) -> Option<&'a T> { - if self.is_null() { - None - } else { - Some(&*self) - } + if self.is_null() { None } else { Some(&*self) } } /// Calculates the offset from a pointer. @@ -1183,7 +1179,10 @@ impl *const T { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] - pub unsafe fn offset(self, count: isize) -> *const T where T: Sized { + pub unsafe fn offset(self, count: isize) -> *const T + where + T: Sized, + { intrinsics::offset(self, count) } @@ -1238,10 +1237,11 @@ impl *const T { /// ``` #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")] #[inline] - pub fn wrapping_offset(self, count: isize) -> *const T where T: Sized { - unsafe { - intrinsics::arith_offset(self, count) - } + pub fn wrapping_offset(self, count: isize) -> *const T + where + T: Sized, + { + unsafe { intrinsics::arith_offset(self, count) } } /// Calculates the distance between two pointers. The returned value is in @@ -1309,7 +1309,10 @@ impl *const T { #[unstable(feature = "ptr_offset_from", issue = "41079")] #[rustc_const_unstable(feature = "const_ptr_offset_from")] #[inline] - pub const unsafe fn offset_from(self, origin: *const T) -> isize where T: Sized { + pub const unsafe fn offset_from(self, origin: *const T) -> isize + where + T: Sized, + { let pointee_size = mem::size_of::(); let ok = 0 < pointee_size && pointee_size <= isize::max_value() as usize; // assert that the pointee size is valid in a const eval compatible way @@ -1354,7 +1357,10 @@ impl *const T { /// ``` #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")] #[inline] - pub fn wrapping_offset_from(self, origin: *const T) -> isize where T: Sized { + pub fn wrapping_offset_from(self, origin: *const T) -> isize + where + T: Sized, + { let pointee_size = mem::size_of::(); assert!(0 < pointee_size && pointee_size <= isize::max_value() as usize); @@ -1416,7 +1422,8 @@ impl *const T { #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] pub unsafe fn add(self, count: usize) -> Self - where T: Sized, + where + T: Sized, { self.offset(count as isize) } @@ -1476,7 +1483,8 @@ impl *const T { #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] pub unsafe fn sub(self, count: usize) -> Self - where T: Sized, + where + T: Sized, { self.offset((count as isize).wrapping_neg()) } @@ -1530,7 +1538,8 @@ impl *const T { #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] pub fn wrapping_add(self, count: usize) -> Self - where T: Sized, + where + T: Sized, { self.wrapping_offset(count as isize) } @@ -1584,7 +1593,8 @@ impl *const T { #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] pub fn wrapping_sub(self, count: usize) -> Self - where T: Sized, + where + T: Sized, { self.wrapping_offset((count as isize).wrapping_neg()) } @@ -1598,7 +1608,8 @@ impl *const T { #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] pub unsafe fn read(self) -> T - where T: Sized, + where + T: Sized, { read(self) } @@ -1616,7 +1627,8 @@ impl *const T { #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] pub unsafe fn read_volatile(self) -> T - where T: Sized, + where + T: Sized, { read_volatile(self) } @@ -1632,7 +1644,8 @@ impl *const T { #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] pub unsafe fn read_unaligned(self) -> T - where T: Sized, + where + T: Sized, { read_unaligned(self) } @@ -1648,7 +1661,8 @@ impl *const T { #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] pub unsafe fn copy_to(self, dest: *mut T, count: usize) - where T: Sized, + where + T: Sized, { copy(self, dest, count) } @@ -1664,7 +1678,8 @@ impl *const T { #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize) - where T: Sized, + where + T: Sized, { copy_nonoverlapping(self, dest, count) } @@ -1709,17 +1724,17 @@ impl *const T { /// # } } /// ``` #[stable(feature = "align_offset", since = "1.36.0")] - pub fn align_offset(self, align: usize) -> usize where T: Sized { + pub fn align_offset(self, align: usize) -> usize + where + T: Sized, + { if !align.is_power_of_two() { panic!("align_offset: align is not a power-of-two"); } - unsafe { - align_offset(self, align) - } + unsafe { align_offset(self, align) } } } - #[lang = "mut_ptr"] impl *mut T { /// Returns `true` if the pointer is null. @@ -1806,11 +1821,7 @@ impl *mut T { #[stable(feature = "ptr_as_ref", since = "1.9.0")] #[inline] pub unsafe fn as_ref<'a>(self) -> Option<&'a T> { - if self.is_null() { - None - } else { - Some(&*self) - } + if self.is_null() { None } else { Some(&*self) } } /// Calculates the offset from a pointer. @@ -1866,7 +1877,10 @@ impl *mut T { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] - pub unsafe fn offset(self, count: isize) -> *mut T where T: Sized { + pub unsafe fn offset(self, count: isize) -> *mut T + where + T: Sized, + { intrinsics::offset(self, count) as *mut T } @@ -1920,10 +1934,11 @@ impl *mut T { /// ``` #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")] #[inline] - pub fn wrapping_offset(self, count: isize) -> *mut T where T: Sized { - unsafe { - intrinsics::arith_offset(self, count) as *mut T - } + pub fn wrapping_offset(self, count: isize) -> *mut T + where + T: Sized, + { + unsafe { intrinsics::arith_offset(self, count) as *mut T } } /// Returns `None` if the pointer is null, or else returns a mutable @@ -1968,11 +1983,7 @@ impl *mut T { #[stable(feature = "ptr_as_ref", since = "1.9.0")] #[inline] pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> { - if self.is_null() { - None - } else { - Some(&mut *self) - } + if self.is_null() { None } else { Some(&mut *self) } } /// Calculates the distance between two pointers. The returned value is in @@ -2040,7 +2051,10 @@ impl *mut T { #[unstable(feature = "ptr_offset_from", issue = "41079")] #[rustc_const_unstable(feature = "const_ptr_offset_from")] #[inline] - pub const unsafe fn offset_from(self, origin: *const T) -> isize where T: Sized { + pub const unsafe fn offset_from(self, origin: *const T) -> isize + where + T: Sized, + { (self as *const T).offset_from(origin) } @@ -2080,7 +2094,10 @@ impl *mut T { /// ``` #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")] #[inline] - pub fn wrapping_offset_from(self, origin: *const T) -> isize where T: Sized { + pub fn wrapping_offset_from(self, origin: *const T) -> isize + where + T: Sized, + { (self as *const T).wrapping_offset_from(origin) } @@ -2138,7 +2155,8 @@ impl *mut T { #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] pub unsafe fn add(self, count: usize) -> Self - where T: Sized, + where + T: Sized, { self.offset(count as isize) } @@ -2198,7 +2216,8 @@ impl *mut T { #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] pub unsafe fn sub(self, count: usize) -> Self - where T: Sized, + where + T: Sized, { self.offset((count as isize).wrapping_neg()) } @@ -2252,7 +2271,8 @@ impl *mut T { #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] pub fn wrapping_add(self, count: usize) -> Self - where T: Sized, + where + T: Sized, { self.wrapping_offset(count as isize) } @@ -2306,7 +2326,8 @@ impl *mut T { #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] pub fn wrapping_sub(self, count: usize) -> Self - where T: Sized, + where + T: Sized, { self.wrapping_offset((count as isize).wrapping_neg()) } @@ -2320,7 +2341,8 @@ impl *mut T { #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] pub unsafe fn read(self) -> T - where T: Sized, + where + T: Sized, { read(self) } @@ -2338,7 +2360,8 @@ impl *mut T { #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] pub unsafe fn read_volatile(self) -> T - where T: Sized, + where + T: Sized, { read_volatile(self) } @@ -2354,7 +2377,8 @@ impl *mut T { #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] pub unsafe fn read_unaligned(self) -> T - where T: Sized, + where + T: Sized, { read_unaligned(self) } @@ -2370,7 +2394,8 @@ impl *mut T { #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] pub unsafe fn copy_to(self, dest: *mut T, count: usize) - where T: Sized, + where + T: Sized, { copy(self, dest, count) } @@ -2386,7 +2411,8 @@ impl *mut T { #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] pub unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize) - where T: Sized, + where + T: Sized, { copy_nonoverlapping(self, dest, count) } @@ -2402,7 +2428,8 @@ impl *mut T { #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] pub unsafe fn copy_from(self, src: *const T, count: usize) - where T: Sized, + where + T: Sized, { copy(src, self, count) } @@ -2418,7 +2445,8 @@ impl *mut T { #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] pub unsafe fn copy_from_nonoverlapping(self, src: *const T, count: usize) - where T: Sized, + where + T: Sized, { copy_nonoverlapping(src, self, count) } @@ -2443,7 +2471,8 @@ impl *mut T { #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] pub unsafe fn write(self, val: T) - where T: Sized, + where + T: Sized, { write(self, val) } @@ -2457,7 +2486,8 @@ impl *mut T { #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] pub unsafe fn write_bytes(self, val: u8, count: usize) - where T: Sized, + where + T: Sized, { write_bytes(self, val, count) } @@ -2475,7 +2505,8 @@ impl *mut T { #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] pub unsafe fn write_volatile(self, val: T) - where T: Sized, + where + T: Sized, { write_volatile(self, val) } @@ -2491,7 +2522,8 @@ impl *mut T { #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] pub unsafe fn write_unaligned(self, val: T) - where T: Sized, + where + T: Sized, { write_unaligned(self, val) } @@ -2505,7 +2537,8 @@ impl *mut T { #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] pub unsafe fn replace(self, src: T) -> T - where T: Sized, + where + T: Sized, { replace(self, src) } @@ -2520,7 +2553,8 @@ impl *mut T { #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] pub unsafe fn swap(self, with: *mut T) - where T: Sized, + where + T: Sized, { swap(self, with) } @@ -2565,13 +2599,14 @@ impl *mut T { /// # } } /// ``` #[stable(feature = "align_offset", since = "1.36.0")] - pub fn align_offset(self, align: usize) -> usize where T: Sized { + pub fn align_offset(self, align: usize) -> usize + where + T: Sized, + { if !align.is_power_of_two() { panic!("align_offset: align is not a power-of-two"); } - unsafe { - align_offset(self, align) - } + unsafe { align_offset(self, align) } } } @@ -2589,7 +2624,7 @@ impl *mut T { /// than trying to adapt this to accommodate that change. /// /// Any questions go to @nagisa. -#[lang="align_offset"] +#[lang = "align_offset"] pub(crate) unsafe fn align_offset(p: *const T, a: usize) -> usize { /// Calculate multiplicative modular inverse of `x` modulo `m`. /// @@ -2629,9 +2664,8 @@ pub(crate) unsafe fn align_offset(p: *const T, a: usize) -> usize { // uses e.g., subtraction `mod n`. It is entirely fine to do them `mod // usize::max_value()` instead, because we take the result `mod n` at the end // anyway. - inverse = inverse.wrapping_mul( - 2usize.wrapping_sub(x.wrapping_mul(inverse)) - ) & (going_mod - 1); + inverse = inverse.wrapping_mul(2usize.wrapping_sub(x.wrapping_mul(inverse))) + & (going_mod - 1); if going_mod > m { return inverse & (m - 1); } @@ -2690,13 +2724,13 @@ pub(crate) unsafe fn align_offset(p: *const T, a: usize) -> usize { usize::max_value() } - - // Equality for pointers #[stable(feature = "rust1", since = "1.0.0")] impl PartialEq for *const T { #[inline] - fn eq(&self, other: &*const T) -> bool { *self == *other } + fn eq(&self, other: &*const T) -> bool { + *self == *other + } } #[stable(feature = "rust1", since = "1.0.0")] @@ -2705,7 +2739,9 @@ impl Eq for *const T {} #[stable(feature = "rust1", since = "1.0.0")] impl PartialEq for *mut T { #[inline] - fn eq(&self, other: &*mut T) -> bool { *self == *other } + fn eq(&self, other: &*mut T) -> bool { + *self == *other + } } #[stable(feature = "rust1", since = "1.0.0")] @@ -2891,7 +2927,7 @@ macro_rules! fnptr_impls_args { }; } -fnptr_impls_args! { } +fnptr_impls_args! {} fnptr_impls_args! { A } fnptr_impls_args! { A, B } fnptr_impls_args! { A, B, C } @@ -2928,16 +2964,24 @@ impl PartialOrd for *const T { } #[inline] - fn lt(&self, other: &*const T) -> bool { *self < *other } + fn lt(&self, other: &*const T) -> bool { + *self < *other + } #[inline] - fn le(&self, other: &*const T) -> bool { *self <= *other } + fn le(&self, other: &*const T) -> bool { + *self <= *other + } #[inline] - fn gt(&self, other: &*const T) -> bool { *self > *other } + fn gt(&self, other: &*const T) -> bool { + *self > *other + } #[inline] - fn ge(&self, other: &*const T) -> bool { *self >= *other } + fn ge(&self, other: &*const T) -> bool { + *self >= *other + } } #[stable(feature = "rust1", since = "1.0.0")] @@ -2962,14 +3006,22 @@ impl PartialOrd for *mut T { } #[inline] - fn lt(&self, other: &*mut T) -> bool { *self < *other } + fn lt(&self, other: &*mut T) -> bool { + *self < *other + } #[inline] - fn le(&self, other: &*mut T) -> bool { *self <= *other } + fn le(&self, other: &*mut T) -> bool { + *self <= *other + } #[inline] - fn gt(&self, other: &*mut T) -> bool { *self > *other } + fn gt(&self, other: &*mut T) -> bool { + *self > *other + } #[inline] - fn ge(&self, other: &*mut T) -> bool { *self >= *other } + fn ge(&self, other: &*mut T) -> bool { + *self >= *other + } } diff --git a/src/libcore/tests/any.rs b/src/libcore/tests/any.rs index 62bebcb03c96a..b0dc99034644a 100644 --- a/src/libcore/tests/any.rs +++ b/src/libcore/tests/any.rs @@ -24,11 +24,8 @@ fn any_referenced() { #[test] fn any_owning() { - let (a, b, c) = ( - box 5_usize as Box, - box TEST as Box, - box Test as Box, - ); + let (a, b, c) = + (box 5_usize as Box, box TEST as Box, box Test as Box); assert!(a.is::()); assert!(!b.is::()); @@ -49,12 +46,12 @@ fn any_downcast_ref() { match a.downcast_ref::() { Some(&5) => {} - x => panic!("Unexpected value {:?}", x) + x => panic!("Unexpected value {:?}", x), } match a.downcast_ref::() { None => {} - x => panic!("Unexpected value {:?}", x) + x => panic!("Unexpected value {:?}", x), } } @@ -72,7 +69,7 @@ fn any_downcast_mut() { assert_eq!(*x, 5); *x = 612; } - x => panic!("Unexpected value {:?}", x) + x => panic!("Unexpected value {:?}", x), } match b_r.downcast_mut::() { @@ -80,27 +77,27 @@ fn any_downcast_mut() { assert_eq!(*x, 7); *x = 413; } - x => panic!("Unexpected value {:?}", x) + x => panic!("Unexpected value {:?}", x), } match a_r.downcast_mut::() { None => (), - x => panic!("Unexpected value {:?}", x) + x => panic!("Unexpected value {:?}", x), } match b_r.downcast_mut::() { None => (), - x => panic!("Unexpected value {:?}", x) + x => panic!("Unexpected value {:?}", x), } match a_r.downcast_mut::() { Some(&mut 612) => {} - x => panic!("Unexpected value {:?}", x) + x => panic!("Unexpected value {:?}", x), } match b_r.downcast_mut::() { Some(&mut 413) => {} - x => panic!("Unexpected value {:?}", x) + x => panic!("Unexpected value {:?}", x), } } diff --git a/src/libcore/tests/array.rs b/src/libcore/tests/array.rs index 4f3b79c78b66c..c2a816f0a7d90 100644 --- a/src/libcore/tests/array.rs +++ b/src/libcore/tests/array.rs @@ -41,7 +41,6 @@ fn array_try_from() { } } - #[test] fn iterator_collect() { let arr = [0, 1, 2, 5, 9]; @@ -150,10 +149,7 @@ fn iterator_flat_map() { #[test] fn iterator_debug() { let arr = [0, 1, 2, 5, 9]; - assert_eq!( - format!("{:?}", IntoIter::new(arr)), - "IntoIter([0, 1, 2, 5, 9])", - ); + assert_eq!(format!("{:?}", IntoIter::new(arr)), "IntoIter([0, 1, 2, 5, 9])",); } #[test] @@ -168,7 +164,7 @@ fn iterator_drops() { struct Foo<'a>(&'a Cell); impl Drop for Foo<'_> { - fn drop(&mut self) { + fn drop(&mut self) { self.0.set(self.0.get() + 1); } } diff --git a/src/libcore/tests/ascii.rs b/src/libcore/tests/ascii.rs index 439ed0c81c8b6..71275d40c4621 100644 --- a/src/libcore/tests/ascii.rs +++ b/src/libcore/tests/ascii.rs @@ -22,10 +22,12 @@ fn test_to_ascii_uppercase() { assert_eq!("hıKß".to_ascii_uppercase(), "HıKß"); for i in 0..501 { - let upper = if 'a' as u32 <= i && i <= 'z' as u32 { i + 'A' as u32 - 'a' as u32 } - else { i }; - assert_eq!((from_u32(i).unwrap()).to_string().to_ascii_uppercase(), - (from_u32(upper).unwrap()).to_string()); + let upper = + if 'a' as u32 <= i && i <= 'z' as u32 { i + 'A' as u32 - 'a' as u32 } else { i }; + assert_eq!( + (from_u32(i).unwrap()).to_string().to_ascii_uppercase(), + (from_u32(upper).unwrap()).to_string() + ); } } @@ -36,23 +38,23 @@ fn test_to_ascii_lowercase() { assert_eq!("HİKß".to_ascii_lowercase(), "hİKß"); for i in 0..501 { - let lower = if 'A' as u32 <= i && i <= 'Z' as u32 { i + 'a' as u32 - 'A' as u32 } - else { i }; - assert_eq!((from_u32(i).unwrap()).to_string().to_ascii_lowercase(), - (from_u32(lower).unwrap()).to_string()); + let lower = + if 'A' as u32 <= i && i <= 'Z' as u32 { i + 'a' as u32 - 'A' as u32 } else { i }; + assert_eq!( + (from_u32(i).unwrap()).to_string().to_ascii_lowercase(), + (from_u32(lower).unwrap()).to_string() + ); } } #[test] fn test_make_ascii_lower_case() { macro_rules! test { - ($from: expr, $to: expr) => { - { - let mut x = $from; - x.make_ascii_lowercase(); - assert_eq!(x, $to); - } - } + ($from: expr, $to: expr) => {{ + let mut x = $from; + x.make_ascii_lowercase(); + assert_eq!(x, $to); + }}; } test!(b'A', b'a'); test!(b'a', b'a'); @@ -65,17 +67,14 @@ fn test_make_ascii_lower_case() { test!("HİKß".to_string(), "hİKß"); } - #[test] fn test_make_ascii_upper_case() { macro_rules! test { - ($from: expr, $to: expr) => { - { - let mut x = $from; - x.make_ascii_uppercase(); - assert_eq!(x, $to); - } - } + ($from: expr, $to: expr) => {{ + let mut x = $from; + x.make_ascii_uppercase(); + assert_eq!(x, $to); + }}; } test!(b'a', b'A'); test!(b'A', b'A'); @@ -88,7 +87,7 @@ fn test_make_ascii_upper_case() { test!("hıKß".to_string(), "HıKß"); let mut x = "Hello".to_string(); - x[..3].make_ascii_uppercase(); // Test IndexMut on String. + x[..3].make_ascii_uppercase(); // Test IndexMut on String. assert_eq!(x, "HELlo") } @@ -103,10 +102,13 @@ fn test_eq_ignore_ascii_case() { assert!(!"ß".eq_ignore_ascii_case("s")); for i in 0..501 { - let lower = if 'A' as u32 <= i && i <= 'Z' as u32 { i + 'a' as u32 - 'A' as u32 } - else { i }; - assert!((from_u32(i).unwrap()).to_string().eq_ignore_ascii_case( - &from_u32(lower).unwrap().to_string())); + let lower = + if 'A' as u32 <= i && i <= 'Z' as u32 { i + 'a' as u32 - 'A' as u32 } else { i }; + assert!( + (from_u32(i).unwrap()) + .to_string() + .eq_ignore_ascii_case(&from_u32(lower).unwrap().to_string()) + ); } } @@ -158,12 +160,14 @@ macro_rules! assert_none { #[test] fn test_is_ascii_alphabetic() { - assert_all!(is_ascii_alphabetic, + assert_all!( + is_ascii_alphabetic, "", "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOQPRSTUVWXYZ", ); - assert_none!(is_ascii_alphabetic, + assert_none!( + is_ascii_alphabetic, "0123456789", "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", " \t\n\x0c\r", @@ -177,11 +181,9 @@ fn test_is_ascii_alphabetic() { #[test] fn test_is_ascii_uppercase() { - assert_all!(is_ascii_uppercase, - "", - "ABCDEFGHIJKLMNOQPRSTUVWXYZ", - ); - assert_none!(is_ascii_uppercase, + assert_all!(is_ascii_uppercase, "", "ABCDEFGHIJKLMNOQPRSTUVWXYZ",); + assert_none!( + is_ascii_uppercase, "abcdefghijklmnopqrstuvwxyz", "0123456789", "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", @@ -196,10 +198,9 @@ fn test_is_ascii_uppercase() { #[test] fn test_is_ascii_lowercase() { - assert_all!(is_ascii_lowercase, - "abcdefghijklmnopqrstuvwxyz", - ); - assert_none!(is_ascii_lowercase, + assert_all!(is_ascii_lowercase, "abcdefghijklmnopqrstuvwxyz",); + assert_none!( + is_ascii_lowercase, "ABCDEFGHIJKLMNOQPRSTUVWXYZ", "0123456789", "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", @@ -214,13 +215,15 @@ fn test_is_ascii_lowercase() { #[test] fn test_is_ascii_alphanumeric() { - assert_all!(is_ascii_alphanumeric, + assert_all!( + is_ascii_alphanumeric, "", "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOQPRSTUVWXYZ", "0123456789", ); - assert_none!(is_ascii_alphanumeric, + assert_none!( + is_ascii_alphanumeric, "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", " \t\n\x0c\r", "\x00\x01\x02\x03\x04\x05\x06\x07", @@ -233,11 +236,9 @@ fn test_is_ascii_alphanumeric() { #[test] fn test_is_ascii_digit() { - assert_all!(is_ascii_digit, - "", - "0123456789", - ); - assert_none!(is_ascii_digit, + assert_all!(is_ascii_digit, "", "0123456789",); + assert_none!( + is_ascii_digit, "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOQPRSTUVWXYZ", "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", @@ -252,12 +253,9 @@ fn test_is_ascii_digit() { #[test] fn test_is_ascii_hexdigit() { - assert_all!(is_ascii_hexdigit, - "", - "0123456789", - "abcdefABCDEF", - ); - assert_none!(is_ascii_hexdigit, + assert_all!(is_ascii_hexdigit, "", "0123456789", "abcdefABCDEF",); + assert_none!( + is_ascii_hexdigit, "ghijklmnopqrstuvwxyz", "GHIJKLMNOQPRSTUVWXYZ", "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", @@ -272,11 +270,9 @@ fn test_is_ascii_hexdigit() { #[test] fn test_is_ascii_punctuation() { - assert_all!(is_ascii_punctuation, - "", - "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", - ); - assert_none!(is_ascii_punctuation, + assert_all!(is_ascii_punctuation, "", "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~",); + assert_none!( + is_ascii_punctuation, "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOQPRSTUVWXYZ", "0123456789", @@ -291,14 +287,16 @@ fn test_is_ascii_punctuation() { #[test] fn test_is_ascii_graphic() { - assert_all!(is_ascii_graphic, + assert_all!( + is_ascii_graphic, "", "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOQPRSTUVWXYZ", "0123456789", "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", ); - assert_none!(is_ascii_graphic, + assert_none!( + is_ascii_graphic, " \t\n\x0c\r", "\x00\x01\x02\x03\x04\x05\x06\x07", "\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", @@ -310,11 +308,9 @@ fn test_is_ascii_graphic() { #[test] fn test_is_ascii_whitespace() { - assert_all!(is_ascii_whitespace, - "", - " \t\n\x0c\r", - ); - assert_none!(is_ascii_whitespace, + assert_all!(is_ascii_whitespace, "", " \t\n\x0c\r",); + assert_none!( + is_ascii_whitespace, "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOQPRSTUVWXYZ", "0123456789", @@ -329,7 +325,8 @@ fn test_is_ascii_whitespace() { #[test] fn test_is_ascii_control() { - assert_all!(is_ascii_control, + assert_all!( + is_ascii_control, "", "\x00\x01\x02\x03\x04\x05\x06\x07", "\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", @@ -337,7 +334,8 @@ fn test_is_ascii_control() { "\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f", "\x7f", ); - assert_none!(is_ascii_control, + assert_none!( + is_ascii_control, "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOQPRSTUVWXYZ", "0123456789", diff --git a/src/libcore/tests/atomic.rs b/src/libcore/tests/atomic.rs index 05fe8460f324e..acbd913982c1f 100644 --- a/src/libcore/tests/atomic.rs +++ b/src/libcore/tests/atomic.rs @@ -1,5 +1,5 @@ -use core::sync::atomic::*; use core::sync::atomic::Ordering::SeqCst; +use core::sync::atomic::*; #[test] fn bool_() { @@ -15,7 +15,7 @@ fn bool_() { fn bool_and() { let a = AtomicBool::new(true); assert_eq!(a.fetch_and(false, SeqCst), true); - assert_eq!(a.load(SeqCst),false); + assert_eq!(a.load(SeqCst), false); } #[test] @@ -89,7 +89,7 @@ fn int_xor() { static S_FALSE: AtomicBool = AtomicBool::new(false); static S_TRUE: AtomicBool = AtomicBool::new(true); -static S_INT: AtomicIsize = AtomicIsize::new(0); +static S_INT: AtomicIsize = AtomicIsize::new(0); static S_UINT: AtomicUsize = AtomicUsize::new(0); #[test] diff --git a/src/libcore/tests/cell.rs b/src/libcore/tests/cell.rs index 4dfd884d2377c..801b60be0f093 100644 --- a/src/libcore/tests/cell.rs +++ b/src/libcore/tests/cell.rs @@ -236,7 +236,7 @@ fn ref_mut_map_accessor() { } let x = X(RefCell::new((7, 'z'))); { - let mut d: RefMut<'_ ,u32> = x.accessor(); + let mut d: RefMut<'_, u32> = x.accessor(); assert_eq!(*d, 7); *d += 1; } @@ -250,7 +250,9 @@ fn as_ptr() { assert_eq!(1, unsafe { *c1.as_ptr() }); let c2: Cell = Cell::new(0); - unsafe { *c2.as_ptr() = 1; } + unsafe { + *c2.as_ptr() = 1; + } assert_eq!(1, c2.get()); let r1: RefCell = RefCell::new(0); @@ -258,7 +260,9 @@ fn as_ptr() { assert_eq!(1, unsafe { *r1.as_ptr() }); let r2: RefCell = RefCell::new(0); - unsafe { *r2.as_ptr() = 1; } + unsafe { + *r2.as_ptr() = 1; + } assert_eq!(1, *r2.borrow()); } diff --git a/src/libcore/tests/char.rs b/src/libcore/tests/char.rs index 57e9f4e384e0f..c16f54081ce06 100644 --- a/src/libcore/tests/char.rs +++ b/src/libcore/tests/char.rs @@ -1,6 +1,6 @@ -use std::{char,str}; use std::convert::TryFrom; use std::str::FromStr; +use std::{char, str}; #[test] fn test_convert() { @@ -143,13 +143,13 @@ fn test_is_control() { #[test] fn test_is_numeric() { - assert!('2'.is_numeric()); - assert!('7'.is_numeric()); - assert!('¾'.is_numeric()); - assert!(!'c'.is_numeric()); - assert!(!'i'.is_numeric()); - assert!(!'z'.is_numeric()); - assert!(!'Q'.is_numeric()); + assert!('2'.is_numeric()); + assert!('7'.is_numeric()); + assert!('¾'.is_numeric()); + assert!(!'c'.is_numeric()); + assert!(!'i'.is_numeric()); + assert!(!'z'.is_numeric()); + assert!(!'Q'.is_numeric()); } #[test] @@ -176,9 +176,9 @@ fn test_escape_debug() { assert_eq!(string('\u{ff}'), "\u{ff}"); assert_eq!(string('\u{11b}'), "\u{11b}"); assert_eq!(string('\u{1d4b6}'), "\u{1d4b6}"); - assert_eq!(string('\u{301}'), "\\u{301}"); // combining character - assert_eq!(string('\u{200b}'),"\\u{200b}"); // zero width space - assert_eq!(string('\u{e000}'), "\\u{e000}"); // private use 1 + assert_eq!(string('\u{301}'), "\\u{301}"); // combining character + assert_eq!(string('\u{200b}'), "\\u{200b}"); // zero width space + assert_eq!(string('\u{e000}'), "\\u{e000}"); // private use 1 assert_eq!(string('\u{100000}'), "\\u{100000}"); // private use 2 } @@ -272,8 +272,8 @@ fn test_len_utf16() { fn test_decode_utf16() { fn check(s: &[u16], expected: &[Result]) { let v = char::decode_utf16(s.iter().cloned()) - .map(|r| r.map_err(|e| e.unpaired_surrogate())) - .collect::>(); + .map(|r| r.map_err(|e| e.unpaired_surrogate())) + .collect::>(); assert_eq!(v, expected); } check(&[0xD800, 0x41, 0x42], &[Err(0xD800), Ok('A'), Ok('B')]); diff --git a/src/libcore/tests/hash/mod.rs b/src/libcore/tests/hash/mod.rs index 1000088e6b063..348245e24f6ea 100644 --- a/src/libcore/tests/hash/mod.rs +++ b/src/libcore/tests/hash/mod.rs @@ -1,7 +1,7 @@ mod sip; -use std::hash::{Hash, Hasher}; use std::default::Default; +use std::hash::{Hash, Hasher}; use std::rc::Rc; struct MyHasher { @@ -20,10 +20,11 @@ impl Hasher for MyHasher { self.hash += *byte as u64; } } - fn finish(&self) -> u64 { self.hash } + fn finish(&self) -> u64 { + self.hash + } } - #[test] fn test_writer_hasher() { fn hash(t: &T) -> u64 { @@ -52,17 +53,17 @@ fn test_writer_hasher() { assert_eq!(hash(&'a'), 97); let s: &str = "a"; - assert_eq!(hash(& s), 97 + 0xFF); + assert_eq!(hash(&s), 97 + 0xFF); let s: Box = String::from("a").into_boxed_str(); - assert_eq!(hash(& s), 97 + 0xFF); + assert_eq!(hash(&s), 97 + 0xFF); let s: Rc<&str> = Rc::new("a"); assert_eq!(hash(&s), 97 + 0xFF); let cs: &[u8] = &[1, 2, 3]; - assert_eq!(hash(& cs), 9); + assert_eq!(hash(&cs), 9); let cs: Box<[u8]> = Box::new([1, 2, 3]); - assert_eq!(hash(& cs), 9); + assert_eq!(hash(&cs), 9); let cs: Rc<[u8]> = Rc::new([1, 2, 3]); - assert_eq!(hash(& cs), 9); + assert_eq!(hash(&cs), 9); let ptr = 5_usize as *const i32; assert_eq!(hash(&ptr), 5); @@ -81,13 +82,23 @@ fn test_writer_hasher() { assert_eq!(hash(&slice_ptr), hash(&ptr) + cs.len() as u64); } -struct Custom { hash: u64 } -struct CustomHasher { output: u64 } +struct Custom { + hash: u64, +} +struct CustomHasher { + output: u64, +} impl Hasher for CustomHasher { - fn finish(&self) -> u64 { self.output } - fn write(&mut self, _: &[u8]) { panic!() } - fn write_u64(&mut self, data: u64) { self.output = data; } + fn finish(&self) -> u64 { + self.output + } + fn write(&mut self, _: &[u8]) { + panic!() + } + fn write_u64(&mut self, data: u64) { + self.output = data; + } } impl Default for CustomHasher { diff --git a/src/libcore/tests/hash/sip.rs b/src/libcore/tests/hash/sip.rs index b615cfd77ef1d..0f09554991591 100644 --- a/src/libcore/tests/hash/sip.rs +++ b/src/libcore/tests/hash/sip.rs @@ -2,7 +2,7 @@ use core::hash::{Hash, Hasher}; use core::hash::{SipHasher, SipHasher13}; -use core::{slice, mem}; +use core::{mem, slice}; // Hash just the bytes of the slice, without length prefix struct Bytes<'a>(&'a [u8]); @@ -16,25 +16,25 @@ impl<'a> Hash for Bytes<'a> { } macro_rules! u8to64_le { - ($buf:expr, $i:expr) => - ($buf[0+$i] as u64 | - ($buf[1+$i] as u64) << 8 | - ($buf[2+$i] as u64) << 16 | - ($buf[3+$i] as u64) << 24 | - ($buf[4+$i] as u64) << 32 | - ($buf[5+$i] as u64) << 40 | - ($buf[6+$i] as u64) << 48 | - ($buf[7+$i] as u64) << 56); - ($buf:expr, $i:expr, $len:expr) => - ({ + ($buf:expr, $i:expr) => { + $buf[0 + $i] as u64 + | ($buf[1 + $i] as u64) << 8 + | ($buf[2 + $i] as u64) << 16 + | ($buf[3 + $i] as u64) << 24 + | ($buf[4 + $i] as u64) << 32 + | ($buf[5 + $i] as u64) << 40 + | ($buf[6 + $i] as u64) << 48 + | ($buf[7 + $i] as u64) << 56 + }; + ($buf:expr, $i:expr, $len:expr) => {{ let mut t = 0; let mut out = 0; while t < $len { - out |= ($buf[t+$i] as u64) << t*8; + out |= ($buf[t + $i] as u64) << t * 8; t += 1; } out - }); + }}; } fn hash_with(mut st: H, x: &T) -> u64 { @@ -49,71 +49,71 @@ fn hash(x: &T) -> u64 { #[test] #[allow(unused_must_use)] fn test_siphash_1_3() { - let vecs : [[u8; 8]; 64] = [ - [ 0xdc, 0xc4, 0x0f, 0x05, 0x58, 0x01, 0xac, 0xab ], - [ 0x93, 0xca, 0x57, 0x7d, 0xf3, 0x9b, 0xf4, 0xc9 ], - [ 0x4d, 0xd4, 0xc7, 0x4d, 0x02, 0x9b, 0xcb, 0x82 ], - [ 0xfb, 0xf7, 0xdd, 0xe7, 0xb8, 0x0a, 0xf8, 0x8b ], - [ 0x28, 0x83, 0xd3, 0x88, 0x60, 0x57, 0x75, 0xcf ], - [ 0x67, 0x3b, 0x53, 0x49, 0x2f, 0xd5, 0xf9, 0xde ], - [ 0xa7, 0x22, 0x9f, 0xc5, 0x50, 0x2b, 0x0d, 0xc5 ], - [ 0x40, 0x11, 0xb1, 0x9b, 0x98, 0x7d, 0x92, 0xd3 ], - [ 0x8e, 0x9a, 0x29, 0x8d, 0x11, 0x95, 0x90, 0x36 ], - [ 0xe4, 0x3d, 0x06, 0x6c, 0xb3, 0x8e, 0xa4, 0x25 ], - [ 0x7f, 0x09, 0xff, 0x92, 0xee, 0x85, 0xde, 0x79 ], - [ 0x52, 0xc3, 0x4d, 0xf9, 0xc1, 0x18, 0xc1, 0x70 ], - [ 0xa2, 0xd9, 0xb4, 0x57, 0xb1, 0x84, 0xa3, 0x78 ], - [ 0xa7, 0xff, 0x29, 0x12, 0x0c, 0x76, 0x6f, 0x30 ], - [ 0x34, 0x5d, 0xf9, 0xc0, 0x11, 0xa1, 0x5a, 0x60 ], - [ 0x56, 0x99, 0x51, 0x2a, 0x6d, 0xd8, 0x20, 0xd3 ], - [ 0x66, 0x8b, 0x90, 0x7d, 0x1a, 0xdd, 0x4f, 0xcc ], - [ 0x0c, 0xd8, 0xdb, 0x63, 0x90, 0x68, 0xf2, 0x9c ], - [ 0x3e, 0xe6, 0x73, 0xb4, 0x9c, 0x38, 0xfc, 0x8f ], - [ 0x1c, 0x7d, 0x29, 0x8d, 0xe5, 0x9d, 0x1f, 0xf2 ], - [ 0x40, 0xe0, 0xcc, 0xa6, 0x46, 0x2f, 0xdc, 0xc0 ], - [ 0x44, 0xf8, 0x45, 0x2b, 0xfe, 0xab, 0x92, 0xb9 ], - [ 0x2e, 0x87, 0x20, 0xa3, 0x9b, 0x7b, 0xfe, 0x7f ], - [ 0x23, 0xc1, 0xe6, 0xda, 0x7f, 0x0e, 0x5a, 0x52 ], - [ 0x8c, 0x9c, 0x34, 0x67, 0xb2, 0xae, 0x64, 0xf4 ], - [ 0x79, 0x09, 0x5b, 0x70, 0x28, 0x59, 0xcd, 0x45 ], - [ 0xa5, 0x13, 0x99, 0xca, 0xe3, 0x35, 0x3e, 0x3a ], - [ 0x35, 0x3b, 0xde, 0x4a, 0x4e, 0xc7, 0x1d, 0xa9 ], - [ 0x0d, 0xd0, 0x6c, 0xef, 0x02, 0xed, 0x0b, 0xfb ], - [ 0xf4, 0xe1, 0xb1, 0x4a, 0xb4, 0x3c, 0xd9, 0x88 ], - [ 0x63, 0xe6, 0xc5, 0x43, 0xd6, 0x11, 0x0f, 0x54 ], - [ 0xbc, 0xd1, 0x21, 0x8c, 0x1f, 0xdd, 0x70, 0x23 ], - [ 0x0d, 0xb6, 0xa7, 0x16, 0x6c, 0x7b, 0x15, 0x81 ], - [ 0xbf, 0xf9, 0x8f, 0x7a, 0xe5, 0xb9, 0x54, 0x4d ], - [ 0x3e, 0x75, 0x2a, 0x1f, 0x78, 0x12, 0x9f, 0x75 ], - [ 0x91, 0x6b, 0x18, 0xbf, 0xbe, 0xa3, 0xa1, 0xce ], - [ 0x06, 0x62, 0xa2, 0xad, 0xd3, 0x08, 0xf5, 0x2c ], - [ 0x57, 0x30, 0xc3, 0xa3, 0x2d, 0x1c, 0x10, 0xb6 ], - [ 0xa1, 0x36, 0x3a, 0xae, 0x96, 0x74, 0xf4, 0xb3 ], - [ 0x92, 0x83, 0x10, 0x7b, 0x54, 0x57, 0x6b, 0x62 ], - [ 0x31, 0x15, 0xe4, 0x99, 0x32, 0x36, 0xd2, 0xc1 ], - [ 0x44, 0xd9, 0x1a, 0x3f, 0x92, 0xc1, 0x7c, 0x66 ], - [ 0x25, 0x88, 0x13, 0xc8, 0xfe, 0x4f, 0x70, 0x65 ], - [ 0xa6, 0x49, 0x89, 0xc2, 0xd1, 0x80, 0xf2, 0x24 ], - [ 0x6b, 0x87, 0xf8, 0xfa, 0xed, 0x1c, 0xca, 0xc2 ], - [ 0x96, 0x21, 0x04, 0x9f, 0xfc, 0x4b, 0x16, 0xc2 ], - [ 0x23, 0xd6, 0xb1, 0x68, 0x93, 0x9c, 0x6e, 0xa1 ], - [ 0xfd, 0x14, 0x51, 0x8b, 0x9c, 0x16, 0xfb, 0x49 ], - [ 0x46, 0x4c, 0x07, 0xdf, 0xf8, 0x43, 0x31, 0x9f ], - [ 0xb3, 0x86, 0xcc, 0x12, 0x24, 0xaf, 0xfd, 0xc6 ], - [ 0x8f, 0x09, 0x52, 0x0a, 0xd1, 0x49, 0xaf, 0x7e ], - [ 0x9a, 0x2f, 0x29, 0x9d, 0x55, 0x13, 0xf3, 0x1c ], - [ 0x12, 0x1f, 0xf4, 0xa2, 0xdd, 0x30, 0x4a, 0xc4 ], - [ 0xd0, 0x1e, 0xa7, 0x43, 0x89, 0xe9, 0xfa, 0x36 ], - [ 0xe6, 0xbc, 0xf0, 0x73, 0x4c, 0xb3, 0x8f, 0x31 ], - [ 0x80, 0xe9, 0xa7, 0x70, 0x36, 0xbf, 0x7a, 0xa2 ], - [ 0x75, 0x6d, 0x3c, 0x24, 0xdb, 0xc0, 0xbc, 0xb4 ], - [ 0x13, 0x15, 0xb7, 0xfd, 0x52, 0xd8, 0xf8, 0x23 ], - [ 0x08, 0x8a, 0x7d, 0xa6, 0x4d, 0x5f, 0x03, 0x8f ], - [ 0x48, 0xf1, 0xe8, 0xb7, 0xe5, 0xd0, 0x9c, 0xd8 ], - [ 0xee, 0x44, 0xa6, 0xf7, 0xbc, 0xe6, 0xf4, 0xf6 ], - [ 0xf2, 0x37, 0x18, 0x0f, 0xd8, 0x9a, 0xc5, 0xae ], - [ 0xe0, 0x94, 0x66, 0x4b, 0x15, 0xf6, 0xb2, 0xc3 ], - [ 0xa8, 0xb3, 0xbb, 0xb7, 0x62, 0x90, 0x19, 0x9d ] + let vecs: [[u8; 8]; 64] = [ + [0xdc, 0xc4, 0x0f, 0x05, 0x58, 0x01, 0xac, 0xab], + [0x93, 0xca, 0x57, 0x7d, 0xf3, 0x9b, 0xf4, 0xc9], + [0x4d, 0xd4, 0xc7, 0x4d, 0x02, 0x9b, 0xcb, 0x82], + [0xfb, 0xf7, 0xdd, 0xe7, 0xb8, 0x0a, 0xf8, 0x8b], + [0x28, 0x83, 0xd3, 0x88, 0x60, 0x57, 0x75, 0xcf], + [0x67, 0x3b, 0x53, 0x49, 0x2f, 0xd5, 0xf9, 0xde], + [0xa7, 0x22, 0x9f, 0xc5, 0x50, 0x2b, 0x0d, 0xc5], + [0x40, 0x11, 0xb1, 0x9b, 0x98, 0x7d, 0x92, 0xd3], + [0x8e, 0x9a, 0x29, 0x8d, 0x11, 0x95, 0x90, 0x36], + [0xe4, 0x3d, 0x06, 0x6c, 0xb3, 0x8e, 0xa4, 0x25], + [0x7f, 0x09, 0xff, 0x92, 0xee, 0x85, 0xde, 0x79], + [0x52, 0xc3, 0x4d, 0xf9, 0xc1, 0x18, 0xc1, 0x70], + [0xa2, 0xd9, 0xb4, 0x57, 0xb1, 0x84, 0xa3, 0x78], + [0xa7, 0xff, 0x29, 0x12, 0x0c, 0x76, 0x6f, 0x30], + [0x34, 0x5d, 0xf9, 0xc0, 0x11, 0xa1, 0x5a, 0x60], + [0x56, 0x99, 0x51, 0x2a, 0x6d, 0xd8, 0x20, 0xd3], + [0x66, 0x8b, 0x90, 0x7d, 0x1a, 0xdd, 0x4f, 0xcc], + [0x0c, 0xd8, 0xdb, 0x63, 0x90, 0x68, 0xf2, 0x9c], + [0x3e, 0xe6, 0x73, 0xb4, 0x9c, 0x38, 0xfc, 0x8f], + [0x1c, 0x7d, 0x29, 0x8d, 0xe5, 0x9d, 0x1f, 0xf2], + [0x40, 0xe0, 0xcc, 0xa6, 0x46, 0x2f, 0xdc, 0xc0], + [0x44, 0xf8, 0x45, 0x2b, 0xfe, 0xab, 0x92, 0xb9], + [0x2e, 0x87, 0x20, 0xa3, 0x9b, 0x7b, 0xfe, 0x7f], + [0x23, 0xc1, 0xe6, 0xda, 0x7f, 0x0e, 0x5a, 0x52], + [0x8c, 0x9c, 0x34, 0x67, 0xb2, 0xae, 0x64, 0xf4], + [0x79, 0x09, 0x5b, 0x70, 0x28, 0x59, 0xcd, 0x45], + [0xa5, 0x13, 0x99, 0xca, 0xe3, 0x35, 0x3e, 0x3a], + [0x35, 0x3b, 0xde, 0x4a, 0x4e, 0xc7, 0x1d, 0xa9], + [0x0d, 0xd0, 0x6c, 0xef, 0x02, 0xed, 0x0b, 0xfb], + [0xf4, 0xe1, 0xb1, 0x4a, 0xb4, 0x3c, 0xd9, 0x88], + [0x63, 0xe6, 0xc5, 0x43, 0xd6, 0x11, 0x0f, 0x54], + [0xbc, 0xd1, 0x21, 0x8c, 0x1f, 0xdd, 0x70, 0x23], + [0x0d, 0xb6, 0xa7, 0x16, 0x6c, 0x7b, 0x15, 0x81], + [0xbf, 0xf9, 0x8f, 0x7a, 0xe5, 0xb9, 0x54, 0x4d], + [0x3e, 0x75, 0x2a, 0x1f, 0x78, 0x12, 0x9f, 0x75], + [0x91, 0x6b, 0x18, 0xbf, 0xbe, 0xa3, 0xa1, 0xce], + [0x06, 0x62, 0xa2, 0xad, 0xd3, 0x08, 0xf5, 0x2c], + [0x57, 0x30, 0xc3, 0xa3, 0x2d, 0x1c, 0x10, 0xb6], + [0xa1, 0x36, 0x3a, 0xae, 0x96, 0x74, 0xf4, 0xb3], + [0x92, 0x83, 0x10, 0x7b, 0x54, 0x57, 0x6b, 0x62], + [0x31, 0x15, 0xe4, 0x99, 0x32, 0x36, 0xd2, 0xc1], + [0x44, 0xd9, 0x1a, 0x3f, 0x92, 0xc1, 0x7c, 0x66], + [0x25, 0x88, 0x13, 0xc8, 0xfe, 0x4f, 0x70, 0x65], + [0xa6, 0x49, 0x89, 0xc2, 0xd1, 0x80, 0xf2, 0x24], + [0x6b, 0x87, 0xf8, 0xfa, 0xed, 0x1c, 0xca, 0xc2], + [0x96, 0x21, 0x04, 0x9f, 0xfc, 0x4b, 0x16, 0xc2], + [0x23, 0xd6, 0xb1, 0x68, 0x93, 0x9c, 0x6e, 0xa1], + [0xfd, 0x14, 0x51, 0x8b, 0x9c, 0x16, 0xfb, 0x49], + [0x46, 0x4c, 0x07, 0xdf, 0xf8, 0x43, 0x31, 0x9f], + [0xb3, 0x86, 0xcc, 0x12, 0x24, 0xaf, 0xfd, 0xc6], + [0x8f, 0x09, 0x52, 0x0a, 0xd1, 0x49, 0xaf, 0x7e], + [0x9a, 0x2f, 0x29, 0x9d, 0x55, 0x13, 0xf3, 0x1c], + [0x12, 0x1f, 0xf4, 0xa2, 0xdd, 0x30, 0x4a, 0xc4], + [0xd0, 0x1e, 0xa7, 0x43, 0x89, 0xe9, 0xfa, 0x36], + [0xe6, 0xbc, 0xf0, 0x73, 0x4c, 0xb3, 0x8f, 0x31], + [0x80, 0xe9, 0xa7, 0x70, 0x36, 0xbf, 0x7a, 0xa2], + [0x75, 0x6d, 0x3c, 0x24, 0xdb, 0xc0, 0xbc, 0xb4], + [0x13, 0x15, 0xb7, 0xfd, 0x52, 0xd8, 0xf8, 0x23], + [0x08, 0x8a, 0x7d, 0xa6, 0x4d, 0x5f, 0x03, 0x8f], + [0x48, 0xf1, 0xe8, 0xb7, 0xe5, 0xd0, 0x9c, 0xd8], + [0xee, 0x44, 0xa6, 0xf7, 0xbc, 0xe6, 0xf4, 0xf6], + [0xf2, 0x37, 0x18, 0x0f, 0xd8, 0x9a, 0xc5, 0xae], + [0xe0, 0x94, 0x66, 0x4b, 0x15, 0xf6, 0xb2, 0xc3], + [0xa8, 0xb3, 0xbb, 0xb7, 0x62, 0x90, 0x19, 0x9d], ]; let k0 = 0x_07_06_05_04_03_02_01_00; @@ -143,71 +143,71 @@ fn test_siphash_1_3() { #[test] #[allow(unused_must_use)] fn test_siphash_2_4() { - let vecs : [[u8; 8]; 64] = [ - [ 0x31, 0x0e, 0x0e, 0xdd, 0x47, 0xdb, 0x6f, 0x72, ], - [ 0xfd, 0x67, 0xdc, 0x93, 0xc5, 0x39, 0xf8, 0x74, ], - [ 0x5a, 0x4f, 0xa9, 0xd9, 0x09, 0x80, 0x6c, 0x0d, ], - [ 0x2d, 0x7e, 0xfb, 0xd7, 0x96, 0x66, 0x67, 0x85, ], - [ 0xb7, 0x87, 0x71, 0x27, 0xe0, 0x94, 0x27, 0xcf, ], - [ 0x8d, 0xa6, 0x99, 0xcd, 0x64, 0x55, 0x76, 0x18, ], - [ 0xce, 0xe3, 0xfe, 0x58, 0x6e, 0x46, 0xc9, 0xcb, ], - [ 0x37, 0xd1, 0x01, 0x8b, 0xf5, 0x00, 0x02, 0xab, ], - [ 0x62, 0x24, 0x93, 0x9a, 0x79, 0xf5, 0xf5, 0x93, ], - [ 0xb0, 0xe4, 0xa9, 0x0b, 0xdf, 0x82, 0x00, 0x9e, ], - [ 0xf3, 0xb9, 0xdd, 0x94, 0xc5, 0xbb, 0x5d, 0x7a, ], - [ 0xa7, 0xad, 0x6b, 0x22, 0x46, 0x2f, 0xb3, 0xf4, ], - [ 0xfb, 0xe5, 0x0e, 0x86, 0xbc, 0x8f, 0x1e, 0x75, ], - [ 0x90, 0x3d, 0x84, 0xc0, 0x27, 0x56, 0xea, 0x14, ], - [ 0xee, 0xf2, 0x7a, 0x8e, 0x90, 0xca, 0x23, 0xf7, ], - [ 0xe5, 0x45, 0xbe, 0x49, 0x61, 0xca, 0x29, 0xa1, ], - [ 0xdb, 0x9b, 0xc2, 0x57, 0x7f, 0xcc, 0x2a, 0x3f, ], - [ 0x94, 0x47, 0xbe, 0x2c, 0xf5, 0xe9, 0x9a, 0x69, ], - [ 0x9c, 0xd3, 0x8d, 0x96, 0xf0, 0xb3, 0xc1, 0x4b, ], - [ 0xbd, 0x61, 0x79, 0xa7, 0x1d, 0xc9, 0x6d, 0xbb, ], - [ 0x98, 0xee, 0xa2, 0x1a, 0xf2, 0x5c, 0xd6, 0xbe, ], - [ 0xc7, 0x67, 0x3b, 0x2e, 0xb0, 0xcb, 0xf2, 0xd0, ], - [ 0x88, 0x3e, 0xa3, 0xe3, 0x95, 0x67, 0x53, 0x93, ], - [ 0xc8, 0xce, 0x5c, 0xcd, 0x8c, 0x03, 0x0c, 0xa8, ], - [ 0x94, 0xaf, 0x49, 0xf6, 0xc6, 0x50, 0xad, 0xb8, ], - [ 0xea, 0xb8, 0x85, 0x8a, 0xde, 0x92, 0xe1, 0xbc, ], - [ 0xf3, 0x15, 0xbb, 0x5b, 0xb8, 0x35, 0xd8, 0x17, ], - [ 0xad, 0xcf, 0x6b, 0x07, 0x63, 0x61, 0x2e, 0x2f, ], - [ 0xa5, 0xc9, 0x1d, 0xa7, 0xac, 0xaa, 0x4d, 0xde, ], - [ 0x71, 0x65, 0x95, 0x87, 0x66, 0x50, 0xa2, 0xa6, ], - [ 0x28, 0xef, 0x49, 0x5c, 0x53, 0xa3, 0x87, 0xad, ], - [ 0x42, 0xc3, 0x41, 0xd8, 0xfa, 0x92, 0xd8, 0x32, ], - [ 0xce, 0x7c, 0xf2, 0x72, 0x2f, 0x51, 0x27, 0x71, ], - [ 0xe3, 0x78, 0x59, 0xf9, 0x46, 0x23, 0xf3, 0xa7, ], - [ 0x38, 0x12, 0x05, 0xbb, 0x1a, 0xb0, 0xe0, 0x12, ], - [ 0xae, 0x97, 0xa1, 0x0f, 0xd4, 0x34, 0xe0, 0x15, ], - [ 0xb4, 0xa3, 0x15, 0x08, 0xbe, 0xff, 0x4d, 0x31, ], - [ 0x81, 0x39, 0x62, 0x29, 0xf0, 0x90, 0x79, 0x02, ], - [ 0x4d, 0x0c, 0xf4, 0x9e, 0xe5, 0xd4, 0xdc, 0xca, ], - [ 0x5c, 0x73, 0x33, 0x6a, 0x76, 0xd8, 0xbf, 0x9a, ], - [ 0xd0, 0xa7, 0x04, 0x53, 0x6b, 0xa9, 0x3e, 0x0e, ], - [ 0x92, 0x59, 0x58, 0xfc, 0xd6, 0x42, 0x0c, 0xad, ], - [ 0xa9, 0x15, 0xc2, 0x9b, 0xc8, 0x06, 0x73, 0x18, ], - [ 0x95, 0x2b, 0x79, 0xf3, 0xbc, 0x0a, 0xa6, 0xd4, ], - [ 0xf2, 0x1d, 0xf2, 0xe4, 0x1d, 0x45, 0x35, 0xf9, ], - [ 0x87, 0x57, 0x75, 0x19, 0x04, 0x8f, 0x53, 0xa9, ], - [ 0x10, 0xa5, 0x6c, 0xf5, 0xdf, 0xcd, 0x9a, 0xdb, ], - [ 0xeb, 0x75, 0x09, 0x5c, 0xcd, 0x98, 0x6c, 0xd0, ], - [ 0x51, 0xa9, 0xcb, 0x9e, 0xcb, 0xa3, 0x12, 0xe6, ], - [ 0x96, 0xaf, 0xad, 0xfc, 0x2c, 0xe6, 0x66, 0xc7, ], - [ 0x72, 0xfe, 0x52, 0x97, 0x5a, 0x43, 0x64, 0xee, ], - [ 0x5a, 0x16, 0x45, 0xb2, 0x76, 0xd5, 0x92, 0xa1, ], - [ 0xb2, 0x74, 0xcb, 0x8e, 0xbf, 0x87, 0x87, 0x0a, ], - [ 0x6f, 0x9b, 0xb4, 0x20, 0x3d, 0xe7, 0xb3, 0x81, ], - [ 0xea, 0xec, 0xb2, 0xa3, 0x0b, 0x22, 0xa8, 0x7f, ], - [ 0x99, 0x24, 0xa4, 0x3c, 0xc1, 0x31, 0x57, 0x24, ], - [ 0xbd, 0x83, 0x8d, 0x3a, 0xaf, 0xbf, 0x8d, 0xb7, ], - [ 0x0b, 0x1a, 0x2a, 0x32, 0x65, 0xd5, 0x1a, 0xea, ], - [ 0x13, 0x50, 0x79, 0xa3, 0x23, 0x1c, 0xe6, 0x60, ], - [ 0x93, 0x2b, 0x28, 0x46, 0xe4, 0xd7, 0x06, 0x66, ], - [ 0xe1, 0x91, 0x5f, 0x5c, 0xb1, 0xec, 0xa4, 0x6c, ], - [ 0xf3, 0x25, 0x96, 0x5c, 0xa1, 0x6d, 0x62, 0x9f, ], - [ 0x57, 0x5f, 0xf2, 0x8e, 0x60, 0x38, 0x1b, 0xe5, ], - [ 0x72, 0x45, 0x06, 0xeb, 0x4c, 0x32, 0x8a, 0x95, ] + let vecs: [[u8; 8]; 64] = [ + [0x31, 0x0e, 0x0e, 0xdd, 0x47, 0xdb, 0x6f, 0x72], + [0xfd, 0x67, 0xdc, 0x93, 0xc5, 0x39, 0xf8, 0x74], + [0x5a, 0x4f, 0xa9, 0xd9, 0x09, 0x80, 0x6c, 0x0d], + [0x2d, 0x7e, 0xfb, 0xd7, 0x96, 0x66, 0x67, 0x85], + [0xb7, 0x87, 0x71, 0x27, 0xe0, 0x94, 0x27, 0xcf], + [0x8d, 0xa6, 0x99, 0xcd, 0x64, 0x55, 0x76, 0x18], + [0xce, 0xe3, 0xfe, 0x58, 0x6e, 0x46, 0xc9, 0xcb], + [0x37, 0xd1, 0x01, 0x8b, 0xf5, 0x00, 0x02, 0xab], + [0x62, 0x24, 0x93, 0x9a, 0x79, 0xf5, 0xf5, 0x93], + [0xb0, 0xe4, 0xa9, 0x0b, 0xdf, 0x82, 0x00, 0x9e], + [0xf3, 0xb9, 0xdd, 0x94, 0xc5, 0xbb, 0x5d, 0x7a], + [0xa7, 0xad, 0x6b, 0x22, 0x46, 0x2f, 0xb3, 0xf4], + [0xfb, 0xe5, 0x0e, 0x86, 0xbc, 0x8f, 0x1e, 0x75], + [0x90, 0x3d, 0x84, 0xc0, 0x27, 0x56, 0xea, 0x14], + [0xee, 0xf2, 0x7a, 0x8e, 0x90, 0xca, 0x23, 0xf7], + [0xe5, 0x45, 0xbe, 0x49, 0x61, 0xca, 0x29, 0xa1], + [0xdb, 0x9b, 0xc2, 0x57, 0x7f, 0xcc, 0x2a, 0x3f], + [0x94, 0x47, 0xbe, 0x2c, 0xf5, 0xe9, 0x9a, 0x69], + [0x9c, 0xd3, 0x8d, 0x96, 0xf0, 0xb3, 0xc1, 0x4b], + [0xbd, 0x61, 0x79, 0xa7, 0x1d, 0xc9, 0x6d, 0xbb], + [0x98, 0xee, 0xa2, 0x1a, 0xf2, 0x5c, 0xd6, 0xbe], + [0xc7, 0x67, 0x3b, 0x2e, 0xb0, 0xcb, 0xf2, 0xd0], + [0x88, 0x3e, 0xa3, 0xe3, 0x95, 0x67, 0x53, 0x93], + [0xc8, 0xce, 0x5c, 0xcd, 0x8c, 0x03, 0x0c, 0xa8], + [0x94, 0xaf, 0x49, 0xf6, 0xc6, 0x50, 0xad, 0xb8], + [0xea, 0xb8, 0x85, 0x8a, 0xde, 0x92, 0xe1, 0xbc], + [0xf3, 0x15, 0xbb, 0x5b, 0xb8, 0x35, 0xd8, 0x17], + [0xad, 0xcf, 0x6b, 0x07, 0x63, 0x61, 0x2e, 0x2f], + [0xa5, 0xc9, 0x1d, 0xa7, 0xac, 0xaa, 0x4d, 0xde], + [0x71, 0x65, 0x95, 0x87, 0x66, 0x50, 0xa2, 0xa6], + [0x28, 0xef, 0x49, 0x5c, 0x53, 0xa3, 0x87, 0xad], + [0x42, 0xc3, 0x41, 0xd8, 0xfa, 0x92, 0xd8, 0x32], + [0xce, 0x7c, 0xf2, 0x72, 0x2f, 0x51, 0x27, 0x71], + [0xe3, 0x78, 0x59, 0xf9, 0x46, 0x23, 0xf3, 0xa7], + [0x38, 0x12, 0x05, 0xbb, 0x1a, 0xb0, 0xe0, 0x12], + [0xae, 0x97, 0xa1, 0x0f, 0xd4, 0x34, 0xe0, 0x15], + [0xb4, 0xa3, 0x15, 0x08, 0xbe, 0xff, 0x4d, 0x31], + [0x81, 0x39, 0x62, 0x29, 0xf0, 0x90, 0x79, 0x02], + [0x4d, 0x0c, 0xf4, 0x9e, 0xe5, 0xd4, 0xdc, 0xca], + [0x5c, 0x73, 0x33, 0x6a, 0x76, 0xd8, 0xbf, 0x9a], + [0xd0, 0xa7, 0x04, 0x53, 0x6b, 0xa9, 0x3e, 0x0e], + [0x92, 0x59, 0x58, 0xfc, 0xd6, 0x42, 0x0c, 0xad], + [0xa9, 0x15, 0xc2, 0x9b, 0xc8, 0x06, 0x73, 0x18], + [0x95, 0x2b, 0x79, 0xf3, 0xbc, 0x0a, 0xa6, 0xd4], + [0xf2, 0x1d, 0xf2, 0xe4, 0x1d, 0x45, 0x35, 0xf9], + [0x87, 0x57, 0x75, 0x19, 0x04, 0x8f, 0x53, 0xa9], + [0x10, 0xa5, 0x6c, 0xf5, 0xdf, 0xcd, 0x9a, 0xdb], + [0xeb, 0x75, 0x09, 0x5c, 0xcd, 0x98, 0x6c, 0xd0], + [0x51, 0xa9, 0xcb, 0x9e, 0xcb, 0xa3, 0x12, 0xe6], + [0x96, 0xaf, 0xad, 0xfc, 0x2c, 0xe6, 0x66, 0xc7], + [0x72, 0xfe, 0x52, 0x97, 0x5a, 0x43, 0x64, 0xee], + [0x5a, 0x16, 0x45, 0xb2, 0x76, 0xd5, 0x92, 0xa1], + [0xb2, 0x74, 0xcb, 0x8e, 0xbf, 0x87, 0x87, 0x0a], + [0x6f, 0x9b, 0xb4, 0x20, 0x3d, 0xe7, 0xb3, 0x81], + [0xea, 0xec, 0xb2, 0xa3, 0x0b, 0x22, 0xa8, 0x7f], + [0x99, 0x24, 0xa4, 0x3c, 0xc1, 0x31, 0x57, 0x24], + [0xbd, 0x83, 0x8d, 0x3a, 0xaf, 0xbf, 0x8d, 0xb7], + [0x0b, 0x1a, 0x2a, 0x32, 0x65, 0xd5, 0x1a, 0xea], + [0x13, 0x50, 0x79, 0xa3, 0x23, 0x1c, 0xe6, 0x60], + [0x93, 0x2b, 0x28, 0x46, 0xe4, 0xd7, 0x06, 0x66], + [0xe1, 0x91, 0x5f, 0x5c, 0xb1, 0xec, 0xa4, 0x6c], + [0xf3, 0x25, 0x96, 0x5c, 0xa1, 0x6d, 0x62, 0x9f], + [0x57, 0x5f, 0xf2, 0x8e, 0x60, 0x38, 0x1b, 0xe5], + [0x72, 0x45, 0x06, 0xeb, 0x4c, 0x32, 0x8a, 0x95], ]; let k0 = 0x_07_06_05_04_03_02_01_00; @@ -320,8 +320,7 @@ fn test_write_short_works() { h1.write_u8(0x01u8); let mut h2 = SipHasher::new(); h2.write(unsafe { - slice::from_raw_parts(&test_usize as *const _ as *const u8, - mem::size_of::()) + slice::from_raw_parts(&test_usize as *const _ as *const u8, mem::size_of::()) }); h2.write(b"bytes"); h2.write(b"string"); diff --git a/src/libcore/tests/intrinsics.rs b/src/libcore/tests/intrinsics.rs index 7544c13dee4bf..fed7c4a5bf399 100644 --- a/src/libcore/tests/intrinsics.rs +++ b/src/libcore/tests/intrinsics.rs @@ -2,7 +2,8 @@ use core::any::TypeId; #[test] fn test_typeid_sized_types() { - struct X; struct Y(u32); + struct X; + struct Y(u32); assert_eq!(TypeId::of::(), TypeId::of::()); assert_eq!(TypeId::of::(), TypeId::of::()); @@ -12,7 +13,8 @@ fn test_typeid_sized_types() { #[test] fn test_typeid_unsized_types() { trait Z {} - struct X(str); struct Y(dyn Z + 'static); + struct X(str); + struct Y(dyn Z + 'static); assert_eq!(TypeId::of::(), TypeId::of::()); assert_eq!(TypeId::of::(), TypeId::of::()); diff --git a/src/libcore/tests/manually_drop.rs b/src/libcore/tests/manually_drop.rs index 49a1c187ea6cd..77a338daf7dcb 100644 --- a/src/libcore/tests/manually_drop.rs +++ b/src/libcore/tests/manually_drop.rs @@ -13,7 +13,7 @@ fn smoke() { drop(x); // also test unsizing - let x : Box> = + let x: Box> = Box::new(ManuallyDrop::new([TypeWithDrop, TypeWithDrop])); drop(x); } diff --git a/src/libcore/tests/mem.rs b/src/libcore/tests/mem.rs index f5b241959fdd2..59588d97787b7 100644 --- a/src/libcore/tests/mem.rs +++ b/src/libcore/tests/mem.rs @@ -96,7 +96,9 @@ fn test_transmute_copy() { #[test] fn test_transmute() { - trait Foo { fn dummy(&self) { } } + trait Foo { + fn dummy(&self) {} + } impl Foo for isize {} let a = box 100isize as Box; @@ -116,13 +118,13 @@ fn test_transmute() { fn test_discriminant_send_sync() { enum Regular { A, - B(i32) + B(i32), } enum NotSendSync { - A(*const i32) + A(*const i32), } - fn is_send_sync() { } + fn is_send_sync() {} is_send_sync::>(); is_send_sync::>(); diff --git a/src/libcore/tests/nonzero.rs b/src/libcore/tests/nonzero.rs index 77e484601bc22..6c5d19845e406 100644 --- a/src/libcore/tests/nonzero.rs +++ b/src/libcore/tests/nonzero.rs @@ -4,9 +4,7 @@ use std::mem::size_of; #[test] fn test_create_nonzero_instance() { - let _a = unsafe { - NonZeroU32::new_unchecked(21) - }; + let _a = unsafe { NonZeroU32::new_unchecked(21) }; } #[test] @@ -17,17 +15,15 @@ fn test_size_nonzero_in_option() { #[test] fn test_match_on_nonzero_option() { - let a = Some(unsafe { - NonZeroU32::new_unchecked(42) - }); + let a = Some(unsafe { NonZeroU32::new_unchecked(42) }); match a { Some(val) => assert_eq!(val.get(), 42), - None => panic!("unexpected None while matching on Some(NonZeroU32(_))") + None => panic!("unexpected None while matching on Some(NonZeroU32(_))"), } match unsafe { Some(NonZeroU32::new_unchecked(43)) } { Some(val) => assert_eq!(val.get(), 43), - None => panic!("unexpected None while matching on Some(NonZeroU32(_))") + None => panic!("unexpected None while matching on Some(NonZeroU32(_))"), } } @@ -45,7 +41,7 @@ fn test_match_option_vec() { let a = Some(vec![1, 2, 3, 4]); match a { Some(v) => assert_eq!(v, [1, 2, 3, 4]), - None => panic!("unexpected None while matching on Some(vec![1, 2, 3, 4])") + None => panic!("unexpected None while matching on Some(vec![1, 2, 3, 4])"), } } @@ -56,7 +52,7 @@ fn test_match_option_rc() { let five = Rc::new(5); match Some(five) { Some(r) => assert_eq!(*r, 5), - None => panic!("unexpected None while matching on Some(Rc::new(5))") + None => panic!("unexpected None while matching on Some(Rc::new(5))"), } } @@ -67,7 +63,7 @@ fn test_match_option_arc() { let five = Arc::new(5); match Some(five) { Some(a) => assert_eq!(*a, 5), - None => panic!("unexpected None while matching on Some(Arc::new(5))") + None => panic!("unexpected None while matching on Some(Arc::new(5))"), } } @@ -85,7 +81,7 @@ fn test_match_option_string() { let five = "Five".to_string(); match Some(five) { Some(s) => assert_eq!(s, "Five"), - None => panic!("unexpected None while matching on Some(String { ... })") + None => panic!("unexpected None while matching on Some(String { ... })"), } } @@ -100,7 +96,9 @@ mod atom { } macro_rules! atom { - ("foo") => { atom::FOO_ATOM } + ("foo") => { + atom::FOO_ATOM + }; } #[test] @@ -108,7 +106,7 @@ fn test_match_nonzero_const_pattern() { match atom!("foo") { // Using as a pattern is supported by the compiler: atom!("foo") => {} - _ => panic!("Expected the const item as a pattern to match.") + _ => panic!("Expected the const item as a pattern to match."), } } @@ -129,10 +127,7 @@ fn test_from_signed_nonzero() { #[test] fn test_from_str() { assert_eq!("123".parse::(), Ok(NonZeroU8::new(123).unwrap())); - assert_eq!( - "0".parse::().err().map(|e| e.kind().clone()), - Some(IntErrorKind::Zero) - ); + assert_eq!("0".parse::().err().map(|e| e.kind().clone()), Some(IntErrorKind::Zero)); assert_eq!( "-1".parse::().err().map(|e| e.kind().clone()), Some(IntErrorKind::InvalidDigit) diff --git a/src/libcore/tests/num/bignum.rs b/src/libcore/tests/num/bignum.rs index 50a3ec046ad13..1457064cc8d57 100644 --- a/src/libcore/tests/num/bignum.rs +++ b/src/libcore/tests/num/bignum.rs @@ -70,7 +70,7 @@ fn test_sub_underflow_2() { fn test_mul_small() { assert_eq!(*Big::from_small(7).mul_small(5), Big::from_small(35)); assert_eq!(*Big::from_small(0xff).mul_small(0xff), Big::from_u64(0xfe01)); - assert_eq!(*Big::from_u64(0xffffff/13).mul_small(13), Big::from_u64(0xffffff)); + assert_eq!(*Big::from_u64(0xffffff / 13).mul_small(13), Big::from_u64(0xffffff)); } #[test] @@ -134,7 +134,7 @@ fn test_mul_digits() { assert_eq!(*Big::from_u64(0x123).mul_digits(&[0x56, 0x4]), Big::from_u64(0x4edc2)); assert_eq!(*Big::from_u64(0x12345).mul_digits(&[0x67]), Big::from_u64(0x7530c3)); assert_eq!(*Big::from_small(0x12).mul_digits(&[0x67, 0x45, 0x3]), Big::from_u64(0x3ae13e)); - assert_eq!(*Big::from_u64(0xffffff/13).mul_digits(&[13]), Big::from_u64(0xffffff)); + assert_eq!(*Big::from_u64(0xffffff / 13).mul_digits(&[13]), Big::from_u64(0xffffff)); assert_eq!(*Big::from_small(13).mul_digits(&[0x3b, 0xb1, 0x13]), Big::from_u64(0xffffff)); } @@ -156,10 +156,14 @@ fn test_div_rem_small() { assert_eq!(as_val(Big::from_small(0xff).div_rem_small(15)), (Big::from_small(17), 0)); assert_eq!(as_val(Big::from_small(0xff).div_rem_small(16)), (Big::from_small(15), 15)); assert_eq!(as_val(Big::from_small(3).div_rem_small(40)), (Big::from_small(0), 3)); - assert_eq!(as_val(Big::from_u64(0xffffff).div_rem_small(123)), - (Big::from_u64(0xffffff / 123), (0xffffffu64 % 123) as u8)); - assert_eq!(as_val(Big::from_u64(0x10000).div_rem_small(123)), - (Big::from_u64(0x10000 / 123), (0x10000u64 % 123) as u8)); + assert_eq!( + as_val(Big::from_u64(0xffffff).div_rem_small(123)), + (Big::from_u64(0xffffff / 123), (0xffffffu64 % 123) as u8) + ); + assert_eq!( + as_val(Big::from_u64(0x10000).div_rem_small(123)), + (Big::from_u64(0x10000 / 123), (0x10000u64 % 123) as u8) + ); } #[test] diff --git a/src/libcore/tests/num/dec2flt/mod.rs b/src/libcore/tests/num/dec2flt/mod.rs index 46eacb4200acc..4b772e12b6ccc 100644 --- a/src/libcore/tests/num/dec2flt/mod.rs +++ b/src/libcore/tests/num/dec2flt/mod.rs @@ -1,6 +1,6 @@ #![allow(overflowing_literals)] -use std::{i64, f32, f64}; +use std::{f32, f64, i64}; mod parse; mod rawfp; @@ -9,7 +9,7 @@ mod rawfp; // to be correct) and see if those strings are parsed back to the value of the literal. // Requires a *polymorphic literal*, i.e., one that can serve as f64 as well as f32. macro_rules! test_literal { - ($x: expr) => ({ + ($x: expr) => {{ let x32: f32 = $x; let x64: f64 = $x; let inputs = &[stringify!($x).into(), format!("{:?}", x64), format!("{:e}", x64)]; @@ -20,7 +20,7 @@ macro_rules! test_literal { assert_eq!(neg_input.parse(), Ok(-x64)); assert_eq!(neg_input.parse(), Ok(-x32)); } - }) + }}; } #[cfg_attr(all(target_arch = "wasm32", target_os = "emscripten"), ignore)] // issue 42630 diff --git a/src/libcore/tests/num/dec2flt/parse.rs b/src/libcore/tests/num/dec2flt/parse.rs index 1eac484119170..bb7e51d30026a 100644 --- a/src/libcore/tests/num/dec2flt/parse.rs +++ b/src/libcore/tests/num/dec2flt/parse.rs @@ -1,5 +1,5 @@ -use core::num::dec2flt::parse::{Decimal, parse_decimal}; -use core::num::dec2flt::parse::ParseResult::{Valid, Invalid}; +use core::num::dec2flt::parse::ParseResult::{Invalid, Valid}; +use core::num::dec2flt::parse::{parse_decimal, Decimal}; #[test] fn missing_pieces() { diff --git a/src/libcore/tests/num/dec2flt/rawfp.rs b/src/libcore/tests/num/dec2flt/rawfp.rs index 747c1bfa3f9c2..665fb6b9efb8c 100644 --- a/src/libcore/tests/num/dec2flt/rawfp.rs +++ b/src/libcore/tests/num/dec2flt/rawfp.rs @@ -1,8 +1,8 @@ +use core::num::dec2flt::rawfp::RawFloat; +use core::num::dec2flt::rawfp::{fp_to_float, next_float, prev_float, round_normal}; +use core::num::diy_float::Fp; use std::f32; use std::f64; -use core::num::diy_float::Fp; -use core::num::dec2flt::rawfp::{fp_to_float, prev_float, next_float, round_normal}; -use core::num::dec2flt::rawfp::RawFloat; fn integer_decode(f: f64) -> (u64, i16, i8) { RawFloat::integer_decode(f) @@ -53,16 +53,23 @@ fn integers_to_f64() { assert_eq!(fp_to_float::(Fp { f: 4, e: -3 }), 0.5); } -const SOME_FLOATS: [f64; 9] = - [0.1f64, 33.568, 42.1e-5, 777.0e9, 1.1111, 0.347997, - 9843579834.35892, 12456.0e-150, 54389573.0e-150]; - +const SOME_FLOATS: [f64; 9] = [ + 0.1f64, + 33.568, + 42.1e-5, + 777.0e9, + 1.1111, + 0.347997, + 9843579834.35892, + 12456.0e-150, + 54389573.0e-150, +]; #[test] fn human_f64_roundtrip() { for &x in &SOME_FLOATS { let (f, e, _) = integer_decode(x); - let fp = Fp { f: f, e: e}; + let fp = Fp { f: f, e: e }; assert_eq!(fp_to_float::(fp), x); } } diff --git a/src/libcore/tests/num/flt2dec/estimator.rs b/src/libcore/tests/num/flt2dec/estimator.rs index c51451708f3ce..8ee06d895cae3 100644 --- a/src/libcore/tests/num/flt2dec/estimator.rs +++ b/src/libcore/tests/num/flt2dec/estimator.rs @@ -3,14 +3,24 @@ use core::num::flt2dec::estimator::*; #[test] fn test_estimate_scaling_factor() { macro_rules! assert_almost_eq { - ($actual:expr, $expected:expr) => ({ + ($actual:expr, $expected:expr) => {{ let actual = $actual; let expected = $expected; - println!("{} - {} = {} - {} = {}", stringify!($expected), stringify!($actual), - expected, actual, expected - actual); - assert!(expected == actual || expected == actual + 1, - "expected {}, actual {}", expected, actual); - }) + println!( + "{} - {} = {} - {} = {}", + stringify!($expected), + stringify!($actual), + expected, + actual, + expected - actual + ); + assert!( + expected == actual || expected == actual + 1, + "expected {}, actual {}", + expected, + actual + ); + }}; } assert_almost_eq!(estimate_scaling_factor(1, 0), 0); diff --git a/src/libcore/tests/num/flt2dec/random.rs b/src/libcore/tests/num/flt2dec/random.rs index d9543793397bf..ecdfc4b30a59f 100644 --- a/src/libcore/tests/num/flt2dec/random.rs +++ b/src/libcore/tests/num/flt2dec/random.rs @@ -3,27 +3,28 @@ use std::i16; use std::str; -use core::num::flt2dec::MAX_SIG_DIGITS; use core::num::flt2dec::strategy::grisu::format_exact_opt; use core::num::flt2dec::strategy::grisu::format_shortest_opt; -use core::num::flt2dec::{decode, DecodableFloat, FullDecoded, Decoded}; +use core::num::flt2dec::MAX_SIG_DIGITS; +use core::num::flt2dec::{decode, DecodableFloat, Decoded, FullDecoded}; -use rand::SeedableRng; -use rand::rngs::StdRng; use rand::distributions::{Distribution, Uniform}; +use rand::rngs::StdRng; +use rand::SeedableRng; pub fn decode_finite(v: T) -> Decoded { match decode(v).1 { FullDecoded::Finite(decoded) => decoded, - full_decoded => panic!("expected finite, got {:?} instead", full_decoded) + full_decoded => panic!("expected finite, got {:?} instead", full_decoded), } } - fn iterate(func: &str, k: usize, n: usize, mut f: F, mut g: G, mut v: V) -> (usize, usize) - where F: FnMut(&Decoded, &mut [u8]) -> Option<(usize, i16)>, - G: FnMut(&Decoded, &mut [u8]) -> (usize, i16), - V: FnMut(usize) -> Decoded { +where + F: FnMut(&Decoded, &mut [u8]) -> Option<(usize, i16)>, + G: FnMut(&Decoded, &mut [u8]) -> (usize, i16), + V: FnMut(usize) -> Decoded, +{ assert!(k <= 1024); let mut npassed = 0; // f(x) = Some(g(x)) @@ -31,8 +32,14 @@ fn iterate(func: &str, k: usize, n: usize, mut f: F, mut g: G, mut v: V for i in 0..n { if (i & 0xfffff) == 0 { - println!("in progress, {:x}/{:x} (ignored={} passed={} failed={})", - i, n, nignored, npassed, i - nignored - npassed); + println!( + "in progress, {:x}/{:x} (ignored={} passed={} failed={})", + i, + n, + nignored, + npassed, + i - nignored - npassed + ); } let decoded = v(i); @@ -43,27 +50,47 @@ fn iterate(func: &str, k: usize, n: usize, mut f: F, mut g: G, mut v: V if e1 == e2 && &buf1[..len1] == &buf2[..len2] { npassed += 1; } else { - println!("equivalence test failed, {:x}/{:x}: {:?} f(i)={}e{} g(i)={}e{}", - i, n, decoded, str::from_utf8(&buf1[..len1]).unwrap(), e1, - str::from_utf8(&buf2[..len2]).unwrap(), e2); + println!( + "equivalence test failed, {:x}/{:x}: {:?} f(i)={}e{} g(i)={}e{}", + i, + n, + decoded, + str::from_utf8(&buf1[..len1]).unwrap(), + e1, + str::from_utf8(&buf2[..len2]).unwrap(), + e2 + ); } } else { nignored += 1; } } - println!("{}({}): done, ignored={} passed={} failed={}", - func, k, nignored, npassed, n - nignored - npassed); - assert!(nignored + npassed == n, - "{}({}): {} out of {} values returns an incorrect value!", - func, k, n - nignored - npassed, n); + println!( + "{}({}): done, ignored={} passed={} failed={}", + func, + k, + nignored, + npassed, + n - nignored - npassed + ); + assert!( + nignored + npassed == n, + "{}({}): {} out of {} values returns an incorrect value!", + func, + k, + n - nignored - npassed, + n + ); (npassed, nignored) } pub fn f32_random_equivalence_test(f: F, g: G, k: usize, n: usize) - where F: FnMut(&Decoded, &mut [u8]) -> Option<(usize, i16)>, - G: FnMut(&Decoded, &mut [u8]) -> (usize, i16) { +where + F: FnMut(&Decoded, &mut [u8]) -> Option<(usize, i16)>, + G: FnMut(&Decoded, &mut [u8]) -> (usize, i16), +{ if cfg!(target_os = "emscripten") { - return // using rng pulls in i128 support, which doesn't work + return; // using rng pulls in i128 support, which doesn't work } let mut rng = StdRng::from_entropy(); let f32_range = Uniform::new(0x0000_0001u32, 0x7f80_0000); @@ -74,10 +101,12 @@ pub fn f32_random_equivalence_test(f: F, g: G, k: usize, n: usize) } pub fn f64_random_equivalence_test(f: F, g: G, k: usize, n: usize) - where F: FnMut(&Decoded, &mut [u8]) -> Option<(usize, i16)>, - G: FnMut(&Decoded, &mut [u8]) -> (usize, i16) { +where + F: FnMut(&Decoded, &mut [u8]) -> Option<(usize, i16)>, + G: FnMut(&Decoded, &mut [u8]) -> (usize, i16), +{ if cfg!(target_os = "emscripten") { - return // using rng pulls in i128 support, which doesn't work + return; // using rng pulls in i128 support, which doesn't work } let mut rng = StdRng::from_entropy(); let f64_range = Uniform::new(0x0000_0000_0000_0001u64, 0x7ff0_0000_0000_0000); @@ -88,8 +117,10 @@ pub fn f64_random_equivalence_test(f: F, g: G, k: usize, n: usize) } pub fn f32_exhaustive_equivalence_test(f: F, g: G, k: usize) - where F: FnMut(&Decoded, &mut [u8]) -> Option<(usize, i16)>, - G: FnMut(&Decoded, &mut [u8]) -> (usize, i16) { +where + F: FnMut(&Decoded, &mut [u8]) -> Option<(usize, i16)>, + G: FnMut(&Decoded, &mut [u8]) -> (usize, i16), +{ // we have only 2^23 * (2^8 - 1) - 1 = 2,139,095,039 positive finite f32 values, // so why not simply testing all of them? // @@ -97,12 +128,11 @@ pub fn f32_exhaustive_equivalence_test(f: F, g: G, k: usize) // but with `-C opt-level=3 -C lto` this only takes about an hour or so. // iterate from 0x0000_0001 to 0x7f7f_ffff, i.e., all finite ranges - let (npassed, nignored) = iterate("f32_exhaustive_equivalence_test", - k, 0x7f7f_ffff, f, g, |i: usize| { - - let x = f32::from_bits(i as u32 + 1); - decode_finite(x) - }); + let (npassed, nignored) = + iterate("f32_exhaustive_equivalence_test", k, 0x7f7f_ffff, f, g, |i: usize| { + let x = f32::from_bits(i as u32 + 1); + decode_finite(x) + }); assert_eq!((npassed, nignored), (2121451881, 17643158)); } @@ -118,7 +148,8 @@ fn shortest_random_equivalence_test() { f32_random_equivalence_test(format_shortest_opt, fallback, MAX_SIG_DIGITS, N); } -#[test] #[ignore] // it is too expensive +#[test] +#[ignore] // it is too expensive fn shortest_f32_exhaustive_equivalence_test() { // it is hard to directly test the optimality of the output, but we can at least test if // two different algorithms agree to each other. @@ -131,13 +162,13 @@ fn shortest_f32_exhaustive_equivalence_test() { f32_exhaustive_equivalence_test(format_shortest_opt, fallback, MAX_SIG_DIGITS); } -#[test] #[ignore] // it is too expensive +#[test] +#[ignore] // it is too expensive fn shortest_f64_hard_random_equivalence_test() { // this again probably has to use appropriate rustc flags. use core::num::flt2dec::strategy::dragon::format_shortest as fallback; - f64_random_equivalence_test(format_shortest_opt, fallback, - MAX_SIG_DIGITS, 100_000_000); + f64_random_equivalence_test(format_shortest_opt, fallback, MAX_SIG_DIGITS, 100_000_000); } #[test] @@ -149,8 +180,12 @@ fn exact_f32_random_equivalence_test() { const N: usize = 3; for k in 1..21 { - f32_random_equivalence_test(|d, buf| format_exact_opt(d, buf, i16::MIN), - |d, buf| fallback(d, buf, i16::MIN), k, N); + f32_random_equivalence_test( + |d, buf| format_exact_opt(d, buf, i16::MIN), + |d, buf| fallback(d, buf, i16::MIN), + k, + N, + ); } } @@ -163,7 +198,11 @@ fn exact_f64_random_equivalence_test() { const N: usize = 3; for k in 1..21 { - f64_random_equivalence_test(|d, buf| format_exact_opt(d, buf, i16::MIN), - |d, buf| fallback(d, buf, i16::MIN), k, N); + f64_random_equivalence_test( + |d, buf| format_exact_opt(d, buf, i16::MIN), + |d, buf| fallback(d, buf, i16::MIN), + k, + N, + ); } } diff --git a/src/libcore/tests/num/flt2dec/strategy/grisu.rs b/src/libcore/tests/num/flt2dec/strategy/grisu.rs index f8bdddfe2e410..1339664646321 100644 --- a/src/libcore/tests/num/flt2dec/strategy/grisu.rs +++ b/src/libcore/tests/num/flt2dec/strategy/grisu.rs @@ -6,12 +6,18 @@ fn test_cached_power() { assert_eq!(CACHED_POW10.first().unwrap().1, CACHED_POW10_FIRST_E); assert_eq!(CACHED_POW10.last().unwrap().1, CACHED_POW10_LAST_E); - for e in -1137..961 { // full range for f64 + for e in -1137..961 { + // full range for f64 let low = ALPHA - e - 64; let high = GAMMA - e - 64; let (_k, cached) = cached_power(low, high); - assert!(low <= cached.e && cached.e <= high, - "cached_power({}, {}) = {:?} is incorrect", low, high, cached); + assert!( + low <= cached.e && cached.e <= high, + "cached_power({}, {}) = {:?} is incorrect", + low, + high, + cached + ); } } @@ -26,7 +32,6 @@ fn test_max_pow10_no_more_than() { } } - #[cfg_attr(all(target_arch = "wasm32", target_os = "emscripten"), ignore)] // issue 42630 #[test] fn shortest_sanity_test() { diff --git a/src/libcore/tests/num/int_macros.rs b/src/libcore/tests/num/int_macros.rs index 0475aeb96ab53..4a44b5f24b910 100644 --- a/src/libcore/tests/num/int_macros.rs +++ b/src/libcore/tests/num/int_macros.rs @@ -1,240 +1,241 @@ -macro_rules! int_module { ($T:ident, $T_i:ident) => ( -#[cfg(test)] -mod tests { - use core::$T_i::*; - use core::isize; - use core::ops::{Shl, Shr, Not, BitXor, BitAnd, BitOr}; - use core::mem; - - use crate::num; - - #[test] - fn test_overflows() { - assert!(MAX > 0); - assert!(MIN <= 0); - assert_eq!(MIN + MAX + 1, 0); - } - - #[test] - fn test_num() { - num::test_num(10 as $T, 2 as $T); - } - - #[test] - fn test_rem_euclid() { - assert_eq!((-1 as $T).rem_euclid(MIN), MAX); - } - - #[test] - pub fn test_abs() { - assert_eq!((1 as $T).abs(), 1 as $T); - assert_eq!((0 as $T).abs(), 0 as $T); - assert_eq!((-1 as $T).abs(), 1 as $T); - } - - #[test] - fn test_signum() { - assert_eq!((1 as $T).signum(), 1 as $T); - assert_eq!((0 as $T).signum(), 0 as $T); - assert_eq!((-0 as $T).signum(), 0 as $T); - assert_eq!((-1 as $T).signum(), -1 as $T); - } - - #[test] - fn test_is_positive() { - assert!((1 as $T).is_positive()); - assert!(!(0 as $T).is_positive()); - assert!(!(-0 as $T).is_positive()); - assert!(!(-1 as $T).is_positive()); - } - - #[test] - fn test_is_negative() { - assert!(!(1 as $T).is_negative()); - assert!(!(0 as $T).is_negative()); - assert!(!(-0 as $T).is_negative()); - assert!((-1 as $T).is_negative()); - } - - #[test] - fn test_bitwise_operators() { - assert_eq!(0b1110 as $T, (0b1100 as $T).bitor(0b1010 as $T)); - assert_eq!(0b1000 as $T, (0b1100 as $T).bitand(0b1010 as $T)); - assert_eq!(0b0110 as $T, (0b1100 as $T).bitxor(0b1010 as $T)); - assert_eq!(0b1110 as $T, (0b0111 as $T).shl(1)); - assert_eq!(0b0111 as $T, (0b1110 as $T).shr(1)); - assert_eq!(-(0b11 as $T) - (1 as $T), (0b11 as $T).not()); - } - - const A: $T = 0b0101100; - const B: $T = 0b0100001; - const C: $T = 0b1111001; - - const _0: $T = 0; - const _1: $T = !0; - - #[test] - fn test_count_ones() { - assert_eq!(A.count_ones(), 3); - assert_eq!(B.count_ones(), 2); - assert_eq!(C.count_ones(), 5); - } - - #[test] - fn test_count_zeros() { - let bits = mem::size_of::<$T>() * 8; - assert_eq!(A.count_zeros(), bits as u32 - 3); - assert_eq!(B.count_zeros(), bits as u32 - 2); - assert_eq!(C.count_zeros(), bits as u32 - 5); - } - - #[test] - fn test_rotate() { - assert_eq!(A.rotate_left(6).rotate_right(2).rotate_right(4), A); - assert_eq!(B.rotate_left(3).rotate_left(2).rotate_right(5), B); - assert_eq!(C.rotate_left(6).rotate_right(2).rotate_right(4), C); - - // Rotating these should make no difference - // - // We test using 124 bits because to ensure that overlong bit shifts do - // not cause undefined behaviour. See #10183. - assert_eq!(_0.rotate_left(124), _0); - assert_eq!(_1.rotate_left(124), _1); - assert_eq!(_0.rotate_right(124), _0); - assert_eq!(_1.rotate_right(124), _1); - - // Rotating by 0 should have no effect - assert_eq!(A.rotate_left(0), A); - assert_eq!(B.rotate_left(0), B); - assert_eq!(C.rotate_left(0), C); - // Rotating by a multiple of word size should also have no effect - assert_eq!(A.rotate_left(64), A); - assert_eq!(B.rotate_left(64), B); - assert_eq!(C.rotate_left(64), C); - } - - #[test] - fn test_swap_bytes() { - assert_eq!(A.swap_bytes().swap_bytes(), A); - assert_eq!(B.swap_bytes().swap_bytes(), B); - assert_eq!(C.swap_bytes().swap_bytes(), C); - - // Swapping these should make no difference - assert_eq!(_0.swap_bytes(), _0); - assert_eq!(_1.swap_bytes(), _1); - } - - #[test] - fn test_le() { - assert_eq!($T::from_le(A.to_le()), A); - assert_eq!($T::from_le(B.to_le()), B); - assert_eq!($T::from_le(C.to_le()), C); - assert_eq!($T::from_le(_0), _0); - assert_eq!($T::from_le(_1), _1); - assert_eq!(_0.to_le(), _0); - assert_eq!(_1.to_le(), _1); - } - - #[test] - fn test_be() { - assert_eq!($T::from_be(A.to_be()), A); - assert_eq!($T::from_be(B.to_be()), B); - assert_eq!($T::from_be(C.to_be()), C); - assert_eq!($T::from_be(_0), _0); - assert_eq!($T::from_be(_1), _1); - assert_eq!(_0.to_be(), _0); - assert_eq!(_1.to_be(), _1); - } - - #[test] - fn test_signed_checked_div() { - assert_eq!((10 as $T).checked_div(2), Some(5)); - assert_eq!((5 as $T).checked_div(0), None); - assert_eq!(isize::MIN.checked_div(-1), None); - } - - #[test] - fn test_saturating_abs() { - assert_eq!((0 as $T).saturating_abs(), 0); - assert_eq!((123 as $T).saturating_abs(), 123); - assert_eq!((-123 as $T).saturating_abs(), 123); - assert_eq!((MAX - 2).saturating_abs(), MAX - 2); - assert_eq!((MAX - 1).saturating_abs(), MAX - 1); - assert_eq!(MAX.saturating_abs(), MAX); - assert_eq!((MIN + 2).saturating_abs(), MAX - 1); - assert_eq!((MIN + 1).saturating_abs(), MAX); - assert_eq!(MIN.saturating_abs(), MAX); - } - - #[test] - fn test_saturating_neg() { - assert_eq!((0 as $T).saturating_neg(), 0); - assert_eq!((123 as $T).saturating_neg(), -123); - assert_eq!((-123 as $T).saturating_neg(), 123); - assert_eq!((MAX - 2).saturating_neg(), MIN + 3); - assert_eq!((MAX - 1).saturating_neg(), MIN + 2); - assert_eq!(MAX.saturating_neg(), MIN + 1); - assert_eq!((MIN + 2).saturating_neg(), MAX - 1); - assert_eq!((MIN + 1).saturating_neg(), MAX); - assert_eq!(MIN.saturating_neg(), MAX); - } - - #[test] - fn test_from_str() { - fn from_str(t: &str) -> Option { - ::std::str::FromStr::from_str(t).ok() +macro_rules! int_module { + ($T:ident, $T_i:ident) => { + #[cfg(test)] + mod tests { + use core::isize; + use core::mem; + use core::ops::{BitAnd, BitOr, BitXor, Not, Shl, Shr}; + use core::$T_i::*; + + use crate::num; + + #[test] + fn test_overflows() { + assert!(MAX > 0); + assert!(MIN <= 0); + assert_eq!(MIN + MAX + 1, 0); + } + + #[test] + fn test_num() { + num::test_num(10 as $T, 2 as $T); + } + + #[test] + fn test_rem_euclid() { + assert_eq!((-1 as $T).rem_euclid(MIN), MAX); + } + + #[test] + pub fn test_abs() { + assert_eq!((1 as $T).abs(), 1 as $T); + assert_eq!((0 as $T).abs(), 0 as $T); + assert_eq!((-1 as $T).abs(), 1 as $T); + } + + #[test] + fn test_signum() { + assert_eq!((1 as $T).signum(), 1 as $T); + assert_eq!((0 as $T).signum(), 0 as $T); + assert_eq!((-0 as $T).signum(), 0 as $T); + assert_eq!((-1 as $T).signum(), -1 as $T); + } + + #[test] + fn test_is_positive() { + assert!((1 as $T).is_positive()); + assert!(!(0 as $T).is_positive()); + assert!(!(-0 as $T).is_positive()); + assert!(!(-1 as $T).is_positive()); + } + + #[test] + fn test_is_negative() { + assert!(!(1 as $T).is_negative()); + assert!(!(0 as $T).is_negative()); + assert!(!(-0 as $T).is_negative()); + assert!((-1 as $T).is_negative()); + } + + #[test] + fn test_bitwise_operators() { + assert_eq!(0b1110 as $T, (0b1100 as $T).bitor(0b1010 as $T)); + assert_eq!(0b1000 as $T, (0b1100 as $T).bitand(0b1010 as $T)); + assert_eq!(0b0110 as $T, (0b1100 as $T).bitxor(0b1010 as $T)); + assert_eq!(0b1110 as $T, (0b0111 as $T).shl(1)); + assert_eq!(0b0111 as $T, (0b1110 as $T).shr(1)); + assert_eq!(-(0b11 as $T) - (1 as $T), (0b11 as $T).not()); + } + + const A: $T = 0b0101100; + const B: $T = 0b0100001; + const C: $T = 0b1111001; + + const _0: $T = 0; + const _1: $T = !0; + + #[test] + fn test_count_ones() { + assert_eq!(A.count_ones(), 3); + assert_eq!(B.count_ones(), 2); + assert_eq!(C.count_ones(), 5); + } + + #[test] + fn test_count_zeros() { + let bits = mem::size_of::<$T>() * 8; + assert_eq!(A.count_zeros(), bits as u32 - 3); + assert_eq!(B.count_zeros(), bits as u32 - 2); + assert_eq!(C.count_zeros(), bits as u32 - 5); + } + + #[test] + fn test_rotate() { + assert_eq!(A.rotate_left(6).rotate_right(2).rotate_right(4), A); + assert_eq!(B.rotate_left(3).rotate_left(2).rotate_right(5), B); + assert_eq!(C.rotate_left(6).rotate_right(2).rotate_right(4), C); + + // Rotating these should make no difference + // + // We test using 124 bits because to ensure that overlong bit shifts do + // not cause undefined behaviour. See #10183. + assert_eq!(_0.rotate_left(124), _0); + assert_eq!(_1.rotate_left(124), _1); + assert_eq!(_0.rotate_right(124), _0); + assert_eq!(_1.rotate_right(124), _1); + + // Rotating by 0 should have no effect + assert_eq!(A.rotate_left(0), A); + assert_eq!(B.rotate_left(0), B); + assert_eq!(C.rotate_left(0), C); + // Rotating by a multiple of word size should also have no effect + assert_eq!(A.rotate_left(64), A); + assert_eq!(B.rotate_left(64), B); + assert_eq!(C.rotate_left(64), C); + } + + #[test] + fn test_swap_bytes() { + assert_eq!(A.swap_bytes().swap_bytes(), A); + assert_eq!(B.swap_bytes().swap_bytes(), B); + assert_eq!(C.swap_bytes().swap_bytes(), C); + + // Swapping these should make no difference + assert_eq!(_0.swap_bytes(), _0); + assert_eq!(_1.swap_bytes(), _1); + } + + #[test] + fn test_le() { + assert_eq!($T::from_le(A.to_le()), A); + assert_eq!($T::from_le(B.to_le()), B); + assert_eq!($T::from_le(C.to_le()), C); + assert_eq!($T::from_le(_0), _0); + assert_eq!($T::from_le(_1), _1); + assert_eq!(_0.to_le(), _0); + assert_eq!(_1.to_le(), _1); + } + + #[test] + fn test_be() { + assert_eq!($T::from_be(A.to_be()), A); + assert_eq!($T::from_be(B.to_be()), B); + assert_eq!($T::from_be(C.to_be()), C); + assert_eq!($T::from_be(_0), _0); + assert_eq!($T::from_be(_1), _1); + assert_eq!(_0.to_be(), _0); + assert_eq!(_1.to_be(), _1); + } + + #[test] + fn test_signed_checked_div() { + assert_eq!((10 as $T).checked_div(2), Some(5)); + assert_eq!((5 as $T).checked_div(0), None); + assert_eq!(isize::MIN.checked_div(-1), None); + } + + #[test] + fn test_saturating_abs() { + assert_eq!((0 as $T).saturating_abs(), 0); + assert_eq!((123 as $T).saturating_abs(), 123); + assert_eq!((-123 as $T).saturating_abs(), 123); + assert_eq!((MAX - 2).saturating_abs(), MAX - 2); + assert_eq!((MAX - 1).saturating_abs(), MAX - 1); + assert_eq!(MAX.saturating_abs(), MAX); + assert_eq!((MIN + 2).saturating_abs(), MAX - 1); + assert_eq!((MIN + 1).saturating_abs(), MAX); + assert_eq!(MIN.saturating_abs(), MAX); + } + + #[test] + fn test_saturating_neg() { + assert_eq!((0 as $T).saturating_neg(), 0); + assert_eq!((123 as $T).saturating_neg(), -123); + assert_eq!((-123 as $T).saturating_neg(), 123); + assert_eq!((MAX - 2).saturating_neg(), MIN + 3); + assert_eq!((MAX - 1).saturating_neg(), MIN + 2); + assert_eq!(MAX.saturating_neg(), MIN + 1); + assert_eq!((MIN + 2).saturating_neg(), MAX - 1); + assert_eq!((MIN + 1).saturating_neg(), MAX); + assert_eq!(MIN.saturating_neg(), MAX); + } + + #[test] + fn test_from_str() { + fn from_str(t: &str) -> Option { + ::std::str::FromStr::from_str(t).ok() + } + assert_eq!(from_str::<$T>("0"), Some(0 as $T)); + assert_eq!(from_str::<$T>("3"), Some(3 as $T)); + assert_eq!(from_str::<$T>("10"), Some(10 as $T)); + assert_eq!(from_str::("123456789"), Some(123456789 as i32)); + assert_eq!(from_str::<$T>("00100"), Some(100 as $T)); + + assert_eq!(from_str::<$T>("-1"), Some(-1 as $T)); + assert_eq!(from_str::<$T>("-3"), Some(-3 as $T)); + assert_eq!(from_str::<$T>("-10"), Some(-10 as $T)); + assert_eq!(from_str::("-123456789"), Some(-123456789 as i32)); + assert_eq!(from_str::<$T>("-00100"), Some(-100 as $T)); + + assert_eq!(from_str::<$T>(""), None); + assert_eq!(from_str::<$T>(" "), None); + assert_eq!(from_str::<$T>("x"), None); + } + + #[test] + fn test_from_str_radix() { + assert_eq!($T::from_str_radix("123", 10), Ok(123 as $T)); + assert_eq!($T::from_str_radix("1001", 2), Ok(9 as $T)); + assert_eq!($T::from_str_radix("123", 8), Ok(83 as $T)); + assert_eq!(i32::from_str_radix("123", 16), Ok(291 as i32)); + assert_eq!(i32::from_str_radix("ffff", 16), Ok(65535 as i32)); + assert_eq!(i32::from_str_radix("FFFF", 16), Ok(65535 as i32)); + assert_eq!($T::from_str_radix("z", 36), Ok(35 as $T)); + assert_eq!($T::from_str_radix("Z", 36), Ok(35 as $T)); + + assert_eq!($T::from_str_radix("-123", 10), Ok(-123 as $T)); + assert_eq!($T::from_str_radix("-1001", 2), Ok(-9 as $T)); + assert_eq!($T::from_str_radix("-123", 8), Ok(-83 as $T)); + assert_eq!(i32::from_str_radix("-123", 16), Ok(-291 as i32)); + assert_eq!(i32::from_str_radix("-ffff", 16), Ok(-65535 as i32)); + assert_eq!(i32::from_str_radix("-FFFF", 16), Ok(-65535 as i32)); + assert_eq!($T::from_str_radix("-z", 36), Ok(-35 as $T)); + assert_eq!($T::from_str_radix("-Z", 36), Ok(-35 as $T)); + + assert_eq!($T::from_str_radix("Z", 35).ok(), None::<$T>); + assert_eq!($T::from_str_radix("-9", 2).ok(), None::<$T>); + } + + #[test] + fn test_pow() { + let mut r = 2 as $T; + + assert_eq!(r.pow(2), 4 as $T); + assert_eq!(r.pow(0), 1 as $T); + r = -2 as $T; + assert_eq!(r.pow(2), 4 as $T); + assert_eq!(r.pow(3), -8 as $T); + } } - assert_eq!(from_str::<$T>("0"), Some(0 as $T)); - assert_eq!(from_str::<$T>("3"), Some(3 as $T)); - assert_eq!(from_str::<$T>("10"), Some(10 as $T)); - assert_eq!(from_str::("123456789"), Some(123456789 as i32)); - assert_eq!(from_str::<$T>("00100"), Some(100 as $T)); - - assert_eq!(from_str::<$T>("-1"), Some(-1 as $T)); - assert_eq!(from_str::<$T>("-3"), Some(-3 as $T)); - assert_eq!(from_str::<$T>("-10"), Some(-10 as $T)); - assert_eq!(from_str::("-123456789"), Some(-123456789 as i32)); - assert_eq!(from_str::<$T>("-00100"), Some(-100 as $T)); - - assert_eq!(from_str::<$T>(""), None); - assert_eq!(from_str::<$T>(" "), None); - assert_eq!(from_str::<$T>("x"), None); - } - - #[test] - fn test_from_str_radix() { - assert_eq!($T::from_str_radix("123", 10), Ok(123 as $T)); - assert_eq!($T::from_str_radix("1001", 2), Ok(9 as $T)); - assert_eq!($T::from_str_radix("123", 8), Ok(83 as $T)); - assert_eq!(i32::from_str_radix("123", 16), Ok(291 as i32)); - assert_eq!(i32::from_str_radix("ffff", 16), Ok(65535 as i32)); - assert_eq!(i32::from_str_radix("FFFF", 16), Ok(65535 as i32)); - assert_eq!($T::from_str_radix("z", 36), Ok(35 as $T)); - assert_eq!($T::from_str_radix("Z", 36), Ok(35 as $T)); - - assert_eq!($T::from_str_radix("-123", 10), Ok(-123 as $T)); - assert_eq!($T::from_str_radix("-1001", 2), Ok(-9 as $T)); - assert_eq!($T::from_str_radix("-123", 8), Ok(-83 as $T)); - assert_eq!(i32::from_str_radix("-123", 16), Ok(-291 as i32)); - assert_eq!(i32::from_str_radix("-ffff", 16), Ok(-65535 as i32)); - assert_eq!(i32::from_str_radix("-FFFF", 16), Ok(-65535 as i32)); - assert_eq!($T::from_str_radix("-z", 36), Ok(-35 as $T)); - assert_eq!($T::from_str_radix("-Z", 36), Ok(-35 as $T)); - - assert_eq!($T::from_str_radix("Z", 35).ok(), None::<$T>); - assert_eq!($T::from_str_radix("-9", 2).ok(), None::<$T>); - } - - #[test] - fn test_pow() { - let mut r = 2 as $T; - - assert_eq!(r.pow(2), 4 as $T); - assert_eq!(r.pow(0), 1 as $T); - r = -2 as $T; - assert_eq!(r.pow(2), 4 as $T); - assert_eq!(r.pow(3), -8 as $T); - } + }; } - -)} diff --git a/src/libcore/tests/num/uint_macros.rs b/src/libcore/tests/num/uint_macros.rs index 04ed14f3d0897..f94b2f56bbbec 100644 --- a/src/libcore/tests/num/uint_macros.rs +++ b/src/libcore/tests/num/uint_macros.rs @@ -1,160 +1,162 @@ -macro_rules! uint_module { ($T:ident, $T_i:ident) => ( -#[cfg(test)] -mod tests { - use core::$T_i::*; - use core::ops::{BitOr, BitAnd, BitXor, Shl, Shr, Not}; - use std::str::FromStr; - use std::mem; - - use crate::num; - - #[test] - fn test_overflows() { - assert!(MAX > 0); - assert!(MIN <= 0); - assert!((MIN + MAX).wrapping_add(1) == 0); - } - - #[test] - fn test_num() { - num::test_num(10 as $T, 2 as $T); - } - - #[test] - fn test_bitwise_operators() { - assert!(0b1110 as $T == (0b1100 as $T).bitor(0b1010 as $T)); - assert!(0b1000 as $T == (0b1100 as $T).bitand(0b1010 as $T)); - assert!(0b0110 as $T == (0b1100 as $T).bitxor(0b1010 as $T)); - assert!(0b1110 as $T == (0b0111 as $T).shl(1)); - assert!(0b0111 as $T == (0b1110 as $T).shr(1)); - assert!(MAX - (0b1011 as $T) == (0b1011 as $T).not()); - } - - const A: $T = 0b0101100; - const B: $T = 0b0100001; - const C: $T = 0b1111001; - - const _0: $T = 0; - const _1: $T = !0; - - #[test] - fn test_count_ones() { - assert!(A.count_ones() == 3); - assert!(B.count_ones() == 2); - assert!(C.count_ones() == 5); - } - - #[test] - fn test_count_zeros() { - let bits = mem::size_of::<$T>() * 8; - assert!(A.count_zeros() == bits as u32 - 3); - assert!(B.count_zeros() == bits as u32 - 2); - assert!(C.count_zeros() == bits as u32 - 5); - } - - #[test] - fn test_rotate() { - assert_eq!(A.rotate_left(6).rotate_right(2).rotate_right(4), A); - assert_eq!(B.rotate_left(3).rotate_left(2).rotate_right(5), B); - assert_eq!(C.rotate_left(6).rotate_right(2).rotate_right(4), C); - - // Rotating these should make no difference - // - // We test using 124 bits because to ensure that overlong bit shifts do - // not cause undefined behaviour. See #10183. - assert_eq!(_0.rotate_left(124), _0); - assert_eq!(_1.rotate_left(124), _1); - assert_eq!(_0.rotate_right(124), _0); - assert_eq!(_1.rotate_right(124), _1); - - // Rotating by 0 should have no effect - assert_eq!(A.rotate_left(0), A); - assert_eq!(B.rotate_left(0), B); - assert_eq!(C.rotate_left(0), C); - // Rotating by a multiple of word size should also have no effect - assert_eq!(A.rotate_left(64), A); - assert_eq!(B.rotate_left(64), B); - assert_eq!(C.rotate_left(64), C); - } - - #[test] - fn test_swap_bytes() { - assert_eq!(A.swap_bytes().swap_bytes(), A); - assert_eq!(B.swap_bytes().swap_bytes(), B); - assert_eq!(C.swap_bytes().swap_bytes(), C); - - // Swapping these should make no difference - assert_eq!(_0.swap_bytes(), _0); - assert_eq!(_1.swap_bytes(), _1); - } - - #[test] - fn test_reverse_bits() { - assert_eq!(A.reverse_bits().reverse_bits(), A); - assert_eq!(B.reverse_bits().reverse_bits(), B); - assert_eq!(C.reverse_bits().reverse_bits(), C); - - // Swapping these should make no difference - assert_eq!(_0.reverse_bits(), _0); - assert_eq!(_1.reverse_bits(), _1); - } - - #[test] - fn test_le() { - assert_eq!($T::from_le(A.to_le()), A); - assert_eq!($T::from_le(B.to_le()), B); - assert_eq!($T::from_le(C.to_le()), C); - assert_eq!($T::from_le(_0), _0); - assert_eq!($T::from_le(_1), _1); - assert_eq!(_0.to_le(), _0); - assert_eq!(_1.to_le(), _1); - } - - #[test] - fn test_be() { - assert_eq!($T::from_be(A.to_be()), A); - assert_eq!($T::from_be(B.to_be()), B); - assert_eq!($T::from_be(C.to_be()), C); - assert_eq!($T::from_be(_0), _0); - assert_eq!($T::from_be(_1), _1); - assert_eq!(_0.to_be(), _0); - assert_eq!(_1.to_be(), _1); - } - - #[test] - fn test_unsigned_checked_div() { - assert!((10 as $T).checked_div(2) == Some(5)); - assert!((5 as $T).checked_div(0) == None); - } - - fn from_str(t: &str) -> Option { - FromStr::from_str(t).ok() - } - - #[test] - pub fn test_from_str() { - assert_eq!(from_str::<$T>("0"), Some(0 as $T)); - assert_eq!(from_str::<$T>("3"), Some(3 as $T)); - assert_eq!(from_str::<$T>("10"), Some(10 as $T)); - assert_eq!(from_str::("123456789"), Some(123456789 as u32)); - assert_eq!(from_str::<$T>("00100"), Some(100 as $T)); - - assert_eq!(from_str::<$T>(""), None); - assert_eq!(from_str::<$T>(" "), None); - assert_eq!(from_str::<$T>("x"), None); - } - - #[test] - pub fn test_parse_bytes() { - assert_eq!($T::from_str_radix("123", 10), Ok(123 as $T)); - assert_eq!($T::from_str_radix("1001", 2), Ok(9 as $T)); - assert_eq!($T::from_str_radix("123", 8), Ok(83 as $T)); - assert_eq!(u16::from_str_radix("123", 16), Ok(291 as u16)); - assert_eq!(u16::from_str_radix("ffff", 16), Ok(65535 as u16)); - assert_eq!($T::from_str_radix("z", 36), Ok(35 as $T)); - - assert_eq!($T::from_str_radix("Z", 10).ok(), None::<$T>); - assert_eq!($T::from_str_radix("_", 2).ok(), None::<$T>); - } +macro_rules! uint_module { + ($T:ident, $T_i:ident) => { + #[cfg(test)] + mod tests { + use core::ops::{BitAnd, BitOr, BitXor, Not, Shl, Shr}; + use core::$T_i::*; + use std::mem; + use std::str::FromStr; + + use crate::num; + + #[test] + fn test_overflows() { + assert!(MAX > 0); + assert!(MIN <= 0); + assert!((MIN + MAX).wrapping_add(1) == 0); + } + + #[test] + fn test_num() { + num::test_num(10 as $T, 2 as $T); + } + + #[test] + fn test_bitwise_operators() { + assert!(0b1110 as $T == (0b1100 as $T).bitor(0b1010 as $T)); + assert!(0b1000 as $T == (0b1100 as $T).bitand(0b1010 as $T)); + assert!(0b0110 as $T == (0b1100 as $T).bitxor(0b1010 as $T)); + assert!(0b1110 as $T == (0b0111 as $T).shl(1)); + assert!(0b0111 as $T == (0b1110 as $T).shr(1)); + assert!(MAX - (0b1011 as $T) == (0b1011 as $T).not()); + } + + const A: $T = 0b0101100; + const B: $T = 0b0100001; + const C: $T = 0b1111001; + + const _0: $T = 0; + const _1: $T = !0; + + #[test] + fn test_count_ones() { + assert!(A.count_ones() == 3); + assert!(B.count_ones() == 2); + assert!(C.count_ones() == 5); + } + + #[test] + fn test_count_zeros() { + let bits = mem::size_of::<$T>() * 8; + assert!(A.count_zeros() == bits as u32 - 3); + assert!(B.count_zeros() == bits as u32 - 2); + assert!(C.count_zeros() == bits as u32 - 5); + } + + #[test] + fn test_rotate() { + assert_eq!(A.rotate_left(6).rotate_right(2).rotate_right(4), A); + assert_eq!(B.rotate_left(3).rotate_left(2).rotate_right(5), B); + assert_eq!(C.rotate_left(6).rotate_right(2).rotate_right(4), C); + + // Rotating these should make no difference + // + // We test using 124 bits because to ensure that overlong bit shifts do + // not cause undefined behaviour. See #10183. + assert_eq!(_0.rotate_left(124), _0); + assert_eq!(_1.rotate_left(124), _1); + assert_eq!(_0.rotate_right(124), _0); + assert_eq!(_1.rotate_right(124), _1); + + // Rotating by 0 should have no effect + assert_eq!(A.rotate_left(0), A); + assert_eq!(B.rotate_left(0), B); + assert_eq!(C.rotate_left(0), C); + // Rotating by a multiple of word size should also have no effect + assert_eq!(A.rotate_left(64), A); + assert_eq!(B.rotate_left(64), B); + assert_eq!(C.rotate_left(64), C); + } + + #[test] + fn test_swap_bytes() { + assert_eq!(A.swap_bytes().swap_bytes(), A); + assert_eq!(B.swap_bytes().swap_bytes(), B); + assert_eq!(C.swap_bytes().swap_bytes(), C); + + // Swapping these should make no difference + assert_eq!(_0.swap_bytes(), _0); + assert_eq!(_1.swap_bytes(), _1); + } + + #[test] + fn test_reverse_bits() { + assert_eq!(A.reverse_bits().reverse_bits(), A); + assert_eq!(B.reverse_bits().reverse_bits(), B); + assert_eq!(C.reverse_bits().reverse_bits(), C); + + // Swapping these should make no difference + assert_eq!(_0.reverse_bits(), _0); + assert_eq!(_1.reverse_bits(), _1); + } + + #[test] + fn test_le() { + assert_eq!($T::from_le(A.to_le()), A); + assert_eq!($T::from_le(B.to_le()), B); + assert_eq!($T::from_le(C.to_le()), C); + assert_eq!($T::from_le(_0), _0); + assert_eq!($T::from_le(_1), _1); + assert_eq!(_0.to_le(), _0); + assert_eq!(_1.to_le(), _1); + } + + #[test] + fn test_be() { + assert_eq!($T::from_be(A.to_be()), A); + assert_eq!($T::from_be(B.to_be()), B); + assert_eq!($T::from_be(C.to_be()), C); + assert_eq!($T::from_be(_0), _0); + assert_eq!($T::from_be(_1), _1); + assert_eq!(_0.to_be(), _0); + assert_eq!(_1.to_be(), _1); + } + + #[test] + fn test_unsigned_checked_div() { + assert!((10 as $T).checked_div(2) == Some(5)); + assert!((5 as $T).checked_div(0) == None); + } + + fn from_str(t: &str) -> Option { + FromStr::from_str(t).ok() + } + + #[test] + pub fn test_from_str() { + assert_eq!(from_str::<$T>("0"), Some(0 as $T)); + assert_eq!(from_str::<$T>("3"), Some(3 as $T)); + assert_eq!(from_str::<$T>("10"), Some(10 as $T)); + assert_eq!(from_str::("123456789"), Some(123456789 as u32)); + assert_eq!(from_str::<$T>("00100"), Some(100 as $T)); + + assert_eq!(from_str::<$T>(""), None); + assert_eq!(from_str::<$T>(" "), None); + assert_eq!(from_str::<$T>("x"), None); + } + + #[test] + pub fn test_parse_bytes() { + assert_eq!($T::from_str_radix("123", 10), Ok(123 as $T)); + assert_eq!($T::from_str_radix("1001", 2), Ok(9 as $T)); + assert_eq!($T::from_str_radix("123", 8), Ok(83 as $T)); + assert_eq!(u16::from_str_radix("123", 16), Ok(291 as u16)); + assert_eq!(u16::from_str_radix("ffff", 16), Ok(65535 as u16)); + assert_eq!($T::from_str_radix("z", 36), Ok(35 as $T)); + + assert_eq!($T::from_str_radix("Z", 10).ok(), None::<$T>); + assert_eq!($T::from_str_radix("_", 2).ok(), None::<$T>); + } + } + }; } -)} diff --git a/src/libcore/tests/ops.rs b/src/libcore/tests/ops.rs index 48755ae4c1641..43eb498d26ab1 100644 --- a/src/libcore/tests/ops.rs +++ b/src/libcore/tests/ops.rs @@ -1,4 +1,4 @@ -use core::ops::{Bound, Range, RangeFull, RangeFrom, RangeTo, RangeInclusive}; +use core::ops::{Bound, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo}; // Test the Range structs without the syntactic sugar. @@ -59,28 +59,27 @@ fn test_range_inclusive() { assert_eq!(r.next(), None); } - #[test] fn test_range_is_empty() { use core::f32::*; - assert!(!(0.0 .. 10.0).is_empty()); - assert!( (-0.0 .. 0.0).is_empty()); - assert!( (10.0 .. 0.0).is_empty()); + assert!(!(0.0..10.0).is_empty()); + assert!((-0.0..0.0).is_empty()); + assert!((10.0..0.0).is_empty()); - assert!(!(NEG_INFINITY .. INFINITY).is_empty()); - assert!( (EPSILON .. NAN).is_empty()); - assert!( (NAN .. EPSILON).is_empty()); - assert!( (NAN .. NAN).is_empty()); + assert!(!(NEG_INFINITY..INFINITY).is_empty()); + assert!((EPSILON..NAN).is_empty()); + assert!((NAN..EPSILON).is_empty()); + assert!((NAN..NAN).is_empty()); - assert!(!(0.0 ..= 10.0).is_empty()); - assert!(!(-0.0 ..= 0.0).is_empty()); - assert!( (10.0 ..= 0.0).is_empty()); + assert!(!(0.0..=10.0).is_empty()); + assert!(!(-0.0..=0.0).is_empty()); + assert!((10.0..=0.0).is_empty()); - assert!(!(NEG_INFINITY ..= INFINITY).is_empty()); - assert!( (EPSILON ..= NAN).is_empty()); - assert!( (NAN ..= EPSILON).is_empty()); - assert!( (NAN ..= NAN).is_empty()); + assert!(!(NEG_INFINITY..=INFINITY).is_empty()); + assert!((EPSILON..=NAN).is_empty()); + assert!((NAN..=EPSILON).is_empty()); + assert!((NAN..=NAN).is_empty()); } #[test] diff --git a/src/libcore/tests/option.rs b/src/libcore/tests/option.rs index ff43fc49f71e3..fa308160fc228 100644 --- a/src/libcore/tests/option.rs +++ b/src/libcore/tests/option.rs @@ -1,8 +1,8 @@ -use core::option::*; -use core::mem; -use core::clone::Clone; use core::array::FixedSizeArray; +use core::clone::Clone; +use core::mem; use core::ops::DerefMut; +use core::option::*; #[test] fn test_get_ptr() { @@ -28,15 +28,15 @@ fn test_get_str() { #[test] fn test_get_resource() { - use std::rc::Rc; use core::cell::RefCell; + use std::rc::Rc; struct R { - i: Rc>, + i: Rc>, } - impl Drop for R { - fn drop(&mut self) { + impl Drop for R { + fn drop(&mut self) { let ii = &*self.i; let i = *ii.borrow(); *ii.borrow_mut() = i + 1; @@ -44,9 +44,7 @@ fn test_get_resource() { } fn r(i: Rc>) -> R { - R { - i, - } + R { i } } let i = Rc::new(RefCell::new(0)); @@ -70,7 +68,8 @@ fn test_option_dance() { assert!(y.is_none()); } -#[test] #[should_panic] +#[test] +#[should_panic] fn test_option_too_much_dance() { struct A; let mut y = Some(A); @@ -210,7 +209,7 @@ fn test_mut_iter() { fn test_ord() { let small = Some(1.0f64); let big = Some(5.0f64); - let nan = Some(0.0f64/0.0); + let nan = Some(0.0f64 / 0.0); assert!(!(nan < big)); assert!(!(nan > big)); assert!(small < big); @@ -226,9 +225,7 @@ fn test_collect() { let v: Option> = (0..3).map(|x| Some(x)).collect(); assert!(v == Some(vec![0, 1, 2])); - let v: Option> = (0..3).map(|x| { - if x > 1 { None } else { Some(x) } - }).collect(); + let v: Option> = (0..3).map(|x| if x > 1 { None } else { Some(x) }).collect(); assert!(v == None); // test that it does not take more elements than it needs diff --git a/src/libcore/tests/ptr.rs b/src/libcore/tests/ptr.rs index 1a6be3a9bbd03..4f5a9be579e13 100644 --- a/src/libcore/tests/ptr.rs +++ b/src/libcore/tests/ptr.rs @@ -1,14 +1,14 @@ -use core::ptr::*; use core::cell::RefCell; +use core::ptr::*; #[test] fn test() { unsafe { struct Pair { fst: isize, - snd: isize + snd: isize, }; - let mut p = Pair {fst: 10, snd: 20}; + let mut p = Pair { fst: 10, snd: 20 }; let pptr: *mut Pair = &mut p; let iptr: *mut isize = pptr as *mut isize; assert_eq!(*iptr, 10); @@ -16,7 +16,7 @@ fn test() { assert_eq!(*iptr, 30); assert_eq!(p.fst, 30); - *pptr = Pair {fst: 50, snd: 60}; + *pptr = Pair { fst: 50, snd: 60 }; assert_eq!(*iptr, 50); assert_eq!(p.fst, 50); assert_eq!(p.snd, 60); @@ -25,17 +25,11 @@ fn test() { let mut v1 = vec![0u16, 0u16, 0u16]; copy(v0.as_ptr().offset(1), v1.as_mut_ptr().offset(1), 1); - assert!((v1[0] == 0u16 && - v1[1] == 32001u16 && - v1[2] == 0u16)); + assert!((v1[0] == 0u16 && v1[1] == 32001u16 && v1[2] == 0u16)); copy(v0.as_ptr().offset(2), v1.as_mut_ptr(), 1); - assert!((v1[0] == 32002u16 && - v1[1] == 32001u16 && - v1[2] == 0u16)); + assert!((v1[0] == 32002u16 && v1[1] == 32001u16 && v1[2] == 0u16)); copy(v0.as_ptr(), v1.as_mut_ptr().offset(2), 1); - assert!((v1[0] == 32002u16 && - v1[1] == 32001u16 && - v1[2] == 32000u16)); + assert!((v1[0] == 32002u16 && v1[1] == 32001u16 && v1[2] == 32000u16)); } } @@ -208,7 +202,7 @@ fn test_ptr_addition() { #[test] fn test_ptr_subtraction() { unsafe { - let xs = vec![0,1,2,3,4,5,6,7,8,9]; + let xs = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; let mut idx = 9; let ptr = xs.as_ptr(); @@ -229,7 +223,7 @@ fn test_ptr_subtraction() { m_ptr = m_ptr.offset(-1); } - assert_eq!(xs_mut, [0,2,4,6,8,10,12,14,16,18]); + assert_eq!(xs_mut, [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]); } } @@ -237,7 +231,9 @@ fn test_ptr_subtraction() { fn test_set_memory() { let mut xs = [0u8; 20]; let ptr = xs.as_mut_ptr(); - unsafe { write_bytes(ptr, 5u8, xs.len()); } + unsafe { + write_bytes(ptr, 5u8, xs.len()); + } assert!(xs == [5u8; 20]); } @@ -257,10 +253,10 @@ fn test_unsized_nonnull() { #[no_mangle] pub fn test_variadic_fnptr() { use core::hash::{Hash, SipHasher}; - extern { + extern "C" { fn test_variadic_fnptr(_: u64, ...) -> f64; } - let p: unsafe extern fn(u64, ...) -> f64 = test_variadic_fnptr; + let p: unsafe extern "C" fn(u64, ...) -> f64 = test_variadic_fnptr; let q = p.clone(); assert_eq!(p, q); assert!(!(p < q)); @@ -285,7 +281,9 @@ fn write_unaligned_drop() { { let c = Dropper(0); let mut t = Dropper(1); - unsafe { write_unaligned(&mut t, c); } + unsafe { + write_unaligned(&mut t, c); + } } DROPS.with(|d| assert_eq!(*d.borrow(), [0])); } @@ -312,11 +310,16 @@ fn align_offset_stride1() { // number of bytes. let mut align = 1; while align < 1024 { - for ptr in 1..2*align { + for ptr in 1..2 * align { let expected = ptr % align; let offset = if expected == 0 { 0 } else { align - expected }; - assert_eq!((ptr as *const u8).align_offset(align), offset, - "ptr = {}, align = {}, size = 1", ptr, align); + assert_eq!( + (ptr as *const u8).align_offset(align), + offset, + "ptr = {}, align = {}, size = 1", + ptr, + align + ); } align = (align + 1).next_power_of_two(); } @@ -353,8 +356,14 @@ fn align_offset_weird_strides() { } let got = ptr.align_offset(align); if got != expected { - eprintln!("aligning {:p} (with stride of {}) to {}, expected {}, got {}", ptr, - ::std::mem::size_of::(), align, expected, got); + eprintln!( + "aligning {:p} (with stride of {}) to {}, expected {}, got {}", + ptr, + ::std::mem::size_of::(), + align, + expected, + got + ); return true; } return false; @@ -365,7 +374,7 @@ fn align_offset_weird_strides() { let mut align = 1; let mut x = false; while align < 1024 { - for ptr in 1usize..4*align { + for ptr in 1usize..4 * align { unsafe { x |= test_weird_stride::(ptr as *const A3, align); x |= test_weird_stride::(ptr as *const A4, align); diff --git a/src/libcore/tests/slice.rs b/src/libcore/tests/slice.rs index 6609bc3135ae0..eac18e93ab681 100644 --- a/src/libcore/tests/slice.rs +++ b/src/libcore/tests/slice.rs @@ -1,4 +1,4 @@ -use core::result::Result::{Ok, Err}; +use core::result::Result::{Err, Ok}; #[test] fn test_position() { @@ -50,8 +50,14 @@ fn test_binary_search() { assert_eq!(b.binary_search(&0), Err(0)); assert_eq!(b.binary_search(&1), Ok(0)); assert_eq!(b.binary_search(&2), Err(1)); - assert!(match b.binary_search(&3) { Ok(1..=3) => true, _ => false }); - assert!(match b.binary_search(&3) { Ok(1..=3) => true, _ => false }); + assert!(match b.binary_search(&3) { + Ok(1..=3) => true, + _ => false, + }); + assert!(match b.binary_search(&3) { + Ok(1..=3) => true, + _ => false, + }); assert_eq!(b.binary_search(&4), Err(4)); assert_eq!(b.binary_search(&5), Err(4)); assert_eq!(b.binary_search(&6), Err(4)); @@ -187,7 +193,8 @@ fn test_chunks_zip() { let v1: &[i32] = &[0, 1, 2, 3, 4]; let v2: &[i32] = &[6, 7, 8, 9, 10]; - let res = v1.chunks(2) + let res = v1 + .chunks(2) .zip(v2.chunks(2)) .map(|(a, b)| a.iter().sum::() + b.iter().sum::()) .collect::>(); @@ -339,7 +346,8 @@ fn test_chunks_exact_zip() { let v1: &[i32] = &[0, 1, 2, 3, 4]; let v2: &[i32] = &[6, 7, 8, 9, 10]; - let res = v1.chunks_exact(2) + let res = v1 + .chunks_exact(2) .zip(v2.chunks_exact(2)) .map(|(a, b)| a.iter().sum::() + b.iter().sum::()) .collect::>(); @@ -482,7 +490,8 @@ fn test_rchunks_zip() { let v1: &[i32] = &[0, 1, 2, 3, 4]; let v2: &[i32] = &[6, 7, 8, 9, 10]; - let res = v1.rchunks(2) + let res = v1 + .rchunks(2) .zip(v2.rchunks(2)) .map(|(a, b)| a.iter().sum::() + b.iter().sum::()) .collect::>(); @@ -619,7 +628,8 @@ fn test_rchunks_exact_zip() { let v1: &[i32] = &[0, 1, 2, 3, 4]; let v2: &[i32] = &[6, 7, 8, 9, 10]; - let res = v1.rchunks_exact(2) + let res = v1 + .rchunks_exact(2) .zip(v2.rchunks_exact(2)) .map(|(a, b)| a.iter().sum::() + b.iter().sum::()) .collect::>(); @@ -756,7 +766,8 @@ fn test_windows_zip() { let v1: &[i32] = &[0, 1, 2, 3, 4]; let v2: &[i32] = &[6, 7, 8, 9, 10]; - let res = v1.windows(2) + let res = v1 + .windows(2) .zip(v2.windows(2)) .map(|(a, b)| a.iter().sum::() + b.iter().sum::()) .collect::>(); @@ -769,11 +780,11 @@ fn test_windows_zip() { fn test_iter_ref_consistency() { use std::fmt::Debug; - fn test(x : T) { - let v : &[T] = &[x, x, x]; - let v_ptrs : [*const T; 3] = match v { + fn test(x: T) { + let v: &[T] = &[x, x, x]; + let v_ptrs: [*const T; 3] = match v { [ref v1, ref v2, ref v3] => [v1 as *const _, v2 as *const _, v3 as *const _], - _ => unreachable!() + _ => unreachable!(), }; let len = v.len(); @@ -817,19 +828,20 @@ fn test_iter_ref_consistency() { assert_eq!(it.size_hint(), (remaining, Some(remaining))); let prev = it.next_back().unwrap(); - assert_eq!(prev as *const _, v_ptrs[remaining-1]); + assert_eq!(prev as *const _, v_ptrs[remaining - 1]); } assert_eq!(it.size_hint(), (0, Some(0))); assert_eq!(it.next_back(), None, "The final call to next_back() should return None"); } } - fn test_mut(x : T) { - let v : &mut [T] = &mut [x, x, x]; - let v_ptrs : [*mut T; 3] = match v { - [ref v1, ref v2, ref v3] => - [v1 as *const _ as *mut _, v2 as *const _ as *mut _, v3 as *const _ as *mut _], - _ => unreachable!() + fn test_mut(x: T) { + let v: &mut [T] = &mut [x, x, x]; + let v_ptrs: [*mut T; 3] = match v { + [ref v1, ref v2, ref v3] => { + [v1 as *const _ as *mut _, v2 as *const _ as *mut _, v3 as *const _ as *mut _] + } + _ => unreachable!(), }; let len = v.len(); @@ -873,7 +885,7 @@ fn test_iter_ref_consistency() { assert_eq!(it.size_hint(), (remaining, Some(remaining))); let prev = it.next_back().unwrap(); - assert_eq!(prev as *mut _, v_ptrs[remaining-1]); + assert_eq!(prev as *mut _, v_ptrs[remaining - 1]); } assert_eq!(it.size_hint(), (0, Some(0))); assert_eq!(it.next_back(), None, "The final call to next_back() should return None"); @@ -897,8 +909,7 @@ mod slice_index { // This checks all six indexing methods, given an input range that // should succeed. (it is NOT suitable for testing invalid inputs) macro_rules! assert_range_eq { - ($arr:expr, $range:expr, $expected:expr) - => { + ($arr:expr, $range:expr, $expected:expr) => { let mut arr = $arr; let mut expected = $expected; { @@ -909,7 +920,8 @@ mod slice_index { assert_eq!(s.get($range), Some(expected), "(in assertion for: get)"); unsafe { assert_eq!( - s.get_unchecked($range), expected, + s.get_unchecked($range), + expected, "(in assertion for: get_unchecked)", ); } @@ -918,22 +930,21 @@ mod slice_index { let s: &mut [_] = &mut arr; let expected: &mut [_] = &mut expected; + assert_eq!(&mut s[$range], expected, "(in assertion for: index_mut)",); assert_eq!( - &mut s[$range], expected, - "(in assertion for: index_mut)", - ); - assert_eq!( - s.get_mut($range), Some(&mut expected[..]), + s.get_mut($range), + Some(&mut expected[..]), "(in assertion for: get_mut)", ); unsafe { assert_eq!( - s.get_unchecked_mut($range), expected, + s.get_unchecked_mut($range), + expected, "(in assertion for: get_unchecked_mut)", ); } } - } + }; } // Make sure the macro can actually detect bugs, @@ -1126,8 +1137,8 @@ fn test_find_rfind() { #[test] fn test_iter_folds() { let a = [1, 2, 3, 4, 5]; // len>4 so the unroll is used - assert_eq!(a.iter().fold(0, |acc, &x| 2*acc + x), 57); - assert_eq!(a.iter().rfold(0, |acc, &x| 2*acc + x), 129); + assert_eq!(a.iter().fold(0, |acc, &x| 2 * acc + x), 57); + assert_eq!(a.iter().rfold(0, |acc, &x| 2 * acc + x), 129); let fold = |acc: i32, &x| acc.checked_mul(2)?.checked_add(x); assert_eq!(a.iter().try_fold(0, &fold), Some(57)); assert_eq!(a.iter().try_rfold(0, &fold), Some(129)); @@ -1214,7 +1225,7 @@ fn brute_force_rotate_test_1() { fn sort_unstable() { use core::cmp::Ordering::{Equal, Greater, Less}; use core::slice::heapsort; - use rand::{SeedableRng, Rng, rngs::StdRng, seq::SliceRandom}; + use rand::{rngs::StdRng, seq::SliceRandom, Rng, SeedableRng}; #[cfg(not(miri))] // Miri is too slow let large_range = 500..510; @@ -1296,7 +1307,7 @@ fn partition_at_index() { use core::cmp::Ordering::{Equal, Greater, Less}; use rand::rngs::StdRng; use rand::seq::SliceRandom; - use rand::{SeedableRng, Rng}; + use rand::{Rng, SeedableRng}; let mut rng = StdRng::from_entropy(); @@ -1504,9 +1515,15 @@ fn test_align_to_simple() { let expect2 = [1 | 2 << 8, 3 | 4 << 8, 5 | 6 << 8]; let expect3 = [2 << 8 | 3, 4 << 8 | 5, 6 << 8 | 7]; let expect4 = [2 | 3 << 8, 4 | 5 << 8, 6 | 7 << 8]; - assert!(aligned == expect1 || aligned == expect2 || aligned == expect3 || aligned == expect4, - "aligned={:?} expected={:?} || {:?} || {:?} || {:?}", - aligned, expect1, expect2, expect3, expect4); + assert!( + aligned == expect1 || aligned == expect2 || aligned == expect3 || aligned == expect4, + "aligned={:?} expected={:?} || {:?} || {:?} || {:?}", + aligned, + expect1, + expect2, + expect3, + expect4 + ); } #[test] @@ -1520,10 +1537,20 @@ fn test_align_to_zst() { #[test] #[cfg(not(miri))] // Miri does not compute a maximal `mid` for `align_offset` fn test_align_to_non_trivial() { - #[repr(align(8))] struct U64(u64, u64); - #[repr(align(8))] struct U64U64U32(u64, u64, u32); - let data = [U64(1, 2), U64(3, 4), U64(5, 6), U64(7, 8), U64(9, 10), U64(11, 12), U64(13, 14), - U64(15, 16)]; + #[repr(align(8))] + struct U64(u64, u64); + #[repr(align(8))] + struct U64U64U32(u64, u64, u32); + let data = [ + U64(1, 2), + U64(3, 4), + U64(5, 6), + U64(7, 8), + U64(9, 10), + U64(11, 12), + U64(13, 14), + U64(15, 16), + ]; let (prefix, aligned, suffix) = unsafe { data.align_to::() }; assert_eq!(aligned.len(), 4); assert_eq!(prefix.len() + suffix.len(), 2); @@ -1538,7 +1565,7 @@ fn test_align_to_empty_mid() { let bytes = [1, 2, 3, 4, 5, 6, 7]; type Chunk = u32; for offset in 0..4 { - let (_, mid, _) = unsafe { bytes[offset..offset+1].align_to::() }; + let (_, mid, _) = unsafe { bytes[offset..offset + 1].align_to::() }; assert_eq!(mid.as_ptr() as usize % mem::align_of::(), 0); } } diff --git a/src/libcore/tests/str_lossy.rs b/src/libcore/tests/str_lossy.rs index f9fd333cca712..d4b47a4708e4b 100644 --- a/src/libcore/tests/str_lossy.rs +++ b/src/libcore/tests/str_lossy.rs @@ -3,65 +3,65 @@ use core::str::lossy::*; #[test] fn chunks() { let mut iter = Utf8Lossy::from_bytes(b"hello").chunks(); - assert_eq!(Some(Utf8LossyChunk { valid: "hello", broken: b"", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "hello", broken: b"" }), iter.next()); assert_eq!(None, iter.next()); let mut iter = Utf8Lossy::from_bytes("ศไทย中华Việt Nam".as_bytes()).chunks(); - assert_eq!(Some(Utf8LossyChunk { valid: "ศไทย中华Việt Nam", broken: b"", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "ศไทย中华Việt Nam", broken: b"" }), iter.next()); assert_eq!(None, iter.next()); let mut iter = Utf8Lossy::from_bytes(b"Hello\xC2 There\xFF Goodbye").chunks(); - assert_eq!(Some(Utf8LossyChunk { valid: "Hello", broken: b"\xC2", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: " There", broken: b"\xFF", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: " Goodbye", broken: b"", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "Hello", broken: b"\xC2" }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: " There", broken: b"\xFF" }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: " Goodbye", broken: b"" }), iter.next()); assert_eq!(None, iter.next()); let mut iter = Utf8Lossy::from_bytes(b"Hello\xC0\x80 There\xE6\x83 Goodbye").chunks(); - assert_eq!(Some(Utf8LossyChunk { valid: "Hello", broken: b"\xC0", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\x80", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: " There", broken: b"\xE6\x83", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: " Goodbye", broken: b"", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "Hello", broken: b"\xC0" }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\x80" }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: " There", broken: b"\xE6\x83" }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: " Goodbye", broken: b"" }), iter.next()); assert_eq!(None, iter.next()); let mut iter = Utf8Lossy::from_bytes(b"\xF5foo\xF5\x80bar").chunks(); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xF5", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "foo", broken: b"\xF5", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\x80", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "bar", broken: b"", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xF5" }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "foo", broken: b"\xF5" }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\x80" }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "bar", broken: b"" }), iter.next()); assert_eq!(None, iter.next()); let mut iter = Utf8Lossy::from_bytes(b"\xF1foo\xF1\x80bar\xF1\x80\x80baz").chunks(); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xF1", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "foo", broken: b"\xF1\x80", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "bar", broken: b"\xF1\x80\x80", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "baz", broken: b"", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xF1" }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "foo", broken: b"\xF1\x80" }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "bar", broken: b"\xF1\x80\x80" }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "baz", broken: b"" }), iter.next()); assert_eq!(None, iter.next()); let mut iter = Utf8Lossy::from_bytes(b"\xF4foo\xF4\x80bar\xF4\xBFbaz").chunks(); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xF4", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "foo", broken: b"\xF4\x80", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "bar", broken: b"\xF4", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xBF", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "baz", broken: b"", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xF4" }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "foo", broken: b"\xF4\x80" }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "bar", broken: b"\xF4" }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xBF" }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "baz", broken: b"" }), iter.next()); assert_eq!(None, iter.next()); let mut iter = Utf8Lossy::from_bytes(b"\xF0\x80\x80\x80foo\xF0\x90\x80\x80bar").chunks(); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xF0", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\x80", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\x80", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\x80", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "foo\u{10000}bar", broken: b"", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xF0" }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\x80" }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\x80" }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\x80" }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "foo\u{10000}bar", broken: b"" }), iter.next()); assert_eq!(None, iter.next()); // surrogates let mut iter = Utf8Lossy::from_bytes(b"\xED\xA0\x80foo\xED\xBF\xBFbar").chunks(); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xED", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xA0", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\x80", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "foo", broken: b"\xED", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xBF", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xBF", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "bar", broken: b"", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xED" }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xA0" }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\x80" }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "foo", broken: b"\xED" }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xBF" }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xBF" }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "bar", broken: b"" }), iter.next()); assert_eq!(None, iter.next()); } @@ -69,13 +69,17 @@ fn chunks() { fn display() { assert_eq!( "Hello\u{FFFD}\u{FFFD} There\u{FFFD} Goodbye", - &Utf8Lossy::from_bytes(b"Hello\xC0\x80 There\xE6\x83 Goodbye").to_string()); + &Utf8Lossy::from_bytes(b"Hello\xC0\x80 There\xE6\x83 Goodbye").to_string() + ); } #[test] fn debug() { assert_eq!( "\"Hello\\xc0\\x80 There\\xe6\\x83 Goodbye\\u{10d4ea}\"", - &format!("{:?}", Utf8Lossy::from_bytes( - b"Hello\xC0\x80 There\xE6\x83 Goodbye\xf4\x8d\x93\xaa"))); + &format!( + "{:?}", + Utf8Lossy::from_bytes(b"Hello\xC0\x80 There\xE6\x83 Goodbye\xf4\x8d\x93\xaa") + ) + ); } diff --git a/src/libcore/tests/time.rs b/src/libcore/tests/time.rs index fac70c468c89d..273f1258bb090 100644 --- a/src/libcore/tests/time.rs +++ b/src/libcore/tests/time.rs @@ -3,10 +3,11 @@ use core::time::Duration; #[test] fn creation() { assert_ne!(Duration::from_secs(1), Duration::from_secs(0)); - assert_eq!(Duration::from_secs(1) + Duration::from_secs(2), - Duration::from_secs(3)); - assert_eq!(Duration::from_millis(10) + Duration::from_secs(4), - Duration::new(4, 10 * 1_000_000)); + assert_eq!(Duration::from_secs(1) + Duration::from_secs(2), Duration::from_secs(3)); + assert_eq!( + Duration::from_millis(10) + Duration::from_secs(4), + Duration::new(4, 10 * 1_000_000) + ); assert_eq!(Duration::from_millis(4000), Duration::new(4, 0)); } @@ -68,29 +69,25 @@ fn nanos() { #[test] fn add() { - assert_eq!(Duration::new(0, 0) + Duration::new(0, 1), - Duration::new(0, 1)); - assert_eq!(Duration::new(0, 500_000_000) + Duration::new(0, 500_000_001), - Duration::new(1, 1)); + assert_eq!(Duration::new(0, 0) + Duration::new(0, 1), Duration::new(0, 1)); + assert_eq!(Duration::new(0, 500_000_000) + Duration::new(0, 500_000_001), Duration::new(1, 1)); } #[test] fn checked_add() { - assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)), - Some(Duration::new(0, 1))); - assert_eq!(Duration::new(0, 500_000_000).checked_add(Duration::new(0, 500_000_001)), - Some(Duration::new(1, 1))); + assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)), Some(Duration::new(0, 1))); + assert_eq!( + Duration::new(0, 500_000_000).checked_add(Duration::new(0, 500_000_001)), + Some(Duration::new(1, 1)) + ); assert_eq!(Duration::new(1, 0).checked_add(Duration::new(::core::u64::MAX, 0)), None); } #[test] fn sub() { - assert_eq!(Duration::new(0, 1) - Duration::new(0, 0), - Duration::new(0, 1)); - assert_eq!(Duration::new(0, 500_000_001) - Duration::new(0, 500_000_000), - Duration::new(0, 1)); - assert_eq!(Duration::new(1, 0) - Duration::new(0, 1), - Duration::new(0, 999_999_999)); + assert_eq!(Duration::new(0, 1) - Duration::new(0, 0), Duration::new(0, 1)); + assert_eq!(Duration::new(0, 500_000_001) - Duration::new(0, 500_000_000), Duration::new(0, 1)); + assert_eq!(Duration::new(1, 0) - Duration::new(0, 1), Duration::new(0, 999_999_999)); } #[test] @@ -99,8 +96,7 @@ fn checked_sub() { let one_nano = Duration::new(0, 1); let one_sec = Duration::new(1, 0); assert_eq!(one_nano.checked_sub(zero), Some(Duration::new(0, 1))); - assert_eq!(one_sec.checked_sub(one_nano), - Some(Duration::new(0, 999_999_999))); + assert_eq!(one_sec.checked_sub(one_nano), Some(Duration::new(0, 999_999_999))); assert_eq!(zero.checked_sub(one_nano), None); assert_eq!(zero.checked_sub(one_sec), None); } @@ -122,8 +118,7 @@ fn mul() { assert_eq!(Duration::new(0, 1) * 2, Duration::new(0, 2)); assert_eq!(Duration::new(1, 1) * 3, Duration::new(3, 3)); assert_eq!(Duration::new(0, 500_000_001) * 4, Duration::new(2, 4)); - assert_eq!(Duration::new(0, 500_000_001) * 4000, - Duration::new(2000, 4000)); + assert_eq!(Duration::new(0, 500_000_001) * 4000, Duration::new(2000, 4000)); } #[test] @@ -131,8 +126,7 @@ fn checked_mul() { assert_eq!(Duration::new(0, 1).checked_mul(2), Some(Duration::new(0, 2))); assert_eq!(Duration::new(1, 1).checked_mul(3), Some(Duration::new(3, 3))); assert_eq!(Duration::new(0, 500_000_001).checked_mul(4), Some(Duration::new(2, 4))); - assert_eq!(Duration::new(0, 500_000_001).checked_mul(4000), - Some(Duration::new(2000, 4000))); + assert_eq!(Duration::new(0, 500_000_001).checked_mul(4000), Some(Duration::new(2000, 4000))); assert_eq!(Duration::new(::core::u64::MAX - 1, 0).checked_mul(2), None); } @@ -140,8 +134,7 @@ fn checked_mul() { fn div() { assert_eq!(Duration::new(0, 1) / 2, Duration::new(0, 0)); assert_eq!(Duration::new(1, 1) / 3, Duration::new(0, 333_333_333)); - assert_eq!(Duration::new(99, 999_999_000) / 100, - Duration::new(0, 999_999_990)); + assert_eq!(Duration::new(99, 999_999_000) / 100, Duration::new(0, 999_999_990)); } #[test] @@ -162,7 +155,7 @@ fn correct_sum() { Duration::new(5, 0), ]; let sum = durations.iter().sum::(); - assert_eq!(sum, Duration::new(1+2+5+4, 1_000_000_000 - 5)); + assert_eq!(sum, Duration::new(1 + 2 + 5 + 4, 1_000_000_000 - 5)); } #[test] @@ -286,9 +279,9 @@ fn debug_formatting_precision_two() { #[test] fn debug_formatting_precision_high() { - assert_eq!(format!("{:.5?}", Duration::new(0, 23_678)), "23.67800µs"); + assert_eq!(format!("{:.5?}", Duration::new(0, 23_678)), "23.67800µs"); - assert_eq!(format!("{:.9?}", Duration::new(1, 000_000_000)), "1.000000000s"); + assert_eq!(format!("{:.9?}", Duration::new(1, 000_000_000)), "1.000000000s"); assert_eq!(format!("{:.10?}", Duration::new(4, 001_000_000)), "4.0010000000s"); assert_eq!(format!("{:.20?}", Duration::new(4, 001_000_000)), "4.00100000000000000000s"); } diff --git a/src/libcore/tests/tuple.rs b/src/libcore/tests/tuple.rs index c7ed1612dd5ea..3a2914698cc26 100644 --- a/src/libcore/tests/tuple.rs +++ b/src/libcore/tests/tuple.rs @@ -1,4 +1,4 @@ -use std::cmp::Ordering::{Equal, Less, Greater}; +use std::cmp::Ordering::{Equal, Greater, Less}; use std::f64::NAN; #[test] From 2b2b16c2a47512ab30df9ef74d85b9b703f6bbe0 Mon Sep 17 00:00:00 2001 From: Matthew Kraai Date: Fri, 6 Dec 2019 09:09:56 -0800 Subject: [PATCH 18/18] Simplify `Layout::extend_packed` --- src/libcore/alloc.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/libcore/alloc.rs b/src/libcore/alloc.rs index 20248f7f6c13e..d8e9fe5fbe2f7 100644 --- a/src/libcore/alloc.rs +++ b/src/libcore/alloc.rs @@ -310,8 +310,7 @@ impl Layout { pub fn extend_packed(&self, next: Self) -> Result { let new_size = self.size().checked_add(next.size()) .ok_or(LayoutErr { private: () })?; - let layout = Layout::from_size_align(new_size, self.align())?; - Ok(layout) + Layout::from_size_align(new_size, self.align()) } /// Creates a layout describing the record for a `[T; n]`.