diff options
| author | Mark Rousskov <mark.simulacrum@gmail.com> | 2019-12-22 17:42:04 -0500 |
|---|---|---|
| committer | Mark Rousskov <mark.simulacrum@gmail.com> | 2019-12-22 17:42:47 -0500 |
| commit | a06baa56b95674fc626b3c3fd680d6a65357fe60 (patch) | |
| tree | cd9d867c2ca3cff5c1d6b3bd73377c44649fb075 /src/libcore | |
| parent | 8eb7c58dbb7b32701af113bc58722d0d1fefb1eb (diff) | |
Format the world
Diffstat (limited to 'src/libcore')
42 files changed, 3109 insertions, 2460 deletions
diff --git a/src/libcore/alloc.rs b/src/libcore/alloc.rs index cb476acfb3a..b2d4b1b5fb9 100644 --- a/src/libcore/alloc.rs +++ b/src/libcore/alloc.rs @@ -7,9 +7,9 @@ use crate::cmp; use crate::fmt; use crate::mem; -use crate::usize; -use crate::ptr::{self, NonNull}; use crate::num::NonZeroUsize; +use crate::ptr::{self, NonNull}; +use crate::usize; /// Represents the combination of a starting address and /// a total capacity of the returned block. @@ -88,9 +88,7 @@ impl Layout { return Err(LayoutErr { private: () }); } - unsafe { - Ok(Layout::from_size_align_unchecked(size, align)) - } + unsafe { Ok(Layout::from_size_align_unchecked(size, align)) } } /// Creates a layout, bypassing all checks. @@ -109,12 +107,16 @@ impl Layout { /// The minimum size in bytes for a memory block of this layout. #[stable(feature = "alloc_layout", since = "1.28.0")] #[inline] - pub fn size(&self) -> usize { self.size_ } + pub fn size(&self) -> usize { + self.size_ + } /// The minimum byte alignment for a memory block of this layout. #[stable(feature = "alloc_layout", since = "1.28.0")] #[inline] - pub fn align(&self) -> usize { self.align_.get() } + pub fn align(&self) -> usize { + self.align_.get() + } /// Constructs a `Layout` suitable for holding a value of type `T`. #[stable(feature = "alloc_layout", since = "1.28.0")] @@ -126,9 +128,7 @@ impl Layout { // result use the unchecked constructor here to avoid inserting code // that panics if it isn't optimized well enough. debug_assert!(Layout::from_size_align(size, align).is_ok()); - unsafe { - Layout::from_size_align_unchecked(size, align) - } + unsafe { Layout::from_size_align_unchecked(size, align) } } /// Produces layout describing a record that could be used to @@ -140,9 +140,7 @@ impl Layout { let (size, align) = (mem::size_of_val(t), mem::align_of_val(t)); // See rationale in `new` for why this is using an unsafe variant below debug_assert!(Layout::from_size_align(size, align).is_ok()); - unsafe { - Layout::from_size_align_unchecked(size, align) - } + unsafe { Layout::from_size_align_unchecked(size, align) } } /// Creates a layout describing the record that can hold a value @@ -206,8 +204,7 @@ impl Layout { // size and padding overflow in the above manner should cause // the allocator to yield an error anyway.) - let len_rounded_up = len.wrapping_add(align).wrapping_sub(1) - & !align.wrapping_sub(1); + let len_rounded_up = len.wrapping_add(align).wrapping_sub(1) & !align.wrapping_sub(1); len_rounded_up.wrapping_sub(len) } @@ -245,8 +242,7 @@ impl Layout { // > must not overflow (i.e., the rounded value must be less than // > `usize::MAX`) let padded_size = self.size() + self.padding_needed_for(self.align()); - let alloc_size = padded_size.checked_mul(n) - .ok_or(LayoutErr { private: () })?; + let alloc_size = padded_size.checked_mul(n).ok_or(LayoutErr { private: () })?; unsafe { // self.align is already known to be valid and alloc_size has been @@ -275,10 +271,8 @@ impl Layout { let new_align = cmp::max(self.align(), next.align()); let pad = self.padding_needed_for(next.align()); - let offset = self.size().checked_add(pad) - .ok_or(LayoutErr { private: () })?; - let new_size = offset.checked_add(next.size()) - .ok_or(LayoutErr { private: () })?; + let offset = self.size().checked_add(pad).ok_or(LayoutErr { private: () })?; + let new_size = offset.checked_add(next.size()).ok_or(LayoutErr { private: () })?; let layout = Layout::from_size_align(new_size, new_align)?; Ok((layout, offset)) @@ -312,8 +306,7 @@ impl Layout { #[unstable(feature = "alloc_layout_extra", issue = "55724")] #[inline] pub fn extend_packed(&self, next: Self) -> Result<Self, LayoutErr> { - let new_size = self.size().checked_add(next.size()) - .ok_or(LayoutErr { private: () })?; + let new_size = self.size().checked_add(next.size()).ok_or(LayoutErr { private: () })?; Layout::from_size_align(new_size, self.align()) } @@ -323,12 +316,10 @@ impl Layout { #[unstable(feature = "alloc_layout_extra", issue = "55724")] #[inline] pub fn array<T>(n: usize) -> Result<Self, LayoutErr> { - Layout::new::<T>() - .repeat(n) - .map(|(k, offs)| { - debug_assert!(offs == mem::size_of::<T>()); - k - }) + Layout::new::<T>().repeat(n).map(|(k, offs)| { + debug_assert!(offs == mem::size_of::<T>()); + k + }) } } @@ -338,7 +329,7 @@ impl Layout { #[stable(feature = "alloc_layout", since = "1.28.0")] #[derive(Clone, PartialEq, Eq, Debug)] pub struct LayoutErr { - private: () + private: (), } // (we need this for downstream impl of trait Error) @@ -577,11 +568,7 @@ pub unsafe trait GlobalAlloc { let new_layout = Layout::from_size_align_unchecked(new_size, layout.align()); let new_ptr = self.alloc(new_layout); if !new_ptr.is_null() { - ptr::copy_nonoverlapping( - ptr, - new_ptr, - cmp::min(layout.size(), new_size), - ); + ptr::copy_nonoverlapping(ptr, new_ptr, cmp::min(layout.size(), new_size)); self.dealloc(ptr, layout); } new_ptr @@ -669,7 +656,6 @@ pub unsafe trait GlobalAlloc { /// the future. #[unstable(feature = "allocator_api", issue = "32838")] pub unsafe trait Alloc { - // (Note: some existing allocators have unspecified but well-defined // behavior in response to a zero size allocation request ; // e.g., in C, `malloc` of 0 will either return a null pointer or a @@ -826,10 +812,12 @@ pub unsafe trait Alloc { /// rather than directly invoking `panic!` or similar. /// /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html - unsafe fn realloc(&mut self, - ptr: NonNull<u8>, - layout: Layout, - new_size: usize) -> Result<NonNull<u8>, AllocErr> { + unsafe fn realloc( + &mut self, + ptr: NonNull<u8>, + layout: Layout, + new_size: usize, + ) -> Result<NonNull<u8>, AllocErr> { let old_size = layout.size(); if new_size >= old_size { @@ -846,9 +834,7 @@ pub unsafe trait Alloc { let new_layout = Layout::from_size_align_unchecked(new_size, layout.align()); let result = self.alloc(new_layout); if let Ok(new_ptr) = result { - ptr::copy_nonoverlapping(ptr.as_ptr(), - new_ptr.as_ptr(), - cmp::min(old_size, new_size)); + ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_ptr(), cmp::min(old_size, new_size)); self.dealloc(ptr, layout); } result @@ -924,14 +910,15 @@ pub unsafe trait Alloc { /// rather than directly invoking `panic!` or similar. /// /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html - unsafe fn realloc_excess(&mut self, - ptr: NonNull<u8>, - layout: Layout, - new_size: usize) -> Result<Excess, AllocErr> { + unsafe fn realloc_excess( + &mut self, + ptr: NonNull<u8>, + layout: Layout, + new_size: usize, + ) -> Result<Excess, AllocErr> { let new_layout = Layout::from_size_align_unchecked(new_size, layout.align()); let usable_size = self.usable_size(&new_layout); - self.realloc(ptr, layout, new_size) - .map(|p| Excess(p, usable_size.1)) + self.realloc(ptr, layout, new_size).map(|p| Excess(p, usable_size.1)) } /// Attempts to extend the allocation referenced by `ptr` to fit `new_size`. @@ -969,20 +956,18 @@ pub unsafe trait Alloc { /// function; clients are expected either to be able to recover from /// `grow_in_place` failures without aborting, or to fall back on /// another reallocation method before resorting to an abort. - unsafe fn grow_in_place(&mut self, - ptr: NonNull<u8>, - layout: Layout, - new_size: usize) -> Result<(), CannotReallocInPlace> { + unsafe fn grow_in_place( + &mut self, + ptr: NonNull<u8>, + layout: Layout, + new_size: usize, + ) -> Result<(), CannotReallocInPlace> { let _ = ptr; // this default implementation doesn't care about the actual address. debug_assert!(new_size >= layout.size()); let (_l, u) = self.usable_size(&layout); // _l <= layout.size() [guaranteed by usable_size()] // layout.size() <= new_layout.size() [required by this method] - if new_size <= u { - Ok(()) - } else { - Err(CannotReallocInPlace) - } + if new_size <= u { Ok(()) } else { Err(CannotReallocInPlace) } } /// Attempts to shrink the allocation referenced by `ptr` to fit `new_size`. @@ -1024,23 +1009,20 @@ pub unsafe trait Alloc { /// function; clients are expected either to be able to recover from /// `shrink_in_place` failures without aborting, or to fall back /// on another reallocation method before resorting to an abort. - unsafe fn shrink_in_place(&mut self, - ptr: NonNull<u8>, - layout: Layout, - new_size: usize) -> Result<(), CannotReallocInPlace> { + unsafe fn shrink_in_place( + &mut self, + ptr: NonNull<u8>, + layout: Layout, + new_size: usize, + ) -> Result<(), CannotReallocInPlace> { let _ = ptr; // this default implementation doesn't care about the actual address. debug_assert!(new_size <= layout.size()); let (l, _u) = self.usable_size(&layout); // layout.size() <= _u [guaranteed by usable_size()] // new_layout.size() <= layout.size() [required by this method] - if l <= new_size { - Ok(()) - } else { - Err(CannotReallocInPlace) - } + if l <= new_size { Ok(()) } else { Err(CannotReallocInPlace) } } - // == COMMON USAGE PATTERNS == // alloc_one, dealloc_one, alloc_array, realloc_array. dealloc_array @@ -1074,14 +1056,11 @@ pub unsafe trait Alloc { /// /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html fn alloc_one<T>(&mut self) -> Result<NonNull<T>, AllocErr> - where Self: Sized + where + Self: Sized, { let k = Layout::new::<T>(); - if k.size() > 0 { - unsafe { self.alloc(k).map(|p| p.cast()) } - } else { - Err(AllocErr) - } + if k.size() > 0 { unsafe { self.alloc(k).map(|p| p.cast()) } } else { Err(AllocErr) } } /// Deallocates a block suitable for holding an instance of `T`. @@ -1102,7 +1081,8 @@ pub unsafe trait Alloc { /// /// * the layout of `T` must *fit* that block of memory. unsafe fn dealloc_one<T>(&mut self, ptr: NonNull<T>) - where Self: Sized + where + Self: Sized, { let k = Layout::new::<T>(); if k.size() > 0 { @@ -1143,14 +1123,11 @@ pub unsafe trait Alloc { /// /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html fn alloc_array<T>(&mut self, n: usize) -> Result<NonNull<T>, AllocErr> - where Self: Sized + where + Self: Sized, { match Layout::array::<T>(n) { - Ok(layout) if layout.size() > 0 => { - unsafe { - self.alloc(layout).map(|p| p.cast()) - } - } + Ok(layout) if layout.size() > 0 => unsafe { self.alloc(layout).map(|p| p.cast()) }, _ => Err(AllocErr), } } @@ -1189,20 +1166,21 @@ pub unsafe trait Alloc { /// rather than directly invoking `panic!` or similar. /// /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html - unsafe fn realloc_array<T>(&mut self, - ptr: NonNull<T>, - n_old: usize, - n_new: usize) -> Result<NonNull<T>, AllocErr> - where Self: Sized + unsafe fn realloc_array<T>( + &mut self, + ptr: NonNull<T>, + n_old: usize, + n_new: usize, + ) -> Result<NonNull<T>, AllocErr> + where + Self: Sized, { match (Layout::array::<T>(n_old), Layout::array::<T>(n_new)) { (Ok(k_old), Ok(k_new)) if k_old.size() > 0 && k_new.size() > 0 => { debug_assert!(k_old.align() == k_new.align()); self.realloc(ptr.cast(), k_old, k_new.size()).map(NonNull::cast) } - _ => { - Err(AllocErr) - } + _ => Err(AllocErr), } } @@ -1227,15 +1205,12 @@ pub unsafe trait Alloc { /// /// Always returns `Err` on arithmetic overflow. unsafe fn dealloc_array<T>(&mut self, ptr: NonNull<T>, n: usize) -> Result<(), AllocErr> - where Self: Sized + where + Self: Sized, { match Layout::array::<T>(n) { - Ok(k) if k.size() > 0 => { - Ok(self.dealloc(ptr.cast(), k)) - } - _ => { - Err(AllocErr) - } + Ok(k) if k.size() > 0 => Ok(self.dealloc(ptr.cast(), k)), + _ => Err(AllocErr), } } } diff --git a/src/libcore/any.rs b/src/libcore/any.rs index 5126fe01a3f..4afea12a362 100644 --- a/src/libcore/any.rs +++ b/src/libcore/any.rs @@ -105,8 +105,10 @@ pub trait Any: 'static { } #[stable(feature = "rust1", since = "1.0.0")] -impl<T: 'static + ?Sized > Any for T { - fn type_id(&self) -> TypeId { TypeId::of::<T>() } +impl<T: 'static + ?Sized> Any for T { + fn type_id(&self) -> TypeId { + TypeId::of::<T>() + } } /////////////////////////////////////////////////////////////////////////////// @@ -193,9 +195,7 @@ impl dyn Any { pub fn downcast_ref<T: Any>(&self) -> Option<&T> { if self.is::<T>() { // SAFETY: just checked whether we are pointing to the correct type - unsafe { - Some(&*(self as *const dyn Any as *const T)) - } + unsafe { Some(&*(self as *const dyn Any as *const T)) } } else { None } @@ -229,16 +229,14 @@ impl dyn Any { pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> { if self.is::<T>() { // SAFETY: just checked whether we are pointing to the correct type - unsafe { - Some(&mut *(self as *mut dyn Any as *mut T)) - } + unsafe { Some(&mut *(self as *mut dyn Any as *mut T)) } } else { None } } } -impl dyn Any+Send { +impl dyn Any + Send { /// Forwards to the method defined on the type `Any`. /// /// # Examples @@ -316,7 +314,7 @@ impl dyn Any+Send { } } -impl dyn Any+Send+Sync { +impl dyn Any + Send + Sync { /// Forwards to the method defined on the type `Any`. /// /// # Examples @@ -433,11 +431,9 @@ impl TypeId { /// assert_eq!(is_string(&"cookie monster".to_string()), true); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature="const_type_id", issue = "41875")] + #[rustc_const_unstable(feature = "const_type_id", issue = "41875")] pub const fn of<T: ?Sized + 'static>() -> TypeId { - TypeId { - t: intrinsics::type_id::<T>(), - } + TypeId { t: intrinsics::type_id::<T>() } } } diff --git a/src/libcore/array/iter.rs b/src/libcore/array/iter.rs index aab9463e3aa..80eaae0d4af 100644 --- a/src/libcore/array/iter.rs +++ b/src/libcore/array/iter.rs @@ -1,5 +1,6 @@ //! Defines the `IntoIter` owned iterator for arrays. +use super::LengthAtMost32; use crate::{ fmt, iter::{ExactSizeIterator, FusedIterator, TrustedLen}, @@ -7,8 +8,6 @@ use crate::{ ops::Range, ptr, }; -use super::LengthAtMost32; - /// A by-value [array] iterator. /// @@ -40,7 +39,7 @@ where alive: Range<usize>, } -impl<T, const N: usize> IntoIter<T, {N}> +impl<T, const N: usize> IntoIter<T, { N }> where [T; N]: LengthAtMost32, { @@ -75,10 +74,7 @@ where data }; - Self { - data, - alive: 0..N, - } + Self { data, alive: 0..N } } /// Returns an immutable slice of all elements that have not been yielded @@ -88,9 +84,7 @@ where // SAFETY: This transmute is safe. As mentioned in `new`, `MaybeUninit` retains // the size and alignment of `T`. Furthermore, we know that all // elements within `alive` are properly initialized. - unsafe { - mem::transmute::<&[MaybeUninit<T>], &[T]>(slice) - } + unsafe { mem::transmute::<&[MaybeUninit<T>], &[T]>(slice) } } /// Returns a mutable slice of all elements that have not been yielded yet. @@ -100,15 +94,12 @@ where // SAFETY: This transmute is safe. As mentioned in `new`, `MaybeUninit` retains // the size and alignment of `T`. Furthermore, we know that all // elements within `alive` are properly initialized. - unsafe { - mem::transmute::<&mut [MaybeUninit<T>], &mut [T]>(slice) - } + unsafe { mem::transmute::<&mut [MaybeUninit<T>], &mut [T]>(slice) } } } - #[stable(feature = "array_value_iter_impls", since = "1.40.0")] -impl<T, const N: usize> Iterator for IntoIter<T, {N}> +impl<T, const N: usize> Iterator for IntoIter<T, { N }> where [T; N]: LengthAtMost32, { @@ -155,7 +146,7 @@ where } #[stable(feature = "array_value_iter_impls", since = "1.40.0")] -impl<T, const N: usize> DoubleEndedIterator for IntoIter<T, {N}> +impl<T, const N: usize> DoubleEndedIterator for IntoIter<T, { N }> where [T; N]: LengthAtMost32, { @@ -191,7 +182,7 @@ where } #[stable(feature = "array_value_iter_impls", since = "1.40.0")] -impl<T, const N: usize> Drop for IntoIter<T, {N}> +impl<T, const N: usize> Drop for IntoIter<T, { N }> where [T; N]: LengthAtMost32, { @@ -199,14 +190,12 @@ where // SAFETY: This is safe: `as_mut_slice` returns exactly the sub-slice // of elements that have not been moved out yet and that remain // to be dropped. - unsafe { - ptr::drop_in_place(self.as_mut_slice()) - } + unsafe { ptr::drop_in_place(self.as_mut_slice()) } } } #[stable(feature = "array_value_iter_impls", since = "1.40.0")] -impl<T, const N: usize> ExactSizeIterator for IntoIter<T, {N}> +impl<T, const N: usize> ExactSizeIterator for IntoIter<T, { N }> where [T; N]: LengthAtMost32, { @@ -221,23 +210,17 @@ where } #[stable(feature = "array_value_iter_impls", since = "1.40.0")] -impl<T, const N: usize> FusedIterator for IntoIter<T, {N}> -where - [T; N]: LengthAtMost32, -{} +impl<T, const N: usize> FusedIterator for IntoIter<T, { N }> where [T; N]: LengthAtMost32 {} // The iterator indeed reports the correct length. The number of "alive" // elements (that will still be yielded) is the length of the range `alive`. // This range is decremented in length in either `next` or `next_back`. It is // always decremented by 1 in those methods, but only if `Some(_)` is returned. #[stable(feature = "array_value_iter_impls", since = "1.40.0")] -unsafe impl<T, const N: usize> TrustedLen for IntoIter<T, {N}> -where - [T; N]: LengthAtMost32, -{} +unsafe impl<T, const N: usize> TrustedLen for IntoIter<T, { N }> where [T; N]: LengthAtMost32 {} #[stable(feature = "array_value_iter_impls", since = "1.40.0")] -impl<T: Clone, const N: usize> Clone for IntoIter<T, {N}> +impl<T: Clone, const N: usize> Clone for IntoIter<T, { N }> where [T; N]: LengthAtMost32, { @@ -260,24 +243,19 @@ where new_data.get_unchecked_mut(idx).write(clone); } - Self { - data: new_data, - alive: self.alive.clone(), - } + Self { data: new_data, alive: self.alive.clone() } } } } #[stable(feature = "array_value_iter_impls", since = "1.40.0")] -impl<T: fmt::Debug, const N: usize> fmt::Debug for IntoIter<T, {N}> +impl<T: fmt::Debug, const N: usize> fmt::Debug for IntoIter<T, { N }> where [T; N]: LengthAtMost32, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // Only print the elements that were not yielded yet: we cannot // access the yielded elements anymore. - f.debug_tuple("IntoIter") - .field(&self.as_slice()) - .finish() + f.debug_tuple("IntoIter").field(&self.as_slice()).finish() } } diff --git a/src/libcore/array/mod.rs b/src/libcore/array/mod.rs index fd80000b6fb..937451274cf 100644 --- a/src/libcore/array/mod.rs +++ b/src/libcore/array/mod.rs @@ -10,7 +10,7 @@ use crate::borrow::{Borrow, BorrowMut}; use crate::cmp::Ordering; use crate::convert::{Infallible, TryFrom}; use crate::fmt; -use crate::hash::{Hash, self}; +use crate::hash::{self, Hash}; use crate::marker::Unsize; use crate::slice::{Iter, IterMut}; @@ -71,10 +71,12 @@ impl fmt::Display for TryFromSliceError { } impl TryFromSliceError { - #[unstable(feature = "array_error_internals", - reason = "available through Error trait and this method should not \ + #[unstable( + feature = "array_error_internals", + reason = "available through Error trait and this method should not \ be exposed publicly", - issue = "none")] + issue = "none" + )] #[inline] #[doc(hidden)] pub fn __description(&self) -> &str { @@ -385,11 +387,12 @@ where } /// Implemented for lengths where trait impls are allowed on arrays in core/std -#[rustc_on_unimplemented( - message="arrays only have std trait implementations for lengths 0..=32", +#[rustc_on_unimplemented(message = "arrays only have std trait implementations for lengths 0..=32")] +#[unstable( + feature = "const_generic_impls_guard", + issue = "none", + reason = "will never be stable, just a temporary step until const generics are stable" )] -#[unstable(feature = "const_generic_impls_guard", issue = "none", - reason = "will never be stable, just a temporary step until const generics are stable")] pub trait LengthAtMost32 {} macro_rules! array_impls { @@ -429,4 +432,4 @@ macro_rules! array_impl_default { }; } -array_impl_default!{32, T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T} +array_impl_default! {32, T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T} diff --git a/src/libcore/benches/pattern.rs b/src/libcore/benches/pattern.rs index a49490cec12..480ac6f36d2 100644 --- a/src/libcore/benches/pattern.rs +++ b/src/libcore/benches/pattern.rs @@ -21,7 +21,6 @@ fn starts_with_str(b: &mut Bencher) { }) } - #[bench] fn ends_with_char(b: &mut Bencher) { let text = black_box("kdjsfhlakfhlsghlkvcnljknfqiunvcijqenwodind"); diff --git a/src/libcore/borrow.rs b/src/libcore/borrow.rs index 4d58aaca941..3e533255bec 100644 --- a/src/libcore/borrow.rs +++ b/src/libcore/borrow.rs @@ -189,7 +189,7 @@ pub trait Borrow<Borrowed: ?Sized> { /// /// [`Borrow<T>`]: trait.Borrow.html #[stable(feature = "rust1", since = "1.0.0")] -pub trait BorrowMut<Borrowed: ?Sized> : Borrow<Borrowed> { +pub trait BorrowMut<Borrowed: ?Sized>: Borrow<Borrowed> { /// Mutably borrows from an owned value. /// /// # Examples @@ -211,25 +211,35 @@ pub trait BorrowMut<Borrowed: ?Sized> : Borrow<Borrowed> { #[stable(feature = "rust1", since = "1.0.0")] impl<T: ?Sized> Borrow<T> for T { - fn borrow(&self) -> &T { self } + fn borrow(&self) -> &T { + self + } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: ?Sized> BorrowMut<T> for T { - fn borrow_mut(&mut self) -> &mut T { self } + fn borrow_mut(&mut self) -> &mut T { + self + } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: ?Sized> Borrow<T> for &T { - fn borrow(&self) -> &T { &**self } + fn borrow(&self) -> &T { + &**self + } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: ?Sized> Borrow<T> for &mut T { - fn borrow(&self) -> &T { &**self } + fn borrow(&self) -> &T { + &**self + } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: ?Sized> BorrowMut<T> for &mut T { - fn borrow_mut(&mut self) -> &mut T { &mut **self } + fn borrow_mut(&mut self) -> &mut T { + &mut **self + } } diff --git a/src/libcore/cell.rs b/src/libcore/cell.rs index 099e5307f64..4fcd0d9737d 100644 --- a/src/libcore/cell.rs +++ b/src/libcore/cell.rs @@ -195,7 +195,7 @@ use crate::cmp::Ordering; use crate::fmt::{self, Debug, Display}; use crate::marker::Unsize; use crate::mem; -use crate::ops::{Deref, DerefMut, CoerceUnsized}; +use crate::ops::{CoerceUnsized, Deref, DerefMut}; use crate::ptr; /// A mutable memory location. @@ -243,7 +243,7 @@ unsafe impl<T: ?Sized> Send for Cell<T> where T: Send {} impl<T: ?Sized> !Sync for Cell<T> {} #[stable(feature = "rust1", since = "1.0.0")] -impl<T:Copy> Clone for Cell<T> { +impl<T: Copy> Clone for Cell<T> { #[inline] fn clone(&self) -> Cell<T> { Cell::new(self.get()) @@ -327,9 +327,7 @@ impl<T> Cell<T> { #[rustc_const_stable(feature = "const_cell_new", since = "1.32.0")] #[inline] pub const fn new(value: T) -> Cell<T> { - Cell { - value: UnsafeCell::new(value), - } + Cell { value: UnsafeCell::new(value) } } /// Sets the contained value. @@ -410,7 +408,7 @@ impl<T> Cell<T> { } } -impl<T:Copy> Cell<T> { +impl<T: Copy> Cell<T> { /// Returns a copy of the contained value. /// /// # Examples @@ -425,7 +423,7 @@ impl<T:Copy> Cell<T> { #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn get(&self) -> T { - unsafe{ *self.value.get() } + unsafe { *self.value.get() } } /// Updates the contained value using a function and returns the new value. @@ -493,9 +491,7 @@ impl<T: ?Sized> Cell<T> { #[inline] #[stable(feature = "cell_get_mut", since = "1.11.0")] pub fn get_mut(&mut self) -> &mut T { - unsafe { - &mut *self.value.get() - } + unsafe { &mut *self.value.get() } } /// Returns a `&Cell<T>` from a `&mut T` @@ -514,9 +510,7 @@ impl<T: ?Sized> Cell<T> { #[inline] #[stable(feature = "as_cell", since = "1.37.0")] pub fn from_mut(t: &mut T) -> &Cell<T> { - unsafe { - &*(t as *mut T as *const Cell<T>) - } + unsafe { &*(t as *mut T as *const Cell<T>) } } } @@ -559,9 +553,7 @@ impl<T> Cell<[T]> { /// ``` #[stable(feature = "as_cell", since = "1.37.0")] pub fn as_slice_of_cells(&self) -> &[Cell<T>] { - unsafe { - &*(self as *const Cell<[T]> as *const [Cell<T>]) - } + unsafe { &*(self as *const Cell<[T]> as *const [Cell<T>]) } } } @@ -654,10 +646,7 @@ impl<T> RefCell<T> { #[rustc_const_stable(feature = "const_refcell_new", since = "1.32.0")] #[inline] pub const fn new(value: T) -> RefCell<T> { - RefCell { - value: UnsafeCell::new(value), - borrow: Cell::new(UNUSED), - } + RefCell { value: UnsafeCell::new(value), borrow: Cell::new(UNUSED) } } /// Consumes the `RefCell`, returning the wrapped value. @@ -700,7 +689,7 @@ impl<T> RefCell<T> { /// assert_eq!(cell, RefCell::new(6)); /// ``` #[inline] - #[stable(feature = "refcell_replace", since="1.24.0")] + #[stable(feature = "refcell_replace", since = "1.24.0")] pub fn replace(&self, t: T) -> T { mem::replace(&mut *self.borrow_mut(), t) } @@ -722,7 +711,7 @@ impl<T> RefCell<T> { /// assert_eq!(cell, RefCell::new(6)); /// ``` #[inline] - #[stable(feature = "refcell_replace_swap", since="1.35.0")] + #[stable(feature = "refcell_replace_swap", since = "1.35.0")] pub fn replace_with<F: FnOnce(&mut T) -> T>(&self, f: F) -> T { let mut_borrow = &mut *self.borrow_mut(); let replacement = f(mut_borrow); @@ -749,7 +738,7 @@ impl<T> RefCell<T> { /// assert_eq!(d, RefCell::new(5)); /// ``` #[inline] - #[stable(feature = "refcell_swap", since="1.24.0")] + #[stable(feature = "refcell_swap", since = "1.24.0")] pub fn swap(&self, other: &Self) { mem::swap(&mut *self.borrow_mut(), &mut *other.borrow_mut()) } @@ -827,10 +816,7 @@ impl<T: ?Sized> RefCell<T> { #[inline] pub fn try_borrow(&self) -> Result<Ref<'_, T>, BorrowError> { match BorrowRef::new(&self.borrow) { - Some(b) => Ok(Ref { - value: unsafe { &*self.value.get() }, - borrow: b, - }), + Some(b) => Ok(Ref { value: unsafe { &*self.value.get() }, borrow: b }), None => Err(BorrowError { _private: () }), } } @@ -905,10 +891,7 @@ impl<T: ?Sized> RefCell<T> { #[inline] pub fn try_borrow_mut(&self) -> Result<RefMut<'_, T>, BorrowMutError> { match BorrowRefMut::new(&self.borrow) { - Some(b) => Ok(RefMut { - value: unsafe { &mut *self.value.get() }, - borrow: b, - }), + Some(b) => Ok(RefMut { value: unsafe { &mut *self.value.get() }, borrow: b }), None => Err(BorrowMutError { _private: () }), } } @@ -957,9 +940,7 @@ impl<T: ?Sized> RefCell<T> { #[inline] #[stable(feature = "cell_get_mut", since = "1.11.0")] pub fn get_mut(&mut self) -> &mut T { - unsafe { - &mut *self.value.get() - } + unsafe { &mut *self.value.get() } } /// Immutably borrows the wrapped value, returning an error if the value is @@ -1189,10 +1170,7 @@ impl<'b, T: ?Sized> Ref<'b, T> { #[stable(feature = "cell_extras", since = "1.15.0")] #[inline] pub fn clone(orig: &Ref<'b, T>) -> Ref<'b, T> { - Ref { - value: orig.value, - borrow: orig.borrow.clone(), - } + Ref { value: orig.value, borrow: orig.borrow.clone() } } /// Makes a new `Ref` for a component of the borrowed data. @@ -1216,12 +1194,10 @@ impl<'b, T: ?Sized> Ref<'b, T> { #[stable(feature = "cell_map", since = "1.8.0")] #[inline] pub fn map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Ref<'b, U> - where F: FnOnce(&T) -> &U + where + F: FnOnce(&T) -> &U, { - Ref { - value: f(orig.value), - borrow: orig.borrow, - } + Ref { value: f(orig.value), borrow: orig.borrow } } /// Splits a `Ref` into multiple `Ref`s for different components of the @@ -1247,7 +1223,8 @@ impl<'b, T: ?Sized> Ref<'b, T> { #[stable(feature = "refcell_map_split", since = "1.35.0")] #[inline] pub fn map_split<U: ?Sized, V: ?Sized, F>(orig: Ref<'b, T>, f: F) -> (Ref<'b, U>, Ref<'b, V>) - where F: FnOnce(&T) -> (&U, &V) + where + F: FnOnce(&T) -> (&U, &V), { let (a, b) = f(orig.value); let borrow = orig.borrow.clone(); @@ -1292,14 +1269,12 @@ impl<'b, T: ?Sized> RefMut<'b, T> { #[stable(feature = "cell_map", since = "1.8.0")] #[inline] pub fn map<U: ?Sized, F>(orig: RefMut<'b, T>, f: F) -> RefMut<'b, U> - where F: FnOnce(&mut T) -> &mut U + where + F: FnOnce(&mut T) -> &mut U, { // FIXME(nll-rfc#40): fix borrow-check let RefMut { value, borrow } = orig; - RefMut { - value: f(value), - borrow, - } + RefMut { value: f(value), borrow } } /// Splits a `RefMut` into multiple `RefMut`s for different components of the @@ -1330,9 +1305,11 @@ impl<'b, T: ?Sized> RefMut<'b, T> { #[stable(feature = "refcell_map_split", since = "1.35.0")] #[inline] pub fn map_split<U: ?Sized, V: ?Sized, F>( - orig: RefMut<'b, T>, f: F + orig: RefMut<'b, T>, + f: F, ) -> (RefMut<'b, U>, RefMut<'b, V>) - where F: FnOnce(&mut T) -> (&mut U, &mut V) + where + F: FnOnce(&mut T) -> (&mut U, &mut V), { let (a, b) = f(orig.value); let borrow = orig.borrow.clone(); @@ -1364,7 +1341,7 @@ impl<'b> BorrowRefMut<'b> { UNUSED => { borrow.set(UNUSED - 1); Some(BorrowRefMut { borrow }) - }, + } _ => None, } } diff --git a/src/libcore/cmp.rs b/src/libcore/cmp.rs index a0e72fb66b0..0d4788dfc57 100644 --- a/src/libcore/cmp.rs +++ b/src/libcore/cmp.rs @@ -195,8 +195,8 @@ use self::Ordering::*; #[doc(alias = "==")] #[doc(alias = "!=")] #[rustc_on_unimplemented( - message="can't compare `{Self}` with `{Rhs}`", - label="no implementation for `{Self} == {Rhs}`", + message = "can't compare `{Self}` with `{Rhs}`", + label = "no implementation for `{Self} == {Rhs}`" )] pub trait PartialEq<Rhs: ?Sized = Self> { /// This method tests for `self` and `other` values to be equal, and is used @@ -209,14 +209,18 @@ pub trait PartialEq<Rhs: ?Sized = Self> { #[inline] #[must_use] #[stable(feature = "rust1", since = "1.0.0")] - fn ne(&self, other: &Rhs) -> bool { !self.eq(other) } + fn ne(&self, other: &Rhs) -> bool { + !self.eq(other) + } } /// Derive macro generating an impl of the trait `PartialEq`. #[rustc_builtin_macro] #[stable(feature = "builtin_macro_prelude", since = "1.38.0")] #[allow_internal_unstable(core_intrinsics, structural_match)] -pub macro PartialEq($item:item) { /* compiler built-in */ } +pub macro PartialEq($item:item) { + /* compiler built-in */ +} /// Trait for equality comparisons which are [equivalence relations]( /// https://en.wikipedia.org/wiki/Equivalence_relation). @@ -278,7 +282,9 @@ pub trait Eq: PartialEq<Self> { #[rustc_builtin_macro] #[stable(feature = "builtin_macro_prelude", since = "1.38.0")] #[allow_internal_unstable(core_intrinsics, derive_eq, structural_match)] -pub macro Eq($item:item) { /* compiler built-in */ } +pub macro Eq($item:item) { + /* compiler built-in */ +} // FIXME: this struct is used solely by #[derive] to // assert that every component of a type implements Eq. @@ -286,10 +292,10 @@ pub macro Eq($item:item) { /* compiler built-in */ } // This struct should never appear in user code. #[doc(hidden)] #[allow(missing_debug_implementations)] -#[unstable(feature = "derive_eq", - reason = "deriving hack, should not be public", - issue = "none")] -pub struct AssertParamIsEq<T: Eq + ?Sized> { _field: crate::marker::PhantomData<T> } +#[unstable(feature = "derive_eq", reason = "deriving hack, should not be public", issue = "none")] +pub struct AssertParamIsEq<T: Eq + ?Sized> { + _field: crate::marker::PhantomData<T>, +} /// An `Ordering` is the result of a comparison between two values. /// @@ -460,13 +466,21 @@ impl<T: PartialOrd> PartialOrd for Reverse<T> { } #[inline] - fn lt(&self, other: &Self) -> bool { other.0 < self.0 } + fn lt(&self, other: &Self) -> bool { + other.0 < self.0 + } #[inline] - fn le(&self, other: &Self) -> bool { other.0 <= self.0 } + fn le(&self, other: &Self) -> bool { + other.0 <= self.0 + } #[inline] - fn gt(&self, other: &Self) -> bool { other.0 > self.0 } + fn gt(&self, other: &Self) -> bool { + other.0 > self.0 + } #[inline] - fn ge(&self, other: &Self) -> bool { other.0 >= self.0 } + fn ge(&self, other: &Self) -> bool { + other.0 >= self.0 + } } #[stable(feature = "reverse_cmp_key", since = "1.19.0")] @@ -570,7 +584,9 @@ pub trait Ord: Eq + PartialOrd<Self> { #[stable(feature = "ord_max_min", since = "1.21.0")] #[inline] fn max(self, other: Self) -> Self - where Self: Sized { + where + Self: Sized, + { max_by(self, other, Ord::cmp) } @@ -587,7 +603,9 @@ pub trait Ord: Eq + PartialOrd<Self> { #[stable(feature = "ord_max_min", since = "1.21.0")] #[inline] fn min(self, other: Self) -> Self - where Self: Sized { + where + Self: Sized, + { min_by(self, other, Ord::cmp) } @@ -611,7 +629,9 @@ pub trait Ord: Eq + PartialOrd<Self> { /// ``` #[unstable(feature = "clamp", issue = "44095")] fn clamp(self, min: Self, max: Self) -> Self - where Self: Sized { + where + Self: Sized, + { assert!(min <= max); if self < min { min @@ -627,7 +647,9 @@ pub trait Ord: Eq + PartialOrd<Self> { #[rustc_builtin_macro] #[stable(feature = "builtin_macro_prelude", since = "1.38.0")] #[allow_internal_unstable(core_intrinsics)] -pub macro Ord($item:item) { /* compiler built-in */ } +pub macro Ord($item:item) { + /* compiler built-in */ +} #[stable(feature = "rust1", since = "1.0.0")] impl Eq for Ordering {} @@ -753,8 +775,8 @@ impl PartialOrd for Ordering { #[doc(alias = "<=")] #[doc(alias = ">=")] #[rustc_on_unimplemented( - message="can't compare `{Self}` with `{Rhs}`", - label="no implementation for `{Self} < {Rhs}` and `{Self} > {Rhs}`", + message = "can't compare `{Self}` with `{Rhs}`", + label = "no implementation for `{Self} < {Rhs}` and `{Self} > {Rhs}`" )] pub trait PartialOrd<Rhs: ?Sized = Self>: PartialEq<Rhs> { /// This method returns an ordering between `self` and `other` values if one exists. @@ -875,7 +897,9 @@ pub trait PartialOrd<Rhs: ?Sized = Self>: PartialEq<Rhs> { #[rustc_builtin_macro] #[stable(feature = "builtin_macro_prelude", since = "1.38.0")] #[allow_internal_unstable(core_intrinsics)] -pub macro PartialOrd($item:item) { /* compiler built-in */ } +pub macro PartialOrd($item:item) { + /* compiler built-in */ +} /// Compares and returns the minimum of two values. /// @@ -1005,8 +1029,8 @@ pub fn max_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T { // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types mod impls { + use crate::cmp::Ordering::{self, Equal, Greater, Less}; use crate::hint::unreachable_unchecked; - use crate::cmp::Ordering::{self, Less, Greater, Equal}; macro_rules! partial_eq_impl { ($($t:ty)*) => ($( @@ -1023,9 +1047,13 @@ mod impls { #[stable(feature = "rust1", since = "1.0.0")] impl PartialEq for () { #[inline] - fn eq(&self, _other: &()) -> bool { true } + fn eq(&self, _other: &()) -> bool { + true + } #[inline] - fn ne(&self, _other: &()) -> bool { false } + fn ne(&self, _other: &()) -> bool { + false + } } partial_eq_impl! { @@ -1119,7 +1147,9 @@ mod impls { #[stable(feature = "rust1", since = "1.0.0")] impl Ord for () { #[inline] - fn cmp(&self, _other: &()) -> Ordering { Equal } + fn cmp(&self, _other: &()) -> Ordering { + Equal + } } #[stable(feature = "rust1", since = "1.0.0")] @@ -1168,31 +1198,54 @@ mod impls { // & pointers #[stable(feature = "rust1", since = "1.0.0")] - impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &A where A: PartialEq<B> { + impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &A + where + A: PartialEq<B>, + { #[inline] - fn eq(&self, other: & &B) -> bool { PartialEq::eq(*self, *other) } + fn eq(&self, other: &&B) -> bool { + PartialEq::eq(*self, *other) + } #[inline] - fn ne(&self, other: & &B) -> bool { PartialEq::ne(*self, *other) } + fn ne(&self, other: &&B) -> bool { + PartialEq::ne(*self, *other) + } } #[stable(feature = "rust1", since = "1.0.0")] - impl<A: ?Sized, B: ?Sized> PartialOrd<&B> for &A where A: PartialOrd<B> { + impl<A: ?Sized, B: ?Sized> PartialOrd<&B> for &A + where + A: PartialOrd<B>, + { #[inline] fn partial_cmp(&self, other: &&B) -> Option<Ordering> { PartialOrd::partial_cmp(*self, *other) } #[inline] - fn lt(&self, other: & &B) -> bool { PartialOrd::lt(*self, *other) } + fn lt(&self, other: &&B) -> bool { + PartialOrd::lt(*self, *other) + } #[inline] - fn le(&self, other: & &B) -> bool { PartialOrd::le(*self, *other) } + fn le(&self, other: &&B) -> bool { + PartialOrd::le(*self, *other) + } #[inline] - fn gt(&self, other: & &B) -> bool { PartialOrd::gt(*self, *other) } + fn gt(&self, other: &&B) -> bool { + PartialOrd::gt(*self, *other) + } #[inline] - fn ge(&self, other: & &B) -> bool { PartialOrd::ge(*self, *other) } + fn ge(&self, other: &&B) -> bool { + PartialOrd::ge(*self, *other) + } } #[stable(feature = "rust1", since = "1.0.0")] - impl<A: ?Sized> Ord for &A where A: Ord { + impl<A: ?Sized> Ord for &A + where + A: Ord, + { #[inline] - fn cmp(&self, other: &Self) -> Ordering { Ord::cmp(*self, *other) } + fn cmp(&self, other: &Self) -> Ordering { + Ord::cmp(*self, *other) + } } #[stable(feature = "rust1", since = "1.0.0")] impl<A: ?Sized> Eq for &A where A: Eq {} @@ -1200,48 +1253,85 @@ mod impls { // &mut pointers #[stable(feature = "rust1", since = "1.0.0")] - impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &mut A where A: PartialEq<B> { + impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &mut A + where + A: PartialEq<B>, + { #[inline] - fn eq(&self, other: &&mut B) -> bool { PartialEq::eq(*self, *other) } + fn eq(&self, other: &&mut B) -> bool { + PartialEq::eq(*self, *other) + } #[inline] - fn ne(&self, other: &&mut B) -> bool { PartialEq::ne(*self, *other) } + fn ne(&self, other: &&mut B) -> bool { + PartialEq::ne(*self, *other) + } } #[stable(feature = "rust1", since = "1.0.0")] - impl<A: ?Sized, B: ?Sized> PartialOrd<&mut B> for &mut A where A: PartialOrd<B> { + impl<A: ?Sized, B: ?Sized> PartialOrd<&mut B> for &mut A + where + A: PartialOrd<B>, + { #[inline] fn partial_cmp(&self, other: &&mut B) -> Option<Ordering> { PartialOrd::partial_cmp(*self, *other) } #[inline] - fn lt(&self, other: &&mut B) -> bool { PartialOrd::lt(*self, *other) } + fn lt(&self, other: &&mut B) -> bool { + PartialOrd::lt(*self, *other) + } #[inline] - fn le(&self, other: &&mut B) -> bool { PartialOrd::le(*self, *other) } + fn le(&self, other: &&mut B) -> bool { + PartialOrd::le(*self, *other) + } #[inline] - fn gt(&self, other: &&mut B) -> bool { PartialOrd::gt(*self, *other) } + fn gt(&self, other: &&mut B) -> bool { + PartialOrd::gt(*self, *other) + } #[inline] - fn ge(&self, other: &&mut B) -> bool { PartialOrd::ge(*self, *other) } + fn ge(&self, other: &&mut B) -> bool { + PartialOrd::ge(*self, *other) + } } #[stable(feature = "rust1", since = "1.0.0")] - impl<A: ?Sized> Ord for &mut A where A: Ord { + impl<A: ?Sized> Ord for &mut A + where + A: Ord, + { #[inline] - fn cmp(&self, other: &Self) -> Ordering { Ord::cmp(*self, *other) } + fn cmp(&self, other: &Self) -> Ordering { + Ord::cmp(*self, *other) + } } #[stable(feature = "rust1", since = "1.0.0")] impl<A: ?Sized> Eq for &mut A where A: Eq {} #[stable(feature = "rust1", since = "1.0.0")] - impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &A where A: PartialEq<B> { + impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &A + where + A: PartialEq<B>, + { #[inline] - fn eq(&self, other: &&mut B) -> bool { PartialEq::eq(*self, *other) } + fn eq(&self, other: &&mut B) -> bool { + PartialEq::eq(*self, *other) + } #[inline] - fn ne(&self, other: &&mut B) -> bool { PartialEq::ne(*self, *other) } + fn ne(&self, other: &&mut B) -> bool { + PartialEq::ne(*self, *other) + } } #[stable(feature = "rust1", since = "1.0.0")] - impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &mut A where A: PartialEq<B> { + impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &mut A + where + A: PartialEq<B>, + { #[inline] - fn eq(&self, other: &&B) -> bool { PartialEq::eq(*self, *other) } + fn eq(&self, other: &&B) -> bool { + PartialEq::eq(*self, *other) + } #[inline] - fn ne(&self, other: &&B) -> bool { PartialEq::ne(*self, *other) } + fn ne(&self, other: &&B) -> bool { + PartialEq::ne(*self, *other) + } } } diff --git a/src/libcore/fmt/builders.rs b/src/libcore/fmt/builders.rs index e6e3454b36f..626eb1e862d 100644 --- a/src/libcore/fmt/builders.rs +++ b/src/libcore/fmt/builders.rs @@ -11,21 +11,18 @@ struct PadAdapterState { impl Default for PadAdapterState { fn default() -> Self { - PadAdapterState { - on_newline: true, - } + PadAdapterState { on_newline: true } } } impl<'buf, 'state> PadAdapter<'buf, 'state> { - fn wrap<'slot, 'fmt: 'buf+'slot>(fmt: &'fmt mut fmt::Formatter<'_>, - slot: &'slot mut Option<Self>, - state: &'state mut PadAdapterState) -> fmt::Formatter<'slot> { + fn wrap<'slot, 'fmt: 'buf + 'slot>( + fmt: &'fmt mut fmt::Formatter<'_>, + slot: &'slot mut Option<Self>, + state: &'state mut PadAdapterState, + ) -> fmt::Formatter<'slot> { fmt.wrap_buf(move |buf| { - *slot = Some(PadAdapter { - buf, - state, - }); + *slot = Some(PadAdapter { buf, state }); slot.as_mut().unwrap() }) } @@ -98,15 +95,12 @@ pub struct DebugStruct<'a, 'b: 'a> { has_fields: bool, } -pub(super) fn debug_struct_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>, - name: &str) - -> DebugStruct<'a, 'b> { +pub(super) fn debug_struct_new<'a, 'b>( + fmt: &'a mut fmt::Formatter<'b>, + name: &str, +) -> DebugStruct<'a, 'b> { let result = fmt.write_str(name); - DebugStruct { - fmt, - result, - has_fields: false, - } + DebugStruct { fmt, result, has_fields: false } } impl<'a, 'b: 'a> DebugStruct<'a, 'b> { @@ -196,11 +190,7 @@ impl<'a, 'b: 'a> DebugStruct<'a, 'b> { pub fn finish(&mut self) -> fmt::Result { if self.has_fields { self.result = self.result.and_then(|_| { - if self.is_pretty() { - self.fmt.write_str("}") - } else { - self.fmt.write_str(" }") - } + if self.is_pretty() { self.fmt.write_str("}") } else { self.fmt.write_str(" }") } }); } self.result @@ -256,12 +246,7 @@ pub(super) fn debug_tuple_new<'a, 'b>( name: &str, ) -> DebugTuple<'a, 'b> { let result = fmt.write_str(name); - DebugTuple { - fmt, - result, - fields: 0, - empty_name: name.is_empty(), - } + DebugTuple { fmt, result, fields: 0, empty_name: name.is_empty() } } impl<'a, 'b: 'a> DebugTuple<'a, 'b> { @@ -423,13 +408,7 @@ pub struct DebugSet<'a, 'b: 'a> { pub(super) fn debug_set_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugSet<'a, 'b> { let result = fmt.write_str("{"); - DebugSet { - inner: DebugInner { - fmt, - result, - has_fields: false, - }, - } + DebugSet { inner: DebugInner { fmt, result, has_fields: false } } } impl<'a, 'b: 'a> DebugSet<'a, 'b> { @@ -487,8 +466,9 @@ impl<'a, 'b: 'a> DebugSet<'a, 'b> { /// ``` #[stable(feature = "debug_builders", since = "1.2.0")] pub fn entries<D, I>(&mut self, entries: I) -> &mut DebugSet<'a, 'b> - where D: fmt::Debug, - I: IntoIterator<Item = D> + where + D: fmt::Debug, + I: IntoIterator<Item = D>, { for entry in entries { self.entry(&entry); @@ -560,13 +540,7 @@ pub struct DebugList<'a, 'b: 'a> { pub(super) fn debug_list_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugList<'a, 'b> { let result = fmt.write_str("["); - DebugList { - inner: DebugInner { - fmt, - result, - has_fields: false, - }, - } + DebugList { inner: DebugInner { fmt, result, has_fields: false } } } impl<'a, 'b: 'a> DebugList<'a, 'b> { @@ -624,8 +598,9 @@ impl<'a, 'b: 'a> DebugList<'a, 'b> { /// ``` #[stable(feature = "debug_builders", since = "1.2.0")] pub fn entries<D, I>(&mut self, entries: I) -> &mut DebugList<'a, 'b> - where D: fmt::Debug, - I: IntoIterator<Item = D> + where + D: fmt::Debug, + I: IntoIterator<Item = D>, { for entry in entries { self.entry(&entry); @@ -702,13 +677,7 @@ pub struct DebugMap<'a, 'b: 'a> { pub(super) fn debug_map_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugMap<'a, 'b> { let result = fmt.write_str("{"); - DebugMap { - fmt, - result, - has_fields: false, - has_key: false, - state: Default::default(), - } + DebugMap { fmt, result, has_fields: false, has_key: false, state: Default::default() } } impl<'a, 'b: 'a> DebugMap<'a, 'b> { @@ -771,13 +740,14 @@ impl<'a, 'b: 'a> DebugMap<'a, 'b> { /// "{\"whole\": [(\"A\", 10), (\"B\", 11)]}", /// ); /// ``` - #[unstable(feature = "debug_map_key_value", - reason = "recently added", - issue = "62482")] + #[unstable(feature = "debug_map_key_value", reason = "recently added", issue = "62482")] pub fn key(&mut self, key: &dyn fmt::Debug) -> &mut DebugMap<'a, 'b> { self.result = self.result.and_then(|_| { - assert!(!self.has_key, "attempted to begin a new map entry \ - without completing the previous one"); + assert!( + !self.has_key, + "attempted to begin a new map entry \ + without completing the previous one" + ); if self.is_pretty() { if !self.has_fields { @@ -835,9 +805,7 @@ impl<'a, 'b: 'a> DebugMap<'a, 'b> { /// "{\"whole\": [(\"A\", 10), (\"B\", 11)]}", /// ); /// ``` - #[unstable(feature = "debug_map_key_value", - reason = "recently added", - issue = "62482")] + #[unstable(feature = "debug_map_key_value", reason = "recently added", issue = "62482")] pub fn value(&mut self, value: &dyn fmt::Debug) -> &mut DebugMap<'a, 'b> { self.result = self.result.and_then(|_| { assert!(self.has_key, "attempted to format a map value before its key"); @@ -885,9 +853,10 @@ impl<'a, 'b: 'a> DebugMap<'a, 'b> { /// ``` #[stable(feature = "debug_builders", since = "1.2.0")] pub fn entries<K, V, I>(&mut self, entries: I) -> &mut DebugMap<'a, 'b> - where K: fmt::Debug, - V: fmt::Debug, - I: IntoIterator<Item = (K, V)> + where + K: fmt::Debug, + V: fmt::Debug, + I: IntoIterator<Item = (K, V)>, { for (k, v) in entries { self.entry(&k, &v); diff --git a/src/libcore/fmt/num.rs b/src/libcore/fmt/num.rs index 3c7aefc090f..7b20677ffb5 100644 --- a/src/libcore/fmt/num.rs +++ b/src/libcore/fmt/num.rs @@ -2,17 +2,17 @@ // ignore-tidy-undocumented-unsafe - use crate::fmt; +use crate::mem::MaybeUninit; use crate::ops::{Div, Rem, Sub}; -use crate::str; -use crate::slice; use crate::ptr; -use crate::mem::MaybeUninit; +use crate::slice; +use crate::str; #[doc(hidden)] -trait Int: PartialEq + PartialOrd + Div<Output=Self> + Rem<Output=Self> + - Sub<Output=Self> + Copy { +trait Int: + PartialEq + PartialOrd + Div<Output = Self> + Rem<Output = Self> + Sub<Output = Self> + Copy +{ fn zero() -> Self; fn from_u8(u: u8) -> Self; fn to_u8(&self) -> u8; @@ -60,33 +60,32 @@ trait GenericRadix { // Accumulate each digit of the number from the least significant // to the most significant figure. for byte in buf.iter_mut().rev() { - let n = x % base; // Get the current place value. - x = x / base; // Deaccumulate the number. + let n = x % base; // Get the current place value. + x = x / base; // Deaccumulate the number. byte.write(Self::digit(n.to_u8())); // Store the digit in the buffer. curr -= 1; if x == zero { // No more digits left to accumulate. - break + break; }; } } else { // Do the same as above, but accounting for two's complement. for byte in buf.iter_mut().rev() { - let n = zero - (x % base); // Get the current place value. - x = x / base; // Deaccumulate the number. + let n = zero - (x % base); // Get the current place value. + x = x / base; // Deaccumulate the number. byte.write(Self::digit(n.to_u8())); // Store the digit in the buffer. curr -= 1; if x == zero { // No more digits left to accumulate. - break + break; }; } } let buf = &buf[curr..]; - let buf = unsafe { str::from_utf8_unchecked(slice::from_raw_parts( - MaybeUninit::first_ptr(buf), - buf.len() - )) }; + let buf = unsafe { + str::from_utf8_unchecked(slice::from_raw_parts(MaybeUninit::first_ptr(buf), buf.len())) + }; f.pad_integral(is_nonnegative, Self::PREFIX, buf) } } @@ -125,9 +124,9 @@ macro_rules! radix { radix! { Binary, 2, "0b", x @ 0 ..= 1 => b'0' + x } radix! { Octal, 8, "0o", x @ 0 ..= 7 => b'0' + x } radix! { LowerHex, 16, "0x", x @ 0 ..= 9 => b'0' + x, - x @ 10 ..= 15 => b'a' + (x - 10) } +x @ 10 ..= 15 => b'a' + (x - 10) } radix! { UpperHex, 16, "0x", x @ 0 ..= 9 => b'0' + x, - x @ 10 ..= 15 => b'A' + (x - 10) } +x @ 10 ..= 15 => b'A' + (x - 10) } macro_rules! int_base { ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => { @@ -137,7 +136,7 @@ macro_rules! int_base { $Radix.fmt_int(*self as $U, f) } } - } + }; } macro_rules! debug { @@ -155,7 +154,7 @@ macro_rules! debug { } } } - } + }; } macro_rules! integer { @@ -171,7 +170,7 @@ macro_rules! integer { int_base! { LowerHex for $Uint as $Uint -> LowerHex } int_base! { UpperHex for $Uint as $Uint -> UpperHex } debug! { $Uint } - } + }; } integer! { isize, usize } integer! { i8, u8 } @@ -180,9 +179,7 @@ integer! { i32, u32 } integer! { i64, u64 } integer! { i128, u128 } - -static DEC_DIGITS_LUT: &[u8; 200] = - b"0001020304050607080910111213141516171819\ +static DEC_DIGITS_LUT: &[u8; 200] = b"0001020304050607080910111213141516171819\ 2021222324252627282930313233343536373839\ 4041424344454647484950515253545556575859\ 6061626364656667686970717273747576777879\ diff --git a/src/libcore/intrinsics.rs b/src/libcore/intrinsics.rs index e73d125c13f..e6bae4864a4 100644 --- a/src/libcore/intrinsics.rs +++ b/src/libcore/intrinsics.rs @@ -29,18 +29,22 @@ //! guaranteed to happen in order. This is the standard mode for working //! with atomic types and is equivalent to Java's `volatile`. -#![unstable(feature = "core_intrinsics", - reason = "intrinsics are unlikely to ever be stabilized, instead \ +#![unstable( + feature = "core_intrinsics", + reason = "intrinsics are unlikely to ever be stabilized, instead \ they should be used through stabilized interfaces \ in the rest of the standard library", - issue = "none")] + issue = "none" +)] #![allow(missing_docs)] use crate::mem; #[stable(feature = "drop_in_place", since = "1.8.0")] -#[rustc_deprecated(reason = "no longer an intrinsic - use `ptr::drop_in_place` directly", - since = "1.18.0")] +#[rustc_deprecated( + reason = "no longer an intrinsic - use `ptr::drop_in_place` directly", + since = "1.18.0" +)] pub use crate::ptr::drop_in_place; extern "rust-intrinsic" { @@ -705,13 +709,14 @@ extern "rust-intrinsic" { /// which is unsafe unless `T` is `Copy`. Also, even if T is /// `Copy`, an all-zero value may not correspond to any legitimate /// state for the type in question. - #[unstable(feature = "core_intrinsics", - reason = "intrinsics are unlikely to ever be stabilized, instead \ + #[unstable( + feature = "core_intrinsics", + reason = "intrinsics are unlikely to ever be stabilized, instead \ they should be used through stabilized interfaces \ in the rest of the standard library", - issue = "none")] - #[rustc_deprecated(reason = "superseded by MaybeUninit, removal planned", - since = "1.38.0")] + issue = "none" + )] + #[rustc_deprecated(reason = "superseded by MaybeUninit, removal planned", since = "1.38.0")] pub fn init<T>() -> T; /// Creates an uninitialized value. @@ -721,13 +726,14 @@ extern "rust-intrinsic" { /// state, which means it may claim either dropped or /// undropped. In the general case one must use `ptr::write` to /// initialize memory previous set to the result of `uninit`. - #[unstable(feature = "core_intrinsics", - reason = "intrinsics are unlikely to ever be stabilized, instead \ + #[unstable( + feature = "core_intrinsics", + reason = "intrinsics are unlikely to ever be stabilized, instead \ they should be used through stabilized interfaces \ in the rest of the standard library", - issue = "none")] - #[rustc_deprecated(reason = "superseded by MaybeUninit, removal planned", - since = "1.38.0")] + issue = "none" + )] + #[rustc_deprecated(reason = "superseded by MaybeUninit, removal planned", since = "1.38.0")] pub fn uninit<T>() -> T; /// Moves a value out of scope without running drop glue. @@ -985,8 +991,7 @@ extern "rust-intrinsic" { /// /// The volatile parameter is set to `true`, so it will not be optimized out /// unless size is equal to zero. - pub fn volatile_copy_nonoverlapping_memory<T>(dst: *mut T, src: *const T, - count: usize); + pub fn volatile_copy_nonoverlapping_memory<T>(dst: *mut T, src: *const T, count: usize); /// Equivalent to the appropriate `llvm.memmove.p0i8.0i8.*` intrinsic, with /// a size of `count` * `size_of::<T>()` and an alignment of /// `min_align_of::<T>()` @@ -1148,7 +1153,6 @@ extern "rust-intrinsic" { /// https://github.com/rust-lang/rust/issues/10184 pub fn float_to_int_approx_unchecked<Float, Int>(value: Float) -> Int; - /// Returns the number of bits set in an integer type `T` pub fn ctpop<T>(x: T) -> T; @@ -1376,11 +1380,7 @@ fn overlaps<T>(src: *const T, dst: *const T, count: usize) -> bool { let src_usize = src as usize; let dst_usize = dst as usize; let size = mem::size_of::<T>().checked_mul(count).unwrap(); - let diff = if src_usize > dst_usize { - src_usize - dst_usize - } else { - dst_usize - src_usize - }; + let diff = if src_usize > dst_usize { src_usize - dst_usize } else { dst_usize - src_usize }; size > diff } diff --git a/src/libcore/iter/adapters/chain.rs b/src/libcore/iter/adapters/chain.rs index 3b669cad1c4..3611a1aadad 100644 --- a/src/libcore/iter/adapters/chain.rs +++ b/src/libcore/iter/adapters/chain.rs @@ -1,7 +1,7 @@ use crate::ops::Try; use crate::usize; -use super::super::{Iterator, DoubleEndedIterator, FusedIterator, TrustedLen}; +use super::super::{DoubleEndedIterator, FusedIterator, Iterator, TrustedLen}; /// An iterator that links two iterators together, in a chain. /// @@ -48,9 +48,10 @@ enum ChainState { } #[stable(feature = "rust1", since = "1.0.0")] -impl<A, B> Iterator for Chain<A, B> where +impl<A, B> Iterator for Chain<A, B> +where A: Iterator, - B: Iterator<Item = A::Item> + B: Iterator<Item = A::Item>, { type Item = A::Item; @@ -79,8 +80,11 @@ impl<A, B> Iterator for Chain<A, B> where } } - fn try_fold<Acc, F, R>(&mut self, init: Acc, mut f: F) -> R where - Self: Sized, F: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc> + fn try_fold<Acc, F, R>(&mut self, init: Acc, mut f: F) -> R + where + Self: Sized, + F: FnMut(Acc, Self::Item) -> R, + R: Try<Ok = Acc>, { let mut accum = init; match self.state { @@ -90,7 +94,7 @@ impl<A, B> Iterator for Chain<A, B> where self.state = ChainState::Back; } } - _ => { } + _ => {} } if let ChainState::Back = self.state { accum = self.b.try_fold(accum, &mut f)?; @@ -99,20 +103,21 @@ impl<A, B> Iterator for Chain<A, B> where } fn fold<Acc, F>(self, init: Acc, mut f: F) -> Acc - where F: FnMut(Acc, Self::Item) -> Acc, + where + F: FnMut(Acc, Self::Item) -> Acc, { let mut accum = init; match self.state { ChainState::Both | ChainState::Front => { accum = self.a.fold(accum, &mut f); } - _ => { } + _ => {} } match self.state { ChainState::Both | ChainState::Back => { accum = self.b.fold(accum, &mut f); } - _ => { } + _ => {} } accum } @@ -123,7 +128,7 @@ impl<A, B> Iterator for Chain<A, B> where ChainState::Both | ChainState::Front => { for x in self.a.by_ref() { if n == 0 { - return Some(x) + return Some(x); } n -= 1; } @@ -133,15 +138,12 @@ impl<A, B> Iterator for Chain<A, B> where } ChainState::Back => {} } - if let ChainState::Back = self.state { - self.b.nth(n) - } else { - None - } + if let ChainState::Back = self.state { self.b.nth(n) } else { None } } #[inline] - fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where + fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> + where P: FnMut(&Self::Item) -> bool, { match self.state { @@ -150,7 +152,7 @@ impl<A, B> Iterator for Chain<A, B> where self.state = ChainState::Back; self.b.find(predicate) } - v => v + v => v, }, ChainState::Front => self.a.find(predicate), ChainState::Back => self.b.find(predicate), @@ -165,9 +167,9 @@ impl<A, B> Iterator for Chain<A, B> where let a_last = self.a.last(); let b_last = self.b.last(); b_last.or(a_last) - }, + } ChainState::Front => self.a.last(), - ChainState::Back => self.b.last() + ChainState::Back => self.b.last(), } } @@ -182,7 +184,7 @@ impl<A, B> Iterator for Chain<A, B> where let upper = match (a_upper, b_upper) { (Some(x), Some(y)) => x.checked_add(y), - _ => None + _ => None, }; (lower, upper) @@ -194,9 +196,10 @@ impl<A, B> Iterator for Chain<A, B> where } #[stable(feature = "rust1", since = "1.0.0")] -impl<A, B> DoubleEndedIterator for Chain<A, B> where +impl<A, B> DoubleEndedIterator for Chain<A, B> +where A: DoubleEndedIterator, - B: DoubleEndedIterator<Item=A::Item>, + B: DoubleEndedIterator<Item = A::Item>, { #[inline] fn next_back(&mut self) -> Option<A::Item> { @@ -219,7 +222,7 @@ impl<A, B> DoubleEndedIterator for Chain<A, B> where ChainState::Both | ChainState::Back => { for x in self.b.by_ref().rev() { if n == 0 { - return Some(x) + return Some(x); } n -= 1; } @@ -229,15 +232,14 @@ impl<A, B> DoubleEndedIterator for Chain<A, B> where } ChainState::Front => {} } - if let ChainState::Front = self.state { - self.a.nth_back(n) - } else { - None - } + if let ChainState::Front = self.state { self.a.nth_back(n) } else { None } } - fn try_rfold<Acc, F, R>(&mut self, init: Acc, mut f: F) -> R where - Self: Sized, F: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc> + fn try_rfold<Acc, F, R>(&mut self, init: Acc, mut f: F) -> R + where + Self: Sized, + F: FnMut(Acc, Self::Item) -> R, + R: Try<Ok = Acc>, { let mut accum = init; match self.state { @@ -247,7 +249,7 @@ impl<A, B> DoubleEndedIterator for Chain<A, B> where self.state = ChainState::Front; } } - _ => { } + _ => {} } if let ChainState::Front = self.state { accum = self.a.try_rfold(accum, &mut f)?; @@ -256,34 +258,39 @@ impl<A, B> DoubleEndedIterator for Chain<A, B> where } fn rfold<Acc, F>(self, init: Acc, mut f: F) -> Acc - where F: FnMut(Acc, Self::Item) -> Acc, + where + F: FnMut(Acc, Self::Item) -> Acc, { let mut accum = init; match self.state { ChainState::Both | ChainState::Back => { accum = self.b.rfold(accum, &mut f); } - _ => { } + _ => {} } match self.state { ChainState::Both | ChainState::Front => { accum = self.a.rfold(accum, &mut f); } - _ => { } + _ => {} } accum } - } // Note: *both* must be fused to handle double-ended iterators. #[stable(feature = "fused", since = "1.26.0")] impl<A, B> FusedIterator for Chain<A, B> - where A: FusedIterator, - B: FusedIterator<Item=A::Item>, -{} +where + A: FusedIterator, + B: FusedIterator<Item = A::Item>, +{ +} #[unstable(feature = "trusted_len", issue = "37572")] unsafe impl<A, B> TrustedLen for Chain<A, B> - where A: TrustedLen, B: TrustedLen<Item=A::Item>, -{} +where + A: TrustedLen, + B: TrustedLen<Item = A::Item>, +{ +} diff --git a/src/libcore/iter/adapters/zip.rs b/src/libcore/iter/adapters/zip.rs index 14d9d5499b8..b13e12e2e86 100644 --- a/src/libcore/iter/adapters/zip.rs +++ b/src/libcore/iter/adapters/zip.rs @@ -2,7 +2,7 @@ use crate::cmp; -use super::super::{Iterator, DoubleEndedIterator, ExactSizeIterator, FusedIterator, TrustedLen}; +use super::super::{DoubleEndedIterator, ExactSizeIterator, FusedIterator, Iterator, TrustedLen}; /// An iterator that iterates two other iterators simultaneously. /// @@ -27,7 +27,9 @@ impl<A: Iterator, B: Iterator> Zip<A, B> { } fn super_nth(&mut self, mut n: usize) -> Option<(A::Item, B::Item)> { while let Some(x) = Iterator::next(self) { - if n == 0 { return Some(x) } + if n == 0 { + return Some(x); + } n -= 1; } None @@ -35,7 +37,10 @@ impl<A: Iterator, B: Iterator> Zip<A, B> { } #[stable(feature = "rust1", since = "1.0.0")] -impl<A, B> Iterator for Zip<A, B> where A: Iterator, B: Iterator +impl<A, B> Iterator for Zip<A, B> +where + A: Iterator, + B: Iterator, { type Item = (A::Item, B::Item); @@ -56,7 +61,8 @@ impl<A, B> Iterator for Zip<A, B> where A: Iterator, B: Iterator } #[stable(feature = "rust1", since = "1.0.0")] -impl<A, B> DoubleEndedIterator for Zip<A, B> where +impl<A, B> DoubleEndedIterator for Zip<A, B> +where A: DoubleEndedIterator + ExactSizeIterator, B: DoubleEndedIterator + ExactSizeIterator, { @@ -75,14 +81,17 @@ trait ZipImpl<A, B> { fn size_hint(&self) -> (usize, Option<usize>); fn nth(&mut self, n: usize) -> Option<Self::Item>; fn next_back(&mut self) -> Option<Self::Item> - where A: DoubleEndedIterator + ExactSizeIterator, - B: DoubleEndedIterator + ExactSizeIterator; + where + A: DoubleEndedIterator + ExactSizeIterator, + B: DoubleEndedIterator + ExactSizeIterator; } // General Zip impl #[doc(hidden)] impl<A, B> ZipImpl<A, B> for Zip<A, B> - where A: Iterator, B: Iterator +where + A: Iterator, + B: Iterator, { type Item = (A::Item, B::Item); default fn new(a: A, b: B) -> Self { @@ -90,7 +99,7 @@ impl<A, B> ZipImpl<A, B> for Zip<A, B> a, b, index: 0, // unused - len: 0, // unused + len: 0, // unused } } @@ -108,17 +117,22 @@ impl<A, B> ZipImpl<A, B> for Zip<A, B> #[inline] default fn next_back(&mut self) -> Option<(A::Item, B::Item)> - where A: DoubleEndedIterator + ExactSizeIterator, - B: DoubleEndedIterator + ExactSizeIterator + where + A: DoubleEndedIterator + ExactSizeIterator, + B: DoubleEndedIterator + ExactSizeIterator, { let a_sz = self.a.len(); let b_sz = self.b.len(); if a_sz != b_sz { // Adjust a, b to equal length if a_sz > b_sz { - for _ in 0..a_sz - b_sz { self.a.next_back(); } + for _ in 0..a_sz - b_sz { + self.a.next_back(); + } } else { - for _ in 0..b_sz - a_sz { self.b.next_back(); } + for _ in 0..b_sz - a_sz { + self.b.next_back(); + } } } match (self.a.next_back(), self.b.next_back()) { @@ -136,10 +150,10 @@ impl<A, B> ZipImpl<A, B> for Zip<A, B> let lower = cmp::min(a_lower, b_lower); let upper = match (a_upper, b_upper) { - (Some(x), Some(y)) => Some(cmp::min(x,y)), + (Some(x), Some(y)) => Some(cmp::min(x, y)), (Some(x), None) => Some(x), (None, Some(y)) => Some(y), - (None, None) => None + (None, None) => None, }; (lower, upper) @@ -148,16 +162,13 @@ impl<A, B> ZipImpl<A, B> for Zip<A, B> #[doc(hidden)] impl<A, B> ZipImpl<A, B> for Zip<A, B> - where A: TrustedRandomAccess, B: TrustedRandomAccess +where + A: TrustedRandomAccess, + B: TrustedRandomAccess, { fn new(a: A, b: B) -> Self { let len = cmp::min(a.len(), b.len()); - Zip { - a, - b, - index: 0, - len, - } + Zip { a, b, index: 0, len } } #[inline] @@ -165,9 +176,7 @@ impl<A, B> ZipImpl<A, B> for Zip<A, B> if self.index < self.len { let i = self.index; self.index += 1; - unsafe { - Some((self.a.get_unchecked(i), self.b.get_unchecked(i))) - } + unsafe { Some((self.a.get_unchecked(i), self.b.get_unchecked(i))) } } else if A::may_have_side_effect() && self.index < self.a.len() { // match the base implementation's potential side effects unsafe { @@ -194,10 +203,14 @@ impl<A, B> ZipImpl<A, B> for Zip<A, B> let i = self.index; self.index += 1; if A::may_have_side_effect() { - unsafe { self.a.get_unchecked(i); } + unsafe { + self.a.get_unchecked(i); + } } if B::may_have_side_effect() { - unsafe { self.b.get_unchecked(i); } + unsafe { + self.b.get_unchecked(i); + } } } @@ -206,8 +219,9 @@ impl<A, B> ZipImpl<A, B> for Zip<A, B> #[inline] fn next_back(&mut self) -> Option<(A::Item, B::Item)> - where A: DoubleEndedIterator + ExactSizeIterator, - B: DoubleEndedIterator + ExactSizeIterator + where + A: DoubleEndedIterator + ExactSizeIterator, + B: DoubleEndedIterator + ExactSizeIterator, { // Adjust a, b to equal length if A::may_have_side_effect() { @@ -229,9 +243,7 @@ impl<A, B> ZipImpl<A, B> for Zip<A, B> if self.index < self.len { self.len -= 1; let i = self.len; - unsafe { - Some((self.a.get_unchecked(i), self.b.get_unchecked(i))) - } + unsafe { Some((self.a.get_unchecked(i), self.b.get_unchecked(i))) } } else { None } @@ -240,12 +252,17 @@ impl<A, B> ZipImpl<A, B> for Zip<A, B> #[stable(feature = "rust1", since = "1.0.0")] impl<A, B> ExactSizeIterator for Zip<A, B> - where A: ExactSizeIterator, B: ExactSizeIterator {} +where + A: ExactSizeIterator, + B: ExactSizeIterator, +{ +} #[doc(hidden)] unsafe impl<A, B> TrustedRandomAccess for Zip<A, B> - where A: TrustedRandomAccess, - B: TrustedRandomAccess, +where + A: TrustedRandomAccess, + B: TrustedRandomAccess, { unsafe fn get_unchecked(&mut self, i: usize) -> (A::Item, B::Item) { (self.a.get_unchecked(i), self.b.get_unchecked(i)) @@ -258,12 +275,19 @@ unsafe impl<A, B> TrustedRandomAccess for Zip<A, B> #[stable(feature = "fused", since = "1.26.0")] impl<A, B> FusedIterator for Zip<A, B> - where A: FusedIterator, B: FusedIterator, {} +where + A: FusedIterator, + B: FusedIterator, +{ +} #[unstable(feature = "trusted_len", issue = "37572")] unsafe impl<A, B> TrustedLen for Zip<A, B> - where A: TrustedLen, B: TrustedLen, -{} +where + A: TrustedLen, + B: TrustedLen, +{ +} /// An iterator whose items are random-accessible efficiently /// @@ -275,7 +299,7 @@ unsafe impl<A, B> TrustedLen for Zip<A, B> /// .get_unchecked() must return distinct mutable references for distinct /// indices (if applicable), and must return a valid reference if index is in /// 0..self.len(). -pub(crate) unsafe trait TrustedRandomAccess : ExactSizeIterator { +pub(crate) unsafe trait TrustedRandomAccess: ExactSizeIterator { unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item; /// Returns `true` if getting an iterator element may have /// side effects. Remember to take inner iterators into account. diff --git a/src/libcore/iter/mod.rs b/src/libcore/iter/mod.rs index fac6ff0f06b..80294de714d 100644 --- a/src/libcore/iter/mod.rs +++ b/src/libcore/iter/mod.rs @@ -309,56 +309,58 @@ use crate::ops::Try; #[stable(feature = "rust1", since = "1.0.0")] pub use self::traits::Iterator; -#[unstable(feature = "step_trait", - reason = "likely to be replaced by finer-grained traits", - issue = "42168")] +#[unstable( + feature = "step_trait", + reason = "likely to be replaced by finer-grained traits", + issue = "42168" +)] pub use self::range::Step; -#[stable(feature = "rust1", since = "1.0.0")] -pub use self::sources::{Repeat, repeat}; -#[stable(feature = "iterator_repeat_with", since = "1.28.0")] -pub use self::sources::{RepeatWith, repeat_with}; #[stable(feature = "iter_empty", since = "1.2.0")] -pub use self::sources::{Empty, empty}; +pub use self::sources::{empty, Empty}; +#[stable(feature = "iter_from_fn", since = "1.34.0")] +pub use self::sources::{from_fn, FromFn}; #[stable(feature = "iter_once", since = "1.2.0")] -pub use self::sources::{Once, once}; +pub use self::sources::{once, Once}; #[unstable(feature = "iter_once_with", issue = "57581")] -pub use self::sources::{OnceWith, once_with}; -#[stable(feature = "iter_from_fn", since = "1.34.0")] -pub use self::sources::{FromFn, from_fn}; +pub use self::sources::{once_with, OnceWith}; +#[stable(feature = "rust1", since = "1.0.0")] +pub use self::sources::{repeat, Repeat}; +#[stable(feature = "iterator_repeat_with", since = "1.28.0")] +pub use self::sources::{repeat_with, RepeatWith}; #[stable(feature = "iter_successors", since = "1.34.0")] -pub use self::sources::{Successors, successors}; +pub use self::sources::{successors, Successors}; -#[stable(feature = "rust1", since = "1.0.0")] -pub use self::traits::{FromIterator, IntoIterator, DoubleEndedIterator, Extend}; -#[stable(feature = "rust1", since = "1.0.0")] -pub use self::traits::{ExactSizeIterator, Sum, Product}; #[stable(feature = "fused", since = "1.26.0")] pub use self::traits::FusedIterator; #[unstable(feature = "trusted_len", issue = "37572")] pub use self::traits::TrustedLen; - #[stable(feature = "rust1", since = "1.0.0")] -pub use self::adapters::{Rev, Cycle, Chain, Zip, Map, Filter, FilterMap, Enumerate}; +pub use self::traits::{DoubleEndedIterator, Extend, FromIterator, IntoIterator}; #[stable(feature = "rust1", since = "1.0.0")] -pub use self::adapters::{Peekable, SkipWhile, TakeWhile, Skip, Take, Scan, FlatMap}; -#[stable(feature = "rust1", since = "1.0.0")] -pub use self::adapters::{Fuse, Inspect}; +pub use self::traits::{ExactSizeIterator, Product, Sum}; + #[stable(feature = "iter_cloned", since = "1.1.0")] pub use self::adapters::Cloned; -#[stable(feature = "iterator_step_by", since = "1.28.0")] -pub use self::adapters::StepBy; -#[stable(feature = "iterator_flatten", since = "1.29.0")] -pub use self::adapters::Flatten; #[stable(feature = "iter_copied", since = "1.36.0")] pub use self::adapters::Copied; +#[stable(feature = "iterator_flatten", since = "1.29.0")] +pub use self::adapters::Flatten; +#[stable(feature = "iterator_step_by", since = "1.28.0")] +pub use self::adapters::StepBy; +#[stable(feature = "rust1", since = "1.0.0")] +pub use self::adapters::{Chain, Cycle, Enumerate, Filter, FilterMap, Map, Rev, Zip}; +#[stable(feature = "rust1", since = "1.0.0")] +pub use self::adapters::{FlatMap, Peekable, Scan, Skip, SkipWhile, Take, TakeWhile}; +#[stable(feature = "rust1", since = "1.0.0")] +pub use self::adapters::{Fuse, Inspect}; -pub(crate) use self::adapters::{TrustedRandomAccess, process_results}; +pub(crate) use self::adapters::{process_results, TrustedRandomAccess}; +mod adapters; mod range; mod sources; mod traits; -mod adapters; /// Used to make try_fold closures more like normal loops #[derive(PartialEq)] @@ -378,9 +380,13 @@ impl<C, B> Try for LoopState<C, B> { } } #[inline] - fn from_error(v: Self::Error) -> Self { LoopState::Break(v) } + fn from_error(v: Self::Error) -> Self { + LoopState::Break(v) + } #[inline] - fn from_ok(v: Self::Ok) -> Self { LoopState::Continue(v) } + fn from_ok(v: Self::Ok) -> Self { + LoopState::Continue(v) + } } impl<C, B> LoopState<C, B> { diff --git a/src/libcore/iter/range.rs b/src/libcore/iter/range.rs index 63036f516a0..eac3c107d22 100644 --- a/src/libcore/iter/range.rs +++ b/src/libcore/iter/range.rs @@ -9,9 +9,11 @@ use super::{FusedIterator, TrustedLen}; /// /// The `steps_between` function provides a way to efficiently compare /// two `Step` objects. -#[unstable(feature = "step_trait", - reason = "likely to be replaced by finer-grained traits", - issue = "42168")] +#[unstable( + feature = "step_trait", + reason = "likely to be replaced by finer-grained traits", + issue = "42168" +)] pub trait Step: Clone + PartialOrd + Sized { /// Returns the number of steps between two step objects. The count is /// inclusive of `start` and exclusive of `end`. @@ -170,8 +172,8 @@ macro_rules! step_impl_signed { } step_impl_unsigned!(usize u8 u16 u32 u64 u128); -step_impl_signed!([isize: usize] [i8: u8] [i16: u16]); -step_impl_signed!([i32: u32] [i64: u64] [i128: u128]); +step_impl_signed!([isize: usize][i8: u8][i16: u16]); +step_impl_signed!([i32: u32][i64: u64][i128: u128]); macro_rules! range_exact_iter_impl { ($($t:ty)*) => ($( @@ -227,7 +229,7 @@ impl<A: Step> Iterator for ops::Range<A> { fn size_hint(&self) -> (usize, Option<usize>) { match Step::steps_between(&self.start, &self.end) { Some(hint) => (hint, Some(hint)), - None => (usize::MAX, None) + None => (usize::MAX, None), } } @@ -236,7 +238,7 @@ impl<A: Step> Iterator for ops::Range<A> { if let Some(plus_n) = self.start.add_usize(n) { if plus_n < self.end { self.start = plus_n.add_one(); - return Some(plus_n) + return Some(plus_n); } } @@ -291,7 +293,7 @@ impl<A: Step> DoubleEndedIterator for ops::Range<A> { if let Some(minus_n) = self.end.sub_usize(n) { if minus_n > self.start { self.end = minus_n.sub_one(); - return Some(self.end.clone()) + return Some(self.end.clone()); } } @@ -396,7 +398,9 @@ impl<A: Step> Iterator for ops::RangeInclusive<A> { #[inline] fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where - Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B> + Self: Sized, + F: FnMut(B, Self::Item) -> R, + R: Try<Ok = B>, { self.compute_is_empty(); @@ -484,8 +488,11 @@ impl<A: Step> DoubleEndedIterator for ops::RangeInclusive<A> { } #[inline] - fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R where - Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B> + fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R + where + Self: Sized, + F: FnMut(B, Self::Item) -> R, + R: Try<Ok = B>, { self.compute_is_empty(); diff --git a/src/libcore/iter/traits/marker.rs b/src/libcore/iter/traits/marker.rs index 602619bce5a..404cc84495c 100644 --- a/src/libcore/iter/traits/marker.rs +++ b/src/libcore/iter/traits/marker.rs @@ -38,7 +38,7 @@ impl<I: FusedIterator + ?Sized> FusedIterator for &mut I {} /// [`usize::MAX`]: ../../std/usize/constant.MAX.html /// [`.size_hint`]: ../../std/iter/trait.Iterator.html#method.size_hint #[unstable(feature = "trusted_len", issue = "37572")] -pub unsafe trait TrustedLen : Iterator {} +pub unsafe trait TrustedLen: Iterator {} #[unstable(feature = "trusted_len", issue = "37572")] unsafe impl<I: TrustedLen + ?Sized> TrustedLen for &mut I {} diff --git a/src/libcore/iter/traits/mod.rs b/src/libcore/iter/traits/mod.rs index cf3013f423c..efd1580a548 100644 --- a/src/libcore/iter/traits/mod.rs +++ b/src/libcore/iter/traits/mod.rs @@ -1,15 +1,15 @@ -mod iterator; +mod accum; +mod collect; mod double_ended; mod exact_size; -mod collect; -mod accum; +mod iterator; mod marker; -#[stable(feature = "rust1", since = "1.0.0")] -pub use self::iterator::Iterator; +pub use self::accum::{Product, Sum}; +pub use self::collect::{Extend, FromIterator, IntoIterator}; pub use self::double_ended::DoubleEndedIterator; pub use self::exact_size::ExactSizeIterator; -pub use self::collect::{FromIterator, IntoIterator, Extend}; -pub use self::accum::{Sum, Product}; +#[stable(feature = "rust1", since = "1.0.0")] +pub use self::iterator::Iterator; #[stable(feature = "rust1", since = "1.0.0")] pub use self::marker::{FusedIterator, TrustedLen}; diff --git a/src/libcore/lib.rs b/src/libcore/lib.rs index a2ab85e64ba..7c5e06ace67 100644 --- a/src/libcore/lib.rs +++ b/src/libcore/lib.rs @@ -49,22 +49,21 @@ // // This cfg won't affect doc tests. #![cfg(not(test))] - #![stable(feature = "core", since = "1.6.0")] -#![doc(html_root_url = "https://doc.rust-lang.org/nightly/", - html_playground_url = "https://play.rust-lang.org/", - issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/", - test(no_crate_inject, attr(deny(warnings))), - test(attr(allow(dead_code, deprecated, unused_variables, unused_mut))))] +#![doc( + html_root_url = "https://doc.rust-lang.org/nightly/", + html_playground_url = "https://play.rust-lang.org/", + issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/", + test(no_crate_inject, attr(deny(warnings))), + test(attr(allow(dead_code, deprecated, unused_variables, unused_mut))) +)] #![no_core] - #![warn(deprecated_in_future)] #![warn(missing_docs)] #![warn(missing_debug_implementations)] #![deny(intra_doc_link_resolution_failure)] // rustdoc is run without -D warnings #![allow(explicit_outlives_requirements)] #![allow(incomplete_features)] - #![feature(allow_internal_unstable)] #![feature(arbitrary_self_types)] #![feature(asm)] @@ -148,22 +147,36 @@ mod int_macros; #[macro_use] mod uint_macros; -#[path = "num/isize.rs"] pub mod isize; -#[path = "num/i8.rs"] pub mod i8; -#[path = "num/i16.rs"] pub mod i16; -#[path = "num/i32.rs"] pub mod i32; -#[path = "num/i64.rs"] pub mod i64; -#[path = "num/i128.rs"] pub mod i128; +#[path = "num/i128.rs"] +pub mod i128; +#[path = "num/i16.rs"] +pub mod i16; +#[path = "num/i32.rs"] +pub mod i32; +#[path = "num/i64.rs"] +pub mod i64; +#[path = "num/i8.rs"] +pub mod i8; +#[path = "num/isize.rs"] +pub mod isize; -#[path = "num/usize.rs"] pub mod usize; -#[path = "num/u8.rs"] pub mod u8; -#[path = "num/u16.rs"] pub mod u16; -#[path = "num/u32.rs"] pub mod u32; -#[path = "num/u64.rs"] pub mod u64; -#[path = "num/u128.rs"] pub mod u128; +#[path = "num/u128.rs"] +pub mod u128; +#[path = "num/u16.rs"] +pub mod u16; +#[path = "num/u32.rs"] +pub mod u32; +#[path = "num/u64.rs"] +pub mod u64; +#[path = "num/u8.rs"] +pub mod u8; +#[path = "num/usize.rs"] +pub mod usize; -#[path = "num/f32.rs"] pub mod f32; -#[path = "num/f64.rs"] pub mod f64; +#[path = "num/f32.rs"] +pub mod f32; +#[path = "num/f64.rs"] +pub mod f64; #[macro_use] pub mod num; @@ -174,24 +187,24 @@ pub mod prelude; /* Core modules for ownership management */ +pub mod hint; pub mod intrinsics; pub mod mem; pub mod ptr; -pub mod hint; /* Core language traits */ +pub mod borrow; #[cfg(not(test))] // See #65860 -pub mod marker; -pub mod ops; +pub mod clone; #[cfg(not(test))] // See #65860 pub mod cmp; -#[cfg(not(test))] // See #65860 -pub mod clone; +pub mod convert; #[cfg(not(test))] // See #65860 pub mod default; -pub mod convert; -pub mod borrow; +#[cfg(not(test))] // See #65860 +pub mod marker; +pub mod ops; /* Core types and methods on primitives */ @@ -199,27 +212,27 @@ pub mod any; #[cfg(not(test))] // See #65860 pub mod array; pub mod ascii; -pub mod sync; pub mod cell; pub mod char; +pub mod ffi; +#[cfg(not(test))] // See #65860 +pub mod iter; +pub mod option; pub mod panic; pub mod panicking; #[cfg(not(test))] // See #65860 pub mod pin; -#[cfg(not(test))] // See #65860 -pub mod iter; -pub mod option; pub mod raw; pub mod result; -pub mod ffi; +pub mod sync; -pub mod slice; #[cfg(not(test))] // See #65860 -pub mod str; +pub mod fmt; #[cfg(not(test))] // See #65860 pub mod hash; +pub mod slice; #[cfg(not(test))] // See #65860 -pub mod fmt; +pub mod str; pub mod time; pub mod unicode; diff --git a/src/libcore/marker.rs b/src/libcore/marker.rs index 1b586c3e5fe..978d6221564 100644 --- a/src/libcore/marker.rs +++ b/src/libcore/marker.rs @@ -31,17 +31,17 @@ use crate::hash::Hasher; #[stable(feature = "rust1", since = "1.0.0")] #[cfg_attr(not(test), rustc_diagnostic_item = "send_trait")] #[rustc_on_unimplemented( - message="`{Self}` cannot be sent between threads safely", - label="`{Self}` cannot be sent between threads safely" + message = "`{Self}` cannot be sent between threads safely", + label = "`{Self}` cannot be sent between threads safely" )] pub unsafe auto trait Send { // empty. } #[stable(feature = "rust1", since = "1.0.0")] -impl<T: ?Sized> !Send for *const T { } +impl<T: ?Sized> !Send for *const T {} #[stable(feature = "rust1", since = "1.0.0")] -impl<T: ?Sized> !Send for *mut T { } +impl<T: ?Sized> !Send for *mut T {} /// Types with a constant size known at compile time. /// @@ -83,11 +83,11 @@ impl<T: ?Sized> !Send for *mut T { } #[stable(feature = "rust1", since = "1.0.0")] #[lang = "sized"] #[rustc_on_unimplemented( - on(parent_trait="std::path::Path", label="borrow the `Path` instead"), - message="the size for values of type `{Self}` cannot be known at compilation time", - label="doesn't have a size known at compile-time", - note="to learn more, visit <https://doc.rust-lang.org/book/\ - ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>", + on(parent_trait = "std::path::Path", label = "borrow the `Path` instead"), + message = "the size for values of type `{Self}` cannot be known at compilation time", + label = "doesn't have a size known at compile-time", + note = "to learn more, visit <https://doc.rust-lang.org/book/\ + ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>" )] #[fundamental] // for Default, for example, which requires that `[T]: !Default` be evaluatable pub trait Sized { @@ -148,7 +148,7 @@ pub trait Unsize<T: ?Sized> { /// [RFC1445]: https://github.com/rust-lang/rfcs/blob/master/text/1445-restrict-constants-in-patterns.md /// [issue 63438]: https://github.com/rust-lang/rust/issues/63438 #[unstable(feature = "structural_match", issue = "31434")] -#[rustc_on_unimplemented(message="the type `{Self}` does not `#[derive(PartialEq)]`")] +#[rustc_on_unimplemented(message = "the type `{Self}` does not `#[derive(PartialEq)]`")] #[lang = "structural_peq"] pub trait StructuralPartialEq { // Empty. @@ -198,7 +198,7 @@ pub trait StructuralPartialEq { /// of the two derives (`#[derive(PartialEq)]` and `#[derive(Eq)]`) and check /// that both of them are present as part of structural-match checking. #[unstable(feature = "structural_match", issue = "31434")] -#[rustc_on_unimplemented(message="the type `{Self}` does not `#[derive(Eq)]`")] +#[rustc_on_unimplemented(message = "the type `{Self}` does not `#[derive(Eq)]`")] #[lang = "structural_teq"] pub trait StructuralEq { // Empty. @@ -362,7 +362,7 @@ pub trait StructuralEq { /// [impls]: #implementors #[stable(feature = "rust1", since = "1.0.0")] #[lang = "copy"] -pub trait Copy : Clone { +pub trait Copy: Clone { // Empty. } @@ -370,7 +370,9 @@ pub trait Copy : Clone { #[rustc_builtin_macro] #[stable(feature = "builtin_macro_prelude", since = "1.38.0")] #[allow_internal_unstable(core_intrinsics, derive_clone_copy)] -pub macro Copy($item:item) { /* compiler built-in */ } +pub macro Copy($item:item) { + /* compiler built-in */ +} /// Types for which it is safe to share references between threads. /// @@ -444,8 +446,8 @@ pub macro Copy($item:item) { /* compiler built-in */ } #[cfg_attr(not(test), rustc_diagnostic_item = "sync_trait")] #[lang = "sync"] #[rustc_on_unimplemented( - message="`{Self}` cannot be shared between threads safely", - label="`{Self}` cannot be shared between threads safely" + message = "`{Self}` cannot be shared between threads safely", + label = "`{Self}` cannot be shared between threads safely" )] pub unsafe auto trait Sync { // FIXME(estebank): once support to add notes in `rustc_on_unimplemented` @@ -462,67 +464,65 @@ pub unsafe auto trait Sync { } #[stable(feature = "rust1", since = "1.0.0")] -impl<T: ?Sized> !Sync for *const T { } +impl<T: ?Sized> !Sync for *const T {} #[stable(feature = "rust1", since = "1.0.0")] -impl<T: ?Sized> !Sync for *mut T { } +impl<T: ?Sized> !Sync for *mut T {} -macro_rules! impls{ - ($t: ident) => ( +macro_rules! impls { + ($t: ident) => { #[stable(feature = "rust1", since = "1.0.0")] - impl<T:?Sized> Hash for $t<T> { + impl<T: ?Sized> Hash for $t<T> { #[inline] - fn hash<H: Hasher>(&self, _: &mut H) { - } + fn hash<H: Hasher>(&self, _: &mut H) {} } #[stable(feature = "rust1", since = "1.0.0")] - impl<T:?Sized> cmp::PartialEq for $t<T> { + impl<T: ?Sized> cmp::PartialEq for $t<T> { fn eq(&self, _other: &$t<T>) -> bool { true } } #[stable(feature = "rust1", since = "1.0.0")] - impl<T:?Sized> cmp::Eq for $t<T> { - } + impl<T: ?Sized> cmp::Eq for $t<T> {} #[stable(feature = "rust1", since = "1.0.0")] - impl<T:?Sized> cmp::PartialOrd for $t<T> { + impl<T: ?Sized> cmp::PartialOrd for $t<T> { fn partial_cmp(&self, _other: &$t<T>) -> Option<cmp::Ordering> { Option::Some(cmp::Ordering::Equal) } } #[stable(feature = "rust1", since = "1.0.0")] - impl<T:?Sized> cmp::Ord for $t<T> { + impl<T: ?Sized> cmp::Ord for $t<T> { fn cmp(&self, _other: &$t<T>) -> cmp::Ordering { cmp::Ordering::Equal } } #[stable(feature = "rust1", since = "1.0.0")] - impl<T:?Sized> Copy for $t<T> { } + impl<T: ?Sized> Copy for $t<T> {} #[stable(feature = "rust1", since = "1.0.0")] - impl<T:?Sized> Clone for $t<T> { + impl<T: ?Sized> Clone for $t<T> { fn clone(&self) -> $t<T> { $t } } #[stable(feature = "rust1", since = "1.0.0")] - impl<T:?Sized> Default for $t<T> { + impl<T: ?Sized> Default for $t<T> { fn default() -> $t<T> { $t } } #[unstable(feature = "structural_match", issue = "31434")] - impl<T: ?Sized> StructuralPartialEq for $t<T> { } + impl<T: ?Sized> StructuralPartialEq for $t<T> {} #[unstable(feature = "structural_match", issue = "31434")] - impl<T: ?Sized> StructuralEq for $t<T> { } - ) + impl<T: ?Sized> StructuralEq for $t<T> {} + }; } /// Zero-sized type used to mark things that "act like" they own a `T`. @@ -661,7 +661,7 @@ macro_rules! impls{ #[lang = "phantom_data"] #[structural_match] #[stable(feature = "rust1", since = "1.0.0")] -pub struct PhantomData<T:?Sized>; +pub struct PhantomData<T: ?Sized>; impls! { PhantomData } @@ -788,5 +788,4 @@ mod copy_impls { // Shared references can be copied, but mutable references *cannot*! #[stable(feature = "rust1", since = "1.0.0")] impl<T: ?Sized> Copy for &T {} - } diff --git a/src/libcore/mem/maybe_uninit.rs b/src/libcore/mem/maybe_uninit.rs index de3b837fb68..5fb3c651b6b 100644 --- a/src/libcore/mem/maybe_uninit.rs +++ b/src/libcore/mem/maybe_uninit.rs @@ -304,14 +304,15 @@ impl<T> MaybeUninit<T> { #[unstable(feature = "maybe_uninit_uninit_array", issue = "none")] #[inline(always)] pub fn uninit_array<const LEN: usize>() -> [Self; LEN] { - unsafe { - MaybeUninit::<[MaybeUninit<T>; LEN]>::uninit().assume_init() - } + unsafe { MaybeUninit::<[MaybeUninit<T>; LEN]>::uninit().assume_init() } } /// A promotable constant, equivalent to `uninit()`. - #[unstable(feature = "internal_uninit_const", issue = "none", - reason = "hack to work around promotability")] + #[unstable( + feature = "internal_uninit_const", + issue = "none", + reason = "hack to work around promotability" + )] pub const UNINIT: Self = Self::uninit(); /// Creates a new `MaybeUninit<T>` in an uninitialized state, with the memory being diff --git a/src/libcore/mem/mod.rs b/src/libcore/mem/mod.rs index db5d2650331..e11072db0dc 100644 --- a/src/libcore/mem/mod.rs +++ b/src/libcore/mem/mod.rs @@ -745,7 +745,7 @@ pub fn replace<T>(dest: &mut T, mut src: T) -> T { /// [`Copy`]: ../../std/marker/trait.Copy.html #[inline] #[stable(feature = "rust1", since = "1.0.0")] -pub fn drop<T>(_x: T) { } +pub fn drop<T>(_x: T) {} /// Interprets `src` as having type `&U`, and then reads `src` without moving /// the contained value. @@ -834,9 +834,7 @@ impl<T> hash::Hash for Discriminant<T> { #[stable(feature = "discriminant_value", since = "1.21.0")] impl<T> fmt::Debug for Discriminant<T> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt.debug_tuple("Discriminant") - .field(&self.0) - .finish() + fmt.debug_tuple("Discriminant").field(&self.0).finish() } } diff --git a/src/libcore/num/f32.rs b/src/libcore/num/f32.rs index 9e379e63810..e1e6c57a0fb 100644 --- a/src/libcore/num/f32.rs +++ b/src/libcore/num/f32.rs @@ -342,7 +342,7 @@ impl f32 { /// /// assert!(abs_difference <= f32::EPSILON); /// ``` - #[stable(feature = "f32_deg_rad_conversions", since="1.7.0")] + #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")] #[inline] pub fn to_degrees(self) -> f32 { // Use a constant for better precision. @@ -361,7 +361,7 @@ impl f32 { /// /// assert!(abs_difference <= f32::EPSILON); /// ``` - #[stable(feature = "f32_deg_rad_conversions", since="1.7.0")] + #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")] #[inline] pub fn to_radians(self) -> f32 { let value: f32 = consts::PI; @@ -424,7 +424,10 @@ impl f32 { /// * Be representable in the return type `Int`, after truncating off its fractional part #[unstable(feature = "float_approx_unchecked_to", issue = "67058")] #[inline] - pub unsafe fn approx_unchecked_to<Int>(self) -> Int where Self: FloatToInt<Int> { + pub unsafe fn approx_unchecked_to<Int>(self) -> Int + where + Self: FloatToInt<Int>, + { FloatToInt::<Int>::approx_unchecked(self) } diff --git a/src/libcore/panic.rs b/src/libcore/panic.rs index a90b025c093..dbfcbca3ffc 100644 --- a/src/libcore/panic.rs +++ b/src/libcore/panic.rs @@ -37,10 +37,12 @@ pub struct PanicInfo<'a> { } impl<'a> PanicInfo<'a> { - #[unstable(feature = "panic_internals", - reason = "internal details of the implementation of the `panic!` \ + #[unstable( + feature = "panic_internals", + reason = "internal details of the implementation of the `panic!` \ and related macros", - issue = "none")] + issue = "none" + )] #[doc(hidden)] #[inline] pub fn internal_constructor( @@ -48,17 +50,15 @@ impl<'a> PanicInfo<'a> { location: &'a Location<'a>, ) -> Self { struct NoPayload; - PanicInfo { - location, - message, - payload: &NoPayload, - } + PanicInfo { location, message, payload: &NoPayload } } - #[unstable(feature = "panic_internals", - reason = "internal details of the implementation of the `panic!` \ + #[unstable( + feature = "panic_internals", + reason = "internal details of the implementation of the `panic!` \ and related macros", - issue = "none")] + issue = "none" + )] #[doc(hidden)] #[inline] pub fn set_payload(&mut self, info: &'a (dyn Any + Send)) { @@ -222,9 +222,11 @@ impl<'a> Location<'a> { /// assert_ne!(this_location.line(), another_location.line()); /// assert_ne!(this_location.column(), another_location.column()); /// ``` - #[unstable(feature = "track_caller", - reason = "uses #[track_caller] which is not yet stable", - issue = "47809")] + #[unstable( + feature = "track_caller", + reason = "uses #[track_caller] which is not yet stable", + issue = "47809" + )] #[track_caller] pub const fn caller() -> &'static Location<'static> { crate::intrinsics::caller_location() @@ -232,10 +234,12 @@ impl<'a> Location<'a> { } impl<'a> Location<'a> { - #![unstable(feature = "panic_internals", - reason = "internal details of the implementation of the `panic!` \ + #![unstable( + feature = "panic_internals", + reason = "internal details of the implementation of the `panic!` \ and related macros", - issue = "none")] + issue = "none" + )] #[doc(hidden)] pub const fn internal_constructor(file: &'a str, line: u32, col: u32) -> Self { Location { file, line, col } diff --git a/src/libcore/ptr/const_ptr.rs b/src/libcore/ptr/const_ptr.rs index be2b7ff5f77..e5297a0c1e0 100644 --- a/src/libcore/ptr/const_ptr.rs +++ b/src/libcore/ptr/const_ptr.rs @@ -1,7 +1,7 @@ -use crate::cmp::Ordering::{self, Less, Equal, Greater}; +use super::*; +use crate::cmp::Ordering::{self, Equal, Greater, Less}; use crate::intrinsics; use crate::mem; -use super::*; // ignore-tidy-undocumented-unsafe @@ -154,8 +154,8 @@ impl<T: ?Sized> *const T { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub unsafe fn offset(self, count: isize) -> *const T - where - T: Sized, + where + T: Sized, { intrinsics::offset(self, count) } @@ -212,8 +212,8 @@ impl<T: ?Sized> *const T { #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")] #[inline] pub fn wrapping_offset(self, count: isize) -> *const T - where - T: Sized, + where + T: Sized, { unsafe { intrinsics::arith_offset(self, count) } } @@ -284,8 +284,8 @@ impl<T: ?Sized> *const T { #[rustc_const_unstable(feature = "const_ptr_offset_from", issue = "41079")] #[inline] pub const unsafe fn offset_from(self, origin: *const T) -> isize - where - T: Sized, + where + T: Sized, { let pointee_size = mem::size_of::<T>(); let ok = 0 < pointee_size && pointee_size <= isize::max_value() as usize; @@ -332,8 +332,8 @@ impl<T: ?Sized> *const T { #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")] #[inline] pub fn wrapping_offset_from(self, origin: *const T) -> isize - where - T: Sized, + where + T: Sized, { let pointee_size = mem::size_of::<T>(); assert!(0 < pointee_size && pointee_size <= isize::max_value() as usize); @@ -396,8 +396,8 @@ impl<T: ?Sized> *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) } @@ -457,8 +457,8 @@ impl<T: ?Sized> *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()) } @@ -512,8 +512,8 @@ impl<T: ?Sized> *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) } @@ -567,8 +567,8 @@ impl<T: ?Sized> *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()) } @@ -582,8 +582,8 @@ impl<T: ?Sized> *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) } @@ -601,8 +601,8 @@ impl<T: ?Sized> *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) } @@ -618,8 +618,8 @@ impl<T: ?Sized> *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) } @@ -635,8 +635,8 @@ impl<T: ?Sized> *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) } @@ -652,8 +652,8 @@ impl<T: ?Sized> *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) } @@ -699,8 +699,8 @@ impl<T: ?Sized> *const T { /// ``` #[stable(feature = "align_offset", since = "1.36.0")] pub fn align_offset(self, align: usize) -> usize - where - T: Sized, + where + T: Sized, { if !align.is_power_of_two() { panic!("align_offset: align is not a power-of-two"); @@ -713,7 +713,9 @@ impl<T: ?Sized> *const T { #[stable(feature = "rust1", since = "1.0.0")] impl<T: ?Sized> 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")] @@ -742,14 +744,22 @@ impl<T: ?Sized> 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 + } } diff --git a/src/libcore/ptr/mod.rs b/src/libcore/ptr/mod.rs index d42b673ff65..d7b351f1345 100644 --- a/src/libcore/ptr/mod.rs +++ b/src/libcore/ptr/mod.rs @@ -69,11 +69,11 @@ #![stable(feature = "rust1", since = "1.0.0")] -use crate::intrinsics; +use crate::cmp::Ordering; use crate::fmt; use crate::hash; +use crate::intrinsics; use crate::mem::{self, MaybeUninit}; -use crate::cmp::Ordering; #[stable(feature = "rust1", since = "1.0.0")] pub use crate::intrinsics::copy_nonoverlapping; diff --git a/src/libcore/ptr/mut_ptr.rs b/src/libcore/ptr/mut_ptr.rs index fd5decbd7ea..b3bb2f179b1 100644 --- a/src/libcore/ptr/mut_ptr.rs +++ b/src/libcore/ptr/mut_ptr.rs @@ -1,6 +1,6 @@ -use crate::cmp::Ordering::{self, Less, Equal, Greater}; -use crate::intrinsics; use super::*; +use crate::cmp::Ordering::{self, Equal, Greater, Less}; +use crate::intrinsics; // ignore-tidy-undocumented-unsafe @@ -148,8 +148,8 @@ impl<T: ?Sized> *mut T { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub unsafe fn offset(self, count: isize) -> *mut T - where - T: Sized, + where + T: Sized, { intrinsics::offset(self, count) as *mut T } @@ -205,8 +205,8 @@ impl<T: ?Sized> *mut T { #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")] #[inline] pub fn wrapping_offset(self, count: isize) -> *mut T - where - T: Sized, + where + T: Sized, { unsafe { intrinsics::arith_offset(self, count) as *mut T } } @@ -322,8 +322,8 @@ impl<T: ?Sized> *mut T { #[rustc_const_unstable(feature = "const_ptr_offset_from", issue = "41079")] #[inline] pub const unsafe fn offset_from(self, origin: *const T) -> isize - where - T: Sized, + where + T: Sized, { (self as *const T).offset_from(origin) } @@ -365,8 +365,8 @@ impl<T: ?Sized> *mut T { #[unstable(feature = "ptr_wrapping_offset_from", issue = "41079")] #[inline] pub fn wrapping_offset_from(self, origin: *const T) -> isize - where - T: Sized, + where + T: Sized, { (self as *const T).wrapping_offset_from(origin) } @@ -425,8 +425,8 @@ impl<T: ?Sized> *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) } @@ -486,8 +486,8 @@ impl<T: ?Sized> *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()) } @@ -541,8 +541,8 @@ impl<T: ?Sized> *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) } @@ -596,8 +596,8 @@ impl<T: ?Sized> *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()) } @@ -611,8 +611,8 @@ impl<T: ?Sized> *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) } @@ -630,8 +630,8 @@ impl<T: ?Sized> *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) } @@ -647,8 +647,8 @@ impl<T: ?Sized> *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) } @@ -664,8 +664,8 @@ impl<T: ?Sized> *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) } @@ -681,8 +681,8 @@ impl<T: ?Sized> *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) } @@ -698,8 +698,8 @@ impl<T: ?Sized> *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) } @@ -715,8 +715,8 @@ impl<T: ?Sized> *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) } @@ -741,8 +741,8 @@ impl<T: ?Sized> *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) } @@ -756,8 +756,8 @@ impl<T: ?Sized> *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) } @@ -775,8 +775,8 @@ impl<T: ?Sized> *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) } @@ -792,8 +792,8 @@ impl<T: ?Sized> *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) } @@ -807,8 +807,8 @@ impl<T: ?Sized> *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) } @@ -823,8 +823,8 @@ impl<T: ?Sized> *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) } @@ -870,8 +870,8 @@ impl<T: ?Sized> *mut T { /// ``` #[stable(feature = "align_offset", since = "1.36.0")] pub fn align_offset(self, align: usize) -> usize - where - T: Sized, + where + T: Sized, { if !align.is_power_of_two() { panic!("align_offset: align is not a power-of-two"); @@ -884,7 +884,9 @@ impl<T: ?Sized> *mut T { #[stable(feature = "rust1", since = "1.0.0")] impl<T: ?Sized> 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")] @@ -912,14 +914,22 @@ impl<T: ?Sized> 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/result.rs b/src/libcore/result.rs index fb4dc62d8c1..ce4c8995a3c 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -283,7 +283,7 @@ impl<T, E> Result<T, E> { pub fn is_ok(&self) -> bool { match *self { Ok(_) => true, - Err(_) => false + Err(_) => false, } } @@ -328,10 +328,13 @@ impl<T, E> Result<T, E> { #[must_use] #[inline] #[unstable(feature = "option_result_contains", issue = "62358")] - pub fn contains<U>(&self, x: &U) -> bool where U: PartialEq<T> { + pub fn contains<U>(&self, x: &U) -> bool + where + U: PartialEq<T>, + { match self { Ok(y) => x == y, - Err(_) => false + Err(_) => false, } } @@ -354,10 +357,13 @@ impl<T, E> Result<T, E> { #[must_use] #[inline] #[unstable(feature = "result_contains_err", issue = "62358")] - pub fn contains_err<F>(&self, f: &F) -> bool where F: PartialEq<E> { + pub fn contains_err<F>(&self, f: &F) -> bool + where + F: PartialEq<E>, + { match self { Ok(_) => false, - Err(e) => f == e + Err(e) => f == e, } } @@ -387,7 +393,7 @@ impl<T, E> Result<T, E> { #[stable(feature = "rust1", since = "1.0.0")] pub fn ok(self) -> Option<T> { match self { - Ok(x) => Some(x), + Ok(x) => Some(x), Err(_) => None, } } @@ -414,7 +420,7 @@ impl<T, E> Result<T, E> { #[stable(feature = "rust1", since = "1.0.0")] pub fn err(self) -> Option<E> { match self { - Ok(_) => None, + Ok(_) => None, Err(x) => Some(x), } } @@ -507,10 +513,10 @@ impl<T, E> Result<T, E> { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U,E> { + pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U, E> { match self { Ok(t) => Ok(op(t)), - Err(e) => Err(e) + Err(e) => Err(e), } } @@ -591,10 +597,10 @@ impl<T, E> Result<T, E> { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T,F> { + pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T, F> { match self { Ok(t) => Ok(t), - Err(e) => Err(op(e)) + Err(e) => Err(op(e)), } } @@ -813,7 +819,7 @@ impl<T, E> Result<T, E> { pub fn unwrap_or(self, optb: T) -> T { match self { Ok(t) => t, - Err(_) => optb + Err(_) => optb, } } @@ -838,7 +844,7 @@ impl<T, E> Result<T, E> { pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T { match self { Ok(t) => t, - Err(e) => op(e) + Err(e) => op(e), } } } @@ -923,7 +929,6 @@ impl<T: Clone, E> Result<&mut T, E> { } } - impl<T, E: fmt::Debug> Result<T, E> { /// Unwraps a result, yielding the content of an [`Ok`]. /// @@ -1100,8 +1105,7 @@ impl<T, E: Deref> Result<T, E> { /// /// Leaves the original `Result` in-place, creating a new one containing a reference to the /// `Err` type's `Deref::Target` type. - pub fn as_deref_err(&self) -> Result<&T, &E::Target> - { + pub fn as_deref_err(&self) -> Result<&T, &E::Target> { self.as_ref().map_err(|e| e.deref()) } } @@ -1112,8 +1116,7 @@ impl<T: Deref, E: Deref> Result<T, E> { /// /// Leaves the original `Result` in-place, creating a new one containing a reference to both /// the `Ok` and `Err` types' `Deref::Target` types. - pub fn as_deref(&self) -> Result<&T::Target, &E::Target> - { + pub fn as_deref(&self) -> Result<&T::Target, &E::Target> { self.as_ref().map(|t| t.deref()).map_err(|e| e.deref()) } } @@ -1135,8 +1138,7 @@ impl<T, E: DerefMut> Result<T, E> { /// /// Leaves the original `Result` in-place, creating a new one containing a mutable reference to /// the `Err` type's `Deref::Target` type. - pub fn as_deref_mut_err(&mut self) -> Result<&mut T, &mut E::Target> - { + pub fn as_deref_mut_err(&mut self) -> Result<&mut T, &mut E::Target> { self.as_mut().map_err(|e| e.deref_mut()) } } @@ -1148,8 +1150,7 @@ impl<T: DerefMut, E: DerefMut> Result<T, E> { /// /// Leaves the original `Result` in-place, creating a new one containing a mutable reference to /// both the `Ok` and `Err` types' `Deref::Target` types. - pub fn as_deref_mut(&mut self) -> Result<&mut T::Target, &mut E::Target> - { + pub fn as_deref_mut(&mut self) -> Result<&mut T::Target, &mut E::Target> { self.as_mut().map(|t| t.deref_mut()).map_err(|e| e.deref_mut()) } } @@ -1212,7 +1213,6 @@ impl<T: Clone, E: Clone> Clone for Result<T, E> { } } - #[stable(feature = "rust1", since = "1.0.0")] impl<T, E> IntoIterator for Result<T, E> { type Item = T; @@ -1276,17 +1276,21 @@ impl<'a, T, E> IntoIterator for &'a mut Result<T, E> { /// [`Result::iter`]: enum.Result.html#method.iter #[derive(Debug)] #[stable(feature = "rust1", since = "1.0.0")] -pub struct Iter<'a, T: 'a> { inner: Option<&'a T> } +pub struct Iter<'a, T: 'a> { + inner: Option<&'a T>, +} #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T> Iterator for Iter<'a, T> { type Item = &'a T; #[inline] - fn next(&mut self) -> Option<&'a T> { self.inner.take() } + fn next(&mut self) -> Option<&'a T> { + self.inner.take() + } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { - let n = if self.inner.is_some() {1} else {0}; + let n = if self.inner.is_some() { 1 } else { 0 }; (n, Some(n)) } } @@ -1294,7 +1298,9 @@ impl<'a, T> Iterator for Iter<'a, T> { #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T> DoubleEndedIterator for Iter<'a, T> { #[inline] - fn next_back(&mut self) -> Option<&'a T> { self.inner.take() } + fn next_back(&mut self) -> Option<&'a T> { + self.inner.take() + } } #[stable(feature = "rust1", since = "1.0.0")] @@ -1309,7 +1315,9 @@ unsafe impl<A> TrustedLen for Iter<'_, A> {} #[stable(feature = "rust1", since = "1.0.0")] impl<T> Clone for Iter<'_, T> { #[inline] - fn clone(&self) -> Self { Iter { inner: self.inner } } + fn clone(&self) -> Self { + Iter { inner: self.inner } + } } /// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`]. @@ -1321,17 +1329,21 @@ impl<T> Clone for Iter<'_, T> { /// [`Result::iter_mut`]: enum.Result.html#method.iter_mut #[derive(Debug)] #[stable(feature = "rust1", since = "1.0.0")] -pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> } +pub struct IterMut<'a, T: 'a> { + inner: Option<&'a mut T>, +} #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T> Iterator for IterMut<'a, T> { type Item = &'a mut T; #[inline] - fn next(&mut self) -> Option<&'a mut T> { self.inner.take() } + fn next(&mut self) -> Option<&'a mut T> { + self.inner.take() + } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { - let n = if self.inner.is_some() {1} else {0}; + let n = if self.inner.is_some() { 1 } else { 0 }; (n, Some(n)) } } @@ -1339,7 +1351,9 @@ impl<'a, T> Iterator for IterMut<'a, T> { #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T> DoubleEndedIterator for IterMut<'a, T> { #[inline] - fn next_back(&mut self) -> Option<&'a mut T> { self.inner.take() } + fn next_back(&mut self) -> Option<&'a mut T> { + self.inner.take() + } } #[stable(feature = "rust1", since = "1.0.0")] @@ -1364,17 +1378,21 @@ unsafe impl<A> TrustedLen for IterMut<'_, A> {} /// [`IntoIterator`]: ../iter/trait.IntoIterator.html #[derive(Clone, Debug)] #[stable(feature = "rust1", since = "1.0.0")] -pub struct IntoIter<T> { inner: Option<T> } +pub struct IntoIter<T> { + inner: Option<T>, +} #[stable(feature = "rust1", since = "1.0.0")] impl<T> Iterator for IntoIter<T> { type Item = T; #[inline] - fn next(&mut self) -> Option<T> { self.inner.take() } + fn next(&mut self) -> Option<T> { + self.inner.take() + } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { - let n = if self.inner.is_some() {1} else {0}; + let n = if self.inner.is_some() { 1 } else { 0 }; (n, Some(n)) } } @@ -1382,7 +1400,9 @@ impl<T> Iterator for IntoIter<T> { #[stable(feature = "rust1", since = "1.0.0")] impl<T> DoubleEndedIterator for IntoIter<T> { #[inline] - fn next_back(&mut self) -> Option<T> { self.inner.take() } + fn next_back(&mut self) -> Option<T> { + self.inner.take() + } } #[stable(feature = "rust1", since = "1.0.0")] @@ -1443,7 +1463,7 @@ impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> { /// Since the third element caused an underflow, no further elements were taken, /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16. #[inline] - fn from_iter<I: IntoIterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> { + fn from_iter<I: IntoIterator<Item = Result<A, E>>>(iter: I) -> Result<V, E> { // FIXME(#11084): This could be replaced with Iterator::scan when this // performance bug is closed. @@ -1452,7 +1472,7 @@ impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> { } #[unstable(feature = "try_trait", issue = "42327")] -impl<T,E> ops::Try for Result<T, E> { +impl<T, E> ops::Try for Result<T, E> { type Ok = T; type Error = E; diff --git a/src/libcore/slice/mod.rs b/src/libcore/slice/mod.rs index 68e12e87789..5ddf5d48965 100644 --- a/src/libcore/slice/mod.rs +++ b/src/libcore/slice/mod.rs @@ -23,23 +23,26 @@ // * The `raw` and `bytes` submodules. // * Boilerplate trait implementations. -use crate::cmp::Ordering::{self, Less, Equal, Greater}; use crate::cmp; +use crate::cmp::Ordering::{self, Equal, Greater, Less}; use crate::fmt; -use crate::intrinsics::{assume, exact_div, unchecked_sub, is_aligned_and_not_null}; +use crate::intrinsics::{assume, exact_div, is_aligned_and_not_null, unchecked_sub}; use crate::isize; use crate::iter::*; -use crate::ops::{FnMut, Range, self}; +use crate::marker::{self, Copy, Send, Sized, Sync}; +use crate::mem; +use crate::ops::{self, FnMut, Range}; use crate::option::Option; use crate::option::Option::{None, Some}; -use crate::result::Result; -use crate::result::Result::{Ok, Err}; use crate::ptr; -use crate::mem; -use crate::marker::{Copy, Send, Sync, Sized, self}; +use crate::result::Result; +use crate::result::Result::{Err, Ok}; -#[unstable(feature = "slice_internals", issue = "none", - reason = "exposed from core to be reused in std; use the memchr crate")] +#[unstable( + feature = "slice_internals", + issue = "none", + reason = "exposed from core to be reused in std; use the memchr crate" +)] /// Pure rust memchr implementation, taken from rust-memchr pub mod memchr; @@ -68,9 +71,7 @@ impl<T> [T] { #[allow(unused_attributes)] #[allow_internal_unstable(const_fn_union)] pub const fn len(&self) -> usize { - unsafe { - crate::ptr::Repr { rust: self }.raw.len - } + unsafe { crate::ptr::Repr { rust: self }.raw.len } } /// Returns `true` if the slice has a length of 0. @@ -158,7 +159,9 @@ impl<T> [T] { #[stable(feature = "slice_splits", since = "1.5.0")] #[inline] pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> { - if self.is_empty() { None } else { + if self.is_empty() { + None + } else { let split = self.split_at_mut(1); Some((&mut split.0[0], split.1)) } @@ -201,11 +204,12 @@ impl<T> [T] { #[inline] pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> { let len = self.len(); - if len == 0 { None } else { + if len == 0 { + None + } else { let split = self.split_at_mut(len - 1); Some((&mut split.1[0], split.0)) } - } /// Returns the last element of the slice, or `None` if it is empty. @@ -265,7 +269,8 @@ impl<T> [T] { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn get<I>(&self, index: I) -> Option<&I::Output> - where I: SliceIndex<Self> + where + I: SliceIndex<Self>, { index.get(self) } @@ -288,7 +293,8 @@ impl<T> [T] { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output> - where I: SliceIndex<Self> + where + I: SliceIndex<Self>, { index.get_mut(self) } @@ -316,7 +322,8 @@ impl<T> [T] { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output - where I: SliceIndex<Self> + where + I: SliceIndex<Self>, { index.get_unchecked(self) } @@ -346,7 +353,8 @@ impl<T> [T] { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output - where I: SliceIndex<Self> + where + I: SliceIndex<Self>, { index.get_unchecked_mut(self) } @@ -549,8 +557,7 @@ impl<T> [T] { // will be, when the length is odd -- so there's no way of emitting // pre- and postludes to use fully-aligned SIMD in the middle.) - let fast_unaligned = - cfg!(any(target_arch = "x86", target_arch = "x86_64")); + let fast_unaligned = cfg!(any(target_arch = "x86", target_arch = "x86_64")); if fast_unaligned && mem::size_of::<T>() == 1 { // Use the llvm.bswap intrinsic to reverse u8s in a usize @@ -621,11 +628,7 @@ impl<T> [T] { ptr.add(self.len()) }; - Iter { - ptr, - end, - _marker: marker::PhantomData - } + Iter { ptr, end, _marker: marker::PhantomData } } } @@ -653,11 +656,7 @@ impl<T> [T] { ptr.add(self.len()) }; - IterMut { - ptr, - end, - _marker: marker::PhantomData - } + IterMut { ptr, end, _marker: marker::PhantomData } } } @@ -1081,8 +1080,7 @@ impl<T> [T] { unsafe { assert!(mid <= len); - (from_raw_parts_mut(ptr, mid), - from_raw_parts_mut(ptr.add(mid), len - mid)) + (from_raw_parts_mut(ptr, mid), from_raw_parts_mut(ptr.add(mid), len - mid)) } } @@ -1129,13 +1127,10 @@ impl<T> [T] { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn split<F>(&self, pred: F) -> Split<'_, T, F> - where F: FnMut(&T) -> bool + where + F: FnMut(&T) -> bool, { - Split { - v: self, - pred, - finished: false - } + Split { v: self, pred, finished: false } } /// Returns an iterator over mutable subslices separated by elements that @@ -1154,7 +1149,8 @@ impl<T> [T] { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F> - where F: FnMut(&T) -> bool + where + F: FnMut(&T) -> bool, { SplitMut { v: self, pred, finished: false } } @@ -1189,7 +1185,8 @@ impl<T> [T] { #[stable(feature = "slice_rsplit", since = "1.27.0")] #[inline] pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F> - where F: FnMut(&T) -> bool + where + F: FnMut(&T) -> bool, { RSplit { inner: self.split(pred) } } @@ -1214,7 +1211,8 @@ impl<T> [T] { #[stable(feature = "slice_rsplit", since = "1.27.0")] #[inline] pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F> - where F: FnMut(&T) -> bool + where + F: FnMut(&T) -> bool, { RSplitMut { inner: self.split_mut(pred) } } @@ -1241,14 +1239,10 @@ impl<T> [T] { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F> - where F: FnMut(&T) -> bool + where + F: FnMut(&T) -> bool, { - SplitN { - inner: GenericSplitN { - iter: self.split(pred), - count: n - } - } + SplitN { inner: GenericSplitN { iter: self.split(pred), count: n } } } /// Returns an iterator over subslices separated by elements that match @@ -1271,14 +1265,10 @@ impl<T> [T] { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F> - where F: FnMut(&T) -> bool + where + F: FnMut(&T) -> bool, { - SplitNMut { - inner: GenericSplitN { - iter: self.split_mut(pred), - count: n - } - } + SplitNMut { inner: GenericSplitN { iter: self.split_mut(pred), count: n } } } /// Returns an iterator over subslices separated by elements that match @@ -1304,14 +1294,10 @@ impl<T> [T] { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F> - where F: FnMut(&T) -> bool + where + F: FnMut(&T) -> bool, { - RSplitN { - inner: GenericSplitN { - iter: self.rsplit(pred), - count: n - } - } + RSplitN { inner: GenericSplitN { iter: self.rsplit(pred), count: n } } } /// Returns an iterator over subslices separated by elements that match @@ -1335,14 +1321,10 @@ impl<T> [T] { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F> - where F: FnMut(&T) -> bool + where + F: FnMut(&T) -> bool, { - RSplitNMut { - inner: GenericSplitN { - iter: self.rsplit_mut(pred), - count: n - } - } + RSplitNMut { inner: GenericSplitN { iter: self.rsplit_mut(pred), count: n } } } /// Returns `true` if the slice contains an element with the given value. @@ -1365,7 +1347,8 @@ impl<T> [T] { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn contains(&self, x: &T) -> bool - where T: PartialEq + where + T: PartialEq, { x.slice_contains(self) } @@ -1392,7 +1375,8 @@ impl<T> [T] { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn starts_with(&self, needle: &[T]) -> bool - where T: PartialEq + where + T: PartialEq, { let n = needle.len(); self.len() >= n && needle == &self[..n] @@ -1420,10 +1404,11 @@ impl<T> [T] { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn ends_with(&self, needle: &[T]) -> bool - where T: PartialEq + where + T: PartialEq, { let (m, n) = (self.len(), needle.len()); - m >= n && needle == &self[m-n..] + m >= n && needle == &self[m - n..] } /// Binary searches this sorted slice for a given element. @@ -1462,7 +1447,8 @@ impl<T> [T] { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn binary_search(&self, x: &T) -> Result<usize, usize> - where T: Ord + where + T: Ord, { self.binary_search_by(|p| p.cmp(x)) } @@ -1502,7 +1488,8 @@ impl<T> [T] { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize> - where F: FnMut(&'a T) -> Ordering + where + F: FnMut(&'a T) -> Ordering, { let s = self; let mut size = s.len(); @@ -1523,7 +1510,6 @@ impl<T> [T] { // base is always in [0, size) because base <= mid. let cmp = f(unsafe { s.get_unchecked(base) }); if cmp == Equal { Ok(base) } else { Err(base + (cmp == Less) as usize) } - } /// Binary searches this sorted slice with a key extraction function. @@ -1560,8 +1546,9 @@ impl<T> [T] { #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")] #[inline] pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize> - where F: FnMut(&'a T) -> B, - B: Ord + where + F: FnMut(&'a T) -> B, + B: Ord, { self.binary_search_by(|k| f(k).cmp(b)) } @@ -1595,7 +1582,8 @@ impl<T> [T] { #[stable(feature = "sort_unstable", since = "1.20.0")] #[inline] pub fn sort_unstable(&mut self) - where T: Ord + where + T: Ord, { sort::quicksort(self, |a, b| a.lt(b)); } @@ -1649,7 +1637,8 @@ impl<T> [T] { #[stable(feature = "sort_unstable", since = "1.20.0")] #[inline] pub fn sort_unstable_by<F>(&mut self, mut compare: F) - where F: FnMut(&T, &T) -> Ordering + where + F: FnMut(&T, &T) -> Ordering, { sort::quicksort(self, |a, b| compare(a, b) == Ordering::Less); } @@ -1686,7 +1675,9 @@ impl<T> [T] { #[stable(feature = "sort_unstable", since = "1.20.0")] #[inline] pub fn sort_unstable_by_key<K, F>(&mut self, mut f: F) - where F: FnMut(&T) -> K, K: Ord + where + F: FnMut(&T) -> K, + K: Ord, { sort::quicksort(self, |a, b| f(a).lt(&f(b))); } @@ -1732,7 +1723,8 @@ impl<T> [T] { #[unstable(feature = "slice_partition_at_index", issue = "55300")] #[inline] pub fn partition_at_index(&mut self, index: usize) -> (&mut [T], &mut T, &mut [T]) - where T: Ord + where + T: Ord, { let mut f = |a: &T, b: &T| a.lt(b); sort::partition_at_index(self, index, &mut f) @@ -1780,9 +1772,13 @@ impl<T> [T] { /// ``` #[unstable(feature = "slice_partition_at_index", issue = "55300")] #[inline] - pub fn partition_at_index_by<F>(&mut self, index: usize, mut compare: F) - -> (&mut [T], &mut T, &mut [T]) - where F: FnMut(&T, &T) -> Ordering + pub fn partition_at_index_by<F>( + &mut self, + index: usize, + mut compare: F, + ) -> (&mut [T], &mut T, &mut [T]) + where + F: FnMut(&T, &T) -> Ordering, { let mut f = |a: &T, b: &T| compare(a, b) == Less; sort::partition_at_index(self, index, &mut f) @@ -1830,9 +1826,14 @@ impl<T> [T] { /// ``` #[unstable(feature = "slice_partition_at_index", issue = "55300")] #[inline] - pub fn partition_at_index_by_key<K, F>(&mut self, index: usize, mut f: F) - -> (&mut [T], &mut T, &mut [T]) - where F: FnMut(&T) -> K, K: Ord + pub fn partition_at_index_by_key<K, F>( + &mut self, + index: usize, + mut f: F, + ) -> (&mut [T], &mut T, &mut [T]) + where + F: FnMut(&T) -> K, + K: Ord, { let mut g = |a: &T, b: &T| f(a).lt(&f(b)); sort::partition_at_index(self, index, &mut g) @@ -1861,7 +1862,8 @@ impl<T> [T] { #[unstable(feature = "slice_partition_dedup", issue = "54279")] #[inline] pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T]) - where T: PartialEq + where + T: PartialEq, { self.partition_dedup_by(|a, b| a == b) } @@ -1894,7 +1896,8 @@ impl<T> [T] { #[unstable(feature = "slice_partition_dedup", issue = "54279")] #[inline] pub fn partition_dedup_by<F>(&mut self, mut same_bucket: F) -> (&mut [T], &mut [T]) - where F: FnMut(&mut T, &mut T) -> bool + where + F: FnMut(&mut T, &mut T) -> bool, { // Although we have a mutable reference to `self`, we cannot make // *arbitrary* changes. The `same_bucket` calls could panic, so we @@ -1955,7 +1958,7 @@ impl<T> [T] { let len = self.len(); if len <= 1 { - return (self, &mut []) + return (self, &mut []); } let ptr = self.as_mut_ptr(); @@ -2004,8 +2007,9 @@ impl<T> [T] { #[unstable(feature = "slice_partition_dedup", issue = "54279")] #[inline] pub fn partition_dedup_by_key<K, F>(&mut self, mut key: F) -> (&mut [T], &mut [T]) - where F: FnMut(&mut T) -> K, - K: PartialEq, + where + F: FnMut(&mut T) -> K, + K: PartialEq, { self.partition_dedup_by(|a, b| key(a) == key(b)) } @@ -2148,9 +2152,11 @@ impl<T> [T] { /// [`copy_from_slice`]: #method.copy_from_slice /// [`split_at_mut`]: #method.split_at_mut #[stable(feature = "clone_from_slice", since = "1.7.0")] - pub fn clone_from_slice(&mut self, src: &[T]) where T: Clone { - assert!(self.len() == src.len(), - "destination and source slices have different lengths"); + pub fn clone_from_slice(&mut self, src: &[T]) + where + T: Clone, + { + assert!(self.len() == src.len(), "destination and source slices have different lengths"); // NOTE: We need to explicitly slice them to the same length // for bounds checking to be elided, and the optimizer will // generate memcpy for simple cases (for example T = u8). @@ -2159,7 +2165,6 @@ impl<T> [T] { for i in 0..len { self[i].clone_from(&src[i]); } - } /// Copies all elements from `src` into `self`, using a memcpy. @@ -2217,12 +2222,13 @@ impl<T> [T] { /// [`clone_from_slice`]: #method.clone_from_slice /// [`split_at_mut`]: #method.split_at_mut #[stable(feature = "copy_from_slice", since = "1.9.0")] - pub fn copy_from_slice(&mut self, src: &[T]) where T: Copy { - assert_eq!(self.len(), src.len(), - "destination and source slices have different lengths"); + pub fn copy_from_slice(&mut self, src: &[T]) + where + T: Copy, + { + assert_eq!(self.len(), src.len(), "destination and source slices have different lengths"); unsafe { - ptr::copy_nonoverlapping( - src.as_ptr(), self.as_mut_ptr(), self.len()); + ptr::copy_nonoverlapping(src.as_ptr(), self.as_mut_ptr(), self.len()); } } @@ -2257,15 +2263,15 @@ impl<T> [T] { { let src_start = match src.start_bound() { ops::Bound::Included(&n) => n, - ops::Bound::Excluded(&n) => n - .checked_add(1) - .unwrap_or_else(|| slice_index_overflow_fail()), + ops::Bound::Excluded(&n) => { + n.checked_add(1).unwrap_or_else(|| slice_index_overflow_fail()) + } ops::Bound::Unbounded => 0, }; let src_end = match src.end_bound() { - ops::Bound::Included(&n) => n - .checked_add(1) - .unwrap_or_else(|| slice_index_overflow_fail()), + ops::Bound::Included(&n) => { + n.checked_add(1).unwrap_or_else(|| slice_index_overflow_fail()) + } ops::Bound::Excluded(&n) => n, ops::Bound::Unbounded => self.len(), }; @@ -2274,11 +2280,7 @@ impl<T> [T] { let count = src_end - src_start; assert!(dest <= self.len() - count, "dest is out of bounds"); unsafe { - ptr::copy( - self.as_ptr().add(src_start), - self.as_mut_ptr().add(dest), - count, - ); + ptr::copy(self.as_ptr().add(src_start), self.as_mut_ptr().add(dest), count); } } @@ -2331,11 +2333,9 @@ impl<T> [T] { /// [`split_at_mut`]: #method.split_at_mut #[stable(feature = "swap_with_slice", since = "1.27.0")] pub fn swap_with_slice(&mut self, other: &mut [T]) { - assert!(self.len() == other.len(), - "destination and source slices have different lengths"); + assert!(self.len() == other.len(), "destination and source slices have different lengths"); unsafe { - ptr::swap_nonoverlapping( - self.as_mut_ptr(), other.as_mut_ptr(), self.len()); + ptr::swap_nonoverlapping(self.as_mut_ptr(), other.as_mut_ptr(), self.len()); } } @@ -2366,8 +2366,12 @@ impl<T> [T] { // We should still make this `const fn` (and revert to recursive algorithm if we do) // because relying on llvm to consteval all this is… well, it makes me uncomfortable. let (ctz_a, mut ctz_b) = unsafe { - if a == 0 { return b; } - if b == 0 { return a; } + if a == 0 { + return b; + } + if b == 0 { + return a; + } (intrinsics::cttz_nonzero(a), intrinsics::cttz_nonzero(b)) }; let k = ctz_a.min(ctz_b); @@ -2448,9 +2452,11 @@ impl<T> [T] { let (left, rest) = self.split_at(offset); // now `rest` is definitely aligned, so `from_raw_parts_mut` below is okay let (us_len, ts_len) = rest.align_to_offsets::<U>(); - (left, - from_raw_parts(rest.as_ptr() as *const U, us_len), - from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len)) + ( + left, + from_raw_parts(rest.as_ptr() as *const U, us_len), + from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len), + ) } } @@ -2503,9 +2509,11 @@ impl<T> [T] { // now `rest` is definitely aligned, so `from_raw_parts_mut` below is okay let (us_len, ts_len) = rest.align_to_offsets::<U>(); let mut_ptr = rest.as_mut_ptr(); - (left, - from_raw_parts_mut(mut_ptr as *mut U, us_len), - from_raw_parts_mut(mut_ptr.add(rest.len() - ts_len), ts_len)) + ( + left, + from_raw_parts_mut(mut_ptr as *mut U, us_len), + from_raw_parts_mut(mut_ptr.add(rest.len() - ts_len), ts_len), + ) } } @@ -2549,7 +2557,7 @@ impl<T> [T] { #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")] pub fn is_sorted_by<F>(&self, mut compare: F) -> bool where - F: FnMut(&T, &T) -> Option<Ordering> + F: FnMut(&T, &T) -> Option<Ordering>, { self.iter().is_sorted_by(|a, b| compare(*a, *b)) } @@ -2575,7 +2583,7 @@ impl<T> [T] { pub fn is_sorted_by_key<F, K>(&self, f: F) -> bool where F: FnMut(&T) -> K, - K: PartialOrd + K: PartialOrd, { self.iter().is_sorted_by_key(f) } @@ -2598,10 +2606,7 @@ impl [u8] { #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] #[inline] pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool { - self.len() == other.len() && - self.iter().zip(other).all(|(a, b)| { - a.eq_ignore_ascii_case(b) - }) + self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a.eq_ignore_ascii_case(b)) } /// Converts this slice to its ASCII upper case equivalent in-place. @@ -2637,12 +2642,12 @@ impl [u8] { byte.make_ascii_lowercase(); } } - } #[stable(feature = "rust1", since = "1.0.0")] impl<T, I> ops::Index<I> for [T] - where I: SliceIndex<[T]> +where + I: SliceIndex<[T]>, { type Output = I::Output; @@ -2654,7 +2659,8 @@ impl<T, I> ops::Index<I> for [T] #[stable(feature = "rust1", since = "1.0.0")] impl<T, I> ops::IndexMut<I> for [T] - where I: SliceIndex<[T]> +where + I: SliceIndex<[T]>, { #[inline] fn index_mut(&mut self, index: I) -> &mut I::Output { @@ -2704,17 +2710,14 @@ mod private_slice_index { /// A helper trait used for indexing operations. #[stable(feature = "slice_get_slice", since = "1.28.0")] #[rustc_on_unimplemented( + on(T = "str", label = "string indices are ranges of `usize`",), on( - T = "str", - label = "string indices are ranges of `usize`", - ), - on( - all(any(T = "str", T = "&str", T = "std::string::String"), _Self="{integer}"), - note="you can use `.chars().nth()` or `.bytes().nth()` + all(any(T = "str", T = "&str", T = "std::string::String"), _Self = "{integer}"), + note = "you can use `.chars().nth()` or `.bytes().nth()` see chapter in The Book <https://doc.rust-lang.org/book/ch08-02-strings.html#indexing-into-strings>" ), message = "the type `{T}` cannot be indexed by `{Self}`", - label = "slice indices are of type `usize` or ranges of `usize`", + label = "slice indices are of type `usize` or ranges of `usize`" )] pub trait SliceIndex<T: ?Sized>: private_slice_index::Sealed { /// The output type returned by methods. @@ -2764,24 +2767,12 @@ impl<T> SliceIndex<[T]> for usize { #[inline] fn get(self, slice: &[T]) -> Option<&T> { - if self < slice.len() { - unsafe { - Some(self.get_unchecked(slice)) - } - } else { - None - } + if self < slice.len() { unsafe { Some(self.get_unchecked(slice)) } } else { None } } #[inline] fn get_mut(self, slice: &mut [T]) -> Option<&mut T> { - if self < slice.len() { - unsafe { - Some(self.get_unchecked_mut(slice)) - } - } else { - None - } + if self < slice.len() { unsafe { Some(self.get_unchecked_mut(slice)) } } else { None } } #[inline] @@ -2808,7 +2799,7 @@ impl<T> SliceIndex<[T]> for usize { } #[stable(feature = "slice_get_slice_impls", since = "1.15.0")] -impl<T> SliceIndex<[T]> for ops::Range<usize> { +impl<T> SliceIndex<[T]> for ops::Range<usize> { type Output = [T]; #[inline] @@ -2816,9 +2807,7 @@ impl<T> SliceIndex<[T]> for ops::Range<usize> { if self.start > self.end || self.end > slice.len() { None } else { - unsafe { - Some(self.get_unchecked(slice)) - } + unsafe { Some(self.get_unchecked(slice)) } } } @@ -2827,9 +2816,7 @@ impl<T> SliceIndex<[T]> for ops::Range<usize> { if self.start > self.end || self.end > slice.len() { None } else { - unsafe { - Some(self.get_unchecked_mut(slice)) - } + unsafe { Some(self.get_unchecked_mut(slice)) } } } @@ -2850,9 +2837,7 @@ impl<T> SliceIndex<[T]> for ops::Range<usize> { } else if self.end > slice.len() { slice_index_len_fail(self.end, slice.len()); } - unsafe { - self.get_unchecked(slice) - } + unsafe { self.get_unchecked(slice) } } #[inline] @@ -2862,9 +2847,7 @@ impl<T> SliceIndex<[T]> for ops::Range<usize> { } else if self.end > slice.len() { slice_index_len_fail(self.end, slice.len()); } - unsafe { - self.get_unchecked_mut(slice) - } + unsafe { self.get_unchecked_mut(slice) } } } @@ -2973,21 +2956,26 @@ impl<T> SliceIndex<[T]> for ops::RangeFull { } } - #[stable(feature = "inclusive_range", since = "1.26.0")] impl<T> SliceIndex<[T]> for ops::RangeInclusive<usize> { type Output = [T]; #[inline] fn get(self, slice: &[T]) -> Option<&[T]> { - if *self.end() == usize::max_value() { None } - else { (*self.start()..self.end() + 1).get(slice) } + if *self.end() == usize::max_value() { + None + } else { + (*self.start()..self.end() + 1).get(slice) + } } #[inline] fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> { - if *self.end() == usize::max_value() { None } - else { (*self.start()..self.end() + 1).get_mut(slice) } + if *self.end() == usize::max_value() { + None + } else { + (*self.start()..self.end() + 1).get_mut(slice) + } } #[inline] @@ -3002,13 +2990,17 @@ impl<T> SliceIndex<[T]> for ops::RangeInclusive<usize> { #[inline] fn index(self, slice: &[T]) -> &[T] { - if *self.end() == usize::max_value() { slice_index_overflow_fail(); } + if *self.end() == usize::max_value() { + slice_index_overflow_fail(); + } (*self.start()..self.end() + 1).index(slice) } #[inline] fn index_mut(self, slice: &mut [T]) -> &mut [T] { - if *self.end() == usize::max_value() { slice_index_overflow_fail(); } + if *self.end() == usize::max_value() { + slice_index_overflow_fail(); + } (*self.start()..self.end() + 1).index_mut(slice) } } @@ -3055,13 +3047,17 @@ impl<T> SliceIndex<[T]> for ops::RangeToInclusive<usize> { #[stable(feature = "rust1", since = "1.0.0")] impl<T> Default for &[T] { /// Creates an empty slice. - fn default() -> Self { &[] } + fn default() -> Self { + &[] + } } #[stable(feature = "mut_slice_default", since = "1.5.0")] impl<T> Default for &mut [T] { /// Creates a mutable empty slice. - fn default() -> Self { &mut [] } + fn default() -> Self { + &mut [] + } } // @@ -3098,7 +3094,9 @@ fn size_from_ptr<T>(_: *const T) -> usize { macro_rules! is_empty { // The way we encode the length of a ZST iterator, this works both for ZST // and non-ZST. - ($self: ident) => {$self.ptr == $self.end} + ($self: ident) => { + $self.ptr == $self.end + }; } // To get rid of some bounds checks (see `position`), we compute the length in a somewhat // unexpected way. (Tested by `codegen/slice-position-bounds-check`.) @@ -3125,7 +3123,7 @@ macro_rules! len { // distance between them must be a multiple of pointee size unsafe { exact_div(diff, size) } } - }} + }}; } // The shared definition of the `Iter` and `IterMut` iterators @@ -3369,17 +3367,15 @@ macro_rules! iterator { pub struct Iter<'a, T: 'a> { ptr: *const T, end: *const T, // If T is a ZST, this is actually ptr+len. This encoding is picked so that - // ptr == end is a quick test for the Iterator being empty, that works - // for both ZST and non-ZST. + // ptr == end is a quick test for the Iterator being empty, that works + // for both ZST and non-ZST. _marker: marker::PhantomData<&'a T>, } #[stable(feature = "core_impl_debug", since = "1.9.0")] impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_tuple("Iter") - .field(&self.as_slice()) - .finish() + f.debug_tuple("Iter").field(&self.as_slice()).finish() } } @@ -3419,7 +3415,7 @@ impl<'a, T> Iter<'a, T> { } } -iterator!{struct Iter -> *const T, &'a T, const, {/* no mut */}, { +iterator! {struct Iter -> *const T, &'a T, const, {/* no mut */}, { fn is_sorted_by<F>(self, mut compare: F) -> bool where Self: Sized, @@ -3433,7 +3429,9 @@ iterator!{struct Iter -> *const T, &'a T, const, {/* no mut */}, { #[stable(feature = "rust1", since = "1.0.0")] impl<T> Clone for Iter<'_, T> { - fn clone(&self) -> Self { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } } + fn clone(&self) -> Self { + Iter { ptr: self.ptr, end: self.end, _marker: self._marker } + } } #[stable(feature = "slice_iter_as_ref", since = "1.13.0")] @@ -3471,17 +3469,15 @@ impl<T> AsRef<[T]> for Iter<'_, T> { pub struct IterMut<'a, T: 'a> { ptr: *mut T, end: *mut T, // If T is a ZST, this is actually ptr+len. This encoding is picked so that - // ptr == end is a quick test for the Iterator being empty, that works - // for both ZST and non-ZST. + // ptr == end is a quick test for the Iterator being empty, that works + // for both ZST and non-ZST. _marker: marker::PhantomData<&'a mut T>, } #[stable(feature = "core_impl_debug", since = "1.9.0")] impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_tuple("IterMut") - .field(&self.make_slice()) - .finish() + f.debug_tuple("IterMut").field(&self.make_slice()).finish() } } @@ -3558,7 +3554,7 @@ impl<'a, T> IterMut<'a, T> { } } -iterator!{struct IterMut -> *mut T, &'a mut T, mut, {mut}, {}} +iterator! {struct IterMut -> *mut T, &'a mut T, mut, {mut}, {}} /// An internal abstraction over the splitting iterators, so that /// splitn, splitn_mut etc can be implemented once. @@ -3577,41 +3573,48 @@ trait SplitIter: DoubleEndedIterator { /// [`split`]: ../../std/primitive.slice.html#method.split /// [slices]: ../../std/primitive.slice.html #[stable(feature = "rust1", since = "1.0.0")] -pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool { +pub struct Split<'a, T: 'a, P> +where + P: FnMut(&T) -> bool, +{ v: &'a [T], pred: P, - finished: bool + finished: bool, } #[stable(feature = "core_impl_debug", since = "1.9.0")] -impl<T: fmt::Debug, P> fmt::Debug for Split<'_, T, P> where P: FnMut(&T) -> bool { +impl<T: fmt::Debug, P> fmt::Debug for Split<'_, T, P> +where + P: FnMut(&T) -> bool, +{ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Split") - .field("v", &self.v) - .field("finished", &self.finished) - .finish() + f.debug_struct("Split").field("v", &self.v).field("finished", &self.finished).finish() } } // FIXME(#26925) Remove in favor of `#[derive(Clone)]` #[stable(feature = "rust1", since = "1.0.0")] -impl<T, P> Clone for Split<'_, T, P> where P: Clone + FnMut(&T) -> bool { +impl<T, P> Clone for Split<'_, T, P> +where + P: Clone + FnMut(&T) -> bool, +{ fn clone(&self) -> Self { - Split { - v: self.v, - pred: self.pred.clone(), - finished: self.finished, - } + Split { v: self.v, pred: self.pred.clone(), finished: self.finished } } } #[stable(feature = "rust1", since = "1.0.0")] -impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool { +impl<'a, T, P> Iterator for Split<'a, T, P> +where + P: FnMut(&T) -> bool, +{ type Item = &'a [T]; #[inline] fn next(&mut self) -> Option<&'a [T]> { - if self.finished { return None; } + if self.finished { + return None; + } match self.v.iter().position(|x| (self.pred)(x)) { None => self.finish(), @@ -3625,19 +3628,20 @@ impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool { #[inline] fn size_hint(&self) -> (usize, Option<usize>) { - if self.finished { - (0, Some(0)) - } else { - (1, Some(self.v.len() + 1)) - } + if self.finished { (0, Some(0)) } else { (1, Some(self.v.len() + 1)) } } } #[stable(feature = "rust1", since = "1.0.0")] -impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool { +impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> +where + P: FnMut(&T) -> bool, +{ #[inline] fn next_back(&mut self) -> Option<&'a [T]> { - if self.finished { return None; } + if self.finished { + return None; + } match self.v.iter().rposition(|x| (self.pred)(x)) { None => self.finish(), @@ -3650,10 +3654,18 @@ impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> boo } } -impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool { +impl<'a, T, P> SplitIter for Split<'a, T, P> +where + P: FnMut(&T) -> bool, +{ #[inline] fn finish(&mut self) -> Option<&'a [T]> { - if self.finished { None } else { self.finished = true; Some(self.v) } + if self.finished { + None + } else { + self.finished = true; + Some(self.v) + } } } @@ -3668,23 +3680,29 @@ impl<T, P> FusedIterator for Split<'_, T, P> where P: FnMut(&T) -> bool {} /// [`split_mut`]: ../../std/primitive.slice.html#method.split_mut /// [slices]: ../../std/primitive.slice.html #[stable(feature = "rust1", since = "1.0.0")] -pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool { +pub struct SplitMut<'a, T: 'a, P> +where + P: FnMut(&T) -> bool, +{ v: &'a mut [T], pred: P, - finished: bool + finished: bool, } #[stable(feature = "core_impl_debug", since = "1.9.0")] -impl<T: fmt::Debug, P> fmt::Debug for SplitMut<'_, T, P> where P: FnMut(&T) -> bool { +impl<T: fmt::Debug, P> fmt::Debug for SplitMut<'_, T, P> +where + P: FnMut(&T) -> bool, +{ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("SplitMut") - .field("v", &self.v) - .field("finished", &self.finished) - .finish() + f.debug_struct("SplitMut").field("v", &self.v).field("finished", &self.finished).finish() } } -impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool { +impl<'a, T, P> SplitIter for SplitMut<'a, T, P> +where + P: FnMut(&T) -> bool, +{ #[inline] fn finish(&mut self) -> Option<&'a mut [T]> { if self.finished { @@ -3697,14 +3715,20 @@ impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool { } #[stable(feature = "rust1", since = "1.0.0")] -impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool { +impl<'a, T, P> Iterator for SplitMut<'a, T, P> +where + P: FnMut(&T) -> bool, +{ type Item = &'a mut [T]; #[inline] fn next(&mut self) -> Option<&'a mut [T]> { - if self.finished { return None; } + if self.finished { + return None; + } - let idx_opt = { // work around borrowck limitations + let idx_opt = { + // work around borrowck limitations let pred = &mut self.pred; self.v.iter().position(|x| (*pred)(x)) }; @@ -3732,14 +3756,18 @@ impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool { } #[stable(feature = "rust1", since = "1.0.0")] -impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where +impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> +where P: FnMut(&T) -> bool, { #[inline] fn next_back(&mut self) -> Option<&'a mut [T]> { - if self.finished { return None; } + if self.finished { + return None; + } - let idx_opt = { // work around borrowck limitations + let idx_opt = { + // work around borrowck limitations let pred = &mut self.pred; self.v.iter().rposition(|x| (*pred)(x)) }; @@ -3767,12 +3795,18 @@ impl<T, P> FusedIterator for SplitMut<'_, T, P> where P: FnMut(&T) -> bool {} /// [slices]: ../../std/primitive.slice.html #[stable(feature = "slice_rsplit", since = "1.27.0")] #[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`? -pub struct RSplit<'a, T:'a, P> where P: FnMut(&T) -> bool { - inner: Split<'a, T, P> +pub struct RSplit<'a, T: 'a, P> +where + P: FnMut(&T) -> bool, +{ + inner: Split<'a, T, P>, } #[stable(feature = "slice_rsplit", since = "1.27.0")] -impl<T: fmt::Debug, P> fmt::Debug for RSplit<'_, T, P> where P: FnMut(&T) -> bool { +impl<T: fmt::Debug, P> fmt::Debug for RSplit<'_, T, P> +where + P: FnMut(&T) -> bool, +{ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("RSplit") .field("v", &self.inner.v) @@ -3782,7 +3816,10 @@ impl<T: fmt::Debug, P> fmt::Debug for RSplit<'_, T, P> where P: FnMut(&T) -> boo } #[stable(feature = "slice_rsplit", since = "1.27.0")] -impl<'a, T, P> Iterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool { +impl<'a, T, P> Iterator for RSplit<'a, T, P> +where + P: FnMut(&T) -> bool, +{ type Item = &'a [T]; #[inline] @@ -3797,7 +3834,10 @@ impl<'a, T, P> Iterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool { } #[stable(feature = "slice_rsplit", since = "1.27.0")] -impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool { +impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P> +where + P: FnMut(&T) -> bool, +{ #[inline] fn next_back(&mut self) -> Option<&'a [T]> { self.inner.next() @@ -3805,7 +3845,10 @@ impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bo } #[stable(feature = "slice_rsplit", since = "1.27.0")] -impl<'a, T, P> SplitIter for RSplit<'a, T, P> where P: FnMut(&T) -> bool { +impl<'a, T, P> SplitIter for RSplit<'a, T, P> +where + P: FnMut(&T) -> bool, +{ #[inline] fn finish(&mut self) -> Option<&'a [T]> { self.inner.finish() @@ -3823,12 +3866,18 @@ impl<T, P> FusedIterator for RSplit<'_, T, P> where P: FnMut(&T) -> bool {} /// [`rsplit_mut`]: ../../std/primitive.slice.html#method.rsplit_mut /// [slices]: ../../std/primitive.slice.html #[stable(feature = "slice_rsplit", since = "1.27.0")] -pub struct RSplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool { - inner: SplitMut<'a, T, P> +pub struct RSplitMut<'a, T: 'a, P> +where + P: FnMut(&T) -> bool, +{ + inner: SplitMut<'a, T, P>, } #[stable(feature = "slice_rsplit", since = "1.27.0")] -impl<T: fmt::Debug, P> fmt::Debug for RSplitMut<'_, T, P> where P: FnMut(&T) -> bool { +impl<T: fmt::Debug, P> fmt::Debug for RSplitMut<'_, T, P> +where + P: FnMut(&T) -> bool, +{ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("RSplitMut") .field("v", &self.inner.v) @@ -3838,7 +3887,10 @@ impl<T: fmt::Debug, P> fmt::Debug for RSplitMut<'_, T, P> where P: FnMut(&T) -> } #[stable(feature = "slice_rsplit", since = "1.27.0")] -impl<'a, T, P> SplitIter for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool { +impl<'a, T, P> SplitIter for RSplitMut<'a, T, P> +where + P: FnMut(&T) -> bool, +{ #[inline] fn finish(&mut self) -> Option<&'a mut [T]> { self.inner.finish() @@ -3846,7 +3898,10 @@ impl<'a, T, P> SplitIter for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool { } #[stable(feature = "slice_rsplit", since = "1.27.0")] -impl<'a, T, P> Iterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool { +impl<'a, T, P> Iterator for RSplitMut<'a, T, P> +where + P: FnMut(&T) -> bool, +{ type Item = &'a mut [T]; #[inline] @@ -3861,7 +3916,8 @@ impl<'a, T, P> Iterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool { } #[stable(feature = "slice_rsplit", since = "1.27.0")] -impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P> where +impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P> +where P: FnMut(&T) -> bool, { #[inline] @@ -3882,15 +3938,21 @@ struct GenericSplitN<I> { count: usize, } -impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> { +impl<T, I: SplitIter<Item = T>> Iterator for GenericSplitN<I> { type Item = T; #[inline] fn next(&mut self) -> Option<T> { match self.count { 0 => None, - 1 => { self.count -= 1; self.iter.finish() } - _ => { self.count -= 1; self.iter.next() } + 1 => { + self.count -= 1; + self.iter.finish() + } + _ => { + self.count -= 1; + self.iter.next() + } } } @@ -3909,16 +3971,20 @@ impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> { /// [`splitn`]: ../../std/primitive.slice.html#method.splitn /// [slices]: ../../std/primitive.slice.html #[stable(feature = "rust1", since = "1.0.0")] -pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool { - inner: GenericSplitN<Split<'a, T, P>> +pub struct SplitN<'a, T: 'a, P> +where + P: FnMut(&T) -> bool, +{ + inner: GenericSplitN<Split<'a, T, P>>, } #[stable(feature = "core_impl_debug", since = "1.9.0")] -impl<T: fmt::Debug, P> fmt::Debug for SplitN<'_, T, P> where P: FnMut(&T) -> bool { +impl<T: fmt::Debug, P> fmt::Debug for SplitN<'_, T, P> +where + P: FnMut(&T) -> bool, +{ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("SplitN") - .field("inner", &self.inner) - .finish() + f.debug_struct("SplitN").field("inner", &self.inner).finish() } } @@ -3931,16 +3997,20 @@ impl<T: fmt::Debug, P> fmt::Debug for SplitN<'_, T, P> where P: FnMut(&T) -> boo /// [`rsplitn`]: ../../std/primitive.slice.html#method.rsplitn /// [slices]: ../../std/primitive.slice.html #[stable(feature = "rust1", since = "1.0.0")] -pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool { - inner: GenericSplitN<RSplit<'a, T, P>> +pub struct RSplitN<'a, T: 'a, P> +where + P: FnMut(&T) -> bool, +{ + inner: GenericSplitN<RSplit<'a, T, P>>, } #[stable(feature = "core_impl_debug", since = "1.9.0")] -impl<T: fmt::Debug, P> fmt::Debug for RSplitN<'_, T, P> where P: FnMut(&T) -> bool { +impl<T: fmt::Debug, P> fmt::Debug for RSplitN<'_, T, P> +where + P: FnMut(&T) -> bool, +{ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("RSplitN") - .field("inner", &self.inner) - .finish() + f.debug_struct("RSplitN").field("inner", &self.inner).finish() } } @@ -3952,16 +4022,20 @@ impl<T: fmt::Debug, P> fmt::Debug for RSplitN<'_, T, P> where P: FnMut(&T) -> bo /// [`splitn_mut`]: ../../std/primitive.slice.html#method.splitn_mut /// [slices]: ../../std/primitive.slice.html #[stable(feature = "rust1", since = "1.0.0")] -pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool { - inner: GenericSplitN<SplitMut<'a, T, P>> +pub struct SplitNMut<'a, T: 'a, P> +where + P: FnMut(&T) -> bool, +{ + inner: GenericSplitN<SplitMut<'a, T, P>>, } #[stable(feature = "core_impl_debug", since = "1.9.0")] -impl<T: fmt::Debug, P> fmt::Debug for SplitNMut<'_, T, P> where P: FnMut(&T) -> bool { +impl<T: fmt::Debug, P> fmt::Debug for SplitNMut<'_, T, P> +where + P: FnMut(&T) -> bool, +{ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("SplitNMut") - .field("inner", &self.inner) - .finish() + f.debug_struct("SplitNMut").field("inner", &self.inner).finish() } } @@ -3974,24 +4048,29 @@ impl<T: fmt::Debug, P> fmt::Debug for SplitNMut<'_, T, P> where P: FnMut(&T) -> /// [`rsplitn_mut`]: ../../std/primitive.slice.html#method.rsplitn_mut /// [slices]: ../../std/primitive.slice.html #[stable(feature = "rust1", since = "1.0.0")] -pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool { - inner: GenericSplitN<RSplitMut<'a, T, P>> +pub struct RSplitNMut<'a, T: 'a, P> +where + P: FnMut(&T) -> bool, +{ + inner: GenericSplitN<RSplitMut<'a, T, P>>, } #[stable(feature = "core_impl_debug", since = "1.9.0")] -impl<T: fmt::Debug, P> fmt::Debug for RSplitNMut<'_, T, P> where P: FnMut(&T) -> bool { +impl<T: fmt::Debug, P> fmt::Debug for RSplitNMut<'_, T, P> +where + P: FnMut(&T) -> bool, +{ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("RSplitNMut") - .field("inner", &self.inner) - .finish() + f.debug_struct("RSplitNMut").field("inner", &self.inner).finish() } } macro_rules! forward_iterator { ($name:ident: $elem:ident, $iter_of:ty) => { #[stable(feature = "rust1", since = "1.0.0")] - impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where - P: FnMut(&T) -> bool + impl<'a, $elem, P> Iterator for $name<'a, $elem, P> + where + P: FnMut(&T) -> bool, { type Item = $iter_of; @@ -4007,9 +4086,8 @@ macro_rules! forward_iterator { } #[stable(feature = "fused", since = "1.26.0")] - impl<'a, $elem, P> FusedIterator for $name<'a, $elem, P> - where P: FnMut(&T) -> bool {} - } + impl<'a, $elem, P> FusedIterator for $name<'a, $elem, P> where P: FnMut(&T) -> bool {} + }; } forward_iterator! { SplitN: T, &'a [T] } @@ -4025,19 +4103,16 @@ forward_iterator! { RSplitNMut: T, &'a mut [T] } /// [slices]: ../../std/primitive.slice.html #[derive(Debug)] #[stable(feature = "rust1", since = "1.0.0")] -pub struct Windows<'a, T:'a> { +pub struct Windows<'a, T: 'a> { v: &'a [T], - size: usize + size: usize, } // FIXME(#26925) Remove in favor of `#[derive(Clone)]` #[stable(feature = "rust1", since = "1.0.0")] impl<T> Clone for Windows<'_, T> { fn clone(&self) -> Self { - Windows { - v: self.v, - size: self.size, - } + Windows { v: self.v, size: self.size } } } @@ -4079,7 +4154,7 @@ impl<'a, T> Iterator for Windows<'a, T> { None } else { let nth = &self.v[n..end]; - self.v = &self.v[n+1..]; + self.v = &self.v[n + 1..]; Some(nth) } } @@ -4102,8 +4177,8 @@ impl<'a, T> DoubleEndedIterator for Windows<'a, T> { if self.size > self.v.len() { None } else { - let ret = Some(&self.v[self.v.len()-self.size..]); - self.v = &self.v[..self.v.len()-1]; + let ret = Some(&self.v[self.v.len() - self.size..]); + self.v = &self.v[..self.v.len() - 1]; ret } } @@ -4115,8 +4190,8 @@ impl<'a, T> DoubleEndedIterator for Windows<'a, T> { self.v = &[]; None } else { - let ret = &self.v[end-self.size..end]; - self.v = &self.v[..end-1]; + let ret = &self.v[end - self.size..end]; + self.v = &self.v[..end - 1]; Some(ret) } } @@ -4136,7 +4211,9 @@ unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> { unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] { from_raw_parts(self.v.as_ptr().add(i), self.size) } - fn may_have_side_effect() -> bool { false } + fn may_have_side_effect() -> bool { + false + } } /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a @@ -4151,19 +4228,16 @@ unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> { /// [slices]: ../../std/primitive.slice.html #[derive(Debug)] #[stable(feature = "rust1", since = "1.0.0")] -pub struct Chunks<'a, T:'a> { +pub struct Chunks<'a, T: 'a> { v: &'a [T], - chunk_size: usize + chunk_size: usize, } // FIXME(#26925) Remove in favor of `#[derive(Clone)]` #[stable(feature = "rust1", since = "1.0.0")] impl<T> Clone for Chunks<'_, T> { fn clone(&self) -> Self { - Chunks { - v: self.v, - chunk_size: self.chunk_size, - } + Chunks { v: self.v, chunk_size: self.chunk_size } } } @@ -4190,7 +4264,7 @@ impl<'a, T> Iterator for Chunks<'a, T> { } else { let n = self.v.len() / self.chunk_size; let rem = self.v.len() % self.chunk_size; - let n = if rem > 0 { n+1 } else { n }; + let n = if rem > 0 { n + 1 } else { n }; (n, Some(n)) } } @@ -4281,7 +4355,9 @@ unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> { }; from_raw_parts(self.v.as_ptr().add(start), end - start) } - fn may_have_side_effect() -> bool { false } + fn may_have_side_effect() -> bool { + false + } } /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size` @@ -4296,9 +4372,9 @@ unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> { /// [slices]: ../../std/primitive.slice.html #[derive(Debug)] #[stable(feature = "rust1", since = "1.0.0")] -pub struct ChunksMut<'a, T:'a> { +pub struct ChunksMut<'a, T: 'a> { v: &'a mut [T], - chunk_size: usize + chunk_size: usize, } #[stable(feature = "rust1", since = "1.0.0")] @@ -4348,7 +4424,7 @@ impl<'a, T> Iterator for ChunksMut<'a, T> { }; let tmp = mem::replace(&mut self.v, &mut []); let (head, tail) = tmp.split_at_mut(end); - let (_, nth) = head.split_at_mut(start); + let (_, nth) = head.split_at_mut(start); self.v = tail; Some(nth) } @@ -4421,7 +4497,9 @@ unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> { }; from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start) } - fn may_have_side_effect() -> bool { false } + fn may_have_side_effect() -> bool { + false + } } /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a @@ -4438,10 +4516,10 @@ unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> { /// [slices]: ../../std/primitive.slice.html #[derive(Debug)] #[stable(feature = "chunks_exact", since = "1.31.0")] -pub struct ChunksExact<'a, T:'a> { +pub struct ChunksExact<'a, T: 'a> { v: &'a [T], rem: &'a [T], - chunk_size: usize + chunk_size: usize, } impl<'a, T> ChunksExact<'a, T> { @@ -4458,11 +4536,7 @@ impl<'a, T> ChunksExact<'a, T> { #[stable(feature = "chunks_exact", since = "1.31.0")] impl<T> Clone for ChunksExact<'_, T> { fn clone(&self) -> Self { - ChunksExact { - v: self.v, - rem: self.rem, - chunk_size: self.chunk_size, - } + ChunksExact { v: self.v, rem: self.rem, chunk_size: self.chunk_size } } } @@ -4560,7 +4634,9 @@ unsafe impl<'a, T> TrustedRandomAccess for ChunksExact<'a, T> { let start = i * self.chunk_size; from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) } - fn may_have_side_effect() -> bool { false } + fn may_have_side_effect() -> bool { + false + } } /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size` @@ -4577,10 +4653,10 @@ unsafe impl<'a, T> TrustedRandomAccess for ChunksExact<'a, T> { /// [slices]: ../../std/primitive.slice.html #[derive(Debug)] #[stable(feature = "chunks_exact", since = "1.31.0")] -pub struct ChunksExactMut<'a, T:'a> { +pub struct ChunksExactMut<'a, T: 'a> { v: &'a mut [T], rem: &'a mut [T], - chunk_size: usize + chunk_size: usize, } impl<'a, T> ChunksExactMut<'a, T> { @@ -4692,7 +4768,9 @@ unsafe impl<'a, T> TrustedRandomAccess for ChunksExactMut<'a, T> { let start = i * self.chunk_size; from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size) } - fn may_have_side_effect() -> bool { false } + fn may_have_side_effect() -> bool { + false + } } /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a @@ -4707,19 +4785,16 @@ unsafe impl<'a, T> TrustedRandomAccess for ChunksExactMut<'a, T> { /// [slices]: ../../std/primitive.slice.html #[derive(Debug)] #[stable(feature = "rchunks", since = "1.31.0")] -pub struct RChunks<'a, T:'a> { +pub struct RChunks<'a, T: 'a> { v: &'a [T], - chunk_size: usize + chunk_size: usize, } // FIXME(#26925) Remove in favor of `#[derive(Clone)]` #[stable(feature = "rchunks", since = "1.31.0")] impl<T> Clone for RChunks<'_, T> { fn clone(&self) -> Self { - RChunks { - v: self.v, - chunk_size: self.chunk_size, - } + RChunks { v: self.v, chunk_size: self.chunk_size } } } @@ -4746,7 +4821,7 @@ impl<'a, T> Iterator for RChunks<'a, T> { } else { let n = self.v.len() / self.chunk_size; let rem = self.v.len() % self.chunk_size; - let n = if rem > 0 { n+1 } else { n }; + let n = if rem > 0 { n + 1 } else { n }; (n, Some(n)) } } @@ -4840,7 +4915,9 @@ unsafe impl<'a, T> TrustedRandomAccess for RChunks<'a, T> { }; from_raw_parts(self.v.as_ptr().add(start), end - start) } - fn may_have_side_effect() -> bool { false } + fn may_have_side_effect() -> bool { + false + } } /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size` @@ -4855,9 +4932,9 @@ unsafe impl<'a, T> TrustedRandomAccess for RChunks<'a, T> { /// [slices]: ../../std/primitive.slice.html #[derive(Debug)] #[stable(feature = "rchunks", since = "1.31.0")] -pub struct RChunksMut<'a, T:'a> { +pub struct RChunksMut<'a, T: 'a> { v: &'a mut [T], - chunk_size: usize + chunk_size: usize, } #[stable(feature = "rchunks", since = "1.31.0")] @@ -4983,7 +5060,9 @@ unsafe impl<'a, T> TrustedRandomAccess for RChunksMut<'a, T> { }; from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start) } - fn may_have_side_effect() -> bool { false } + fn may_have_side_effect() -> bool { + false + } } /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a @@ -5000,10 +5079,10 @@ unsafe impl<'a, T> TrustedRandomAccess for RChunksMut<'a, T> { /// [slices]: ../../std/primitive.slice.html #[derive(Debug)] #[stable(feature = "rchunks", since = "1.31.0")] -pub struct RChunksExact<'a, T:'a> { +pub struct RChunksExact<'a, T: 'a> { v: &'a [T], rem: &'a [T], - chunk_size: usize + chunk_size: usize, } impl<'a, T> RChunksExact<'a, T> { @@ -5020,11 +5099,7 @@ impl<'a, T> RChunksExact<'a, T> { #[stable(feature = "rchunks", since = "1.31.0")] impl<'a, T> Clone for RChunksExact<'a, T> { fn clone(&self) -> RChunksExact<'a, T> { - RChunksExact { - v: self.v, - rem: self.rem, - chunk_size: self.chunk_size, - } + RChunksExact { v: self.v, rem: self.rem, chunk_size: self.chunk_size } } } @@ -5126,7 +5201,9 @@ unsafe impl<'a, T> TrustedRandomAccess for RChunksExact<'a, T> { let start = end - self.chunk_size; from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) } - fn may_have_side_effect() -> bool { false } + fn may_have_side_effect() -> bool { + false + } } /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size` @@ -5143,10 +5220,10 @@ unsafe impl<'a, T> TrustedRandomAccess for RChunksExact<'a, T> { /// [slices]: ../../std/primitive.slice.html #[derive(Debug)] #[stable(feature = "rchunks", since = "1.31.0")] -pub struct RChunksExactMut<'a, T:'a> { +pub struct RChunksExactMut<'a, T: 'a> { v: &'a mut [T], rem: &'a mut [T], - chunk_size: usize + chunk_size: usize, } impl<'a, T> RChunksExactMut<'a, T> { @@ -5263,7 +5340,9 @@ unsafe impl<'a, T> TrustedRandomAccess for RChunksExactMut<'a, T> { let start = end - self.chunk_size; from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size) } - fn may_have_side_effect() -> bool { false } + fn may_have_side_effect() -> bool { + false + } } // @@ -5322,8 +5401,10 @@ unsafe impl<'a, T> TrustedRandomAccess for RChunksExactMut<'a, T> { #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T] { debug_assert!(is_aligned_and_not_null(data), "attempt to create unaligned or null slice"); - debug_assert!(mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize, - "attempt to create slice covering at least half the address space"); + debug_assert!( + mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize, + "attempt to create slice covering at least half the address space" + ); &*ptr::slice_from_raw_parts(data, len) } @@ -5360,32 +5441,31 @@ pub unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T] { #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T] { debug_assert!(is_aligned_and_not_null(data), "attempt to create unaligned or null slice"); - debug_assert!(mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize, - "attempt to create slice covering at least half the address space"); + debug_assert!( + mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize, + "attempt to create slice covering at least half the address space" + ); &mut *ptr::slice_from_raw_parts_mut(data, len) } /// Converts a reference to T into a slice of length 1 (without copying). #[stable(feature = "from_ref", since = "1.28.0")] pub fn from_ref<T>(s: &T) -> &[T] { - unsafe { - from_raw_parts(s, 1) - } + unsafe { from_raw_parts(s, 1) } } /// Converts a reference to T into a slice of length 1 (without copying). #[stable(feature = "from_ref", since = "1.28.0")] pub fn from_mut<T>(s: &mut T) -> &mut [T] { - unsafe { - from_raw_parts_mut(s, 1) - } + unsafe { from_raw_parts_mut(s, 1) } } // This function is public only because there is no other way to unit test heapsort. #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "none")] #[doc(hidden)] pub fn heapsort<T, F>(v: &mut [T], mut is_less: F) - where F: FnMut(&T, &T) -> bool +where + F: FnMut(&T, &T) -> bool, { sort::heapsort(v, &mut is_less); } @@ -5394,7 +5474,7 @@ pub fn heapsort<T, F>(v: &mut [T], mut is_less: F) // Comparison traits // -extern { +extern "C" { /// Calls implementation provided memcmp. /// /// Interprets the data as u8. @@ -5406,7 +5486,10 @@ extern { } #[stable(feature = "rust1", since = "1.0.0")] -impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> { +impl<A, B> PartialEq<[B]> for [A] +where + A: PartialEq<B>, +{ fn eq(&self, other: &[B]) -> bool { SlicePartialEq::equal(self, other) } @@ -5440,12 +5523,15 @@ impl<T: PartialOrd> PartialOrd for [T] { trait SlicePartialEq<B> { fn equal(&self, other: &[B]) -> bool; - fn not_equal(&self, other: &[B]) -> bool { !self.equal(other) } + fn not_equal(&self, other: &[B]) -> bool { + !self.equal(other) + } } // Generic slice equality impl<A, B> SlicePartialEq<B> for [A] - where A: PartialEq<B> +where + A: PartialEq<B>, { default fn equal(&self, other: &[B]) -> bool { if self.len() != other.len() { @@ -5458,7 +5544,8 @@ impl<A, B> SlicePartialEq<B> for [A] // Use an equal-pointer optimization when types are `Eq` impl<A> SlicePartialEq<A> for [A] - where A: PartialEq<A> + Eq +where + A: PartialEq<A> + Eq, { default fn equal(&self, other: &[A]) -> bool { if self.len() != other.len() { @@ -5475,7 +5562,8 @@ impl<A> SlicePartialEq<A> for [A] // Use memcmp for bytewise equality when the types allow impl<A> SlicePartialEq<A> for [A] - where A: PartialEq<A> + BytewiseEquality +where + A: PartialEq<A> + BytewiseEquality, { fn equal(&self, other: &[A]) -> bool { if self.len() != other.len() { @@ -5486,8 +5574,7 @@ impl<A> SlicePartialEq<A> for [A] } unsafe { let size = mem::size_of_val(self); - memcmp(self.as_ptr() as *const u8, - other.as_ptr() as *const u8, size) == 0 + memcmp(self.as_ptr() as *const u8, other.as_ptr() as *const u8, size) == 0 } } } @@ -5499,7 +5586,8 @@ trait SlicePartialOrd<B> { } impl<A> SlicePartialOrd<A> for [A] - where A: PartialOrd +where + A: PartialOrd, { default fn partial_compare(&self, other: &[A]) -> Option<Ordering> { let l = cmp::min(self.len(), other.len()); @@ -5521,7 +5609,8 @@ impl<A> SlicePartialOrd<A> for [A] } impl<A> SlicePartialOrd<A> for [A] - where A: Ord +where + A: Ord, { default fn partial_compare(&self, other: &[A]) -> Option<Ordering> { Some(SliceOrd::compare(self, other)) @@ -5535,7 +5624,8 @@ trait SliceOrd<B> { } impl<A> SliceOrd<A> for [A] - where A: Ord +where + A: Ord, { default fn compare(&self, other: &[A]) -> Ordering { let l = cmp::min(self.len(), other.len()); @@ -5561,10 +5651,8 @@ impl<A> SliceOrd<A> for [A] impl SliceOrd<u8> for [u8] { #[inline] fn compare(&self, other: &[u8]) -> Ordering { - let order = unsafe { - memcmp(self.as_ptr(), other.as_ptr(), - cmp::min(self.len(), other.len())) - }; + let order = + unsafe { memcmp(self.as_ptr(), other.as_ptr(), cmp::min(self.len(), other.len())) }; if order == 0 { self.len().cmp(&other.len()) } else if order < 0 { @@ -5578,7 +5666,7 @@ impl SliceOrd<u8> for [u8] { #[doc(hidden)] /// Trait implemented for types that can be compared for equality using /// their bytewise representation -trait BytewiseEquality: Eq + Copy { } +trait BytewiseEquality: Eq + Copy {} macro_rules! impl_marker_for { ($traitname:ident, $($ty:ty)*) => { @@ -5596,7 +5684,9 @@ unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> { unsafe fn get_unchecked(&mut self, i: usize) -> &'a T { &*self.ptr.add(i) } - fn may_have_side_effect() -> bool { false } + fn may_have_side_effect() -> bool { + false + } } #[doc(hidden)] @@ -5604,14 +5694,19 @@ unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> { unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut T { &mut *self.ptr.add(i) } - fn may_have_side_effect() -> bool { false } + fn may_have_side_effect() -> bool { + false + } } trait SliceContains: Sized { fn slice_contains(&self, x: &[Self]) -> bool; } -impl<T> SliceContains for T where T: PartialEq { +impl<T> SliceContains for T +where + T: PartialEq, +{ default fn slice_contains(&self, x: &[Self]) -> bool { x.iter().any(|y| *y == *self) } diff --git a/src/libcore/str/lossy.rs b/src/libcore/str/lossy.rs index cf6ee6ed593..8a1fb9de546 100644 --- a/src/libcore/str/lossy.rs +++ b/src/libcore/str/lossy.rs @@ -1,14 +1,14 @@ use crate::char; -use crate::str as core_str; use crate::fmt::{self, Write}; use crate::mem; +use crate::str as core_str; // ignore-tidy-undocumented-unsafe /// Lossy UTF-8 string. #[unstable(feature = "str_internals", issue = "none")] pub struct Utf8Lossy { - bytes: [u8] + bytes: [u8], } impl Utf8Lossy { @@ -25,7 +25,6 @@ impl Utf8Lossy { } } - /// Iterator over lossy UTF-8 string #[unstable(feature = "str_internals", issue = "none")] #[allow(missing_debug_implementations)] @@ -65,20 +64,21 @@ impl<'a> Iterator for Utf8LossyChunksIter<'a> { i += 1; if byte < 128 { - } else { let w = core_str::utf8_char_width(byte); - macro_rules! error { () => ({ - unsafe { - let r = Utf8LossyChunk { - valid: core_str::from_utf8_unchecked(&self.source[0..i_]), - broken: &self.source[i_..i], - }; - self.source = &self.source[i..]; - return Some(r); - } - })} + macro_rules! error { + () => {{ + unsafe { + let r = Utf8LossyChunk { + valid: core_str::from_utf8_unchecked(&self.source[0..i_]), + broken: &self.source[i_..i], + }; + self.source = &self.source[i..]; + return Some(r); + } + }}; + } match w { 2 => { @@ -89,10 +89,10 @@ impl<'a> Iterator for Utf8LossyChunksIter<'a> { } 3 => { match (byte, safe_get(self.source, i)) { - (0xE0, 0xA0 ..= 0xBF) => (), - (0xE1 ..= 0xEC, 0x80 ..= 0xBF) => (), - (0xED, 0x80 ..= 0x9F) => (), - (0xEE ..= 0xEF, 0x80 ..= 0xBF) => (), + (0xE0, 0xA0..=0xBF) => (), + (0xE1..=0xEC, 0x80..=0xBF) => (), + (0xED, 0x80..=0x9F) => (), + (0xEE..=0xEF, 0x80..=0xBF) => (), _ => { error!(); } @@ -105,9 +105,9 @@ impl<'a> Iterator for Utf8LossyChunksIter<'a> { } 4 => { match (byte, safe_get(self.source, i)) { - (0xF0, 0x90 ..= 0xBF) => (), - (0xF1 ..= 0xF3, 0x80 ..= 0xBF) => (), - (0xF4, 0x80 ..= 0x8F) => (), + (0xF0, 0x90..=0xBF) => (), + (0xF1..=0xF3, 0x80..=0xBF) => (), + (0xF4, 0x80..=0x8F) => (), _ => { error!(); } @@ -138,13 +138,12 @@ impl<'a> Iterator for Utf8LossyChunksIter<'a> { } } - impl fmt::Display for Utf8Lossy { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // If we're the empty string then our iterator won't actually yield // anything, so perform the formatting manually if self.bytes.is_empty() { - return "".fmt(f) + return "".fmt(f); } for Utf8LossyChunk { valid, broken } in self.chunks() { @@ -153,7 +152,7 @@ impl fmt::Display for Utf8Lossy { // respect various formatting flags if possible. if valid.len() == self.bytes.len() { assert!(broken.is_empty()); - return valid.fmt(f) + return valid.fmt(f); } f.write_str(valid)?; @@ -170,7 +169,6 @@ impl fmt::Debug for Utf8Lossy { f.write_char('"')?; for Utf8LossyChunk { valid, broken } in self.chunks() { - // Valid part. // Here we partially parse UTF-8 again which is suboptimal. { diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index 15b65ed7655..ab771b1164b 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -8,16 +8,16 @@ #![stable(feature = "rust1", since = "1.0.0")] use self::pattern::Pattern; -use self::pattern::{Searcher, SearchStep, ReverseSearcher, DoubleEndedSearcher}; +use self::pattern::{DoubleEndedSearcher, ReverseSearcher, SearchStep, Searcher}; use crate::char; use crate::fmt::{self, Write}; -use crate::iter::{Map, Cloned, FusedIterator, TrustedLen, TrustedRandomAccess, Filter}; -use crate::iter::{Flatten, FlatMap, Chain}; -use crate::slice::{self, SliceIndex, Split as SliceSplit}; +use crate::iter::{Chain, FlatMap, Flatten}; +use crate::iter::{Cloned, Filter, FusedIterator, Map, TrustedLen, TrustedRandomAccess}; use crate::mem; use crate::ops::Try; use crate::option; +use crate::slice::{self, SliceIndex, Split as SliceSplit}; pub mod pattern; @@ -133,9 +133,9 @@ impl FromStr for bool { #[inline] fn from_str(s: &str) -> Result<bool, ParseBoolError> { match s { - "true" => Ok(true), + "true" => Ok(true), "false" => Ok(false), - _ => Err(ParseBoolError { _priv: () }), + _ => Err(ParseBoolError { _priv: () }), } } } @@ -145,7 +145,9 @@ impl FromStr for bool { /// [`from_str`]: ../../std/primitive.bool.html#method.from_str #[derive(Debug, Clone, PartialEq, Eq)] #[stable(feature = "rust1", since = "1.0.0")] -pub struct ParseBoolError { _priv: () } +pub struct ParseBoolError { + _priv: (), +} #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Display for ParseBoolError { @@ -230,7 +232,9 @@ impl Utf8Error { /// assert_eq!(1, error.valid_up_to()); /// ``` #[stable(feature = "utf8_error", since = "1.5.0")] - pub fn valid_up_to(&self) -> usize { self.valid_up_to } + pub fn valid_up_to(&self) -> usize { + self.valid_up_to + } /// Provides more information about the failure: /// @@ -444,8 +448,11 @@ pub unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str { impl fmt::Display for Utf8Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if let Some(error_len) = self.error_len { - write!(f, "invalid utf-8 sequence of {} bytes from index {}", - error_len, self.valid_up_to) + write!( + f, + "invalid utf-8 sequence of {} bytes from index {}", + error_len, self.valid_up_to + ) } else { write!(f, "incomplete utf-8 byte sequence from index {}", self.valid_up_to) } @@ -468,23 +475,29 @@ Section: Iterators #[derive(Clone)] #[stable(feature = "rust1", since = "1.0.0")] pub struct Chars<'a> { - iter: slice::Iter<'a, u8> + iter: slice::Iter<'a, u8>, } /// Returns the initial codepoint accumulator for the first byte. /// The first byte is special, only want bottom 5 bits for width 2, 4 bits /// for width 3, and 3 bits for width 4. #[inline] -fn utf8_first_byte(byte: u8, width: u32) -> u32 { (byte & (0x7F >> width)) as u32 } +fn utf8_first_byte(byte: u8, width: u32) -> u32 { + (byte & (0x7F >> width)) as u32 +} /// Returns the value of `ch` updated with continuation byte `byte`. #[inline] -fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 { (ch << 6) | (byte & CONT_MASK) as u32 } +fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 { + (ch << 6) | (byte & CONT_MASK) as u32 +} /// Checks whether the byte is a UTF-8 continuation byte (i.e., starts with the /// bits `10`). #[inline] -fn utf8_is_cont_byte(byte: u8) -> bool { (byte & !CONT_MASK) == TAG_CONT_U8 } +fn utf8_is_cont_byte(byte: u8) -> bool { + (byte & !CONT_MASK) == TAG_CONT_U8 +} #[inline] fn unwrap_or_0(opt: Option<&u8>) -> u8 { @@ -502,7 +515,7 @@ pub fn next_code_point<'a, I: Iterator<Item = &'a u8>>(bytes: &mut I) -> Option< // Decode UTF-8 let x = *bytes.next()?; if x < 128 { - return Some(x as u32) + return Some(x as u32); } // Multibyte case follows @@ -532,7 +545,8 @@ pub fn next_code_point<'a, I: Iterator<Item = &'a u8>>(bytes: &mut I) -> Option< /// UTF-8-like encoding). #[inline] fn next_code_point_reverse<'a, I>(bytes: &mut I) -> Option<u32> - where I: DoubleEndedIterator<Item = &'a u8>, +where + I: DoubleEndedIterator<Item = &'a u8>, { // Decode UTF-8 let w = match *bytes.next_back()? { @@ -568,9 +582,7 @@ impl<'a> Iterator for Chars<'a> { fn next(&mut self) -> Option<char> { next_code_point(&mut self.iter).map(|ch| { // str invariant says `ch` is a valid Unicode Scalar Value - unsafe { - char::from_u32_unchecked(ch) - } + unsafe { char::from_u32_unchecked(ch) } }) } @@ -617,9 +629,7 @@ impl<'a> DoubleEndedIterator for Chars<'a> { fn next_back(&mut self) -> Option<char> { next_code_point_reverse(&mut self.iter).map(|ch| { // str invariant says `ch` is a valid Unicode Scalar Value - unsafe { - char::from_u32_unchecked(ch) - } + unsafe { char::from_u32_unchecked(ch) } }) } } @@ -770,32 +780,41 @@ impl Iterator for Bytes<'_> { } #[inline] - fn all<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool { + fn all<F>(&mut self, f: F) -> bool + where + F: FnMut(Self::Item) -> bool, + { self.0.all(f) } #[inline] - fn any<F>(&mut self, f: F) -> bool where F: FnMut(Self::Item) -> bool { + fn any<F>(&mut self, f: F) -> bool + where + F: FnMut(Self::Item) -> bool, + { self.0.any(f) } #[inline] - fn find<P>(&mut self, predicate: P) -> Option<Self::Item> where - P: FnMut(&Self::Item) -> bool + fn find<P>(&mut self, predicate: P) -> Option<Self::Item> + where + P: FnMut(&Self::Item) -> bool, { self.0.find(predicate) } #[inline] - fn position<P>(&mut self, predicate: P) -> Option<usize> where - P: FnMut(Self::Item) -> bool + fn position<P>(&mut self, predicate: P) -> Option<usize> + where + P: FnMut(Self::Item) -> bool, { self.0.position(predicate) } #[inline] - fn rposition<P>(&mut self, predicate: P) -> Option<usize> where - P: FnMut(Self::Item) -> bool + fn rposition<P>(&mut self, predicate: P) -> Option<usize> + where + P: FnMut(Self::Item) -> bool, { self.0.rposition(predicate) } @@ -814,8 +833,9 @@ impl DoubleEndedIterator for Bytes<'_> { } #[inline] - fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item> where - P: FnMut(&Self::Item) -> bool + fn rfind<P>(&mut self, predicate: P) -> Option<Self::Item> + where + P: FnMut(&Self::Item) -> bool, { self.0.rfind(predicate) } @@ -845,7 +865,9 @@ unsafe impl TrustedRandomAccess for Bytes<'_> { unsafe fn get_unchecked(&mut self, i: usize) -> u8 { self.0.get_unchecked(i) } - fn may_have_side_effect() -> bool { false } + fn may_have_side_effect() -> bool { + false + } } /// This macro generates a Clone impl for string pattern API @@ -861,7 +883,7 @@ macro_rules! derive_pattern_clone { $e } } - } + }; } /// This macro generates two public iterator structs @@ -1047,7 +1069,7 @@ macro_rules! generate_pattern_iterators { } => {} } -derive_pattern_clone!{ +derive_pattern_clone! { clone SplitInternal with |s| SplitInternal { matcher: s.matcher.clone(), ..*s } } @@ -1091,7 +1113,9 @@ impl<'a, P: Pattern<'a>> SplitInternal<'a, P> { #[inline] fn next(&mut self) -> Option<&'a str> { - if self.finished { return None } + if self.finished { + return None; + } let haystack = self.matcher.haystack(); match self.matcher.next_match() { @@ -1106,15 +1130,22 @@ impl<'a, P: Pattern<'a>> SplitInternal<'a, P> { #[inline] fn next_back(&mut self) -> Option<&'a str> - where P::Searcher: ReverseSearcher<'a> + where + P::Searcher: ReverseSearcher<'a>, { - if self.finished { return None } + if self.finished { + return None; + } if !self.allow_trailing_empty { self.allow_trailing_empty = true; match self.next_back() { Some(elt) if !elt.is_empty() => return Some(elt), - _ => if self.finished { return None } + _ => { + if self.finished { + return None; + } + } } } @@ -1169,7 +1200,7 @@ generate_pattern_iterators! { delegate double ended; } -derive_pattern_clone!{ +derive_pattern_clone! { clone SplitNInternal with |s| SplitNInternal { iter: s.iter.clone(), ..*s } } @@ -1197,19 +1228,32 @@ impl<'a, P: Pattern<'a>> SplitNInternal<'a, P> { fn next(&mut self) -> Option<&'a str> { match self.count { 0 => None, - 1 => { self.count = 0; self.iter.get_end() } - _ => { self.count -= 1; self.iter.next() } + 1 => { + self.count = 0; + self.iter.get_end() + } + _ => { + self.count -= 1; + self.iter.next() + } } } #[inline] fn next_back(&mut self) -> Option<&'a str> - where P::Searcher: ReverseSearcher<'a> + where + P::Searcher: ReverseSearcher<'a>, { match self.count { 0 => None, - 1 => { self.count = 0; self.iter.get_end() } - _ => { self.count -= 1; self.iter.next_back() } + 1 => { + self.count = 0; + self.iter.get_end() + } + _ => { + self.count -= 1; + self.iter.next_back() + } } } } @@ -1232,7 +1276,7 @@ generate_pattern_iterators! { delegate single ended; } -derive_pattern_clone!{ +derive_pattern_clone! { clone MatchIndicesInternal with |s| MatchIndicesInternal(s.0.clone()) } @@ -1244,27 +1288,26 @@ where P: Pattern<'a, Searcher: fmt::Debug>, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_tuple("MatchIndicesInternal") - .field(&self.0) - .finish() + f.debug_tuple("MatchIndicesInternal").field(&self.0).finish() } } impl<'a, P: Pattern<'a>> MatchIndicesInternal<'a, P> { #[inline] fn next(&mut self) -> Option<(usize, &'a str)> { - self.0.next_match().map(|(start, end)| unsafe { - (start, self.0.haystack().get_unchecked(start..end)) - }) + self.0 + .next_match() + .map(|(start, end)| unsafe { (start, self.0.haystack().get_unchecked(start..end)) }) } #[inline] fn next_back(&mut self) -> Option<(usize, &'a str)> - where P::Searcher: ReverseSearcher<'a> + where + P::Searcher: ReverseSearcher<'a>, { - self.0.next_match_back().map(|(start, end)| unsafe { - (start, self.0.haystack().get_unchecked(start..end)) - }) + self.0 + .next_match_back() + .map(|(start, end)| unsafe { (start, self.0.haystack().get_unchecked(start..end)) }) } } @@ -1286,7 +1329,7 @@ generate_pattern_iterators! { delegate double ended; } -derive_pattern_clone!{ +derive_pattern_clone! { clone MatchesInternal with |s| MatchesInternal(s.0.clone()) } @@ -1298,9 +1341,7 @@ where P: Pattern<'a, Searcher: fmt::Debug>, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_tuple("MatchesInternal") - .field(&self.0) - .finish() + f.debug_tuple("MatchesInternal").field(&self.0).finish() } } @@ -1315,7 +1356,8 @@ impl<'a, P: Pattern<'a>> MatchesInternal<'a, P> { #[inline] fn next_back(&mut self) -> Option<&'a str> - where P::Searcher: ReverseSearcher<'a> + where + P::Searcher: ReverseSearcher<'a>, { self.0.next_match_back().map(|(a, b)| unsafe { // Indices are known to be on utf8 boundaries @@ -1461,21 +1503,20 @@ fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> { let old_offset = index; macro_rules! err { ($error_len: expr) => { - return Err(Utf8Error { - valid_up_to: old_offset, - error_len: $error_len, - }) - } + return Err(Utf8Error { valid_up_to: old_offset, error_len: $error_len }); + }; } - macro_rules! next { () => {{ - index += 1; - // we needed data, but there was none: error! - if index >= len { - err!(None) - } - v[index] - }}} + macro_rules! next { + () => {{ + index += 1; + // we needed data, but there was none: error! + if index >= len { + err!(None) + } + v[index] + }}; + } let first = v[index]; if first >= 128 { @@ -1499,16 +1540,18 @@ fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> { // UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) / // %xF4 %x80-8F 2( UTF8-tail ) match w { - 2 => if next!() & !CONT_MASK != TAG_CONT_U8 { - err!(Some(1)) - }, + 2 => { + if next!() & !CONT_MASK != TAG_CONT_U8 { + err!(Some(1)) + } + } 3 => { match (first, next!()) { - (0xE0 , 0xA0 ..= 0xBF) | - (0xE1 ..= 0xEC, 0x80 ..= 0xBF) | - (0xED , 0x80 ..= 0x9F) | - (0xEE ..= 0xEF, 0x80 ..= 0xBF) => {} - _ => err!(Some(1)) + (0xE0, 0xA0..=0xBF) + | (0xE1..=0xEC, 0x80..=0xBF) + | (0xED, 0x80..=0x9F) + | (0xEE..=0xEF, 0x80..=0xBF) => {} + _ => err!(Some(1)), } if next!() & !CONT_MASK != TAG_CONT_U8 { err!(Some(2)) @@ -1516,10 +1559,8 @@ fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> { } 4 => { match (first, next!()) { - (0xF0 , 0x90 ..= 0xBF) | - (0xF1 ..= 0xF3, 0x80 ..= 0xBF) | - (0xF4 , 0x80 ..= 0x8F) => {} - _ => err!(Some(1)) + (0xF0, 0x90..=0xBF) | (0xF1..=0xF3, 0x80..=0xBF) | (0xF4, 0x80..=0x8F) => {} + _ => err!(Some(1)), } if next!() & !CONT_MASK != TAG_CONT_U8 { err!(Some(2)) @@ -1528,7 +1569,7 @@ fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> { err!(Some(3)) } } - _ => err!(Some(1)) + _ => err!(Some(1)), } index += 1; } else { @@ -1564,22 +1605,22 @@ fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> { // https://tools.ietf.org/html/rfc3629 static UTF8_CHAR_WIDTH: [u8; 256] = [ -1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, -1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F -1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, -1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F -1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, -1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F -1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, -1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F -0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, -0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F -0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, -0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF -0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2, -2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF -3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF -4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, // 0x1F + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, // 0x3F + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, // 0x5F + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, // 0x7F + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, // 0x9F + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, // 0xBF + 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, // 0xDF + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xEF + 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xFF ]; /// Given a first byte, determines how many bytes are in this UTF-8 character. @@ -1625,7 +1666,9 @@ mod traits { self.as_bytes() == other.as_bytes() } #[inline] - fn ne(&self, other: &str) -> bool { !(*self).eq(other) } + fn ne(&self, other: &str) -> bool { + !(*self).eq(other) + } } #[stable(feature = "rust1", since = "1.0.0")] @@ -1757,9 +1800,10 @@ mod traits { type Output = str; #[inline] fn get(self, slice: &str) -> Option<&Self::Output> { - if self.start <= self.end && - slice.is_char_boundary(self.start) && - slice.is_char_boundary(self.end) { + if self.start <= self.end + && slice.is_char_boundary(self.start) + && slice.is_char_boundary(self.end) + { Some(unsafe { self.get_unchecked(slice) }) } else { None @@ -1767,9 +1811,10 @@ mod traits { } #[inline] fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> { - if self.start <= self.end && - slice.is_char_boundary(self.start) && - slice.is_char_boundary(self.end) { + if self.start <= self.end + && slice.is_char_boundary(self.start) + && slice.is_char_boundary(self.end) + { Some(unsafe { self.get_unchecked_mut(slice) }) } else { None @@ -1796,9 +1841,10 @@ mod traits { fn index_mut(self, slice: &mut str) -> &mut Self::Output { // is_char_boundary checks that the index is in [0, .len()] // cannot reuse `get` as above, because of NLL trouble - if self.start <= self.end && - slice.is_char_boundary(self.start) && - slice.is_char_boundary(self.end) { + if self.start <= self.end + && slice.is_char_boundary(self.start) + && slice.is_char_boundary(self.end) + { unsafe { self.get_unchecked_mut(slice) } } else { super::slice_error_fail(slice, self.start, self.end) @@ -1950,31 +1996,41 @@ mod traits { type Output = str; #[inline] fn get(self, slice: &str) -> Option<&Self::Output> { - if *self.end() == usize::max_value() { None } - else { (*self.start()..self.end()+1).get(slice) } + if *self.end() == usize::max_value() { + None + } else { + (*self.start()..self.end() + 1).get(slice) + } } #[inline] fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> { - if *self.end() == usize::max_value() { None } - else { (*self.start()..self.end()+1).get_mut(slice) } + if *self.end() == usize::max_value() { + None + } else { + (*self.start()..self.end() + 1).get_mut(slice) + } } #[inline] unsafe fn get_unchecked(self, slice: &str) -> &Self::Output { - (*self.start()..self.end()+1).get_unchecked(slice) + (*self.start()..self.end() + 1).get_unchecked(slice) } #[inline] unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output { - (*self.start()..self.end()+1).get_unchecked_mut(slice) + (*self.start()..self.end() + 1).get_unchecked_mut(slice) } #[inline] fn index(self, slice: &str) -> &Self::Output { - if *self.end() == usize::max_value() { str_index_overflow_fail(); } - (*self.start()..self.end()+1).index(slice) + if *self.end() == usize::max_value() { + str_index_overflow_fail(); + } + (*self.start()..self.end() + 1).index(slice) } #[inline] fn index_mut(self, slice: &mut str) -> &mut Self::Output { - if *self.end() == usize::max_value() { str_index_overflow_fail(); } - (*self.start()..self.end()+1).index_mut(slice) + if *self.end() == usize::max_value() { + str_index_overflow_fail(); + } + (*self.start()..self.end() + 1).index_mut(slice) } } @@ -1997,31 +2053,33 @@ mod traits { type Output = str; #[inline] fn get(self, slice: &str) -> Option<&Self::Output> { - if self.end == usize::max_value() { None } - else { (..self.end+1).get(slice) } + if self.end == usize::max_value() { None } else { (..self.end + 1).get(slice) } } #[inline] fn get_mut(self, slice: &mut str) -> Option<&mut Self::Output> { - if self.end == usize::max_value() { None } - else { (..self.end+1).get_mut(slice) } + if self.end == usize::max_value() { None } else { (..self.end + 1).get_mut(slice) } } #[inline] unsafe fn get_unchecked(self, slice: &str) -> &Self::Output { - (..self.end+1).get_unchecked(slice) + (..self.end + 1).get_unchecked(slice) } #[inline] unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output { - (..self.end+1).get_unchecked_mut(slice) + (..self.end + 1).get_unchecked_mut(slice) } #[inline] fn index(self, slice: &str) -> &Self::Output { - if self.end == usize::max_value() { str_index_overflow_fail(); } - (..self.end+1).index(slice) + if self.end == usize::max_value() { + str_index_overflow_fail(); + } + (..self.end + 1).index(slice) } #[inline] fn index_mut(self, slice: &mut str) -> &mut Self::Output { - if self.end == usize::max_value() { str_index_overflow_fail(); } - (..self.end+1).index_mut(slice) + if self.end == usize::max_value() { + str_index_overflow_fail(); + } + (..self.end + 1).index_mut(slice) } } } @@ -2053,8 +2111,14 @@ fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! { } // 2. begin <= end - assert!(begin <= end, "begin <= end ({} <= {}) when slicing `{}`{}", - begin, end, s_trunc, ellipsis); + assert!( + begin <= end, + "begin <= end ({} <= {}) when slicing `{}`{}", + begin, + end, + s_trunc, + ellipsis + ); // 3. character boundary let index = if !s.is_char_boundary(begin) { begin } else { end }; @@ -2065,9 +2129,11 @@ fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! { } // `char_start` must be less than len and a char boundary let ch = s[char_start..].chars().next().unwrap(); - let char_range = char_start .. char_start + ch.len_utf8(); - panic!("byte index {} is not a char boundary; it is inside {:?} (bytes {:?}) of `{}`{}", - index, ch, char_range, s_trunc, ellipsis); + let char_range = char_start..char_start + ch.len_utf8(); + panic!( + "byte index {} is not a char boundary; it is inside {:?} (bytes {:?}) of `{}`{}", + index, ch, char_range, s_trunc, ellipsis + ); } #[lang = "str"] @@ -2146,7 +2212,9 @@ impl str { // 0 and len are always ok. // Test for 0 explicitly so that it can optimize out the check // easily and skip reading string data for that case. - if index == 0 || index == self.len() { return true; } + if index == 0 || index == self.len() { + return true; + } match self.as_bytes().get(index) { None => false, // This is bit magic equivalent to: b < 128 || b >= 192 @@ -2505,10 +2573,7 @@ impl str { pub fn split_at(&self, mid: usize) -> (&str, &str) { // is_char_boundary checks that the index is in [0, .len()] if self.is_char_boundary(mid) { - unsafe { - (self.get_unchecked(0..mid), - self.get_unchecked(mid..self.len())) - } + unsafe { (self.get_unchecked(0..mid), self.get_unchecked(mid..self.len())) } } else { slice_error_fail(self, 0, mid) } @@ -2553,11 +2618,10 @@ impl str { let len = self.len(); let ptr = self.as_mut_ptr(); unsafe { - (from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, mid)), - from_utf8_unchecked_mut(slice::from_raw_parts_mut( - ptr.add(mid), - len - mid - ))) + ( + from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, mid)), + from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr.add(mid), len - mid)), + ) } } else { slice_error_fail(self, 0, mid) @@ -2611,7 +2675,7 @@ impl str { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn chars(&self) -> Chars<'_> { - Chars{iter: self.as_bytes().iter()} + Chars { iter: self.as_bytes().iter() } } /// Returns an iterator over the [`char`]s of a string slice, and their @@ -2775,11 +2839,8 @@ impl str { #[stable(feature = "split_ascii_whitespace", since = "1.34.0")] #[inline] pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_> { - let inner = self - .as_bytes() - .split(IsAsciiWhitespace) - .filter(BytesIsNotEmpty) - .map(UnsafeBytesToStr); + let inner = + self.as_bytes().split(IsAsciiWhitespace).filter(BytesIsNotEmpty).map(UnsafeBytesToStr); SplitAsciiWhitespace { inner } } @@ -3220,10 +3281,7 @@ impl str { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> { - SplitTerminator(SplitInternal { - allow_trailing_empty: false, - ..self.split(pat).0 - }) + SplitTerminator(SplitInternal { allow_trailing_empty: false, ..self.split(pat).0 }) } /// An iterator over substrings of `self`, separated by characters @@ -3317,10 +3375,7 @@ impl str { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> { - SplitN(SplitNInternal { - iter: self.split(pat).0, - count: n, - }) + SplitN(SplitNInternal { iter: self.split(pat).0, count: n }) } /// An iterator over substrings of this string slice, separated by a @@ -3662,7 +3717,7 @@ impl str { #[rustc_deprecated( since = "1.33.0", reason = "superseded by `trim_start`", - suggestion = "trim_start", + suggestion = "trim_start" )] pub fn trim_left(&self) -> &str { self.trim_start() @@ -3703,7 +3758,7 @@ impl str { #[rustc_deprecated( since = "1.33.0", reason = "superseded by `trim_end`", - suggestion = "trim_end", + suggestion = "trim_end" )] pub fn trim_right(&self) -> &str { self.trim_end() @@ -3745,7 +3800,7 @@ impl str { if let Some((a, b)) = matcher.next_reject() { i = a; j = b; // Remember earliest known match, correct it below if - // last match is different + // last match is different } if let Some((_, b)) = matcher.next_reject_back() { j = b; @@ -3818,8 +3873,11 @@ impl str { pub fn strip_prefix<'a, P: Pattern<'a>>(&'a self, prefix: P) -> Option<&'a str> { let mut matcher = prefix.into_searcher(self); if let SearchStep::Match(start, len) = matcher.next() { - debug_assert_eq!(start, 0, "The first search step from Searcher \ - must include the first character"); + debug_assert_eq!( + start, 0, + "The first search step from Searcher \ + must include the first character" + ); unsafe { // Searcher is known to return valid indices. Some(self.get_unchecked(len..)) @@ -3855,8 +3913,12 @@ impl str { { let mut matcher = suffix.into_searcher(self); if let SearchStep::Match(start, end) = matcher.next_back() { - debug_assert_eq!(end, self.len(), "The first search step from ReverseSearcher \ - must include the last character"); + debug_assert_eq!( + end, + self.len(), + "The first search step from ReverseSearcher \ + must include the last character" + ); unsafe { // Searcher is known to return valid indices. Some(self.get_unchecked(..start)) @@ -3944,7 +4006,7 @@ impl str { #[rustc_deprecated( since = "1.33.0", reason = "superseded by `trim_start_matches`", - suggestion = "trim_start_matches", + suggestion = "trim_start_matches" )] pub fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str { self.trim_start_matches(pat) @@ -3986,7 +4048,7 @@ impl str { #[rustc_deprecated( since = "1.33.0", reason = "superseded by `trim_end_matches`", - suggestion = "trim_end_matches", + suggestion = "trim_end_matches" )] pub fn trim_right_matches<'a, P>(&'a self, pat: P) -> &'a str where @@ -4173,11 +4235,12 @@ impl str { pub fn escape_debug(&self) -> EscapeDebug<'_> { let mut chars = self.chars(); EscapeDebug { - inner: chars.next() + inner: chars + .next() .map(|first| first.escape_debug_ext(true)) .into_iter() .flatten() - .chain(chars.flat_map(CharEscapeDebugContinue)) + .chain(chars.flat_map(CharEscapeDebugContinue)), } } @@ -4285,13 +4348,17 @@ impl AsRef<[u8]> for str { #[stable(feature = "rust1", since = "1.0.0")] impl Default for &str { /// Creates an empty str - fn default() -> Self { "" } + fn default() -> Self { + "" + } } #[stable(feature = "default_mut_str", since = "1.28.0")] impl Default for &mut str { /// Creates an empty mutable str - fn default() -> Self { unsafe { from_utf8_unchecked_mut(&mut []) } } + fn default() -> Self { + unsafe { from_utf8_unchecked_mut(&mut []) } + } } /// An iterator over the non-whitespace substrings of a string, @@ -4477,7 +4544,7 @@ impl FusedIterator for EncodeUtf16<'_> {} pub struct EscapeDebug<'a> { inner: Chain< Flatten<option::IntoIter<char::EscapeDebug>>, - FlatMap<Chars<'a>, char::EscapeDebug, CharEscapeDebugContinue> + FlatMap<Chars<'a>, char::EscapeDebug, CharEscapeDebugContinue>, >, } diff --git a/src/libcore/str/pattern.rs b/src/libcore/str/pattern.rs index b7ebd5f88b5..2cbdeb2e4ee 100644 --- a/src/libcore/str/pattern.rs +++ b/src/libcore/str/pattern.rs @@ -5,9 +5,11 @@ // ignore-tidy-undocumented-unsafe -#![unstable(feature = "pattern", - reason = "API not fully fleshed out and ready to be stabilized", - issue = "27721")] +#![unstable( + feature = "pattern", + reason = "API not fully fleshed out and ready to be stabilized", + issue = "27721" +)] use crate::cmp; use crate::fmt; @@ -53,7 +55,8 @@ pub trait Pattern<'a>: Sized { /// Checks whether the pattern matches at the back of the haystack #[inline] fn is_suffix_of(self, haystack: &'a str) -> bool - where Self::Searcher: ReverseSearcher<'a> + where + Self::Searcher: ReverseSearcher<'a>, { match self.into_searcher(haystack).next_back() { SearchStep::Match(_, j) if haystack.len() == j => true, @@ -78,7 +81,7 @@ pub enum SearchStep { Reject(usize, usize), /// Expresses that every byte of the haystack has been visited, ending /// the iteration. - Done + Done, } /// A searcher for a string pattern. @@ -189,7 +192,7 @@ pub unsafe trait ReverseSearcher<'a>: Searcher<'a> { /// Finds the next `Match` result. See `next_back()` #[inline] - fn next_match_back(&mut self) -> Option<(usize, usize)>{ + fn next_match_back(&mut self) -> Option<(usize, usize)> { loop { match self.next_back() { SearchStep::Match(a, b) => return Some((a, b)), @@ -201,7 +204,7 @@ pub unsafe trait ReverseSearcher<'a>: Searcher<'a> { /// Finds the next `Reject` result. See `next_back()` #[inline] - fn next_reject_back(&mut self) -> Option<(usize, usize)>{ + fn next_reject_back(&mut self) -> Option<(usize, usize)> { loop { match self.next_back() { SearchStep::Reject(a, b) => return Some((a, b)), @@ -235,7 +238,6 @@ pub unsafe trait ReverseSearcher<'a>: Searcher<'a> { /// `"[aa]a"` or `"a[aa]"`, depending from which side it is searched. pub trait DoubleEndedSearcher<'a>: ReverseSearcher<'a> {} - ///////////////////////////////////////////////////////////////////////////// // Impl for char ///////////////////////////////////////////////////////////////////////////// @@ -247,7 +249,6 @@ pub struct CharSearcher<'a> { // safety invariant: `finger`/`finger_back` must be a valid utf8 byte index of `haystack` // This invariant can be broken *within* next_match and next_match_back, however // they must exit with fingers on valid code point boundaries. - /// `finger` is the current byte index of the forward search. /// Imagine that it exists before the byte at its index, i.e. /// `haystack[finger]` is the first byte of the slice we must inspect during @@ -429,7 +430,7 @@ impl<'a> Pattern<'a> for char { finger_back: haystack.len(), needle: self, utf8_size, - utf8_encoded + utf8_encoded, } } @@ -449,7 +450,9 @@ impl<'a> Pattern<'a> for char { } #[inline] - fn is_suffix_of(self, haystack: &'a str) -> bool where Self::Searcher: ReverseSearcher<'a> + fn is_suffix_of(self, haystack: &'a str) -> bool + where + Self::Searcher: ReverseSearcher<'a>, { self.encode_utf8(&mut [0u8; 4]).is_suffix_of(haystack) } @@ -464,15 +467,20 @@ trait MultiCharEq { fn matches(&mut self, c: char) -> bool; } -impl<F> MultiCharEq for F where F: FnMut(char) -> bool { +impl<F> MultiCharEq for F +where + F: FnMut(char) -> bool, +{ #[inline] - fn matches(&mut self, c: char) -> bool { (*self)(c) } + fn matches(&mut self, c: char) -> bool { + (*self)(c) + } } impl MultiCharEq for &[char] { #[inline] fn matches(&mut self, c: char) -> bool { - self.iter().any(|&m| { m == c }) + self.iter().any(|&m| m == c) } } @@ -490,11 +498,7 @@ impl<'a, C: MultiCharEq> Pattern<'a> for MultiCharEqPattern<C> { #[inline] fn into_searcher(self, haystack: &'a str) -> MultiCharEqSearcher<'a, C> { - MultiCharEqSearcher { - haystack, - char_eq: self.0, - char_indices: haystack.char_indices(), - } + MultiCharEqSearcher { haystack, char_eq: self.0, char_indices: haystack.char_indices() } } } @@ -642,10 +646,12 @@ impl<'a, 'b> Pattern<'a> for &'b [char] { /// Associated type for `<F as Pattern<'a>>::Searcher`. #[derive(Clone)] pub struct CharPredicateSearcher<'a, F>(<MultiCharEqPattern<F> as Pattern<'a>>::Searcher) - where F: FnMut(char) -> bool; +where + F: FnMut(char) -> bool; impl<F> fmt::Debug for CharPredicateSearcher<'_, F> - where F: FnMut(char) -> bool +where + F: FnMut(char) -> bool, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("CharPredicateSearcher") @@ -655,22 +661,26 @@ impl<F> fmt::Debug for CharPredicateSearcher<'_, F> } } unsafe impl<'a, F> Searcher<'a> for CharPredicateSearcher<'a, F> - where F: FnMut(char) -> bool +where + F: FnMut(char) -> bool, { searcher_methods!(forward); } unsafe impl<'a, F> ReverseSearcher<'a> for CharPredicateSearcher<'a, F> - where F: FnMut(char) -> bool +where + F: FnMut(char) -> bool, { searcher_methods!(reverse); } -impl<'a, F> DoubleEndedSearcher<'a> for CharPredicateSearcher<'a, F> - where F: FnMut(char) -> bool {} +impl<'a, F> DoubleEndedSearcher<'a> for CharPredicateSearcher<'a, F> where F: FnMut(char) -> bool {} /// Searches for chars that match the given predicate -impl<'a, F> Pattern<'a> for F where F: FnMut(char) -> bool { +impl<'a, F> Pattern<'a> for F +where + F: FnMut(char) -> bool, +{ pattern_methods!(CharPredicateSearcher<'a, F>, MultiCharEqPattern, CharPredicateSearcher); } @@ -712,7 +722,6 @@ impl<'a, 'b> Pattern<'a> for &'b str { } } - ///////////////////////////////////////////////////////////////////////////// // Two Way substring searcher ///////////////////////////////////////////////////////////////////////////// @@ -757,9 +766,10 @@ impl<'a, 'b> StrSearcher<'a, 'b> { StrSearcher { haystack, needle, - searcher: StrSearcherImpl::TwoWay( - TwoWaySearcher::new(needle.as_bytes(), haystack.len()) - ), + searcher: StrSearcherImpl::TwoWay(TwoWaySearcher::new( + needle.as_bytes(), + haystack.len(), + )), } } } @@ -798,10 +808,11 @@ unsafe impl<'a, 'b> Searcher<'a> for StrSearcher<'a, 'b> { return SearchStep::Done; } let is_long = searcher.memory == usize::MAX; - match searcher.next::<RejectAndMatch>(self.haystack.as_bytes(), - self.needle.as_bytes(), - is_long) - { + match searcher.next::<RejectAndMatch>( + self.haystack.as_bytes(), + self.needle.as_bytes(), + is_long, + ) { SearchStep::Reject(a, mut b) => { // skip to next char boundary while !self.haystack.is_char_boundary(b) { @@ -819,27 +830,29 @@ unsafe impl<'a, 'b> Searcher<'a> for StrSearcher<'a, 'b> { #[inline] fn next_match(&mut self) -> Option<(usize, usize)> { match self.searcher { - StrSearcherImpl::Empty(..) => { - loop { - match self.next() { - SearchStep::Match(a, b) => return Some((a, b)), - SearchStep::Done => return None, - SearchStep::Reject(..) => { } - } + StrSearcherImpl::Empty(..) => loop { + match self.next() { + SearchStep::Match(a, b) => return Some((a, b)), + SearchStep::Done => return None, + SearchStep::Reject(..) => {} } - } + }, StrSearcherImpl::TwoWay(ref mut searcher) => { let is_long = searcher.memory == usize::MAX; // write out `true` and `false` cases to encourage the compiler // to specialize the two cases separately. if is_long { - searcher.next::<MatchOnly>(self.haystack.as_bytes(), - self.needle.as_bytes(), - true) + searcher.next::<MatchOnly>( + self.haystack.as_bytes(), + self.needle.as_bytes(), + true, + ) } else { - searcher.next::<MatchOnly>(self.haystack.as_bytes(), - self.needle.as_bytes(), - false) + searcher.next::<MatchOnly>( + self.haystack.as_bytes(), + self.needle.as_bytes(), + false, + ) } } } @@ -868,10 +881,11 @@ unsafe impl<'a, 'b> ReverseSearcher<'a> for StrSearcher<'a, 'b> { return SearchStep::Done; } let is_long = searcher.memory == usize::MAX; - match searcher.next_back::<RejectAndMatch>(self.haystack.as_bytes(), - self.needle.as_bytes(), - is_long) - { + match searcher.next_back::<RejectAndMatch>( + self.haystack.as_bytes(), + self.needle.as_bytes(), + is_long, + ) { SearchStep::Reject(mut a, b) => { // skip to next char boundary while !self.haystack.is_char_boundary(a) { @@ -889,26 +903,28 @@ unsafe impl<'a, 'b> ReverseSearcher<'a> for StrSearcher<'a, 'b> { #[inline] fn next_match_back(&mut self) -> Option<(usize, usize)> { match self.searcher { - StrSearcherImpl::Empty(..) => { - loop { - match self.next_back() { - SearchStep::Match(a, b) => return Some((a, b)), - SearchStep::Done => return None, - SearchStep::Reject(..) => { } - } + StrSearcherImpl::Empty(..) => loop { + match self.next_back() { + SearchStep::Match(a, b) => return Some((a, b)), + SearchStep::Done => return None, + SearchStep::Reject(..) => {} } - } + }, StrSearcherImpl::TwoWay(ref mut searcher) => { let is_long = searcher.memory == usize::MAX; // write out `true` and `false`, like `next_match` if is_long { - searcher.next_back::<MatchOnly>(self.haystack.as_bytes(), - self.needle.as_bytes(), - true) + searcher.next_back::<MatchOnly>( + self.haystack.as_bytes(), + self.needle.as_bytes(), + true, + ) } else { - searcher.next_back::<MatchOnly>(self.haystack.as_bytes(), - self.needle.as_bytes(), - false) + searcher.next_back::<MatchOnly>( + self.haystack.as_bytes(), + self.needle.as_bytes(), + false, + ) } } } @@ -1016,12 +1032,11 @@ impl TwoWaySearcher { let (crit_pos_false, period_false) = TwoWaySearcher::maximal_suffix(needle, false); let (crit_pos_true, period_true) = TwoWaySearcher::maximal_suffix(needle, true); - let (crit_pos, period) = - if crit_pos_false > crit_pos_true { - (crit_pos_false, period_false) - } else { - (crit_pos_true, period_true) - }; + let (crit_pos, period) = if crit_pos_false > crit_pos_true { + (crit_pos_false, period_false) + } else { + (crit_pos_true, period_true) + }; // A particularly readable explanation of what's going on here can be found // in Crochemore and Rytter's book "Text Algorithms", ch 13. Specifically @@ -1032,7 +1047,7 @@ impl TwoWaySearcher { // &v[..period]. If it is, we use "Algorithm CP1". Otherwise we use // "Algorithm CP2", which is optimized for when the period of the needle // is large. - if &needle[..crit_pos] == &needle[period.. period + crit_pos] { + if &needle[..crit_pos] == &needle[period..period + crit_pos] { // short period case -- the period is exact // compute a separate critical factorization for the reversed needle // x = u' v' where |v'| < period(x). @@ -1042,9 +1057,11 @@ impl TwoWaySearcher { // (crit_pos = 1, period = 3) while being factored with approximate // period in reverse (crit_pos = 2, period = 2). We use the given // reverse factorization but keep the exact period. - let crit_pos_back = needle.len() - cmp::max( - TwoWaySearcher::reverse_maximal_suffix(needle, period, false), - TwoWaySearcher::reverse_maximal_suffix(needle, period, true)); + let crit_pos_back = needle.len() + - cmp::max( + TwoWaySearcher::reverse_maximal_suffix(needle, period, false), + TwoWaySearcher::reverse_maximal_suffix(needle, period, true), + ); TwoWaySearcher { crit_pos, @@ -1095,9 +1112,9 @@ impl TwoWaySearcher { // How far we can jump when we encounter a mismatch is all based on the fact // that (u, v) is a critical factorization for the needle. #[inline] - fn next<S>(&mut self, haystack: &[u8], needle: &[u8], long_period: bool) - -> S::Output - where S: TwoWayStrategy + fn next<S>(&mut self, haystack: &[u8], needle: &[u8], long_period: bool) -> S::Output + where + S: TwoWayStrategy, { // `next()` uses `self.position` as its cursor let old_pos = self.position; @@ -1128,8 +1145,8 @@ impl TwoWaySearcher { } // See if the right part of the needle matches - let start = if long_period { self.crit_pos } - else { cmp::max(self.crit_pos, self.memory) }; + let start = + if long_period { self.crit_pos } else { cmp::max(self.crit_pos, self.memory) }; for i in start..needle.len() { if needle[i] != haystack[self.position + i] { self.position += i - self.crit_pos + 1; @@ -1178,9 +1195,9 @@ impl TwoWaySearcher { // To search in reverse through the haystack, we search forward through // a reversed haystack with a reversed needle, matching first u' and then v'. #[inline] - fn next_back<S>(&mut self, haystack: &[u8], needle: &[u8], long_period: bool) - -> S::Output - where S: TwoWayStrategy + fn next_back<S>(&mut self, haystack: &[u8], needle: &[u8], long_period: bool) -> S::Output + where + S: TwoWayStrategy, { // `next_back()` uses `self.end` as its cursor -- so that `next()` and `next_back()` // are independent. @@ -1212,8 +1229,11 @@ impl TwoWaySearcher { } // See if the left part of the needle matches - let crit = if long_period { self.crit_pos_back } - else { cmp::min(self.crit_pos_back, self.memory_back) }; + let crit = if long_period { + self.crit_pos_back + } else { + cmp::min(self.crit_pos_back, self.memory_back) + }; for i in (0..crit).rev() { if needle[i] != haystack[self.end - needle.len() + i] { self.end -= self.crit_pos_back - i; @@ -1225,8 +1245,7 @@ impl TwoWaySearcher { } // See if the right part of the needle matches - let needle_end = if long_period { needle.len() } - else { self.memory_back }; + let needle_end = if long_period { needle.len() } else { self.memory_back }; for i in self.crit_pos_back..needle_end { if needle[i] != haystack[self.end - needle.len() + i] { self.end -= self.period; @@ -1266,7 +1285,7 @@ impl TwoWaySearcher { let mut left = 0; // Corresponds to i in the paper let mut right = 1; // Corresponds to j in the paper let mut offset = 0; // Corresponds to k in the paper, but starting at 0 - // to match 0-based indexing. + // to match 0-based indexing. let mut period = 1; // Corresponds to p in the paper while let Some(&a) = arr.get(right + offset) { @@ -1308,13 +1327,11 @@ impl TwoWaySearcher { // a critical factorization. // // For long period cases, the resulting period is not exact (it is too short). - fn reverse_maximal_suffix(arr: &[u8], known_period: usize, - order_greater: bool) -> usize - { + fn reverse_maximal_suffix(arr: &[u8], known_period: usize, order_greater: bool) -> usize { let mut left = 0; // Corresponds to i in the paper let mut right = 1; // Corresponds to j in the paper let mut offset = 0; // Corresponds to k in the paper, but starting at 0 - // to match 0-based indexing. + // to match 0-based indexing. let mut period = 1; // Corresponds to p in the paper let n = arr.len(); @@ -1360,29 +1377,41 @@ trait TwoWayStrategy { } /// Skip to match intervals as quickly as possible -enum MatchOnly { } +enum MatchOnly {} impl TwoWayStrategy for MatchOnly { type Output = Option<(usize, usize)>; #[inline] - fn use_early_reject() -> bool { false } + fn use_early_reject() -> bool { + false + } #[inline] - fn rejecting(_a: usize, _b: usize) -> Self::Output { None } + fn rejecting(_a: usize, _b: usize) -> Self::Output { + None + } #[inline] - fn matching(a: usize, b: usize) -> Self::Output { Some((a, b)) } + fn matching(a: usize, b: usize) -> Self::Output { + Some((a, b)) + } } /// Emit Rejects regularly -enum RejectAndMatch { } +enum RejectAndMatch {} impl TwoWayStrategy for RejectAndMatch { type Output = SearchStep; #[inline] - fn use_early_reject() -> bool { true } + fn use_early_reject() -> bool { + true + } #[inline] - fn rejecting(a: usize, b: usize) -> Self::Output { SearchStep::Reject(a, b) } + fn rejecting(a: usize, b: usize) -> Self::Output { + SearchStep::Reject(a, b) + } #[inline] - fn matching(a: usize, b: usize) -> Self::Output { SearchStep::Match(a, b) } + fn matching(a: usize, b: usize) -> Self::Output { + SearchStep::Match(a, b) + } } diff --git a/src/libcore/sync/atomic.rs b/src/libcore/sync/atomic.rs index 1f09895597a..a2352c08e73 100644 --- a/src/libcore/sync/atomic.rs +++ b/src/libcore/sync/atomic.rs @@ -120,9 +120,9 @@ use self::Ordering::*; -use crate::intrinsics; use crate::cell::UnsafeCell; use crate::fmt; +use crate::intrinsics; use crate::hint::spin_loop; @@ -313,7 +313,7 @@ pub enum Ordering { #[rustc_deprecated( since = "1.34.0", reason = "the `new` function is now preferred", - suggestion = "AtomicBool::new(false)", + suggestion = "AtomicBool::new(false)" )] pub const ATOMIC_BOOL_INIT: AtomicBool = AtomicBool::new(false); @@ -557,12 +557,13 @@ impl AtomicBool { #[inline] #[stable(feature = "extended_compare_and_swap", since = "1.10.0")] #[cfg(target_has_atomic = "8")] - pub fn compare_exchange(&self, - current: bool, - new: bool, - success: Ordering, - failure: Ordering) - -> Result<bool, bool> { + pub fn compare_exchange( + &self, + current: bool, + new: bool, + success: Ordering, + failure: Ordering, + ) -> Result<bool, bool> { match unsafe { atomic_compare_exchange(self.v.get(), current as u8, new as u8, success, failure) } { @@ -613,12 +614,13 @@ impl AtomicBool { #[inline] #[stable(feature = "extended_compare_and_swap", since = "1.10.0")] #[cfg(target_has_atomic = "8")] - pub fn compare_exchange_weak(&self, - current: bool, - new: bool, - success: Ordering, - failure: Ordering) - -> Result<bool, bool> { + pub fn compare_exchange_weak( + &self, + current: bool, + new: bool, + success: Ordering, + failure: Ordering, + ) -> Result<bool, bool> { match unsafe { atomic_compare_exchange_weak(self.v.get(), current as u8, new as u8, success, failure) } { @@ -834,9 +836,7 @@ impl AtomicBool { /// # } /// ``` #[inline] - #[unstable(feature = "atomic_mut_ptr", - reason = "recently added", - issue = "66893")] + #[unstable(feature = "atomic_mut_ptr", reason = "recently added", issue = "66893")] pub fn as_mut_ptr(&self) -> *mut bool { self.v.get() as *mut bool } @@ -1073,18 +1073,21 @@ impl<T> AtomicPtr<T> { #[inline] #[stable(feature = "extended_compare_and_swap", since = "1.10.0")] #[cfg(target_has_atomic = "ptr")] - pub fn compare_exchange(&self, - current: *mut T, - new: *mut T, - success: Ordering, - failure: Ordering) - -> Result<*mut T, *mut T> { + pub fn compare_exchange( + &self, + current: *mut T, + new: *mut T, + success: Ordering, + failure: Ordering, + ) -> Result<*mut T, *mut T> { unsafe { - let res = atomic_compare_exchange(self.p.get() as *mut usize, - current as usize, - new as usize, - success, - failure); + let res = atomic_compare_exchange( + self.p.get() as *mut usize, + current as usize, + new as usize, + success, + failure, + ); match res { Ok(x) => Ok(x as *mut T), Err(x) => Err(x as *mut T), @@ -1133,18 +1136,21 @@ impl<T> AtomicPtr<T> { #[inline] #[stable(feature = "extended_compare_and_swap", since = "1.10.0")] #[cfg(target_has_atomic = "ptr")] - pub fn compare_exchange_weak(&self, - current: *mut T, - new: *mut T, - success: Ordering, - failure: Ordering) - -> Result<*mut T, *mut T> { + pub fn compare_exchange_weak( + &self, + current: *mut T, + new: *mut T, + success: Ordering, + failure: Ordering, + ) -> Result<*mut T, *mut T> { unsafe { - let res = atomic_compare_exchange_weak(self.p.get() as *mut usize, - current as usize, - new as usize, - success, - failure); + let res = atomic_compare_exchange_weak( + self.p.get() as *mut usize, + current as usize, + new as usize, + success, + failure, + ); match res { Ok(x) => Ok(x as *mut T), Err(x) => Err(x as *mut T), @@ -1166,14 +1172,18 @@ impl From<bool> for AtomicBool { /// assert_eq!(format!("{:?}", atomic_bool), "true") /// ``` #[inline] - fn from(b: bool) -> Self { Self::new(b) } + fn from(b: bool) -> Self { + Self::new(b) + } } #[cfg(target_has_atomic_load_store = "ptr")] #[stable(feature = "atomic_from", since = "1.23.0")] impl<T> From<*mut T> for AtomicPtr<T> { #[inline] - fn from(p: *mut T) -> Self { Self::new(p) } + fn from(p: *mut T) -> Self { + Self::new(p) + } } #[cfg(target_has_atomic_load_store = "8")] @@ -2156,20 +2166,26 @@ atomic_int! { #[cfg(target_has_atomic_load_store = "ptr")] #[cfg(target_pointer_width = "16")] macro_rules! ptr_width { - () => { 2 } + () => { + 2 + }; } #[cfg(target_has_atomic_load_store = "ptr")] #[cfg(target_pointer_width = "32")] macro_rules! ptr_width { - () => { 4 } + () => { + 4 + }; } #[cfg(target_has_atomic_load_store = "ptr")] #[cfg(target_pointer_width = "64")] macro_rules! ptr_width { - () => { 8 } + () => { + 8 + }; } #[cfg(target_has_atomic_load_store = "ptr")] -atomic_int!{ +atomic_int! { cfg(target_has_atomic = "ptr"), stable(feature = "rust1", since = "1.0.0"), stable(feature = "extended_compare_and_swap", since = "1.10.0"), @@ -2187,7 +2203,7 @@ atomic_int!{ isize AtomicIsize ATOMIC_ISIZE_INIT } #[cfg(target_has_atomic_load_store = "ptr")] -atomic_int!{ +atomic_int! { cfg(target_has_atomic = "ptr"), stable(feature = "rust1", since = "1.0.0"), stable(feature = "extended_compare_and_swap", since = "1.10.0"), @@ -2279,12 +2295,13 @@ unsafe fn atomic_sub<T>(dst: *mut T, val: T, order: Ordering) -> T { #[inline] #[cfg(target_has_atomic = "8")] -unsafe fn atomic_compare_exchange<T>(dst: *mut T, - old: T, - new: T, - success: Ordering, - failure: Ordering) - -> Result<T, T> { +unsafe fn atomic_compare_exchange<T>( + dst: *mut T, + old: T, + new: T, + success: Ordering, + failure: Ordering, +) -> Result<T, T> { let (val, ok) = match (success, failure) { (Acquire, Acquire) => intrinsics::atomic_cxchg_acq(dst, old, new), (Release, Relaxed) => intrinsics::atomic_cxchg_rel(dst, old, new), @@ -2304,12 +2321,13 @@ unsafe fn atomic_compare_exchange<T>(dst: *mut T, #[inline] #[cfg(target_has_atomic = "8")] -unsafe fn atomic_compare_exchange_weak<T>(dst: *mut T, - old: T, - new: T, - success: Ordering, - failure: Ordering) - -> Result<T, T> { +unsafe fn atomic_compare_exchange_weak<T>( + dst: *mut T, + old: T, + new: T, + success: Ordering, + failure: Ordering, +) -> Result<T, T> { let (val, ok) = match (success, failure) { (Acquire, Acquire) => intrinsics::atomic_cxchgweak_acq(dst, old, new), (Release, Relaxed) => intrinsics::atomic_cxchgweak_rel(dst, old, new), @@ -2525,7 +2543,6 @@ pub fn fence(order: Ordering) { } } - /// A compiler memory fence. /// /// `compiler_fence` does not emit any machine code, but restricts the kinds @@ -2613,7 +2630,6 @@ pub fn compiler_fence(order: Ordering) { } } - #[cfg(target_has_atomic_load_store = "8")] #[stable(feature = "atomic_debug", since = "1.3.0")] impl fmt::Debug for AtomicBool { diff --git a/src/libcore/tests/cmp.rs b/src/libcore/tests/cmp.rs index 56a2f4acf6e..4086917780f 100644 --- a/src/libcore/tests/cmp.rs +++ b/src/libcore/tests/cmp.rs @@ -101,7 +101,7 @@ fn test_ordering_then_with() { fn test_user_defined_eq() { // Our type. struct SketchyNum { - num : isize + num: isize, } // Our implementation of `PartialEq` to support `==` and `!=`. @@ -113,6 +113,6 @@ fn test_user_defined_eq() { } // Now these binary operators will work when applied! - assert!(SketchyNum {num: 37} == SketchyNum {num: 34}); - assert!(SketchyNum {num: 25} != SketchyNum {num: 57}); + assert!(SketchyNum { num: 37 } == SketchyNum { num: 34 }); + assert!(SketchyNum { num: 25 } != SketchyNum { num: 57 }); } diff --git a/src/libcore/tests/fmt/builders.rs b/src/libcore/tests/fmt/builders.rs index 25572443281..90a9bccda15 100644 --- a/src/libcore/tests/fmt/builders.rs +++ b/src/libcore/tests/fmt/builders.rs @@ -21,18 +21,17 @@ mod debug_struct { impl fmt::Debug for Foo { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt.debug_struct("Foo") - .field("bar", &true) - .finish() + fmt.debug_struct("Foo").field("bar", &true).finish() } } assert_eq!("Foo { bar: true }", format!("{:?}", Foo)); assert_eq!( -"Foo { + "Foo { bar: true, }", - format!("{:#?}", Foo)); + format!("{:#?}", Foo) + ); } #[test] @@ -50,11 +49,12 @@ mod debug_struct { assert_eq!("Foo { bar: true, baz: 10/20 }", format!("{:?}", Foo)); assert_eq!( -"Foo { + "Foo { bar: true, baz: 10/20, }", - format!("{:#?}", Foo)); + format!("{:#?}", Foo) + ); } #[test] @@ -74,24 +74,24 @@ mod debug_struct { impl fmt::Debug for Bar { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt.debug_struct("Bar") - .field("foo", &Foo) - .field("hello", &"world") - .finish() + fmt.debug_struct("Bar").field("foo", &Foo).field("hello", &"world").finish() } } - assert_eq!("Bar { foo: Foo { bar: true, baz: 10/20 }, hello: \"world\" }", - format!("{:?}", Bar)); assert_eq!( -"Bar { + "Bar { foo: Foo { bar: true, baz: 10/20 }, hello: \"world\" }", + format!("{:?}", Bar) + ); + assert_eq!( + "Bar { foo: Foo { bar: true, baz: 10/20, }, hello: \"world\", }", - format!("{:#?}", Bar)); + format!("{:#?}", Bar) + ); } } @@ -118,18 +118,17 @@ mod debug_tuple { impl fmt::Debug for Foo { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt.debug_tuple("Foo") - .field(&true) - .finish() + fmt.debug_tuple("Foo").field(&true).finish() } } assert_eq!("Foo(true)", format!("{:?}", Foo)); assert_eq!( -"Foo( + "Foo( true, )", - format!("{:#?}", Foo)); + format!("{:#?}", Foo) + ); } #[test] @@ -138,20 +137,18 @@ mod debug_tuple { impl fmt::Debug for Foo { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt.debug_tuple("Foo") - .field(&true) - .field(&format_args!("{}/{}", 10, 20)) - .finish() + fmt.debug_tuple("Foo").field(&true).field(&format_args!("{}/{}", 10, 20)).finish() } } assert_eq!("Foo(true, 10/20)", format!("{:?}", Foo)); assert_eq!( -"Foo( + "Foo( true, 10/20, )", - format!("{:#?}", Foo)); + format!("{:#?}", Foo) + ); } #[test] @@ -160,10 +157,7 @@ mod debug_tuple { impl fmt::Debug for Foo { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt.debug_tuple("Foo") - .field(&true) - .field(&format_args!("{}/{}", 10, 20)) - .finish() + fmt.debug_tuple("Foo").field(&true).field(&format_args!("{}/{}", 10, 20)).finish() } } @@ -171,24 +165,21 @@ mod debug_tuple { impl fmt::Debug for Bar { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt.debug_tuple("Bar") - .field(&Foo) - .field(&"world") - .finish() + fmt.debug_tuple("Bar").field(&Foo).field(&"world").finish() } } - assert_eq!("Bar(Foo(true, 10/20), \"world\")", - format!("{:?}", Bar)); + assert_eq!("Bar(Foo(true, 10/20), \"world\")", format!("{:?}", Bar)); assert_eq!( -"Bar( + "Bar( Foo( true, 10/20, ), \"world\", )", - format!("{:#?}", Bar)); + format!("{:#?}", Bar) + ); } } @@ -215,9 +206,7 @@ mod debug_map { impl fmt::Debug for Entry { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt.debug_map() - .entry(&"bar", &true) - .finish() + fmt.debug_map().entry(&"bar", &true).finish() } } @@ -225,9 +214,7 @@ mod debug_map { impl fmt::Debug for KeyValue { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt.debug_map() - .key(&"bar").value(&true) - .finish() + fmt.debug_map().key(&"bar").value(&true).finish() } } @@ -236,10 +223,11 @@ mod debug_map { assert_eq!("{\"bar\": true}", format!("{:?}", Entry)); assert_eq!( -"{ + "{ \"bar\": true, }", - format!("{:#?}", Entry)); + format!("{:#?}", Entry) + ); } #[test] @@ -260,8 +248,10 @@ mod debug_map { impl fmt::Debug for KeyValue { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_map() - .key(&"bar").value(&true) - .key(&10).value(&format_args!("{}/{}", 10, 20)) + .key(&"bar") + .value(&true) + .key(&10) + .value(&format_args!("{}/{}", 10, 20)) .finish() } } @@ -271,11 +261,12 @@ mod debug_map { assert_eq!("{\"bar\": true, 10: 10/20}", format!("{:?}", Entry)); assert_eq!( -"{ + "{ \"bar\": true, 10: 10/20, }", - format!("{:#?}", Entry)); + format!("{:#?}", Entry) + ); } #[test] @@ -295,18 +286,17 @@ mod debug_map { impl fmt::Debug for Bar { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt.debug_map() - .entry(&"foo", &Foo) - .entry(&Foo, &"world") - .finish() + fmt.debug_map().entry(&"foo", &Foo).entry(&Foo, &"world").finish() } } - assert_eq!("{\"foo\": {\"bar\": true, 10: 10/20}, \ + assert_eq!( + "{\"foo\": {\"bar\": true, 10: 10/20}, \ {\"bar\": true, 10: 10/20}: \"world\"}", - format!("{:?}", Bar)); + format!("{:?}", Bar) + ); assert_eq!( -"{ + "{ \"foo\": { \"bar\": true, 10: 10/20, @@ -316,7 +306,8 @@ mod debug_map { 10: 10/20, }: \"world\", }", - format!("{:#?}", Bar)); + format!("{:#?}", Bar) + ); } #[test] @@ -366,10 +357,7 @@ mod debug_map { impl fmt::Debug for Foo { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt.debug_map() - .key(&"bar") - .key(&"invalid") - .finish() + fmt.debug_map().key(&"bar").key(&"invalid").finish() } } @@ -383,9 +371,7 @@ mod debug_map { impl fmt::Debug for Foo { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt.debug_map() - .key(&"bar") - .finish() + fmt.debug_map().key(&"bar").finish() } } @@ -399,10 +385,7 @@ mod debug_map { impl fmt::Debug for Foo { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt.debug_map() - .value(&"invalid") - .key(&"bar") - .finish() + fmt.debug_map().value(&"invalid").key(&"bar").finish() } } @@ -433,18 +416,17 @@ mod debug_set { impl fmt::Debug for Foo { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt.debug_set() - .entry(&true) - .finish() + fmt.debug_set().entry(&true).finish() } } assert_eq!("{true}", format!("{:?}", Foo)); assert_eq!( -"{ + "{ true, }", - format!("{:#?}", Foo)); + format!("{:#?}", Foo) + ); } #[test] @@ -453,20 +435,18 @@ mod debug_set { impl fmt::Debug for Foo { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt.debug_set() - .entry(&true) - .entry(&format_args!("{}/{}", 10, 20)) - .finish() + fmt.debug_set().entry(&true).entry(&format_args!("{}/{}", 10, 20)).finish() } } assert_eq!("{true, 10/20}", format!("{:?}", Foo)); assert_eq!( -"{ + "{ true, 10/20, }", - format!("{:#?}", Foo)); + format!("{:#?}", Foo) + ); } #[test] @@ -475,10 +455,7 @@ mod debug_set { impl fmt::Debug for Foo { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt.debug_set() - .entry(&true) - .entry(&format_args!("{}/{}", 10, 20)) - .finish() + fmt.debug_set().entry(&true).entry(&format_args!("{}/{}", 10, 20)).finish() } } @@ -486,24 +463,21 @@ mod debug_set { impl fmt::Debug for Bar { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt.debug_set() - .entry(&Foo) - .entry(&"world") - .finish() + fmt.debug_set().entry(&Foo).entry(&"world").finish() } } - assert_eq!("{{true, 10/20}, \"world\"}", - format!("{:?}", Bar)); + assert_eq!("{{true, 10/20}, \"world\"}", format!("{:?}", Bar)); assert_eq!( -"{ + "{ { true, 10/20, }, \"world\", }", - format!("{:#?}", Bar)); + format!("{:#?}", Bar) + ); } } @@ -530,18 +504,17 @@ mod debug_list { impl fmt::Debug for Foo { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt.debug_list() - .entry(&true) - .finish() + fmt.debug_list().entry(&true).finish() } } assert_eq!("[true]", format!("{:?}", Foo)); assert_eq!( -"[ + "[ true, ]", - format!("{:#?}", Foo)); + format!("{:#?}", Foo) + ); } #[test] @@ -550,20 +523,18 @@ mod debug_list { impl fmt::Debug for Foo { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt.debug_list() - .entry(&true) - .entry(&format_args!("{}/{}", 10, 20)) - .finish() + fmt.debug_list().entry(&true).entry(&format_args!("{}/{}", 10, 20)).finish() } } assert_eq!("[true, 10/20]", format!("{:?}", Foo)); assert_eq!( -"[ + "[ true, 10/20, ]", - format!("{:#?}", Foo)); + format!("{:#?}", Foo) + ); } #[test] @@ -572,10 +543,7 @@ mod debug_list { impl fmt::Debug for Foo { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt.debug_list() - .entry(&true) - .entry(&format_args!("{}/{}", 10, 20)) - .finish() + fmt.debug_list().entry(&true).entry(&format_args!("{}/{}", 10, 20)).finish() } } @@ -583,24 +551,21 @@ mod debug_list { impl fmt::Debug for Bar { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt.debug_list() - .entry(&Foo) - .entry(&"world") - .finish() + fmt.debug_list().entry(&Foo).entry(&"world").finish() } } - assert_eq!("[[true, 10/20], \"world\"]", - format!("{:?}", Bar)); + assert_eq!("[[true, 10/20], \"world\"]", format!("{:?}", Bar)); assert_eq!( -"[ + "[ [ true, 10/20, ], \"world\", ]", - format!("{:#?}", Bar)); + format!("{:#?}", Bar) + ); } } @@ -627,34 +592,54 @@ fn test_formatting_parameters_are_forwarded() { assert_eq!(format!("{:03?}", list), "[1024, 007]"); assert_eq!(format!("{:03?}", map), r#"{"bar": 1024, "baz": 007}"#); assert_eq!(format!("{:03?}", set), "{007, 1024}"); - assert_eq!(format!("{:#03?}", struct_), " + assert_eq!( + format!("{:#03?}", struct_), + " Foo { bar: 1024, baz: 007, } - ".trim()); - assert_eq!(format!("{:#03?}", tuple), " + " + .trim() + ); + assert_eq!( + format!("{:#03?}", tuple), + " ( 1024, 007, ) - ".trim()); - assert_eq!(format!("{:#03?}", list), " + " + .trim() + ); + assert_eq!( + format!("{:#03?}", list), + " [ 1024, 007, ] - ".trim()); - assert_eq!(format!("{:#03?}", map), r#" + " + .trim() + ); + assert_eq!( + format!("{:#03?}", map), + r#" { "bar": 1024, "baz": 007, } - "#.trim()); - assert_eq!(format!("{:#03?}", set), " + "# + .trim() + ); + assert_eq!( + format!("{:#03?}", set), + " { 007, 1024, } - ".trim()); + " + .trim() + ); } diff --git a/src/libcore/tests/hash/mod.rs b/src/libcore/tests/hash/mod.rs index ba0220f0d92..1566d357490 100644 --- a/src/libcore/tests/hash/mod.rs +++ b/src/libcore/tests/hash/mod.rs @@ -71,7 +71,8 @@ fn test_writer_hasher() { let ptr = 5_usize as *mut i32; assert_eq!(hash(&ptr), 5); - if cfg!(miri) { // Miri cannot hash pointers + if cfg!(miri) { + // Miri cannot hash pointers return; } diff --git a/src/libcore/tests/iter.rs b/src/libcore/tests/iter.rs index c9096b713f2..cf28ec8a636 100644 --- a/src/libcore/tests/iter.rs +++ b/src/libcore/tests/iter.rs @@ -1,58 +1,58 @@ use core::cell::Cell; use core::convert::TryFrom; use core::iter::*; -use core::{i8, i16, isize}; use core::usize; +use core::{i16, i8, isize}; #[test] fn test_lt() { let empty: [isize; 0] = []; - let xs = [1,2,3]; - let ys = [1,2,0]; + let xs = [1, 2, 3]; + let ys = [1, 2, 0]; assert!(!xs.iter().lt(ys.iter())); assert!(!xs.iter().le(ys.iter())); - assert!( xs.iter().gt(ys.iter())); - assert!( xs.iter().ge(ys.iter())); + assert!(xs.iter().gt(ys.iter())); + assert!(xs.iter().ge(ys.iter())); - assert!( ys.iter().lt(xs.iter())); - assert!( ys.iter().le(xs.iter())); + assert!(ys.iter().lt(xs.iter())); + assert!(ys.iter().le(xs.iter())); assert!(!ys.iter().gt(xs.iter())); assert!(!ys.iter().ge(xs.iter())); - assert!( empty.iter().lt(xs.iter())); - assert!( empty.iter().le(xs.iter())); + assert!(empty.iter().lt(xs.iter())); + assert!(empty.iter().le(xs.iter())); assert!(!empty.iter().gt(xs.iter())); assert!(!empty.iter().ge(xs.iter())); // Sequence with NaN let u = [1.0f64, 2.0]; - let v = [0.0f64/0.0, 3.0]; + let v = [0.0f64 / 0.0, 3.0]; assert!(!u.iter().lt(v.iter())); assert!(!u.iter().le(v.iter())); assert!(!u.iter().gt(v.iter())); assert!(!u.iter().ge(v.iter())); - let a = [0.0f64/0.0]; + let a = [0.0f64 / 0.0]; let b = [1.0f64]; let c = [2.0f64]; - assert!(a.iter().lt(b.iter()) == (a[0] < b[0])); + assert!(a.iter().lt(b.iter()) == (a[0] < b[0])); assert!(a.iter().le(b.iter()) == (a[0] <= b[0])); - assert!(a.iter().gt(b.iter()) == (a[0] > b[0])); + assert!(a.iter().gt(b.iter()) == (a[0] > b[0])); assert!(a.iter().ge(b.iter()) == (a[0] >= b[0])); - assert!(c.iter().lt(b.iter()) == (c[0] < b[0])); + assert!(c.iter().lt(b.iter()) == (c[0] < b[0])); assert!(c.iter().le(b.iter()) == (c[0] <= b[0])); - assert!(c.iter().gt(b.iter()) == (c[0] > b[0])); + assert!(c.iter().gt(b.iter()) == (c[0] > b[0])); assert!(c.iter().ge(b.iter()) == (c[0] >= b[0])); } #[test] fn test_multi_iter() { - let xs = [1,2,3,4]; - let ys = [4,3,2,1]; + let xs = [1, 2, 3, 4]; + let ys = [4, 3, 2, 1]; assert!(xs.iter().eq(ys.iter().rev())); assert!(xs.iter().lt(xs.iter().skip(2))); } @@ -229,11 +229,7 @@ fn test_iterator_chain_size_hint() { } fn size_hint(&self) -> (usize, Option<usize>) { - if self.is_empty { - (0, Some(0)) - } else { - (1, Some(1)) - } + if self.is_empty { (0, Some(0)) } else { (1, Some(1)) } } } @@ -277,7 +273,9 @@ fn test_zip_nth() { fn test_zip_nth_side_effects() { let mut a = Vec::new(); let mut b = Vec::new(); - let value = [1, 2, 3, 4, 5, 6].iter().cloned() + let value = [1, 2, 3, 4, 5, 6] + .iter() + .cloned() .map(|n| { a.push(n); n * 10 @@ -356,7 +354,9 @@ fn test_iterator_step_by_nth_overflow() { struct Test(Bigger); impl Iterator for &mut Test { type Item = i32; - fn next(&mut self) -> Option<Self::Item> { Some(21) } + fn next(&mut self) -> Option<Self::Item> { + Some(21) + } fn nth(&mut self, n: usize) -> Option<Self::Item> { self.0 += n as Bigger + 1; Some(42) @@ -499,7 +499,7 @@ fn test_iterator_step_by_size_hint() { let mut it = StubSizeHint(usize::MAX, None).step_by(1); assert_eq!(it.size_hint(), (usize::MAX, None)); it.next(); - assert_eq!(it.size_hint(), (usize::MAX-1, None)); + assert_eq!(it.size_hint(), (usize::MAX - 1, None)); // still infinite with larger step let mut it = StubSizeHint(7, None).step_by(3); @@ -508,18 +508,24 @@ fn test_iterator_step_by_size_hint() { assert_eq!(it.size_hint(), (2, None)); // propagates ExactSizeIterator - let a = [1,2,3,4,5]; + let a = [1, 2, 3, 4, 5]; let it = a.iter().step_by(2); assert_eq!(it.len(), 3); // Cannot be TrustedLen as a step greater than one makes an iterator // with (usize::MAX, None) no longer meet the safety requirements - trait TrustedLenCheck { fn test(self) -> bool; } - impl<T:Iterator> TrustedLenCheck for T { - default fn test(self) -> bool { false } + trait TrustedLenCheck { + fn test(self) -> bool; + } + impl<T: Iterator> TrustedLenCheck for T { + default fn test(self) -> bool { + false + } } - impl<T:TrustedLen> TrustedLenCheck for T { - fn test(self) -> bool { true } + impl<T: TrustedLen> TrustedLenCheck for T { + fn test(self) -> bool { + true + } } assert!(TrustedLenCheck::test(a.iter())); assert!(!TrustedLenCheck::test(a.iter().step_by(1))); @@ -527,23 +533,22 @@ fn test_iterator_step_by_size_hint() { #[test] fn test_filter_map() { - let it = (0..).step_by(1).take(10) - .filter_map(|x| if x % 2 == 0 { Some(x*x) } else { None }); - assert_eq!(it.collect::<Vec<usize>>(), [0*0, 2*2, 4*4, 6*6, 8*8]); + let it = (0..).step_by(1).take(10).filter_map(|x| if x % 2 == 0 { Some(x * x) } else { None }); + assert_eq!(it.collect::<Vec<usize>>(), [0 * 0, 2 * 2, 4 * 4, 6 * 6, 8 * 8]); } #[test] fn test_filter_map_fold() { let xs = [0, 1, 2, 3, 4, 5, 6, 7, 8]; - let ys = [0*0, 2*2, 4*4, 6*6, 8*8]; - let it = xs.iter().filter_map(|&x| if x % 2 == 0 { Some(x*x) } else { None }); + let ys = [0 * 0, 2 * 2, 4 * 4, 6 * 6, 8 * 8]; + let it = xs.iter().filter_map(|&x| if x % 2 == 0 { Some(x * x) } else { None }); let i = it.fold(0, |i, x| { assert_eq!(x, ys[i]); i + 1 }); assert_eq!(i, ys.len()); - let it = xs.iter().filter_map(|&x| if x % 2 == 0 { Some(x*x) } else { None }); + let it = xs.iter().filter_map(|&x| if x % 2 == 0 { Some(x * x) } else { None }); let i = it.rfold(ys.len(), |i, x| { assert_eq!(x, ys[i - 1]); i - 1 @@ -736,7 +741,6 @@ fn test_iterator_peekable_count() { let mut it = zs.iter().peekable(); assert_eq!(it.peek(), None); - } #[test] @@ -805,10 +809,7 @@ pub struct CycleIter<'a, T> { } pub fn cycle<T>(data: &[T]) -> CycleIter<'_, T> { - CycleIter { - index: 0, - data, - } + CycleIter { index: 0, data } } impl<'a, T> Iterator for CycleIter<'a, T> { @@ -832,7 +833,9 @@ fn test_iterator_peekable_remember_peek_none_1() { let is_the_last = iter.peek().is_none(); assert_eq!(is_the_last, n == data.len() - 1); n += 1; - if n > data.len() { break; } + if n > data.len() { + break; + } } assert_eq!(n, data.len()); } @@ -914,7 +917,7 @@ fn test_iterator_skip() { while let Some(&x) = it.next() { assert_eq!(x, ys[i]); i += 1; - assert_eq!(it.len(), xs.len()-5-i); + assert_eq!(it.len(), xs.len() - 5 - i); } assert_eq!(i, ys.len()); assert_eq!(it.len(), 0); @@ -972,7 +975,6 @@ fn test_iterator_skip_nth() { let mut it = xs.iter().skip(12); assert_eq!(it.nth(0), None); - } #[test] @@ -1037,7 +1039,6 @@ fn test_iterator_skip_fold() { i }); assert_eq!(i, 1); - } #[test] @@ -1178,7 +1179,7 @@ fn test_iterator_flat_map() { fn test_iterator_flat_map_fold() { let xs = [0, 3, 6]; let ys = [1, 2, 3, 4, 5, 6, 7]; - let mut it = xs.iter().flat_map(|&x| x..x+3); + let mut it = xs.iter().flat_map(|&x| x..x + 3); assert_eq!(it.next(), Some(0)); assert_eq!(it.next_back(), Some(8)); let i = it.fold(0, |i, x| { @@ -1187,7 +1188,7 @@ fn test_iterator_flat_map_fold() { }); assert_eq!(i, ys.len()); - let mut it = xs.iter().flat_map(|&x| x..x+3); + let mut it = xs.iter().flat_map(|&x| x..x + 3); assert_eq!(it.next(), Some(0)); assert_eq!(it.next_back(), Some(8)); let i = it.rfold(ys.len(), |i, x| { @@ -1216,7 +1217,7 @@ fn test_iterator_flatten() { fn test_iterator_flatten_fold() { let xs = [0, 3, 6]; let ys = [1, 2, 3, 4, 5, 6, 7]; - let mut it = xs.iter().map(|&x| x..x+3).flatten(); + let mut it = xs.iter().map(|&x| x..x + 3).flatten(); assert_eq!(it.next(), Some(0)); assert_eq!(it.next_back(), Some(8)); let i = it.fold(0, |i, x| { @@ -1225,7 +1226,7 @@ fn test_iterator_flatten_fold() { }); assert_eq!(i, ys.len()); - let mut it = xs.iter().map(|&x| x..x+3).flatten(); + let mut it = xs.iter().map(|&x| x..x + 3).flatten(); assert_eq!(it.next(), Some(0)); assert_eq!(it.next_back(), Some(8)); let i = it.rfold(ys.len(), |i, x| { @@ -1240,10 +1241,7 @@ fn test_inspect() { let xs = [1, 2, 3, 4]; let mut n = 0; - let ys = xs.iter() - .cloned() - .inspect(|_| n += 1) - .collect::<Vec<usize>>(); + let ys = xs.iter().cloned().inspect(|_| n += 1).collect::<Vec<usize>>(); assert_eq!(n, xs.len()); assert_eq!(&xs[..], &ys[..]); @@ -1483,7 +1481,7 @@ fn test_iterator_size_hint() { assert_eq!(c.clone().enumerate().size_hint(), (usize::MAX, None)); assert_eq!(c.clone().chain(vi.clone().cloned()).size_hint(), (usize::MAX, None)); assert_eq!(c.clone().zip(vi.clone()).size_hint(), (10, Some(10))); - assert_eq!(c.clone().scan(0, |_,_| Some(0)).size_hint(), (0, None)); + assert_eq!(c.clone().scan(0, |_, _| Some(0)).size_hint(), (0, None)); assert_eq!(c.clone().filter(|_| false).size_hint(), (0, None)); assert_eq!(c.clone().map(|_| 0).size_hint(), (usize::MAX, None)); assert_eq!(c.filter_map(|_| Some(0)).size_hint(), (0, None)); @@ -1497,9 +1495,9 @@ fn test_iterator_size_hint() { assert_eq!(vi.clone().enumerate().size_hint(), (10, Some(10))); assert_eq!(vi.clone().chain(v2).size_hint(), (13, Some(13))); assert_eq!(vi.clone().zip(v2).size_hint(), (3, Some(3))); - assert_eq!(vi.clone().scan(0, |_,_| Some(0)).size_hint(), (0, Some(10))); + assert_eq!(vi.clone().scan(0, |_, _| Some(0)).size_hint(), (0, Some(10))); assert_eq!(vi.clone().filter(|_| false).size_hint(), (0, Some(10))); - assert_eq!(vi.clone().map(|&i| i+1).size_hint(), (10, Some(10))); + assert_eq!(vi.clone().map(|&i| i + 1).size_hint(), (10, Some(10))); assert_eq!(vi.filter_map(|_| Some(0)).size_hint(), (0, Some(10))); } @@ -1555,11 +1553,7 @@ fn test_find_map() { assert_eq!(iter.next(), Some(&7)); fn half_if_even(x: &isize) -> Option<isize> { - if x % 2 == 0 { - Some(x / 2) - } else { - None - } + if x % 2 == 0 { Some(x / 2) } else { None } } } @@ -1618,8 +1612,7 @@ fn test_rev() { let mut it = xs.iter(); it.next(); it.next(); - assert!(it.rev().cloned().collect::<Vec<isize>>() == - vec![16, 14, 12, 10, 8, 6]); + assert!(it.rev().cloned().collect::<Vec<isize>>() == vec![16, 14, 12, 10, 8, 6]); } #[test] @@ -1748,14 +1741,22 @@ fn test_double_ended_chain() { assert_eq!(it.next_back().unwrap(), &7); assert_eq!(it.next_back(), None); - // test that .chain() is well behaved with an unfused iterator struct CrazyIterator(bool); - impl CrazyIterator { fn new() -> CrazyIterator { CrazyIterator(false) } } + impl CrazyIterator { + fn new() -> CrazyIterator { + CrazyIterator(false) + } + } impl Iterator for CrazyIterator { type Item = i32; fn next(&mut self) -> Option<i32> { - if self.0 { Some(99) } else { self.0 = true; None } + if self.0 { + Some(99) + } else { + self.0 = true; + None + } } } @@ -1771,8 +1772,14 @@ fn test_double_ended_chain() { #[test] fn test_rposition() { - fn f(xy: &(isize, char)) -> bool { let (_x, y) = *xy; y == 'b' } - fn g(xy: &(isize, char)) -> bool { let (_x, y) = *xy; y == 'd' } + fn f(xy: &(isize, char)) -> bool { + let (_x, y) = *xy; + y == 'b' + } + fn g(xy: &(isize, char)) -> bool { + let (_x, y) = *xy; + y == 'd' + } let v = [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')]; assert_eq!(v.iter().rposition(f), Some(3)); @@ -1788,9 +1795,7 @@ fn test_rev_rposition() { #[test] #[should_panic] fn test_rposition_panic() { - let v: [(Box<_>, Box<_>); 4] = - [(box 0, box 0), (box 0, box 0), - (box 0, box 0), (box 0, box 0)]; + let v: [(Box<_>, Box<_>); 4] = [(box 0, box 0), (box 0, box 0), (box 0, box 0), (box 0, box 0)]; let mut i = 0; v.iter().rposition(|_elt| { if i == 2 { @@ -1801,38 +1806,37 @@ fn test_rposition_panic() { }); } - #[test] fn test_double_ended_flat_map() { - let u = [0,1]; - let v = [5,6,7,8]; + let u = [0, 1]; + let v = [5, 6, 7, 8]; let mut it = u.iter().flat_map(|x| &v[*x..v.len()]); assert_eq!(it.next_back().unwrap(), &8); - assert_eq!(it.next().unwrap(), &5); + assert_eq!(it.next().unwrap(), &5); assert_eq!(it.next_back().unwrap(), &7); assert_eq!(it.next_back().unwrap(), &6); assert_eq!(it.next_back().unwrap(), &8); - assert_eq!(it.next().unwrap(), &6); + assert_eq!(it.next().unwrap(), &6); assert_eq!(it.next_back().unwrap(), &7); assert_eq!(it.next_back(), None); - assert_eq!(it.next(), None); + assert_eq!(it.next(), None); assert_eq!(it.next_back(), None); } #[test] fn test_double_ended_flatten() { - let u = [0,1]; - let v = [5,6,7,8]; + let u = [0, 1]; + let v = [5, 6, 7, 8]; let mut it = u.iter().map(|x| &v[*x..v.len()]).flatten(); assert_eq!(it.next_back().unwrap(), &8); - assert_eq!(it.next().unwrap(), &5); + assert_eq!(it.next().unwrap(), &5); assert_eq!(it.next_back().unwrap(), &7); assert_eq!(it.next_back().unwrap(), &6); assert_eq!(it.next_back().unwrap(), &8); - assert_eq!(it.next().unwrap(), &6); + assert_eq!(it.next().unwrap(), &6); assert_eq!(it.next_back().unwrap(), &7); assert_eq!(it.next_back(), None); - assert_eq!(it.next(), None); + assert_eq!(it.next(), None); assert_eq!(it.next_back(), None); } @@ -1867,8 +1871,10 @@ fn test_range() { assert_eq!((-70..58).size_hint(), (128, Some(128))); assert_eq!((-128..127).size_hint(), (255, Some(255))); - assert_eq!((-2..isize::MAX).size_hint(), - (isize::MAX as usize + 2, Some(isize::MAX as usize + 2))); + assert_eq!( + (-2..isize::MAX).size_hint(), + (isize::MAX as usize + 2, Some(isize::MAX as usize + 2)) + ); } #[test] @@ -2171,15 +2177,15 @@ fn test_range_inclusive_folds() { assert!(it.is_empty()); let mut it = 10..=20; - assert_eq!(it.try_fold(0, |a,b| Some(a+b)), Some(165)); + assert_eq!(it.try_fold(0, |a, b| Some(a + b)), Some(165)); assert!(it.is_empty()); - assert_eq!(it.try_fold(0, |a,b| Some(a+b)), Some(0)); + assert_eq!(it.try_fold(0, |a, b| Some(a + b)), Some(0)); assert!(it.is_empty()); let mut it = 10..=20; - assert_eq!(it.try_rfold(0, |a,b| Some(a+b)), Some(165)); + assert_eq!(it.try_rfold(0, |a, b| Some(a + b)), Some(165)); assert!(it.is_empty()); - assert_eq!(it.try_rfold(0, |a,b| Some(a+b)), Some(0)); + assert_eq!(it.try_rfold(0, |a, b| Some(a + b)), Some(0)); assert!(it.is_empty()); } @@ -2292,15 +2298,19 @@ fn test_repeat_with_take() { is_trusted_len(repeat_with(|| 42).take(3)); assert_eq!(repeat_with(|| 42).take(3).size_hint(), (3, Some(3))); assert_eq!(repeat_with(|| 42).take(0).size_hint(), (0, Some(0))); - assert_eq!(repeat_with(|| 42).take(usize::MAX).size_hint(), - (usize::MAX, Some(usize::MAX))); + assert_eq!(repeat_with(|| 42).take(usize::MAX).size_hint(), (usize::MAX, Some(usize::MAX))); } #[test] fn test_repeat_with_take_collect() { let mut curr = 1; - let v: Vec<_> = repeat_with(|| { let tmp = curr; curr *= 2; tmp }) - .take(5).collect(); + let v: Vec<_> = repeat_with(|| { + let tmp = curr; + curr *= 2; + tmp + }) + .take(5) + .collect(); assert_eq!(v, vec![1, 2, 4, 8, 16]); } @@ -2472,7 +2482,7 @@ fn test_step_replace_no_between() { #[test] fn test_rev_try_folds() { - let f = &|acc, x| i32::checked_add(2*acc, x); + let f = &|acc, x| i32::checked_add(2 * acc, x); assert_eq!((1..10).rev().try_fold(7, f), (1..10).try_rfold(7, f)); assert_eq!((1..10).rev().try_rfold(7, f), (1..10).try_fold(7, f)); @@ -2488,8 +2498,8 @@ fn test_rev_try_folds() { #[test] fn test_cloned_try_folds() { let a = [1, 2, 3, 4, 5, 6, 7, 8, 9]; - let f = &|acc, x| i32::checked_add(2*acc, x); - let f_ref = &|acc, &x| i32::checked_add(2*acc, x); + let f = &|acc, x| i32::checked_add(2 * acc, x); + let f_ref = &|acc, &x| i32::checked_add(2 * acc, x); assert_eq!(a.iter().cloned().try_fold(7, f), a.iter().try_fold(7, f_ref)); assert_eq!(a.iter().cloned().try_rfold(7, f), a.iter().try_rfold(7, f_ref)); @@ -2506,7 +2516,7 @@ fn test_cloned_try_folds() { fn test_chain_try_folds() { let c = || (0..10).chain(10..20); - let f = &|acc, x| i32::checked_add(2*acc, x); + let f = &|acc, x| i32::checked_add(2 * acc, x); assert_eq!(c().try_fold(7, f), (0..20).try_fold(7, f)); assert_eq!(c().try_rfold(7, f), (0..20).rev().try_fold(7, f)); @@ -2515,14 +2525,14 @@ fn test_chain_try_folds() { assert_eq!(iter.next(), Some(6), "stopped in front, state Both"); assert_eq!(iter.position(|x| x == 13), Some(6)); assert_eq!(iter.next(), Some(14), "stopped in back, state Back"); - assert_eq!(iter.try_fold(0, |acc, x| Some(acc+x)), Some((15..20).sum())); + assert_eq!(iter.try_fold(0, |acc, x| Some(acc + x)), Some((15..20).sum())); let mut iter = c().rev(); // use rev to access try_rfold assert_eq!(iter.position(|x| x == 15), Some(4)); assert_eq!(iter.next(), Some(14), "stopped in back, state Both"); assert_eq!(iter.position(|x| x == 5), Some(8)); assert_eq!(iter.next(), Some(4), "stopped in front, state Front"); - assert_eq!(iter.try_fold(0, |acc, x| Some(acc+x)), Some((0..4).sum())); + assert_eq!(iter.try_fold(0, |acc, x| Some(acc + x)), Some((0..4).sum())); let mut iter = c(); iter.by_ref().rev().nth(14); // skip the last 15, ending in state Front @@ -2535,11 +2545,11 @@ fn test_chain_try_folds() { #[test] fn test_map_try_folds() { - let f = &|acc, x| i32::checked_add(2*acc, x); - assert_eq!((0..10).map(|x| x+3).try_fold(7, f), (3..13).try_fold(7, f)); - assert_eq!((0..10).map(|x| x+3).try_rfold(7, f), (3..13).try_rfold(7, f)); + let f = &|acc, x| i32::checked_add(2 * acc, x); + assert_eq!((0..10).map(|x| x + 3).try_fold(7, f), (3..13).try_fold(7, f)); + assert_eq!((0..10).map(|x| x + 3).try_rfold(7, f), (3..13).try_rfold(7, f)); - let mut iter = (0..40).map(|x| x+10); + let mut iter = (0..40).map(|x| x + 10); assert_eq!(iter.try_fold(0, i8::checked_add), None); assert_eq!(iter.next(), Some(20)); assert_eq!(iter.try_rfold(0, i8::checked_add), None); @@ -2548,8 +2558,10 @@ fn test_map_try_folds() { #[test] fn test_filter_try_folds() { - fn p(&x: &i32) -> bool { 0 <= x && x < 10 } - let f = &|acc, x| i32::checked_add(2*acc, x); + fn p(&x: &i32) -> bool { + 0 <= x && x < 10 + } + let f = &|acc, x| i32::checked_add(2 * acc, x); assert_eq!((-10..20).filter(p).try_fold(7, f), (0..10).try_fold(7, f)); assert_eq!((-10..20).filter(p).try_rfold(7, f), (0..10).try_rfold(7, f)); @@ -2562,12 +2574,12 @@ fn test_filter_try_folds() { #[test] fn test_filter_map_try_folds() { - let mp = &|x| if 0 <= x && x < 10 { Some(x*2) } else { None }; - let f = &|acc, x| i32::checked_add(2*acc, x); - assert_eq!((-9..20).filter_map(mp).try_fold(7, f), (0..10).map(|x| 2*x).try_fold(7, f)); - assert_eq!((-9..20).filter_map(mp).try_rfold(7, f), (0..10).map(|x| 2*x).try_rfold(7, f)); + let mp = &|x| if 0 <= x && x < 10 { Some(x * 2) } else { None }; + let f = &|acc, x| i32::checked_add(2 * acc, x); + assert_eq!((-9..20).filter_map(mp).try_fold(7, f), (0..10).map(|x| 2 * x).try_fold(7, f)); + assert_eq!((-9..20).filter_map(mp).try_rfold(7, f), (0..10).map(|x| 2 * x).try_rfold(7, f)); - let mut iter = (0..40).filter_map(|x| if x%2 == 1 { None } else { Some(x*2 + 10) }); + let mut iter = (0..40).filter_map(|x| if x % 2 == 1 { None } else { Some(x * 2 + 10) }); assert_eq!(iter.try_fold(0, i8::checked_add), None); assert_eq!(iter.next(), Some(38)); assert_eq!(iter.try_rfold(0, i8::checked_add), None); @@ -2576,9 +2588,9 @@ fn test_filter_map_try_folds() { #[test] fn test_enumerate_try_folds() { - let f = &|acc, (i, x)| usize::checked_add(2*acc, x/(i+1) + i); - assert_eq!((9..18).enumerate().try_fold(7, f), (0..9).map(|i| (i, i+9)).try_fold(7, f)); - assert_eq!((9..18).enumerate().try_rfold(7, f), (0..9).map(|i| (i, i+9)).try_rfold(7, f)); + let f = &|acc, (i, x)| usize::checked_add(2 * acc, x / (i + 1) + i); + assert_eq!((9..18).enumerate().try_fold(7, f), (0..9).map(|i| (i, i + 9)).try_fold(7, f)); + assert_eq!((9..18).enumerate().try_rfold(7, f), (0..9).map(|i| (i, i + 9)).try_rfold(7, f)); let mut iter = (100..200).enumerate(); let f = &|acc, (i, x)| u8::checked_add(acc, u8::checked_div(x, i as u8 + 1)?); @@ -2590,7 +2602,7 @@ fn test_enumerate_try_folds() { #[test] fn test_peek_try_folds() { - let f = &|acc, x| i32::checked_add(2*acc, x); + let f = &|acc, x| i32::checked_add(2 * acc, x); assert_eq!((1..20).peekable().try_fold(7, f), (1..20).try_fold(7, f)); assert_eq!((1..20).peekable().try_rfold(7, f), (1..20).try_rfold(7, f)); @@ -2637,8 +2649,10 @@ fn test_peek_try_folds() { #[test] fn test_skip_while_try_fold() { - let f = &|acc, x| i32::checked_add(2*acc, x); - fn p(&x: &i32) -> bool { (x % 10) <= 5 } + let f = &|acc, x| i32::checked_add(2 * acc, x); + fn p(&x: &i32) -> bool { + (x % 10) <= 5 + } assert_eq!((1..20).skip_while(p).try_fold(7, f), (6..20).try_fold(7, f)); let mut iter = (1..20).skip_while(p); assert_eq!(iter.nth(5), Some(11)); @@ -2651,13 +2665,13 @@ fn test_skip_while_try_fold() { #[test] fn test_take_while_folds() { - let f = &|acc, x| i32::checked_add(2*acc, x); + let f = &|acc, x| i32::checked_add(2 * acc, x); assert_eq!((1..20).take_while(|&x| x != 10).try_fold(7, f), (1..10).try_fold(7, f)); let mut iter = (1..20).take_while(|&x| x != 10); - assert_eq!(iter.try_fold(0, |x, y| Some(x+y)), Some((1..10).sum())); + assert_eq!(iter.try_fold(0, |x, y| Some(x + y)), Some((1..10).sum())); assert_eq!(iter.next(), None, "flag should be set"); let iter = (1..20).take_while(|&x| x != 10); - assert_eq!(iter.fold(0, |x, y| x+y), (1..10).sum()); + assert_eq!(iter.fold(0, |x, y| x + y), (1..10).sum()); let mut iter = (10..50).take_while(|&x| x != 40); assert_eq!(iter.try_fold(0, i8::checked_add), None); @@ -2666,7 +2680,7 @@ fn test_take_while_folds() { #[test] fn test_skip_try_folds() { - let f = &|acc, x| i32::checked_add(2*acc, x); + let f = &|acc, x| i32::checked_add(2 * acc, x); assert_eq!((1..20).skip(9).try_fold(7, f), (10..20).try_fold(7, f)); assert_eq!((1..20).skip(9).try_rfold(7, f), (10..20).try_rfold(7, f)); @@ -2713,7 +2727,7 @@ fn test_skip_nth_back() { #[test] fn test_take_try_folds() { - let f = &|acc, x| i32::checked_add(2*acc, x); + let f = &|acc, x| i32::checked_add(2 * acc, x); assert_eq!((10..30).take(10).try_fold(7, f), (10..20).try_fold(7, f)); assert_eq!((10..30).take(10).try_rfold(7, f), (10..20).try_rfold(7, f)); @@ -2738,15 +2752,16 @@ fn test_take_try_folds() { #[test] fn test_flat_map_try_folds() { - let f = &|acc, x| i32::checked_add(acc*2/3, x); - let mr = &|x| (5*x)..(5*x + 5); + let f = &|acc, x| i32::checked_add(acc * 2 / 3, x); + let mr = &|x| (5 * x)..(5 * x + 5); assert_eq!((0..10).flat_map(mr).try_fold(7, f), (0..50).try_fold(7, f)); assert_eq!((0..10).flat_map(mr).try_rfold(7, f), (0..50).try_rfold(7, f)); let mut iter = (0..10).flat_map(mr); - iter.next(); iter.next_back(); // have front and back iters in progress + iter.next(); + iter.next_back(); // have front and back iters in progress assert_eq!(iter.try_rfold(7, f), (1..49).try_rfold(7, f)); - let mut iter = (0..10).flat_map(|x| (4*x)..(4*x + 4)); + let mut iter = (0..10).flat_map(|x| (4 * x)..(4 * x + 4)); assert_eq!(iter.try_fold(0, i8::checked_add), None); assert_eq!(iter.next(), Some(17)); assert_eq!(iter.try_rfold(0, i8::checked_add), None); @@ -2755,15 +2770,16 @@ fn test_flat_map_try_folds() { #[test] fn test_flatten_try_folds() { - let f = &|acc, x| i32::checked_add(acc*2/3, x); - let mr = &|x| (5*x)..(5*x + 5); + let f = &|acc, x| i32::checked_add(acc * 2 / 3, x); + let mr = &|x| (5 * x)..(5 * x + 5); assert_eq!((0..10).map(mr).flatten().try_fold(7, f), (0..50).try_fold(7, f)); assert_eq!((0..10).map(mr).flatten().try_rfold(7, f), (0..50).try_rfold(7, f)); let mut iter = (0..10).map(mr).flatten(); - iter.next(); iter.next_back(); // have front and back iters in progress + iter.next(); + iter.next_back(); // have front and back iters in progress assert_eq!(iter.try_rfold(7, f), (1..49).try_rfold(7, f)); - let mut iter = (0..10).map(|x| (4*x)..(4*x + 4)).flatten(); + let mut iter = (0..10).map(|x| (4 * x)..(4 * x + 4)).flatten(); assert_eq!(iter.try_fold(0, i8::checked_add), None); assert_eq!(iter.next(), Some(17)); assert_eq!(iter.try_rfold(0, i8::checked_add), None); @@ -2773,13 +2789,21 @@ fn test_flatten_try_folds() { #[test] fn test_functor_laws() { // identity: - fn identity<T>(x: T) -> T { x } + fn identity<T>(x: T) -> T { + x + } assert_eq!((0..10).map(identity).sum::<usize>(), (0..10).sum()); // composition: - fn f(x: usize) -> usize { x + 3 } - fn g(x: usize) -> usize { x * 2 } - fn h(x: usize) -> usize { g(f(x)) } + fn f(x: usize) -> usize { + x + 3 + } + fn g(x: usize) -> usize { + x * 2 + } + fn h(x: usize) -> usize { + g(f(x)) + } assert_eq!((0..10).map(f).map(g).sum::<usize>(), (0..10).map(h).sum()); } @@ -2798,10 +2822,16 @@ fn test_monad_laws_right_identity() { #[test] fn test_monad_laws_associativity() { - fn f(x: usize) -> impl Iterator<Item = usize> { 0..x } - fn g(x: usize) -> impl Iterator<Item = usize> { (0..x).rev() } - assert_eq!((0..10).flat_map(f).flat_map(g).sum::<usize>(), - (0..10).flat_map(|x| f(x).flat_map(g)).sum::<usize>()); + fn f(x: usize) -> impl Iterator<Item = usize> { + 0..x + } + fn g(x: usize) -> impl Iterator<Item = usize> { + (0..x).rev() + } + assert_eq!( + (0..10).flat_map(f).flat_map(g).sum::<usize>(), + (0..10).flat_map(|x| f(x).flat_map(g)).sum::<usize>() + ); } #[test] diff --git a/src/libcore/tests/num/dec2flt/mod.rs b/src/libcore/tests/num/dec2flt/mod.rs index 6bb348fd752..a1fa5556ae5 100644 --- a/src/libcore/tests/num/dec2flt/mod.rs +++ b/src/libcore/tests/num/dec2flt/mod.rs @@ -32,7 +32,8 @@ fn ordinary() { test_literal!(12345.); test_literal!(0.9999999); - if cfg!(miri) { // Miri is too slow + if cfg!(miri) { + // Miri is too slow return; } @@ -82,7 +83,8 @@ fn zero() { test_literal!(0.0); test_literal!(1e-325); - if cfg!(miri) { // Miri is too slow + if cfg!(miri) { + // Miri is too slow return; } diff --git a/src/libcore/tests/num/flt2dec/mod.rs b/src/libcore/tests/num/flt2dec/mod.rs index 2f94ea2fc4b..f6935048246 100644 --- a/src/libcore/tests/num/flt2dec/mod.rs +++ b/src/libcore/tests/num/flt2dec/mod.rs @@ -1,9 +1,10 @@ -use std::{str, i16, f32, f64, fmt}; +use std::{f32, f64, fmt, i16, str}; -use core::num::flt2dec::{decode, DecodableFloat, FullDecoded, Decoded}; -use core::num::flt2dec::{MAX_SIG_DIGITS, round_up, Part, Formatted, Sign}; -use core::num::flt2dec::{to_shortest_str, to_shortest_exp_str, - to_exact_exp_str, to_exact_fixed_str}; +use core::num::flt2dec::{decode, DecodableFloat, Decoded, FullDecoded}; +use core::num::flt2dec::{round_up, Formatted, Part, Sign, MAX_SIG_DIGITS}; +use core::num::flt2dec::{ + to_exact_exp_str, to_exact_fixed_str, to_shortest_exp_str, to_shortest_str, +}; pub use test::Bencher; @@ -17,7 +18,7 @@ mod random; pub fn decode_finite<T: DecodableFloat>(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), } } @@ -81,7 +82,7 @@ fn ldexp_f32(a: f32, b: i32) -> f32 { } fn ldexp_f64(a: f64, b: i32) -> f64 { - extern { + extern "C" { fn ldexp(x: f64, n: i32) -> f64; } // SAFETY: assuming a correct `ldexp` has been supplied, the given arguments cannot possibly @@ -90,7 +91,10 @@ fn ldexp_f64(a: f64, b: i32) -> f64 { } fn check_exact<F, T>(mut f: F, v: T, vstr: &str, expected: &[u8], expectedk: i16) - where T: DecodableFloat, F: FnMut(&Decoded, &mut [u8], i16) -> (usize, i16) { +where + T: DecodableFloat, + F: FnMut(&Decoded, &mut [u8], i16) -> (usize, i16), +{ // use a large enough buffer let mut buf = [b'_'; 1024]; let mut expected_ = [b'_'; 1024]; @@ -105,14 +109,18 @@ fn check_exact<F, T>(mut f: F, v: T, vstr: &str, expected: &[u8], expectedk: i16 if expected[i] >= b'5' { // check if this is a rounding-to-even case. // we avoid rounding ...x5000... (with infinite zeroes) to ...(x+1) when x is even. - if !(i+1 < expected.len() && expected[i-1] & 1 == 0 && - expected[i] == b'5' && - expected[i+1] == b' ') { + if !(i + 1 < expected.len() + && expected[i - 1] & 1 == 0 + && expected[i] == b'5' + && expected[i + 1] == b' ') + { // if this returns true, expected_[..i] is all `9`s and being rounded up. // we should always return `100..00` (`i` digits) instead, since that's // what we can came up with `i` digits anyway. `round_up` assumes that // the adjustment to the length is done by caller, which we simply ignore. - if let Some(_) = round_up(&mut expected_, i) { expectedk_ += 1; } + if let Some(_) = round_up(&mut expected_, i) { + expectedk_ += 1; + } } } @@ -146,9 +154,11 @@ fn check_exact<F, T>(mut f: F, v: T, vstr: &str, expected: &[u8], expectedk: i16 // check infinite zero digits if let Some(cut) = cut { - for i in cut..expected.len()-1 { + for i in cut..expected.len() - 1 { expected_[..cut].copy_from_slice(&expected[..cut]); - for c in &mut expected_[cut..i] { *c = b'0'; } + for c in &mut expected_[cut..i] { + *c = b'0'; + } try_exact!(f(&decoded) => &mut buf, &expected_[..i], expectedk; "exact infzero mismatch for v={v}, i={i}: \ @@ -162,23 +172,29 @@ fn check_exact<F, T>(mut f: F, v: T, vstr: &str, expected: &[u8], expectedk: i16 } } -trait TestableFloat : DecodableFloat + fmt::Display { +trait TestableFloat: DecodableFloat + fmt::Display { /// Returns `x * 2^exp`. Almost same to `std::{f32,f64}::ldexp`. /// This is used for testing. fn ldexpi(f: i64, exp: isize) -> Self; } impl TestableFloat for f32 { - fn ldexpi(f: i64, exp: isize) -> Self { f as Self * (exp as Self).exp2() } + fn ldexpi(f: i64, exp: isize) -> Self { + f as Self * (exp as Self).exp2() + } } impl TestableFloat for f64 { - fn ldexpi(f: i64, exp: isize) -> Self { f as Self * (exp as Self).exp2() } + fn ldexpi(f: i64, exp: isize) -> Self { + f as Self * (exp as Self).exp2() + } } fn check_exact_one<F, T>(mut f: F, x: i64, e: isize, tstr: &str, expected: &[u8], expectedk: i16) - where T: TestableFloat, - F: FnMut(&Decoded, &mut [u8], i16) -> (usize, i16) { +where + T: TestableFloat, + F: FnMut(&Decoded, &mut [u8], i16) -> (usize, i16), +{ // use a large enough buffer let mut buf = [b'_'; 1024]; let v: T = TestableFloat::ldexpi(x, e); @@ -193,15 +209,15 @@ fn check_exact_one<F, T>(mut f: F, x: i64, e: isize, tstr: &str, expected: &[u8] } macro_rules! check_exact { - ($f:ident($v:expr) => $buf:expr, $exp:expr) => ( - check_exact(|d,b,k| $f(d,b,k), $v, stringify!($v), $buf, $exp) - ) + ($f:ident($v:expr) => $buf:expr, $exp:expr) => { + check_exact(|d, b, k| $f(d, b, k), $v, stringify!($v), $buf, $exp) + }; } macro_rules! check_exact_one { - ($f:ident($x:expr, $e:expr; $t:ty) => $buf:expr, $exp:expr) => ( - check_exact_one::<_, $t>(|d,b,k| $f(d,b,k), $x, $e, stringify!($t), $buf, $exp) - ) + ($f:ident($x:expr, $e:expr; $t:ty) => $buf:expr, $exp:expr) => { + check_exact_one::<_, $t>(|d, b, k| $f(d, b, k), $x, $e, stringify!($t), $buf, $exp) + }; } // in the following comments, three numbers are spaced by 1 ulp apart, @@ -212,7 +228,10 @@ macro_rules! check_exact_one { // [1] Vern Paxson, A Program for Testing IEEE Decimal-Binary Conversion // ftp://ftp.ee.lbl.gov/testbase-report.ps.Z -pub fn f32_shortest_sanity_test<F>(mut f: F) where F: FnMut(&Decoded, &mut [u8]) -> (usize, i16) { +pub fn f32_shortest_sanity_test<F>(mut f: F) +where + F: FnMut(&Decoded, &mut [u8]) -> (usize, i16), +{ // 0.0999999940395355224609375 // 0.100000001490116119384765625 // 0.10000000894069671630859375 @@ -257,7 +276,9 @@ pub fn f32_shortest_sanity_test<F>(mut f: F) where F: FnMut(&Decoded, &mut [u8]) } pub fn f32_exact_sanity_test<F>(mut f: F) - where F: FnMut(&Decoded, &mut [u8], i16) -> (usize, i16) { +where + F: FnMut(&Decoded, &mut [u8], i16) -> (usize, i16), +{ let minf32 = ldexp_f32(1.0, -149); check_exact!(f(0.1f32) => b"100000001490116119384765625 ", 0); @@ -298,7 +319,10 @@ pub fn f32_exact_sanity_test<F>(mut f: F) check_exact_one!(f(13248074, 95; f32) => b"524810279937", 36); } -pub fn f64_shortest_sanity_test<F>(mut f: F) where F: FnMut(&Decoded, &mut [u8]) -> (usize, i16) { +pub fn f64_shortest_sanity_test<F>(mut f: F) +where + F: FnMut(&Decoded, &mut [u8]) -> (usize, i16), +{ // 0.0999999999999999777955395074968691915273... // 0.1000000000000000055511151231257827021181... // 0.1000000000000000333066907387546962127089... @@ -362,7 +386,9 @@ pub fn f64_shortest_sanity_test<F>(mut f: F) where F: FnMut(&Decoded, &mut [u8]) } pub fn f64_exact_sanity_test<F>(mut f: F) - where F: FnMut(&Decoded, &mut [u8], i16) -> (usize, i16) { +where + F: FnMut(&Decoded, &mut [u8], i16) -> (usize, i16), +{ let minf64 = ldexp_f64(1.0, -1074); check_exact!(f(0.1f64) => b"1000000000000000055511151231257827021181", 0); @@ -446,7 +472,10 @@ pub fn f64_exact_sanity_test<F>(mut f: F) check_exact_one!(f(8549497411294502, -448; f64) => b"1176257830728540379990", -118); } -pub fn more_shortest_sanity_test<F>(mut f: F) where F: FnMut(&Decoded, &mut [u8]) -> (usize, i16) { +pub fn more_shortest_sanity_test<F>(mut f: F) +where + F: FnMut(&Decoded, &mut [u8]) -> (usize, i16), +{ check_shortest!(f{mant: 99_999_999_999_999_999, minus: 1, plus: 1, exp: 0, inclusive: true} => b"1", 18); check_shortest!(f{mant: 99_999_999_999_999_999, minus: 1, plus: 1, @@ -454,7 +483,9 @@ pub fn more_shortest_sanity_test<F>(mut f: F) where F: FnMut(&Decoded, &mut [u8] } fn to_string_with_parts<F>(mut f: F) -> String - where F: for<'a> FnMut(&'a mut [u8], &'a mut [Part<'a>]) -> Formatted<'a> { +where + F: for<'a> FnMut(&'a mut [u8], &'a mut [Part<'a>]) -> Formatted<'a>, +{ let mut buf = [0; 1024]; let mut parts = [Part::Zero(0); 16]; let formatted = f(&mut buf, &mut parts); @@ -464,66 +495,72 @@ fn to_string_with_parts<F>(mut f: F) -> String } pub fn to_shortest_str_test<F>(mut f_: F) - where F: FnMut(&Decoded, &mut [u8]) -> (usize, i16) { +where + F: FnMut(&Decoded, &mut [u8]) -> (usize, i16), +{ use core::num::flt2dec::Sign::*; fn to_string<T, F>(f: &mut F, v: T, sign: Sign, frac_digits: usize, upper: bool) -> String - where T: DecodableFloat, F: FnMut(&Decoded, &mut [u8]) -> (usize, i16) { - to_string_with_parts(|buf, parts| to_shortest_str(|d,b| f(d,b), v, sign, - frac_digits, upper, buf, parts)) + where + T: DecodableFloat, + F: FnMut(&Decoded, &mut [u8]) -> (usize, i16), + { + to_string_with_parts(|buf, parts| { + to_shortest_str(|d, b| f(d, b), v, sign, frac_digits, upper, buf, parts) + }) } let f = &mut f_; - assert_eq!(to_string(f, 0.0, Minus, 0, false), "0"); - assert_eq!(to_string(f, 0.0, MinusRaw, 0, false), "0"); - assert_eq!(to_string(f, 0.0, MinusPlus, 0, false), "+0"); - assert_eq!(to_string(f, 0.0, MinusPlusRaw, 0, false), "+0"); - assert_eq!(to_string(f, -0.0, Minus, 0, false), "0"); - assert_eq!(to_string(f, -0.0, MinusRaw, 0, false), "-0"); - assert_eq!(to_string(f, -0.0, MinusPlus, 0, false), "+0"); + assert_eq!(to_string(f, 0.0, Minus, 0, false), "0"); + assert_eq!(to_string(f, 0.0, MinusRaw, 0, false), "0"); + assert_eq!(to_string(f, 0.0, MinusPlus, 0, false), "+0"); + assert_eq!(to_string(f, 0.0, MinusPlusRaw, 0, false), "+0"); + assert_eq!(to_string(f, -0.0, Minus, 0, false), "0"); + assert_eq!(to_string(f, -0.0, MinusRaw, 0, false), "-0"); + assert_eq!(to_string(f, -0.0, MinusPlus, 0, false), "+0"); assert_eq!(to_string(f, -0.0, MinusPlusRaw, 0, false), "-0"); - assert_eq!(to_string(f, 0.0, Minus, 1, true), "0.0"); - assert_eq!(to_string(f, 0.0, MinusRaw, 1, true), "0.0"); - assert_eq!(to_string(f, 0.0, MinusPlus, 1, true), "+0.0"); - assert_eq!(to_string(f, 0.0, MinusPlusRaw, 1, true), "+0.0"); - assert_eq!(to_string(f, -0.0, Minus, 8, true), "0.00000000"); - assert_eq!(to_string(f, -0.0, MinusRaw, 8, true), "-0.00000000"); - assert_eq!(to_string(f, -0.0, MinusPlus, 8, true), "+0.00000000"); - assert_eq!(to_string(f, -0.0, MinusPlusRaw, 8, true), "-0.00000000"); - - assert_eq!(to_string(f, 1.0/0.0, Minus, 0, false), "inf"); - assert_eq!(to_string(f, 1.0/0.0, MinusRaw, 0, true), "inf"); - assert_eq!(to_string(f, 1.0/0.0, MinusPlus, 0, false), "+inf"); - assert_eq!(to_string(f, 1.0/0.0, MinusPlusRaw, 0, true), "+inf"); - assert_eq!(to_string(f, 0.0/0.0, Minus, 0, false), "NaN"); - assert_eq!(to_string(f, 0.0/0.0, MinusRaw, 1, true), "NaN"); - assert_eq!(to_string(f, 0.0/0.0, MinusPlus, 8, false), "NaN"); - assert_eq!(to_string(f, 0.0/0.0, MinusPlusRaw, 64, true), "NaN"); - assert_eq!(to_string(f, -1.0/0.0, Minus, 0, false), "-inf"); - assert_eq!(to_string(f, -1.0/0.0, MinusRaw, 1, true), "-inf"); - assert_eq!(to_string(f, -1.0/0.0, MinusPlus, 8, false), "-inf"); - assert_eq!(to_string(f, -1.0/0.0, MinusPlusRaw, 64, true), "-inf"); - - assert_eq!(to_string(f, 3.14, Minus, 0, false), "3.14"); - assert_eq!(to_string(f, 3.14, MinusRaw, 0, false), "3.14"); - assert_eq!(to_string(f, 3.14, MinusPlus, 0, false), "+3.14"); - assert_eq!(to_string(f, 3.14, MinusPlusRaw, 0, false), "+3.14"); - assert_eq!(to_string(f, -3.14, Minus, 0, false), "-3.14"); - assert_eq!(to_string(f, -3.14, MinusRaw, 0, false), "-3.14"); - assert_eq!(to_string(f, -3.14, MinusPlus, 0, false), "-3.14"); + assert_eq!(to_string(f, 0.0, Minus, 1, true), "0.0"); + assert_eq!(to_string(f, 0.0, MinusRaw, 1, true), "0.0"); + assert_eq!(to_string(f, 0.0, MinusPlus, 1, true), "+0.0"); + assert_eq!(to_string(f, 0.0, MinusPlusRaw, 1, true), "+0.0"); + assert_eq!(to_string(f, -0.0, Minus, 8, true), "0.00000000"); + assert_eq!(to_string(f, -0.0, MinusRaw, 8, true), "-0.00000000"); + assert_eq!(to_string(f, -0.0, MinusPlus, 8, true), "+0.00000000"); + assert_eq!(to_string(f, -0.0, MinusPlusRaw, 8, true), "-0.00000000"); + + assert_eq!(to_string(f, 1.0 / 0.0, Minus, 0, false), "inf"); + assert_eq!(to_string(f, 1.0 / 0.0, MinusRaw, 0, true), "inf"); + assert_eq!(to_string(f, 1.0 / 0.0, MinusPlus, 0, false), "+inf"); + assert_eq!(to_string(f, 1.0 / 0.0, MinusPlusRaw, 0, true), "+inf"); + assert_eq!(to_string(f, 0.0 / 0.0, Minus, 0, false), "NaN"); + assert_eq!(to_string(f, 0.0 / 0.0, MinusRaw, 1, true), "NaN"); + assert_eq!(to_string(f, 0.0 / 0.0, MinusPlus, 8, false), "NaN"); + assert_eq!(to_string(f, 0.0 / 0.0, MinusPlusRaw, 64, true), "NaN"); + assert_eq!(to_string(f, -1.0 / 0.0, Minus, 0, false), "-inf"); + assert_eq!(to_string(f, -1.0 / 0.0, MinusRaw, 1, true), "-inf"); + assert_eq!(to_string(f, -1.0 / 0.0, MinusPlus, 8, false), "-inf"); + assert_eq!(to_string(f, -1.0 / 0.0, MinusPlusRaw, 64, true), "-inf"); + + assert_eq!(to_string(f, 3.14, Minus, 0, false), "3.14"); + assert_eq!(to_string(f, 3.14, MinusRaw, 0, false), "3.14"); + assert_eq!(to_string(f, 3.14, MinusPlus, 0, false), "+3.14"); + assert_eq!(to_string(f, 3.14, MinusPlusRaw, 0, false), "+3.14"); + assert_eq!(to_string(f, -3.14, Minus, 0, false), "-3.14"); + assert_eq!(to_string(f, -3.14, MinusRaw, 0, false), "-3.14"); + assert_eq!(to_string(f, -3.14, MinusPlus, 0, false), "-3.14"); assert_eq!(to_string(f, -3.14, MinusPlusRaw, 0, false), "-3.14"); - assert_eq!(to_string(f, 3.14, Minus, 1, true), "3.14"); - assert_eq!(to_string(f, 3.14, MinusRaw, 2, true), "3.14"); - assert_eq!(to_string(f, 3.14, MinusPlus, 3, true), "+3.140"); - assert_eq!(to_string(f, 3.14, MinusPlusRaw, 4, true), "+3.1400"); - assert_eq!(to_string(f, -3.14, Minus, 8, true), "-3.14000000"); - assert_eq!(to_string(f, -3.14, MinusRaw, 8, true), "-3.14000000"); - assert_eq!(to_string(f, -3.14, MinusPlus, 8, true), "-3.14000000"); - assert_eq!(to_string(f, -3.14, MinusPlusRaw, 8, true), "-3.14000000"); - - assert_eq!(to_string(f, 7.5e-11, Minus, 0, false), "0.000000000075"); - assert_eq!(to_string(f, 7.5e-11, Minus, 3, false), "0.000000000075"); + assert_eq!(to_string(f, 3.14, Minus, 1, true), "3.14"); + assert_eq!(to_string(f, 3.14, MinusRaw, 2, true), "3.14"); + assert_eq!(to_string(f, 3.14, MinusPlus, 3, true), "+3.140"); + assert_eq!(to_string(f, 3.14, MinusPlusRaw, 4, true), "+3.1400"); + assert_eq!(to_string(f, -3.14, Minus, 8, true), "-3.14000000"); + assert_eq!(to_string(f, -3.14, MinusRaw, 8, true), "-3.14000000"); + assert_eq!(to_string(f, -3.14, MinusPlus, 8, true), "-3.14000000"); + assert_eq!(to_string(f, -3.14, MinusPlusRaw, 8, true), "-3.14000000"); + + assert_eq!(to_string(f, 7.5e-11, Minus, 0, false), "0.000000000075"); + assert_eq!(to_string(f, 7.5e-11, Minus, 3, false), "0.000000000075"); assert_eq!(to_string(f, 7.5e-11, Minus, 12, false), "0.000000000075"); assert_eq!(to_string(f, 7.5e-11, Minus, 13, false), "0.0000000000750"); @@ -536,23 +573,24 @@ pub fn to_shortest_str_test<F>(mut f_: F) assert_eq!(to_string(f, f32::MAX, Minus, 8, false), format!("34028235{:0>31}.00000000", "")); let minf32 = ldexp_f32(1.0, -149); - assert_eq!(to_string(f, minf32, Minus, 0, false), format!("0.{:0>44}1", "")); + assert_eq!(to_string(f, minf32, Minus, 0, false), format!("0.{:0>44}1", "")); assert_eq!(to_string(f, minf32, Minus, 45, false), format!("0.{:0>44}1", "")); assert_eq!(to_string(f, minf32, Minus, 46, false), format!("0.{:0>44}10", "")); - assert_eq!(to_string(f, f64::MAX, Minus, 0, false), - format!("17976931348623157{:0>292}", "")); - assert_eq!(to_string(f, f64::MAX, Minus, 1, false), - format!("17976931348623157{:0>292}.0", "")); - assert_eq!(to_string(f, f64::MAX, Minus, 8, false), - format!("17976931348623157{:0>292}.00000000", "")); + assert_eq!(to_string(f, f64::MAX, Minus, 0, false), format!("17976931348623157{:0>292}", "")); + assert_eq!(to_string(f, f64::MAX, Minus, 1, false), format!("17976931348623157{:0>292}.0", "")); + assert_eq!( + to_string(f, f64::MAX, Minus, 8, false), + format!("17976931348623157{:0>292}.00000000", "") + ); let minf64 = ldexp_f64(1.0, -1074); - assert_eq!(to_string(f, minf64, Minus, 0, false), format!("0.{:0>323}5", "")); + assert_eq!(to_string(f, minf64, Minus, 0, false), format!("0.{:0>323}5", "")); assert_eq!(to_string(f, minf64, Minus, 324, false), format!("0.{:0>323}5", "")); assert_eq!(to_string(f, minf64, Minus, 325, false), format!("0.{:0>323}50", "")); - if cfg!(miri) { // Miri is too slow + if cfg!(miri) { + // Miri is too slow return; } @@ -561,86 +599,92 @@ pub fn to_shortest_str_test<F>(mut f_: F) } pub fn to_shortest_exp_str_test<F>(mut f_: F) - where F: FnMut(&Decoded, &mut [u8]) -> (usize, i16) { +where + F: FnMut(&Decoded, &mut [u8]) -> (usize, i16), +{ use core::num::flt2dec::Sign::*; fn to_string<T, F>(f: &mut F, v: T, sign: Sign, exp_bounds: (i16, i16), upper: bool) -> String - where T: DecodableFloat, F: FnMut(&Decoded, &mut [u8]) -> (usize, i16) { - to_string_with_parts(|buf, parts| to_shortest_exp_str(|d,b| f(d,b), v, sign, - exp_bounds, upper, buf, parts)) + where + T: DecodableFloat, + F: FnMut(&Decoded, &mut [u8]) -> (usize, i16), + { + to_string_with_parts(|buf, parts| { + to_shortest_exp_str(|d, b| f(d, b), v, sign, exp_bounds, upper, buf, parts) + }) } let f = &mut f_; - assert_eq!(to_string(f, 0.0, Minus, (-4, 16), false), "0"); - assert_eq!(to_string(f, 0.0, MinusRaw, (-4, 16), false), "0"); - assert_eq!(to_string(f, 0.0, MinusPlus, (-4, 16), false), "+0"); - assert_eq!(to_string(f, 0.0, MinusPlusRaw, (-4, 16), false), "+0"); - assert_eq!(to_string(f, -0.0, Minus, (-4, 16), false), "0"); - assert_eq!(to_string(f, -0.0, MinusRaw, (-4, 16), false), "-0"); - assert_eq!(to_string(f, -0.0, MinusPlus, (-4, 16), false), "+0"); + assert_eq!(to_string(f, 0.0, Minus, (-4, 16), false), "0"); + assert_eq!(to_string(f, 0.0, MinusRaw, (-4, 16), false), "0"); + assert_eq!(to_string(f, 0.0, MinusPlus, (-4, 16), false), "+0"); + assert_eq!(to_string(f, 0.0, MinusPlusRaw, (-4, 16), false), "+0"); + assert_eq!(to_string(f, -0.0, Minus, (-4, 16), false), "0"); + assert_eq!(to_string(f, -0.0, MinusRaw, (-4, 16), false), "-0"); + assert_eq!(to_string(f, -0.0, MinusPlus, (-4, 16), false), "+0"); assert_eq!(to_string(f, -0.0, MinusPlusRaw, (-4, 16), false), "-0"); - assert_eq!(to_string(f, 0.0, Minus, ( 0, 0), true), "0E0"); - assert_eq!(to_string(f, 0.0, MinusRaw, ( 0, 0), false), "0e0"); - assert_eq!(to_string(f, 0.0, MinusPlus, (-9, -5), true), "+0E0"); - assert_eq!(to_string(f, 0.0, MinusPlusRaw, ( 5, 9), false), "+0e0"); - assert_eq!(to_string(f, -0.0, Minus, ( 0, 0), true), "0E0"); - assert_eq!(to_string(f, -0.0, MinusRaw, ( 0, 0), false), "-0e0"); - assert_eq!(to_string(f, -0.0, MinusPlus, (-9, -5), true), "+0E0"); - assert_eq!(to_string(f, -0.0, MinusPlusRaw, ( 5, 9), false), "-0e0"); - - assert_eq!(to_string(f, 1.0/0.0, Minus, (-4, 16), false), "inf"); - assert_eq!(to_string(f, 1.0/0.0, MinusRaw, (-4, 16), true), "inf"); - assert_eq!(to_string(f, 1.0/0.0, MinusPlus, (-4, 16), false), "+inf"); - assert_eq!(to_string(f, 1.0/0.0, MinusPlusRaw, (-4, 16), true), "+inf"); - assert_eq!(to_string(f, 0.0/0.0, Minus, ( 0, 0), false), "NaN"); - assert_eq!(to_string(f, 0.0/0.0, MinusRaw, ( 0, 0), true), "NaN"); - assert_eq!(to_string(f, 0.0/0.0, MinusPlus, (-9, -5), false), "NaN"); - assert_eq!(to_string(f, 0.0/0.0, MinusPlusRaw, ( 5, 9), true), "NaN"); - assert_eq!(to_string(f, -1.0/0.0, Minus, ( 0, 0), false), "-inf"); - assert_eq!(to_string(f, -1.0/0.0, MinusRaw, ( 0, 0), true), "-inf"); - assert_eq!(to_string(f, -1.0/0.0, MinusPlus, (-9, -5), false), "-inf"); - assert_eq!(to_string(f, -1.0/0.0, MinusPlusRaw, ( 5, 9), true), "-inf"); - - assert_eq!(to_string(f, 3.14, Minus, (-4, 16), false), "3.14"); - assert_eq!(to_string(f, 3.14, MinusRaw, (-4, 16), false), "3.14"); - assert_eq!(to_string(f, 3.14, MinusPlus, (-4, 16), false), "+3.14"); - assert_eq!(to_string(f, 3.14, MinusPlusRaw, (-4, 16), false), "+3.14"); - assert_eq!(to_string(f, -3.14, Minus, (-4, 16), false), "-3.14"); - assert_eq!(to_string(f, -3.14, MinusRaw, (-4, 16), false), "-3.14"); - assert_eq!(to_string(f, -3.14, MinusPlus, (-4, 16), false), "-3.14"); + assert_eq!(to_string(f, 0.0, Minus, (0, 0), true), "0E0"); + assert_eq!(to_string(f, 0.0, MinusRaw, (0, 0), false), "0e0"); + assert_eq!(to_string(f, 0.0, MinusPlus, (-9, -5), true), "+0E0"); + assert_eq!(to_string(f, 0.0, MinusPlusRaw, (5, 9), false), "+0e0"); + assert_eq!(to_string(f, -0.0, Minus, (0, 0), true), "0E0"); + assert_eq!(to_string(f, -0.0, MinusRaw, (0, 0), false), "-0e0"); + assert_eq!(to_string(f, -0.0, MinusPlus, (-9, -5), true), "+0E0"); + assert_eq!(to_string(f, -0.0, MinusPlusRaw, (5, 9), false), "-0e0"); + + assert_eq!(to_string(f, 1.0 / 0.0, Minus, (-4, 16), false), "inf"); + assert_eq!(to_string(f, 1.0 / 0.0, MinusRaw, (-4, 16), true), "inf"); + assert_eq!(to_string(f, 1.0 / 0.0, MinusPlus, (-4, 16), false), "+inf"); + assert_eq!(to_string(f, 1.0 / 0.0, MinusPlusRaw, (-4, 16), true), "+inf"); + assert_eq!(to_string(f, 0.0 / 0.0, Minus, (0, 0), false), "NaN"); + assert_eq!(to_string(f, 0.0 / 0.0, MinusRaw, (0, 0), true), "NaN"); + assert_eq!(to_string(f, 0.0 / 0.0, MinusPlus, (-9, -5), false), "NaN"); + assert_eq!(to_string(f, 0.0 / 0.0, MinusPlusRaw, (5, 9), true), "NaN"); + assert_eq!(to_string(f, -1.0 / 0.0, Minus, (0, 0), false), "-inf"); + assert_eq!(to_string(f, -1.0 / 0.0, MinusRaw, (0, 0), true), "-inf"); + assert_eq!(to_string(f, -1.0 / 0.0, MinusPlus, (-9, -5), false), "-inf"); + assert_eq!(to_string(f, -1.0 / 0.0, MinusPlusRaw, (5, 9), true), "-inf"); + + assert_eq!(to_string(f, 3.14, Minus, (-4, 16), false), "3.14"); + assert_eq!(to_string(f, 3.14, MinusRaw, (-4, 16), false), "3.14"); + assert_eq!(to_string(f, 3.14, MinusPlus, (-4, 16), false), "+3.14"); + assert_eq!(to_string(f, 3.14, MinusPlusRaw, (-4, 16), false), "+3.14"); + assert_eq!(to_string(f, -3.14, Minus, (-4, 16), false), "-3.14"); + assert_eq!(to_string(f, -3.14, MinusRaw, (-4, 16), false), "-3.14"); + assert_eq!(to_string(f, -3.14, MinusPlus, (-4, 16), false), "-3.14"); assert_eq!(to_string(f, -3.14, MinusPlusRaw, (-4, 16), false), "-3.14"); - assert_eq!(to_string(f, 3.14, Minus, ( 0, 0), true), "3.14E0"); - assert_eq!(to_string(f, 3.14, MinusRaw, ( 0, 0), false), "3.14e0"); - assert_eq!(to_string(f, 3.14, MinusPlus, (-9, -5), true), "+3.14E0"); - assert_eq!(to_string(f, 3.14, MinusPlusRaw, ( 5, 9), false), "+3.14e0"); - assert_eq!(to_string(f, -3.14, Minus, ( 0, 0), true), "-3.14E0"); - assert_eq!(to_string(f, -3.14, MinusRaw, ( 0, 0), false), "-3.14e0"); - assert_eq!(to_string(f, -3.14, MinusPlus, (-9, -5), true), "-3.14E0"); - assert_eq!(to_string(f, -3.14, MinusPlusRaw, ( 5, 9), false), "-3.14e0"); - - assert_eq!(to_string(f, 0.1, Minus, (-4, 16), false), "0.1"); - assert_eq!(to_string(f, 0.1, MinusRaw, (-4, 16), false), "0.1"); - assert_eq!(to_string(f, 0.1, MinusPlus, (-4, 16), false), "+0.1"); - assert_eq!(to_string(f, 0.1, MinusPlusRaw, (-4, 16), false), "+0.1"); - assert_eq!(to_string(f, -0.1, Minus, (-4, 16), false), "-0.1"); - assert_eq!(to_string(f, -0.1, MinusRaw, (-4, 16), false), "-0.1"); - assert_eq!(to_string(f, -0.1, MinusPlus, (-4, 16), false), "-0.1"); + assert_eq!(to_string(f, 3.14, Minus, (0, 0), true), "3.14E0"); + assert_eq!(to_string(f, 3.14, MinusRaw, (0, 0), false), "3.14e0"); + assert_eq!(to_string(f, 3.14, MinusPlus, (-9, -5), true), "+3.14E0"); + assert_eq!(to_string(f, 3.14, MinusPlusRaw, (5, 9), false), "+3.14e0"); + assert_eq!(to_string(f, -3.14, Minus, (0, 0), true), "-3.14E0"); + assert_eq!(to_string(f, -3.14, MinusRaw, (0, 0), false), "-3.14e0"); + assert_eq!(to_string(f, -3.14, MinusPlus, (-9, -5), true), "-3.14E0"); + assert_eq!(to_string(f, -3.14, MinusPlusRaw, (5, 9), false), "-3.14e0"); + + assert_eq!(to_string(f, 0.1, Minus, (-4, 16), false), "0.1"); + assert_eq!(to_string(f, 0.1, MinusRaw, (-4, 16), false), "0.1"); + assert_eq!(to_string(f, 0.1, MinusPlus, (-4, 16), false), "+0.1"); + assert_eq!(to_string(f, 0.1, MinusPlusRaw, (-4, 16), false), "+0.1"); + assert_eq!(to_string(f, -0.1, Minus, (-4, 16), false), "-0.1"); + assert_eq!(to_string(f, -0.1, MinusRaw, (-4, 16), false), "-0.1"); + assert_eq!(to_string(f, -0.1, MinusPlus, (-4, 16), false), "-0.1"); assert_eq!(to_string(f, -0.1, MinusPlusRaw, (-4, 16), false), "-0.1"); - assert_eq!(to_string(f, 0.1, Minus, ( 0, 0), true), "1E-1"); - assert_eq!(to_string(f, 0.1, MinusRaw, ( 0, 0), false), "1e-1"); - assert_eq!(to_string(f, 0.1, MinusPlus, (-9, -5), true), "+1E-1"); - assert_eq!(to_string(f, 0.1, MinusPlusRaw, ( 5, 9), false), "+1e-1"); - assert_eq!(to_string(f, -0.1, Minus, ( 0, 0), true), "-1E-1"); - assert_eq!(to_string(f, -0.1, MinusRaw, ( 0, 0), false), "-1e-1"); - assert_eq!(to_string(f, -0.1, MinusPlus, (-9, -5), true), "-1E-1"); - assert_eq!(to_string(f, -0.1, MinusPlusRaw, ( 5, 9), false), "-1e-1"); - - assert_eq!(to_string(f, 7.5e-11, Minus, ( -4, 16), false), "7.5e-11"); + assert_eq!(to_string(f, 0.1, Minus, (0, 0), true), "1E-1"); + assert_eq!(to_string(f, 0.1, MinusRaw, (0, 0), false), "1e-1"); + assert_eq!(to_string(f, 0.1, MinusPlus, (-9, -5), true), "+1E-1"); + assert_eq!(to_string(f, 0.1, MinusPlusRaw, (5, 9), false), "+1e-1"); + assert_eq!(to_string(f, -0.1, Minus, (0, 0), true), "-1E-1"); + assert_eq!(to_string(f, -0.1, MinusRaw, (0, 0), false), "-1e-1"); + assert_eq!(to_string(f, -0.1, MinusPlus, (-9, -5), true), "-1E-1"); + assert_eq!(to_string(f, -0.1, MinusPlusRaw, (5, 9), false), "-1e-1"); + + assert_eq!(to_string(f, 7.5e-11, Minus, (-4, 16), false), "7.5e-11"); assert_eq!(to_string(f, 7.5e-11, Minus, (-11, 10), false), "0.000000000075"); assert_eq!(to_string(f, 7.5e-11, Minus, (-10, 11), false), "7.5e-11"); - assert_eq!(to_string(f, 1.9971e20, Minus, ( -4, 16), false), "1.9971e20"); + assert_eq!(to_string(f, 1.9971e20, Minus, (-4, 16), false), "1.9971e20"); assert_eq!(to_string(f, 1.9971e20, Minus, (-20, 21), false), "199710000000000000000"); assert_eq!(to_string(f, 1.9971e20, Minus, (-21, 20), false), "1.9971e20"); @@ -649,24 +693,24 @@ pub fn to_shortest_exp_str_test<F>(mut f_: F) assert_eq!(to_string(f, 1.0e23, Minus, (23, 24), false), "100000000000000000000000"); assert_eq!(to_string(f, 1.0e23, Minus, (24, 25), false), "1e23"); - assert_eq!(to_string(f, f32::MAX, Minus, ( -4, 16), false), "3.4028235e38"); + assert_eq!(to_string(f, f32::MAX, Minus, (-4, 16), false), "3.4028235e38"); assert_eq!(to_string(f, f32::MAX, Minus, (-39, 38), false), "3.4028235e38"); assert_eq!(to_string(f, f32::MAX, Minus, (-38, 39), false), format!("34028235{:0>31}", "")); let minf32 = ldexp_f32(1.0, -149); - assert_eq!(to_string(f, minf32, Minus, ( -4, 16), false), "1e-45"); + assert_eq!(to_string(f, minf32, Minus, (-4, 16), false), "1e-45"); assert_eq!(to_string(f, minf32, Minus, (-44, 45), false), "1e-45"); assert_eq!(to_string(f, minf32, Minus, (-45, 44), false), format!("0.{:0>44}1", "")); - assert_eq!(to_string(f, f64::MAX, Minus, ( -4, 16), false), - "1.7976931348623157e308"); - assert_eq!(to_string(f, f64::MAX, Minus, (-308, 309), false), - format!("17976931348623157{:0>292}", "")); - assert_eq!(to_string(f, f64::MAX, Minus, (-309, 308), false), - "1.7976931348623157e308"); + assert_eq!(to_string(f, f64::MAX, Minus, (-4, 16), false), "1.7976931348623157e308"); + assert_eq!( + to_string(f, f64::MAX, Minus, (-308, 309), false), + format!("17976931348623157{:0>292}", "") + ); + assert_eq!(to_string(f, f64::MAX, Minus, (-309, 308), false), "1.7976931348623157e308"); let minf64 = ldexp_f64(1.0, -1074); - assert_eq!(to_string(f, minf64, Minus, ( -4, 16), false), "5e-324"); + assert_eq!(to_string(f, minf64, Minus, (-4, 16), false), "5e-324"); assert_eq!(to_string(f, minf64, Minus, (-324, 323), false), format!("0.{:0>323}5", "")); assert_eq!(to_string(f, minf64, Minus, (-323, 324), false), "5e-324"); @@ -674,88 +718,94 @@ pub fn to_shortest_exp_str_test<F>(mut f_: F) } pub fn to_exact_exp_str_test<F>(mut f_: F) - where F: FnMut(&Decoded, &mut [u8], i16) -> (usize, i16) { +where + F: FnMut(&Decoded, &mut [u8], i16) -> (usize, i16), +{ use core::num::flt2dec::Sign::*; fn to_string<T, F>(f: &mut F, v: T, sign: Sign, ndigits: usize, upper: bool) -> String - where T: DecodableFloat, F: FnMut(&Decoded, &mut [u8], i16) -> (usize, i16) { - to_string_with_parts(|buf, parts| to_exact_exp_str(|d,b,l| f(d,b,l), v, sign, - ndigits, upper, buf, parts)) + where + T: DecodableFloat, + F: FnMut(&Decoded, &mut [u8], i16) -> (usize, i16), + { + to_string_with_parts(|buf, parts| { + to_exact_exp_str(|d, b, l| f(d, b, l), v, sign, ndigits, upper, buf, parts) + }) } let f = &mut f_; - assert_eq!(to_string(f, 0.0, Minus, 1, true), "0E0"); - assert_eq!(to_string(f, 0.0, MinusRaw, 1, false), "0e0"); - assert_eq!(to_string(f, 0.0, MinusPlus, 1, true), "+0E0"); - assert_eq!(to_string(f, 0.0, MinusPlusRaw, 1, false), "+0e0"); - assert_eq!(to_string(f, -0.0, Minus, 1, true), "0E0"); - assert_eq!(to_string(f, -0.0, MinusRaw, 1, false), "-0e0"); - assert_eq!(to_string(f, -0.0, MinusPlus, 1, true), "+0E0"); + assert_eq!(to_string(f, 0.0, Minus, 1, true), "0E0"); + assert_eq!(to_string(f, 0.0, MinusRaw, 1, false), "0e0"); + assert_eq!(to_string(f, 0.0, MinusPlus, 1, true), "+0E0"); + assert_eq!(to_string(f, 0.0, MinusPlusRaw, 1, false), "+0e0"); + assert_eq!(to_string(f, -0.0, Minus, 1, true), "0E0"); + assert_eq!(to_string(f, -0.0, MinusRaw, 1, false), "-0e0"); + assert_eq!(to_string(f, -0.0, MinusPlus, 1, true), "+0E0"); assert_eq!(to_string(f, -0.0, MinusPlusRaw, 1, false), "-0e0"); - assert_eq!(to_string(f, 0.0, Minus, 2, true), "0.0E0"); - assert_eq!(to_string(f, 0.0, MinusRaw, 2, false), "0.0e0"); - assert_eq!(to_string(f, 0.0, MinusPlus, 2, true), "+0.0E0"); - assert_eq!(to_string(f, 0.0, MinusPlusRaw, 2, false), "+0.0e0"); - assert_eq!(to_string(f, -0.0, Minus, 8, true), "0.0000000E0"); - assert_eq!(to_string(f, -0.0, MinusRaw, 8, false), "-0.0000000e0"); - assert_eq!(to_string(f, -0.0, MinusPlus, 8, true), "+0.0000000E0"); + assert_eq!(to_string(f, 0.0, Minus, 2, true), "0.0E0"); + assert_eq!(to_string(f, 0.0, MinusRaw, 2, false), "0.0e0"); + assert_eq!(to_string(f, 0.0, MinusPlus, 2, true), "+0.0E0"); + assert_eq!(to_string(f, 0.0, MinusPlusRaw, 2, false), "+0.0e0"); + assert_eq!(to_string(f, -0.0, Minus, 8, true), "0.0000000E0"); + assert_eq!(to_string(f, -0.0, MinusRaw, 8, false), "-0.0000000e0"); + assert_eq!(to_string(f, -0.0, MinusPlus, 8, true), "+0.0000000E0"); assert_eq!(to_string(f, -0.0, MinusPlusRaw, 8, false), "-0.0000000e0"); - assert_eq!(to_string(f, 1.0/0.0, Minus, 1, false), "inf"); - assert_eq!(to_string(f, 1.0/0.0, MinusRaw, 1, true), "inf"); - assert_eq!(to_string(f, 1.0/0.0, MinusPlus, 1, false), "+inf"); - assert_eq!(to_string(f, 1.0/0.0, MinusPlusRaw, 1, true), "+inf"); - assert_eq!(to_string(f, 0.0/0.0, Minus, 8, false), "NaN"); - assert_eq!(to_string(f, 0.0/0.0, MinusRaw, 8, true), "NaN"); - assert_eq!(to_string(f, 0.0/0.0, MinusPlus, 8, false), "NaN"); - assert_eq!(to_string(f, 0.0/0.0, MinusPlusRaw, 8, true), "NaN"); - assert_eq!(to_string(f, -1.0/0.0, Minus, 64, false), "-inf"); - assert_eq!(to_string(f, -1.0/0.0, MinusRaw, 64, true), "-inf"); - assert_eq!(to_string(f, -1.0/0.0, MinusPlus, 64, false), "-inf"); - assert_eq!(to_string(f, -1.0/0.0, MinusPlusRaw, 64, true), "-inf"); - - assert_eq!(to_string(f, 3.14, Minus, 1, true), "3E0"); - assert_eq!(to_string(f, 3.14, MinusRaw, 1, false), "3e0"); - assert_eq!(to_string(f, 3.14, MinusPlus, 1, true), "+3E0"); - assert_eq!(to_string(f, 3.14, MinusPlusRaw, 1, false), "+3e0"); - assert_eq!(to_string(f, -3.14, Minus, 2, true), "-3.1E0"); - assert_eq!(to_string(f, -3.14, MinusRaw, 2, false), "-3.1e0"); - assert_eq!(to_string(f, -3.14, MinusPlus, 2, true), "-3.1E0"); + assert_eq!(to_string(f, 1.0 / 0.0, Minus, 1, false), "inf"); + assert_eq!(to_string(f, 1.0 / 0.0, MinusRaw, 1, true), "inf"); + assert_eq!(to_string(f, 1.0 / 0.0, MinusPlus, 1, false), "+inf"); + assert_eq!(to_string(f, 1.0 / 0.0, MinusPlusRaw, 1, true), "+inf"); + assert_eq!(to_string(f, 0.0 / 0.0, Minus, 8, false), "NaN"); + assert_eq!(to_string(f, 0.0 / 0.0, MinusRaw, 8, true), "NaN"); + assert_eq!(to_string(f, 0.0 / 0.0, MinusPlus, 8, false), "NaN"); + assert_eq!(to_string(f, 0.0 / 0.0, MinusPlusRaw, 8, true), "NaN"); + assert_eq!(to_string(f, -1.0 / 0.0, Minus, 64, false), "-inf"); + assert_eq!(to_string(f, -1.0 / 0.0, MinusRaw, 64, true), "-inf"); + assert_eq!(to_string(f, -1.0 / 0.0, MinusPlus, 64, false), "-inf"); + assert_eq!(to_string(f, -1.0 / 0.0, MinusPlusRaw, 64, true), "-inf"); + + assert_eq!(to_string(f, 3.14, Minus, 1, true), "3E0"); + assert_eq!(to_string(f, 3.14, MinusRaw, 1, false), "3e0"); + assert_eq!(to_string(f, 3.14, MinusPlus, 1, true), "+3E0"); + assert_eq!(to_string(f, 3.14, MinusPlusRaw, 1, false), "+3e0"); + assert_eq!(to_string(f, -3.14, Minus, 2, true), "-3.1E0"); + assert_eq!(to_string(f, -3.14, MinusRaw, 2, false), "-3.1e0"); + assert_eq!(to_string(f, -3.14, MinusPlus, 2, true), "-3.1E0"); assert_eq!(to_string(f, -3.14, MinusPlusRaw, 2, false), "-3.1e0"); - assert_eq!(to_string(f, 3.14, Minus, 3, true), "3.14E0"); - assert_eq!(to_string(f, 3.14, MinusRaw, 3, false), "3.14e0"); - assert_eq!(to_string(f, 3.14, MinusPlus, 3, true), "+3.14E0"); - assert_eq!(to_string(f, 3.14, MinusPlusRaw, 3, false), "+3.14e0"); - assert_eq!(to_string(f, -3.14, Minus, 4, true), "-3.140E0"); - assert_eq!(to_string(f, -3.14, MinusRaw, 4, false), "-3.140e0"); - assert_eq!(to_string(f, -3.14, MinusPlus, 4, true), "-3.140E0"); + assert_eq!(to_string(f, 3.14, Minus, 3, true), "3.14E0"); + assert_eq!(to_string(f, 3.14, MinusRaw, 3, false), "3.14e0"); + assert_eq!(to_string(f, 3.14, MinusPlus, 3, true), "+3.14E0"); + assert_eq!(to_string(f, 3.14, MinusPlusRaw, 3, false), "+3.14e0"); + assert_eq!(to_string(f, -3.14, Minus, 4, true), "-3.140E0"); + assert_eq!(to_string(f, -3.14, MinusRaw, 4, false), "-3.140e0"); + assert_eq!(to_string(f, -3.14, MinusPlus, 4, true), "-3.140E0"); assert_eq!(to_string(f, -3.14, MinusPlusRaw, 4, false), "-3.140e0"); - assert_eq!(to_string(f, 0.195, Minus, 1, false), "2e-1"); - assert_eq!(to_string(f, 0.195, MinusRaw, 1, true), "2E-1"); - assert_eq!(to_string(f, 0.195, MinusPlus, 1, false), "+2e-1"); - assert_eq!(to_string(f, 0.195, MinusPlusRaw, 1, true), "+2E-1"); - assert_eq!(to_string(f, -0.195, Minus, 2, false), "-2.0e-1"); - assert_eq!(to_string(f, -0.195, MinusRaw, 2, true), "-2.0E-1"); - assert_eq!(to_string(f, -0.195, MinusPlus, 2, false), "-2.0e-1"); - assert_eq!(to_string(f, -0.195, MinusPlusRaw, 2, true), "-2.0E-1"); - assert_eq!(to_string(f, 0.195, Minus, 3, false), "1.95e-1"); - assert_eq!(to_string(f, 0.195, MinusRaw, 3, true), "1.95E-1"); - assert_eq!(to_string(f, 0.195, MinusPlus, 3, false), "+1.95e-1"); - assert_eq!(to_string(f, 0.195, MinusPlusRaw, 3, true), "+1.95E-1"); - assert_eq!(to_string(f, -0.195, Minus, 4, false), "-1.950e-1"); - assert_eq!(to_string(f, -0.195, MinusRaw, 4, true), "-1.950E-1"); - assert_eq!(to_string(f, -0.195, MinusPlus, 4, false), "-1.950e-1"); - assert_eq!(to_string(f, -0.195, MinusPlusRaw, 4, true), "-1.950E-1"); - - assert_eq!(to_string(f, 9.5, Minus, 1, false), "1e1"); - assert_eq!(to_string(f, 9.5, Minus, 2, false), "9.5e0"); - assert_eq!(to_string(f, 9.5, Minus, 3, false), "9.50e0"); + assert_eq!(to_string(f, 0.195, Minus, 1, false), "2e-1"); + assert_eq!(to_string(f, 0.195, MinusRaw, 1, true), "2E-1"); + assert_eq!(to_string(f, 0.195, MinusPlus, 1, false), "+2e-1"); + assert_eq!(to_string(f, 0.195, MinusPlusRaw, 1, true), "+2E-1"); + assert_eq!(to_string(f, -0.195, Minus, 2, false), "-2.0e-1"); + assert_eq!(to_string(f, -0.195, MinusRaw, 2, true), "-2.0E-1"); + assert_eq!(to_string(f, -0.195, MinusPlus, 2, false), "-2.0e-1"); + assert_eq!(to_string(f, -0.195, MinusPlusRaw, 2, true), "-2.0E-1"); + assert_eq!(to_string(f, 0.195, Minus, 3, false), "1.95e-1"); + assert_eq!(to_string(f, 0.195, MinusRaw, 3, true), "1.95E-1"); + assert_eq!(to_string(f, 0.195, MinusPlus, 3, false), "+1.95e-1"); + assert_eq!(to_string(f, 0.195, MinusPlusRaw, 3, true), "+1.95E-1"); + assert_eq!(to_string(f, -0.195, Minus, 4, false), "-1.950e-1"); + assert_eq!(to_string(f, -0.195, MinusRaw, 4, true), "-1.950E-1"); + assert_eq!(to_string(f, -0.195, MinusPlus, 4, false), "-1.950e-1"); + assert_eq!(to_string(f, -0.195, MinusPlusRaw, 4, true), "-1.950E-1"); + + assert_eq!(to_string(f, 9.5, Minus, 1, false), "1e1"); + assert_eq!(to_string(f, 9.5, Minus, 2, false), "9.5e0"); + assert_eq!(to_string(f, 9.5, Minus, 3, false), "9.50e0"); assert_eq!(to_string(f, 9.5, Minus, 30, false), "9.50000000000000000000000000000e0"); - assert_eq!(to_string(f, 1.0e25, Minus, 1, false), "1e25"); - assert_eq!(to_string(f, 1.0e25, Minus, 2, false), "1.0e25"); + assert_eq!(to_string(f, 1.0e25, Minus, 1, false), "1e25"); + assert_eq!(to_string(f, 1.0e25, Minus, 2, false), "1.0e25"); assert_eq!(to_string(f, 1.0e25, Minus, 15, false), "1.00000000000000e25"); assert_eq!(to_string(f, 1.0e25, Minus, 16, false), "1.000000000000000e25"); assert_eq!(to_string(f, 1.0e25, Minus, 17, false), "1.0000000000000001e25"); @@ -771,104 +821,136 @@ pub fn to_exact_exp_str_test<F>(mut f_: F) assert_eq!(to_string(f, 1.0e25, Minus, 27, false), "1.00000000000000009059696640e25"); assert_eq!(to_string(f, 1.0e25, Minus, 30, false), "1.00000000000000009059696640000e25"); - assert_eq!(to_string(f, 1.0e-6, Minus, 1, false), "1e-6"); - assert_eq!(to_string(f, 1.0e-6, Minus, 2, false), "1.0e-6"); + assert_eq!(to_string(f, 1.0e-6, Minus, 1, false), "1e-6"); + assert_eq!(to_string(f, 1.0e-6, Minus, 2, false), "1.0e-6"); assert_eq!(to_string(f, 1.0e-6, Minus, 16, false), "1.000000000000000e-6"); assert_eq!(to_string(f, 1.0e-6, Minus, 17, false), "9.9999999999999995e-7"); assert_eq!(to_string(f, 1.0e-6, Minus, 18, false), "9.99999999999999955e-7"); assert_eq!(to_string(f, 1.0e-6, Minus, 19, false), "9.999999999999999547e-7"); assert_eq!(to_string(f, 1.0e-6, Minus, 20, false), "9.9999999999999995475e-7"); assert_eq!(to_string(f, 1.0e-6, Minus, 30, false), "9.99999999999999954748111825886e-7"); - assert_eq!(to_string(f, 1.0e-6, Minus, 40, false), - "9.999999999999999547481118258862586856139e-7"); - assert_eq!(to_string(f, 1.0e-6, Minus, 50, false), - "9.9999999999999995474811182588625868561393872369081e-7"); - assert_eq!(to_string(f, 1.0e-6, Minus, 60, false), - "9.99999999999999954748111825886258685613938723690807819366455e-7"); - assert_eq!(to_string(f, 1.0e-6, Minus, 70, false), - "9.999999999999999547481118258862586856139387236908078193664550781250000e-7"); - - assert_eq!(to_string(f, f32::MAX, Minus, 1, false), "3e38"); - assert_eq!(to_string(f, f32::MAX, Minus, 2, false), "3.4e38"); - assert_eq!(to_string(f, f32::MAX, Minus, 4, false), "3.403e38"); - assert_eq!(to_string(f, f32::MAX, Minus, 8, false), "3.4028235e38"); + assert_eq!( + to_string(f, 1.0e-6, Minus, 40, false), + "9.999999999999999547481118258862586856139e-7" + ); + assert_eq!( + to_string(f, 1.0e-6, Minus, 50, false), + "9.9999999999999995474811182588625868561393872369081e-7" + ); + assert_eq!( + to_string(f, 1.0e-6, Minus, 60, false), + "9.99999999999999954748111825886258685613938723690807819366455e-7" + ); + assert_eq!( + to_string(f, 1.0e-6, Minus, 70, false), + "9.999999999999999547481118258862586856139387236908078193664550781250000e-7" + ); + + assert_eq!(to_string(f, f32::MAX, Minus, 1, false), "3e38"); + assert_eq!(to_string(f, f32::MAX, Minus, 2, false), "3.4e38"); + assert_eq!(to_string(f, f32::MAX, Minus, 4, false), "3.403e38"); + assert_eq!(to_string(f, f32::MAX, Minus, 8, false), "3.4028235e38"); assert_eq!(to_string(f, f32::MAX, Minus, 16, false), "3.402823466385289e38"); assert_eq!(to_string(f, f32::MAX, Minus, 32, false), "3.4028234663852885981170418348452e38"); - assert_eq!(to_string(f, f32::MAX, Minus, 64, false), - "3.402823466385288598117041834845169254400000000000000000000000000e38"); + assert_eq!( + to_string(f, f32::MAX, Minus, 64, false), + "3.402823466385288598117041834845169254400000000000000000000000000e38" + ); let minf32 = ldexp_f32(1.0, -149); - assert_eq!(to_string(f, minf32, Minus, 1, false), "1e-45"); - assert_eq!(to_string(f, minf32, Minus, 2, false), "1.4e-45"); - assert_eq!(to_string(f, minf32, Minus, 4, false), "1.401e-45"); - assert_eq!(to_string(f, minf32, Minus, 8, false), "1.4012985e-45"); - assert_eq!(to_string(f, minf32, Minus, 16, false), "1.401298464324817e-45"); - assert_eq!(to_string(f, minf32, Minus, 32, false), "1.4012984643248170709237295832899e-45"); - assert_eq!(to_string(f, minf32, Minus, 64, false), - "1.401298464324817070923729583289916131280261941876515771757068284e-45"); - assert_eq!(to_string(f, minf32, Minus, 128, false), - "1.401298464324817070923729583289916131280261941876515771757068283\ - 8897910826858606014866381883621215820312500000000000000000000000e-45"); - - if cfg!(miri) { // Miri is too slow + assert_eq!(to_string(f, minf32, Minus, 1, false), "1e-45"); + assert_eq!(to_string(f, minf32, Minus, 2, false), "1.4e-45"); + assert_eq!(to_string(f, minf32, Minus, 4, false), "1.401e-45"); + assert_eq!(to_string(f, minf32, Minus, 8, false), "1.4012985e-45"); + assert_eq!(to_string(f, minf32, Minus, 16, false), "1.401298464324817e-45"); + assert_eq!(to_string(f, minf32, Minus, 32, false), "1.4012984643248170709237295832899e-45"); + assert_eq!( + to_string(f, minf32, Minus, 64, false), + "1.401298464324817070923729583289916131280261941876515771757068284e-45" + ); + assert_eq!( + to_string(f, minf32, Minus, 128, false), + "1.401298464324817070923729583289916131280261941876515771757068283\ + 8897910826858606014866381883621215820312500000000000000000000000e-45" + ); + + if cfg!(miri) { + // Miri is too slow return; } - assert_eq!(to_string(f, f64::MAX, Minus, 1, false), "2e308"); - assert_eq!(to_string(f, f64::MAX, Minus, 2, false), "1.8e308"); - assert_eq!(to_string(f, f64::MAX, Minus, 4, false), "1.798e308"); - assert_eq!(to_string(f, f64::MAX, Minus, 8, false), "1.7976931e308"); - assert_eq!(to_string(f, f64::MAX, Minus, 16, false), "1.797693134862316e308"); - assert_eq!(to_string(f, f64::MAX, Minus, 32, false), "1.7976931348623157081452742373170e308"); - assert_eq!(to_string(f, f64::MAX, Minus, 64, false), - "1.797693134862315708145274237317043567980705675258449965989174768e308"); - assert_eq!(to_string(f, f64::MAX, Minus, 128, false), - "1.797693134862315708145274237317043567980705675258449965989174768\ - 0315726078002853876058955863276687817154045895351438246423432133e308"); - assert_eq!(to_string(f, f64::MAX, Minus, 256, false), - "1.797693134862315708145274237317043567980705675258449965989174768\ + assert_eq!(to_string(f, f64::MAX, Minus, 1, false), "2e308"); + assert_eq!(to_string(f, f64::MAX, Minus, 2, false), "1.8e308"); + assert_eq!(to_string(f, f64::MAX, Minus, 4, false), "1.798e308"); + assert_eq!(to_string(f, f64::MAX, Minus, 8, false), "1.7976931e308"); + assert_eq!(to_string(f, f64::MAX, Minus, 16, false), "1.797693134862316e308"); + assert_eq!(to_string(f, f64::MAX, Minus, 32, false), "1.7976931348623157081452742373170e308"); + assert_eq!( + to_string(f, f64::MAX, Minus, 64, false), + "1.797693134862315708145274237317043567980705675258449965989174768e308" + ); + assert_eq!( + to_string(f, f64::MAX, Minus, 128, false), + "1.797693134862315708145274237317043567980705675258449965989174768\ + 0315726078002853876058955863276687817154045895351438246423432133e308" + ); + assert_eq!( + to_string(f, f64::MAX, Minus, 256, false), + "1.797693134862315708145274237317043567980705675258449965989174768\ 0315726078002853876058955863276687817154045895351438246423432132\ 6889464182768467546703537516986049910576551282076245490090389328\ - 9440758685084551339423045832369032229481658085593321233482747978e308"); - assert_eq!(to_string(f, f64::MAX, Minus, 512, false), - "1.797693134862315708145274237317043567980705675258449965989174768\ + 9440758685084551339423045832369032229481658085593321233482747978e308" + ); + assert_eq!( + to_string(f, f64::MAX, Minus, 512, false), + "1.797693134862315708145274237317043567980705675258449965989174768\ 0315726078002853876058955863276687817154045895351438246423432132\ 6889464182768467546703537516986049910576551282076245490090389328\ 9440758685084551339423045832369032229481658085593321233482747978\ 2620414472316873817718091929988125040402618412485836800000000000\ 0000000000000000000000000000000000000000000000000000000000000000\ 0000000000000000000000000000000000000000000000000000000000000000\ - 0000000000000000000000000000000000000000000000000000000000000000e308"); + 0000000000000000000000000000000000000000000000000000000000000000e308" + ); // okay, this is becoming tough. fortunately for us, this is almost the worst case. let minf64 = ldexp_f64(1.0, -1074); - assert_eq!(to_string(f, minf64, Minus, 1, false), "5e-324"); - assert_eq!(to_string(f, minf64, Minus, 2, false), "4.9e-324"); - assert_eq!(to_string(f, minf64, Minus, 4, false), "4.941e-324"); - assert_eq!(to_string(f, minf64, Minus, 8, false), "4.9406565e-324"); - assert_eq!(to_string(f, minf64, Minus, 16, false), "4.940656458412465e-324"); - assert_eq!(to_string(f, minf64, Minus, 32, false), "4.9406564584124654417656879286822e-324"); - assert_eq!(to_string(f, minf64, Minus, 64, false), - "4.940656458412465441765687928682213723650598026143247644255856825e-324"); - assert_eq!(to_string(f, minf64, Minus, 128, false), - "4.940656458412465441765687928682213723650598026143247644255856825\ - 0067550727020875186529983636163599237979656469544571773092665671e-324"); - assert_eq!(to_string(f, minf64, Minus, 256, false), - "4.940656458412465441765687928682213723650598026143247644255856825\ + assert_eq!(to_string(f, minf64, Minus, 1, false), "5e-324"); + assert_eq!(to_string(f, minf64, Minus, 2, false), "4.9e-324"); + assert_eq!(to_string(f, minf64, Minus, 4, false), "4.941e-324"); + assert_eq!(to_string(f, minf64, Minus, 8, false), "4.9406565e-324"); + assert_eq!(to_string(f, minf64, Minus, 16, false), "4.940656458412465e-324"); + assert_eq!(to_string(f, minf64, Minus, 32, false), "4.9406564584124654417656879286822e-324"); + assert_eq!( + to_string(f, minf64, Minus, 64, false), + "4.940656458412465441765687928682213723650598026143247644255856825e-324" + ); + assert_eq!( + to_string(f, minf64, Minus, 128, false), + "4.940656458412465441765687928682213723650598026143247644255856825\ + 0067550727020875186529983636163599237979656469544571773092665671e-324" + ); + assert_eq!( + to_string(f, minf64, Minus, 256, false), + "4.940656458412465441765687928682213723650598026143247644255856825\ 0067550727020875186529983636163599237979656469544571773092665671\ 0355939796398774796010781878126300713190311404527845817167848982\ - 1036887186360569987307230500063874091535649843873124733972731696e-324"); - assert_eq!(to_string(f, minf64, Minus, 512, false), - "4.940656458412465441765687928682213723650598026143247644255856825\ + 1036887186360569987307230500063874091535649843873124733972731696e-324" + ); + assert_eq!( + to_string(f, minf64, Minus, 512, false), + "4.940656458412465441765687928682213723650598026143247644255856825\ 0067550727020875186529983636163599237979656469544571773092665671\ 0355939796398774796010781878126300713190311404527845817167848982\ 1036887186360569987307230500063874091535649843873124733972731696\ 1514003171538539807412623856559117102665855668676818703956031062\ 4931945271591492455329305456544401127480129709999541931989409080\ 4165633245247571478690147267801593552386115501348035264934720193\ - 7902681071074917033322268447533357208324319360923828934583680601e-324"); - assert_eq!(to_string(f, minf64, Minus, 1024, false), - "4.940656458412465441765687928682213723650598026143247644255856825\ + 7902681071074917033322268447533357208324319360923828934583680601e-324" + ); + assert_eq!( + to_string(f, minf64, Minus, 1024, false), + "4.940656458412465441765687928682213723650598026143247644255856825\ 0067550727020875186529983636163599237979656469544571773092665671\ 0355939796398774796010781878126300713190311404527845817167848982\ 1036887186360569987307230500063874091535649843873124733972731696\ @@ -883,100 +965,117 @@ pub fn to_exact_exp_str_test<F>(mut f_: F) 0000000000000000000000000000000000000000000000000000000000000000\ 0000000000000000000000000000000000000000000000000000000000000000\ 0000000000000000000000000000000000000000000000000000000000000000\ - 0000000000000000000000000000000000000000000000000000000000000000e-324"); + 0000000000000000000000000000000000000000000000000000000000000000e-324" + ); // very large output - assert_eq!(to_string(f, 0.0, Minus, 80000, false), format!("0.{:0>79999}e0", "")); - assert_eq!(to_string(f, 1.0e1, Minus, 80000, false), format!("1.{:0>79999}e1", "")); - assert_eq!(to_string(f, 1.0e0, Minus, 80000, false), format!("1.{:0>79999}e0", "")); - assert_eq!(to_string(f, 1.0e-1, Minus, 80000, false), - format!("1.000000000000000055511151231257827021181583404541015625{:0>79945}\ - e-1", "")); - assert_eq!(to_string(f, 1.0e-20, Minus, 80000, false), - format!("9.999999999999999451532714542095716517295037027873924471077157760\ - 66783064379706047475337982177734375{:0>79901}e-21", "")); + assert_eq!(to_string(f, 0.0, Minus, 80000, false), format!("0.{:0>79999}e0", "")); + assert_eq!(to_string(f, 1.0e1, Minus, 80000, false), format!("1.{:0>79999}e1", "")); + assert_eq!(to_string(f, 1.0e0, Minus, 80000, false), format!("1.{:0>79999}e0", "")); + assert_eq!( + to_string(f, 1.0e-1, Minus, 80000, false), + format!( + "1.000000000000000055511151231257827021181583404541015625{:0>79945}\ + e-1", + "" + ) + ); + assert_eq!( + to_string(f, 1.0e-20, Minus, 80000, false), + format!( + "9.999999999999999451532714542095716517295037027873924471077157760\ + 66783064379706047475337982177734375{:0>79901}e-21", + "" + ) + ); } pub fn to_exact_fixed_str_test<F>(mut f_: F) - where F: FnMut(&Decoded, &mut [u8], i16) -> (usize, i16) { +where + F: FnMut(&Decoded, &mut [u8], i16) -> (usize, i16), +{ use core::num::flt2dec::Sign::*; fn to_string<T, F>(f: &mut F, v: T, sign: Sign, frac_digits: usize, upper: bool) -> String - where T: DecodableFloat, F: FnMut(&Decoded, &mut [u8], i16) -> (usize, i16) { - to_string_with_parts(|buf, parts| to_exact_fixed_str(|d,b,l| f(d,b,l), v, sign, - frac_digits, upper, buf, parts)) + where + T: DecodableFloat, + F: FnMut(&Decoded, &mut [u8], i16) -> (usize, i16), + { + to_string_with_parts(|buf, parts| { + to_exact_fixed_str(|d, b, l| f(d, b, l), v, sign, frac_digits, upper, buf, parts) + }) } let f = &mut f_; - assert_eq!(to_string(f, 0.0, Minus, 0, false), "0"); - assert_eq!(to_string(f, 0.0, MinusRaw, 0, false), "0"); - assert_eq!(to_string(f, 0.0, MinusPlus, 0, false), "+0"); - assert_eq!(to_string(f, 0.0, MinusPlusRaw, 0, false), "+0"); - assert_eq!(to_string(f, -0.0, Minus, 0, false), "0"); - assert_eq!(to_string(f, -0.0, MinusRaw, 0, false), "-0"); - assert_eq!(to_string(f, -0.0, MinusPlus, 0, false), "+0"); + assert_eq!(to_string(f, 0.0, Minus, 0, false), "0"); + assert_eq!(to_string(f, 0.0, MinusRaw, 0, false), "0"); + assert_eq!(to_string(f, 0.0, MinusPlus, 0, false), "+0"); + assert_eq!(to_string(f, 0.0, MinusPlusRaw, 0, false), "+0"); + assert_eq!(to_string(f, -0.0, Minus, 0, false), "0"); + assert_eq!(to_string(f, -0.0, MinusRaw, 0, false), "-0"); + assert_eq!(to_string(f, -0.0, MinusPlus, 0, false), "+0"); assert_eq!(to_string(f, -0.0, MinusPlusRaw, 0, false), "-0"); - assert_eq!(to_string(f, 0.0, Minus, 1, true), "0.0"); - assert_eq!(to_string(f, 0.0, MinusRaw, 1, true), "0.0"); - assert_eq!(to_string(f, 0.0, MinusPlus, 1, true), "+0.0"); - assert_eq!(to_string(f, 0.0, MinusPlusRaw, 1, true), "+0.0"); - assert_eq!(to_string(f, -0.0, Minus, 8, true), "0.00000000"); - assert_eq!(to_string(f, -0.0, MinusRaw, 8, true), "-0.00000000"); - assert_eq!(to_string(f, -0.0, MinusPlus, 8, true), "+0.00000000"); - assert_eq!(to_string(f, -0.0, MinusPlusRaw, 8, true), "-0.00000000"); - - assert_eq!(to_string(f, 1.0/0.0, Minus, 0, false), "inf"); - assert_eq!(to_string(f, 1.0/0.0, MinusRaw, 1, true), "inf"); - assert_eq!(to_string(f, 1.0/0.0, MinusPlus, 8, false), "+inf"); - assert_eq!(to_string(f, 1.0/0.0, MinusPlusRaw, 64, true), "+inf"); - assert_eq!(to_string(f, 0.0/0.0, Minus, 0, false), "NaN"); - assert_eq!(to_string(f, 0.0/0.0, MinusRaw, 1, true), "NaN"); - assert_eq!(to_string(f, 0.0/0.0, MinusPlus, 8, false), "NaN"); - assert_eq!(to_string(f, 0.0/0.0, MinusPlusRaw, 64, true), "NaN"); - assert_eq!(to_string(f, -1.0/0.0, Minus, 0, false), "-inf"); - assert_eq!(to_string(f, -1.0/0.0, MinusRaw, 1, true), "-inf"); - assert_eq!(to_string(f, -1.0/0.0, MinusPlus, 8, false), "-inf"); - assert_eq!(to_string(f, -1.0/0.0, MinusPlusRaw, 64, true), "-inf"); - - assert_eq!(to_string(f, 3.14, Minus, 0, false), "3"); - assert_eq!(to_string(f, 3.14, MinusRaw, 0, false), "3"); - assert_eq!(to_string(f, 3.14, MinusPlus, 0, false), "+3"); - assert_eq!(to_string(f, 3.14, MinusPlusRaw, 0, false), "+3"); - assert_eq!(to_string(f, -3.14, Minus, 0, false), "-3"); - assert_eq!(to_string(f, -3.14, MinusRaw, 0, false), "-3"); - assert_eq!(to_string(f, -3.14, MinusPlus, 0, false), "-3"); + assert_eq!(to_string(f, 0.0, Minus, 1, true), "0.0"); + assert_eq!(to_string(f, 0.0, MinusRaw, 1, true), "0.0"); + assert_eq!(to_string(f, 0.0, MinusPlus, 1, true), "+0.0"); + assert_eq!(to_string(f, 0.0, MinusPlusRaw, 1, true), "+0.0"); + assert_eq!(to_string(f, -0.0, Minus, 8, true), "0.00000000"); + assert_eq!(to_string(f, -0.0, MinusRaw, 8, true), "-0.00000000"); + assert_eq!(to_string(f, -0.0, MinusPlus, 8, true), "+0.00000000"); + assert_eq!(to_string(f, -0.0, MinusPlusRaw, 8, true), "-0.00000000"); + + assert_eq!(to_string(f, 1.0 / 0.0, Minus, 0, false), "inf"); + assert_eq!(to_string(f, 1.0 / 0.0, MinusRaw, 1, true), "inf"); + assert_eq!(to_string(f, 1.0 / 0.0, MinusPlus, 8, false), "+inf"); + assert_eq!(to_string(f, 1.0 / 0.0, MinusPlusRaw, 64, true), "+inf"); + assert_eq!(to_string(f, 0.0 / 0.0, Minus, 0, false), "NaN"); + assert_eq!(to_string(f, 0.0 / 0.0, MinusRaw, 1, true), "NaN"); + assert_eq!(to_string(f, 0.0 / 0.0, MinusPlus, 8, false), "NaN"); + assert_eq!(to_string(f, 0.0 / 0.0, MinusPlusRaw, 64, true), "NaN"); + assert_eq!(to_string(f, -1.0 / 0.0, Minus, 0, false), "-inf"); + assert_eq!(to_string(f, -1.0 / 0.0, MinusRaw, 1, true), "-inf"); + assert_eq!(to_string(f, -1.0 / 0.0, MinusPlus, 8, false), "-inf"); + assert_eq!(to_string(f, -1.0 / 0.0, MinusPlusRaw, 64, true), "-inf"); + + assert_eq!(to_string(f, 3.14, Minus, 0, false), "3"); + assert_eq!(to_string(f, 3.14, MinusRaw, 0, false), "3"); + assert_eq!(to_string(f, 3.14, MinusPlus, 0, false), "+3"); + assert_eq!(to_string(f, 3.14, MinusPlusRaw, 0, false), "+3"); + assert_eq!(to_string(f, -3.14, Minus, 0, false), "-3"); + assert_eq!(to_string(f, -3.14, MinusRaw, 0, false), "-3"); + assert_eq!(to_string(f, -3.14, MinusPlus, 0, false), "-3"); assert_eq!(to_string(f, -3.14, MinusPlusRaw, 0, false), "-3"); - assert_eq!(to_string(f, 3.14, Minus, 1, true), "3.1"); - assert_eq!(to_string(f, 3.14, MinusRaw, 2, true), "3.14"); - assert_eq!(to_string(f, 3.14, MinusPlus, 3, true), "+3.140"); - assert_eq!(to_string(f, 3.14, MinusPlusRaw, 4, true), "+3.1400"); - assert_eq!(to_string(f, -3.14, Minus, 8, true), "-3.14000000"); - assert_eq!(to_string(f, -3.14, MinusRaw, 8, true), "-3.14000000"); - assert_eq!(to_string(f, -3.14, MinusPlus, 8, true), "-3.14000000"); - assert_eq!(to_string(f, -3.14, MinusPlusRaw, 8, true), "-3.14000000"); - - assert_eq!(to_string(f, 0.195, Minus, 0, false), "0"); - assert_eq!(to_string(f, 0.195, MinusRaw, 0, false), "0"); - assert_eq!(to_string(f, 0.195, MinusPlus, 0, false), "+0"); - assert_eq!(to_string(f, 0.195, MinusPlusRaw, 0, false), "+0"); - assert_eq!(to_string(f, -0.195, Minus, 0, false), "-0"); - assert_eq!(to_string(f, -0.195, MinusRaw, 0, false), "-0"); - assert_eq!(to_string(f, -0.195, MinusPlus, 0, false), "-0"); + assert_eq!(to_string(f, 3.14, Minus, 1, true), "3.1"); + assert_eq!(to_string(f, 3.14, MinusRaw, 2, true), "3.14"); + assert_eq!(to_string(f, 3.14, MinusPlus, 3, true), "+3.140"); + assert_eq!(to_string(f, 3.14, MinusPlusRaw, 4, true), "+3.1400"); + assert_eq!(to_string(f, -3.14, Minus, 8, true), "-3.14000000"); + assert_eq!(to_string(f, -3.14, MinusRaw, 8, true), "-3.14000000"); + assert_eq!(to_string(f, -3.14, MinusPlus, 8, true), "-3.14000000"); + assert_eq!(to_string(f, -3.14, MinusPlusRaw, 8, true), "-3.14000000"); + + assert_eq!(to_string(f, 0.195, Minus, 0, false), "0"); + assert_eq!(to_string(f, 0.195, MinusRaw, 0, false), "0"); + assert_eq!(to_string(f, 0.195, MinusPlus, 0, false), "+0"); + assert_eq!(to_string(f, 0.195, MinusPlusRaw, 0, false), "+0"); + assert_eq!(to_string(f, -0.195, Minus, 0, false), "-0"); + assert_eq!(to_string(f, -0.195, MinusRaw, 0, false), "-0"); + assert_eq!(to_string(f, -0.195, MinusPlus, 0, false), "-0"); assert_eq!(to_string(f, -0.195, MinusPlusRaw, 0, false), "-0"); - assert_eq!(to_string(f, 0.195, Minus, 1, true), "0.2"); - assert_eq!(to_string(f, 0.195, MinusRaw, 2, true), "0.20"); - assert_eq!(to_string(f, 0.195, MinusPlus, 3, true), "+0.195"); - assert_eq!(to_string(f, 0.195, MinusPlusRaw, 4, true), "+0.1950"); - assert_eq!(to_string(f, -0.195, Minus, 5, true), "-0.19500"); - assert_eq!(to_string(f, -0.195, MinusRaw, 6, true), "-0.195000"); - assert_eq!(to_string(f, -0.195, MinusPlus, 7, true), "-0.1950000"); - assert_eq!(to_string(f, -0.195, MinusPlusRaw, 8, true), "-0.19500000"); - - assert_eq!(to_string(f, 999.5, Minus, 0, false), "1000"); - assert_eq!(to_string(f, 999.5, Minus, 1, false), "999.5"); - assert_eq!(to_string(f, 999.5, Minus, 2, false), "999.50"); - assert_eq!(to_string(f, 999.5, Minus, 3, false), "999.500"); + assert_eq!(to_string(f, 0.195, Minus, 1, true), "0.2"); + assert_eq!(to_string(f, 0.195, MinusRaw, 2, true), "0.20"); + assert_eq!(to_string(f, 0.195, MinusPlus, 3, true), "+0.195"); + assert_eq!(to_string(f, 0.195, MinusPlusRaw, 4, true), "+0.1950"); + assert_eq!(to_string(f, -0.195, Minus, 5, true), "-0.19500"); + assert_eq!(to_string(f, -0.195, MinusRaw, 6, true), "-0.195000"); + assert_eq!(to_string(f, -0.195, MinusPlus, 7, true), "-0.1950000"); + assert_eq!(to_string(f, -0.195, MinusPlusRaw, 8, true), "-0.19500000"); + + assert_eq!(to_string(f, 999.5, Minus, 0, false), "1000"); + assert_eq!(to_string(f, 999.5, Minus, 1, false), "999.5"); + assert_eq!(to_string(f, 999.5, Minus, 2, false), "999.50"); + assert_eq!(to_string(f, 999.5, Minus, 3, false), "999.500"); assert_eq!(to_string(f, 999.5, Minus, 30, false), "999.500000000000000000000000000000"); assert_eq!(to_string(f, 0.5, Minus, 0, false), "1"); @@ -984,32 +1083,32 @@ pub fn to_exact_fixed_str_test<F>(mut f_: F) assert_eq!(to_string(f, 0.5, Minus, 2, false), "0.50"); assert_eq!(to_string(f, 0.5, Minus, 3, false), "0.500"); - assert_eq!(to_string(f, 0.95, Minus, 0, false), "1"); - assert_eq!(to_string(f, 0.95, Minus, 1, false), "0.9"); // because it really is less than 0.95 - assert_eq!(to_string(f, 0.95, Minus, 2, false), "0.95"); - assert_eq!(to_string(f, 0.95, Minus, 3, false), "0.950"); + assert_eq!(to_string(f, 0.95, Minus, 0, false), "1"); + assert_eq!(to_string(f, 0.95, Minus, 1, false), "0.9"); // because it really is less than 0.95 + assert_eq!(to_string(f, 0.95, Minus, 2, false), "0.95"); + assert_eq!(to_string(f, 0.95, Minus, 3, false), "0.950"); assert_eq!(to_string(f, 0.95, Minus, 10, false), "0.9500000000"); assert_eq!(to_string(f, 0.95, Minus, 30, false), "0.949999999999999955591079014994"); - assert_eq!(to_string(f, 0.095, Minus, 0, false), "0"); - assert_eq!(to_string(f, 0.095, Minus, 1, false), "0.1"); - assert_eq!(to_string(f, 0.095, Minus, 2, false), "0.10"); - assert_eq!(to_string(f, 0.095, Minus, 3, false), "0.095"); - assert_eq!(to_string(f, 0.095, Minus, 4, false), "0.0950"); + assert_eq!(to_string(f, 0.095, Minus, 0, false), "0"); + assert_eq!(to_string(f, 0.095, Minus, 1, false), "0.1"); + assert_eq!(to_string(f, 0.095, Minus, 2, false), "0.10"); + assert_eq!(to_string(f, 0.095, Minus, 3, false), "0.095"); + assert_eq!(to_string(f, 0.095, Minus, 4, false), "0.0950"); assert_eq!(to_string(f, 0.095, Minus, 10, false), "0.0950000000"); assert_eq!(to_string(f, 0.095, Minus, 30, false), "0.095000000000000001110223024625"); - assert_eq!(to_string(f, 0.0095, Minus, 0, false), "0"); - assert_eq!(to_string(f, 0.0095, Minus, 1, false), "0.0"); - assert_eq!(to_string(f, 0.0095, Minus, 2, false), "0.01"); - assert_eq!(to_string(f, 0.0095, Minus, 3, false), "0.009"); // really is less than 0.0095 - assert_eq!(to_string(f, 0.0095, Minus, 4, false), "0.0095"); - assert_eq!(to_string(f, 0.0095, Minus, 5, false), "0.00950"); + assert_eq!(to_string(f, 0.0095, Minus, 0, false), "0"); + assert_eq!(to_string(f, 0.0095, Minus, 1, false), "0.0"); + assert_eq!(to_string(f, 0.0095, Minus, 2, false), "0.01"); + assert_eq!(to_string(f, 0.0095, Minus, 3, false), "0.009"); // really is less than 0.0095 + assert_eq!(to_string(f, 0.0095, Minus, 4, false), "0.0095"); + assert_eq!(to_string(f, 0.0095, Minus, 5, false), "0.00950"); assert_eq!(to_string(f, 0.0095, Minus, 10, false), "0.0095000000"); assert_eq!(to_string(f, 0.0095, Minus, 30, false), "0.009499999999999999764077607267"); - assert_eq!(to_string(f, 7.5e-11, Minus, 0, false), "0"); - assert_eq!(to_string(f, 7.5e-11, Minus, 3, false), "0.000"); + assert_eq!(to_string(f, 7.5e-11, Minus, 0, false), "0"); + assert_eq!(to_string(f, 7.5e-11, Minus, 3, false), "0.000"); assert_eq!(to_string(f, 7.5e-11, Minus, 10, false), "0.0000000001"); assert_eq!(to_string(f, 7.5e-11, Minus, 11, false), "0.00000000007"); // ditto assert_eq!(to_string(f, 7.5e-11, Minus, 12, false), "0.000000000075"); @@ -1021,77 +1120,102 @@ pub fn to_exact_fixed_str_test<F>(mut f_: F) assert_eq!(to_string(f, 1.0e25, Minus, 1, false), "10000000000000000905969664.0"); assert_eq!(to_string(f, 1.0e25, Minus, 3, false), "10000000000000000905969664.000"); - assert_eq!(to_string(f, 1.0e-6, Minus, 0, false), "0"); - assert_eq!(to_string(f, 1.0e-6, Minus, 3, false), "0.000"); - assert_eq!(to_string(f, 1.0e-6, Minus, 6, false), "0.000001"); - assert_eq!(to_string(f, 1.0e-6, Minus, 9, false), "0.000001000"); + assert_eq!(to_string(f, 1.0e-6, Minus, 0, false), "0"); + assert_eq!(to_string(f, 1.0e-6, Minus, 3, false), "0.000"); + assert_eq!(to_string(f, 1.0e-6, Minus, 6, false), "0.000001"); + assert_eq!(to_string(f, 1.0e-6, Minus, 9, false), "0.000001000"); assert_eq!(to_string(f, 1.0e-6, Minus, 12, false), "0.000001000000"); assert_eq!(to_string(f, 1.0e-6, Minus, 22, false), "0.0000010000000000000000"); assert_eq!(to_string(f, 1.0e-6, Minus, 23, false), "0.00000099999999999999995"); assert_eq!(to_string(f, 1.0e-6, Minus, 24, false), "0.000000999999999999999955"); assert_eq!(to_string(f, 1.0e-6, Minus, 25, false), "0.0000009999999999999999547"); assert_eq!(to_string(f, 1.0e-6, Minus, 35, false), "0.00000099999999999999995474811182589"); - assert_eq!(to_string(f, 1.0e-6, Minus, 45, false), - "0.000000999999999999999954748111825886258685614"); - assert_eq!(to_string(f, 1.0e-6, Minus, 55, false), - "0.0000009999999999999999547481118258862586856139387236908"); - assert_eq!(to_string(f, 1.0e-6, Minus, 65, false), - "0.00000099999999999999995474811182588625868561393872369080781936646"); - assert_eq!(to_string(f, 1.0e-6, Minus, 75, false), - "0.000000999999999999999954748111825886258685613938723690807819366455078125000"); - - assert_eq!(to_string(f, f32::MAX, Minus, 0, false), - "340282346638528859811704183484516925440"); - assert_eq!(to_string(f, f32::MAX, Minus, 1, false), - "340282346638528859811704183484516925440.0"); - assert_eq!(to_string(f, f32::MAX, Minus, 2, false), - "340282346638528859811704183484516925440.00"); - - if cfg!(miri) { // Miri is too slow + assert_eq!( + to_string(f, 1.0e-6, Minus, 45, false), + "0.000000999999999999999954748111825886258685614" + ); + assert_eq!( + to_string(f, 1.0e-6, Minus, 55, false), + "0.0000009999999999999999547481118258862586856139387236908" + ); + assert_eq!( + to_string(f, 1.0e-6, Minus, 65, false), + "0.00000099999999999999995474811182588625868561393872369080781936646" + ); + assert_eq!( + to_string(f, 1.0e-6, Minus, 75, false), + "0.000000999999999999999954748111825886258685613938723690807819366455078125000" + ); + + assert_eq!(to_string(f, f32::MAX, Minus, 0, false), "340282346638528859811704183484516925440"); + assert_eq!( + to_string(f, f32::MAX, Minus, 1, false), + "340282346638528859811704183484516925440.0" + ); + assert_eq!( + to_string(f, f32::MAX, Minus, 2, false), + "340282346638528859811704183484516925440.00" + ); + + if cfg!(miri) { + // Miri is too slow return; } let minf32 = ldexp_f32(1.0, -149); - assert_eq!(to_string(f, minf32, Minus, 0, false), "0"); - assert_eq!(to_string(f, minf32, Minus, 1, false), "0.0"); - assert_eq!(to_string(f, minf32, Minus, 2, false), "0.00"); - assert_eq!(to_string(f, minf32, Minus, 4, false), "0.0000"); - assert_eq!(to_string(f, minf32, Minus, 8, false), "0.00000000"); - assert_eq!(to_string(f, minf32, Minus, 16, false), "0.0000000000000000"); - assert_eq!(to_string(f, minf32, Minus, 32, false), "0.00000000000000000000000000000000"); - assert_eq!(to_string(f, minf32, Minus, 64, false), - "0.0000000000000000000000000000000000000000000014012984643248170709"); - assert_eq!(to_string(f, minf32, Minus, 128, false), - "0.0000000000000000000000000000000000000000000014012984643248170709\ - 2372958328991613128026194187651577175706828388979108268586060149"); - assert_eq!(to_string(f, minf32, Minus, 256, false), - "0.0000000000000000000000000000000000000000000014012984643248170709\ + assert_eq!(to_string(f, minf32, Minus, 0, false), "0"); + assert_eq!(to_string(f, minf32, Minus, 1, false), "0.0"); + assert_eq!(to_string(f, minf32, Minus, 2, false), "0.00"); + assert_eq!(to_string(f, minf32, Minus, 4, false), "0.0000"); + assert_eq!(to_string(f, minf32, Minus, 8, false), "0.00000000"); + assert_eq!(to_string(f, minf32, Minus, 16, false), "0.0000000000000000"); + assert_eq!(to_string(f, minf32, Minus, 32, false), "0.00000000000000000000000000000000"); + assert_eq!( + to_string(f, minf32, Minus, 64, false), + "0.0000000000000000000000000000000000000000000014012984643248170709" + ); + assert_eq!( + to_string(f, minf32, Minus, 128, false), + "0.0000000000000000000000000000000000000000000014012984643248170709\ + 2372958328991613128026194187651577175706828388979108268586060149" + ); + assert_eq!( + to_string(f, minf32, Minus, 256, false), + "0.0000000000000000000000000000000000000000000014012984643248170709\ 2372958328991613128026194187651577175706828388979108268586060148\ 6638188362121582031250000000000000000000000000000000000000000000\ - 0000000000000000000000000000000000000000000000000000000000000000"); + 0000000000000000000000000000000000000000000000000000000000000000" + ); - assert_eq!(to_string(f, f64::MAX, Minus, 0, false), - "1797693134862315708145274237317043567980705675258449965989174768\ + assert_eq!( + to_string(f, f64::MAX, Minus, 0, false), + "1797693134862315708145274237317043567980705675258449965989174768\ 0315726078002853876058955863276687817154045895351438246423432132\ 6889464182768467546703537516986049910576551282076245490090389328\ 9440758685084551339423045832369032229481658085593321233482747978\ - 26204144723168738177180919299881250404026184124858368"); - assert_eq!(to_string(f, f64::MAX, Minus, 10, false), - "1797693134862315708145274237317043567980705675258449965989174768\ + 26204144723168738177180919299881250404026184124858368" + ); + assert_eq!( + to_string(f, f64::MAX, Minus, 10, false), + "1797693134862315708145274237317043567980705675258449965989174768\ 0315726078002853876058955863276687817154045895351438246423432132\ 6889464182768467546703537516986049910576551282076245490090389328\ 9440758685084551339423045832369032229481658085593321233482747978\ - 26204144723168738177180919299881250404026184124858368.0000000000"); + 26204144723168738177180919299881250404026184124858368.0000000000" + ); let minf64 = ldexp_f64(1.0, -1074); assert_eq!(to_string(f, minf64, Minus, 0, false), "0"); assert_eq!(to_string(f, minf64, Minus, 1, false), "0.0"); assert_eq!(to_string(f, minf64, Minus, 10, false), "0.0000000000"); - assert_eq!(to_string(f, minf64, Minus, 100, false), - "0.0000000000000000000000000000000000000000000000000000000000000000\ - 000000000000000000000000000000000000"); - assert_eq!(to_string(f, minf64, Minus, 1000, false), - "0.0000000000000000000000000000000000000000000000000000000000000000\ + assert_eq!( + to_string(f, minf64, Minus, 100, false), + "0.0000000000000000000000000000000000000000000000000000000000000000\ + 000000000000000000000000000000000000" + ); + assert_eq!( + to_string(f, minf64, Minus, 1000, false), + "0.0000000000000000000000000000000000000000000000000000000000000000\ 0000000000000000000000000000000000000000000000000000000000000000\ 0000000000000000000000000000000000000000000000000000000000000000\ 0000000000000000000000000000000000000000000000000000000000000000\ @@ -1106,15 +1230,23 @@ pub fn to_exact_fixed_str_test<F>(mut f_: F) 1937902681071074917033322268447533357208324319360923828934583680\ 6010601150616980975307834227731832924790498252473077637592724787\ 4656084778203734469699533647017972677717585125660551199131504891\ - 1014510378627381672509558373897335989937"); + 1014510378627381672509558373897335989937" + ); // very large output - assert_eq!(to_string(f, 0.0, Minus, 80000, false), format!("0.{:0>80000}", "")); - assert_eq!(to_string(f, 1.0e1, Minus, 80000, false), format!("10.{:0>80000}", "")); - assert_eq!(to_string(f, 1.0e0, Minus, 80000, false), format!("1.{:0>80000}", "")); - assert_eq!(to_string(f, 1.0e-1, Minus, 80000, false), - format!("0.1000000000000000055511151231257827021181583404541015625{:0>79945}", "")); - assert_eq!(to_string(f, 1.0e-20, Minus, 80000, false), - format!("0.0000000000000000000099999999999999994515327145420957165172950370\ - 2787392447107715776066783064379706047475337982177734375{:0>79881}", "")); + assert_eq!(to_string(f, 0.0, Minus, 80000, false), format!("0.{:0>80000}", "")); + assert_eq!(to_string(f, 1.0e1, Minus, 80000, false), format!("10.{:0>80000}", "")); + assert_eq!(to_string(f, 1.0e0, Minus, 80000, false), format!("1.{:0>80000}", "")); + assert_eq!( + to_string(f, 1.0e-1, Minus, 80000, false), + format!("0.1000000000000000055511151231257827021181583404541015625{:0>79945}", "") + ); + assert_eq!( + to_string(f, 1.0e-20, Minus, 80000, false), + format!( + "0.0000000000000000000099999999999999994515327145420957165172950370\ + 2787392447107715776066783064379706047475337982177734375{:0>79881}", + "" + ) + ); } diff --git a/src/libcore/tests/num/mod.rs b/src/libcore/tests/num/mod.rs index a17c094679e..f61793a3bca 100644 --- a/src/libcore/tests/num/mod.rs +++ b/src/libcore/tests/num/mod.rs @@ -1,32 +1,31 @@ -use core::convert::{TryFrom, TryInto}; use core::cmp::PartialEq; +use core::convert::{TryFrom, TryInto}; use core::fmt::Debug; use core::marker::Copy; use core::num::TryFromIntError; -use core::ops::{Add, Sub, Mul, Div, Rem}; +use core::ops::{Add, Div, Mul, Rem, Sub}; use core::option::Option; -use core::option::Option::{Some, None}; +use core::option::Option::{None, Some}; #[macro_use] mod int_macros; -mod i8; mod i16; mod i32; mod i64; +mod i8; #[macro_use] mod uint_macros; -mod u8; mod u16; mod u32; mod u64; +mod u8; -mod flt2dec; -mod dec2flt; mod bignum; - +mod dec2flt; +mod flt2dec; /// Adds the attribute to all items in the block. macro_rules! cfg_block { @@ -48,25 +47,29 @@ macro_rules! assume_usize_width { } /// Helper function for testing numeric operations -pub fn test_num<T>(ten: T, two: T) where +pub fn test_num<T>(ten: T, two: T) +where T: PartialEq - + Add<Output=T> + Sub<Output=T> - + Mul<Output=T> + Div<Output=T> - + Rem<Output=T> + Debug - + Copy + + Add<Output = T> + + Sub<Output = T> + + Mul<Output = T> + + Div<Output = T> + + Rem<Output = T> + + Debug + + Copy, { - assert_eq!(ten.add(two), ten + two); - assert_eq!(ten.sub(two), ten - two); - assert_eq!(ten.mul(two), ten * two); - assert_eq!(ten.div(two), ten / two); - assert_eq!(ten.rem(two), ten % two); + assert_eq!(ten.add(two), ten + two); + assert_eq!(ten.sub(two), ten - two); + assert_eq!(ten.mul(two), ten * two); + assert_eq!(ten.div(two), ten / two); + assert_eq!(ten.rem(two), ten % two); } #[test] fn from_str_issue7588() { - let u : Option<u8> = u8::from_str_radix("1000", 10).ok(); + let u: Option<u8> = u8::from_str_radix("1000", 10).ok(); assert_eq!(u, None); - let s : Option<i16> = i16::from_str_radix("80000", 10).ok(); + let s: Option<i16> = i16::from_str_radix("80000", 10).ok(); assert_eq!(s, None); } @@ -144,7 +147,7 @@ macro_rules! test_impl_from { assert_eq!(large_max as $Small, small_max); assert_eq!(large_min as $Small, small_min); } - } + }; } // Unsigned -> Unsigned @@ -242,7 +245,6 @@ fn test_f32f64() { assert!(nan.is_nan()); } - /// Conversions where the full width of $source can be represented as $target macro_rules! test_impl_try_from_always_ok { ($fn_name:ident, $source:ty, $target: ty) => { @@ -251,14 +253,11 @@ macro_rules! test_impl_try_from_always_ok { let max = <$source>::max_value(); let min = <$source>::min_value(); let zero: $source = 0; - assert_eq!(<$target as TryFrom<$source>>::try_from(max).unwrap(), - max as $target); - assert_eq!(<$target as TryFrom<$source>>::try_from(min).unwrap(), - min as $target); - assert_eq!(<$target as TryFrom<$source>>::try_from(zero).unwrap(), - zero as $target); + assert_eq!(<$target as TryFrom<$source>>::try_from(max).unwrap(), max as $target); + assert_eq!(<$target as TryFrom<$source>>::try_from(min).unwrap(), min as $target); + assert_eq!(<$target as TryFrom<$source>>::try_from(zero).unwrap(), zero as $target); } - } + }; } test_impl_try_from_always_ok! { test_try_u8u8, u8, u8 } @@ -368,14 +367,12 @@ macro_rules! test_impl_try_from_signed_to_unsigned_upper_ok { let min = <$source>::min_value(); let zero: $source = 0; let neg_one: $source = -1; - assert_eq!(<$target as TryFrom<$source>>::try_from(max).unwrap(), - max as $target); + assert_eq!(<$target as TryFrom<$source>>::try_from(max).unwrap(), max as $target); assert!(<$target as TryFrom<$source>>::try_from(min).is_err()); - assert_eq!(<$target as TryFrom<$source>>::try_from(zero).unwrap(), - zero as $target); + assert_eq!(<$target as TryFrom<$source>>::try_from(zero).unwrap(), zero as $target); assert!(<$target as TryFrom<$source>>::try_from(neg_one).is_err()); } - } + }; } test_impl_try_from_signed_to_unsigned_upper_ok! { test_try_i8u8, i8, u8 } @@ -435,12 +432,10 @@ macro_rules! test_impl_try_from_unsigned_to_signed_upper_err { let min = <$source>::min_value(); let zero: $source = 0; assert!(<$target as TryFrom<$source>>::try_from(max).is_err()); - assert_eq!(<$target as TryFrom<$source>>::try_from(min).unwrap(), - min as $target); - assert_eq!(<$target as TryFrom<$source>>::try_from(zero).unwrap(), - zero as $target); + assert_eq!(<$target as TryFrom<$source>>::try_from(min).unwrap(), min as $target); + assert_eq!(<$target as TryFrom<$source>>::try_from(zero).unwrap(), zero as $target); } - } + }; } test_impl_try_from_unsigned_to_signed_upper_err! { test_try_u8i8, u8, i8 } @@ -503,16 +498,17 @@ macro_rules! test_impl_try_from_same_sign_err { if min != 0 { assert!(<$target as TryFrom<$source>>::try_from(min).is_err()); } - assert_eq!(<$target as TryFrom<$source>>::try_from(zero).unwrap(), - zero as $target); - assert_eq!(<$target as TryFrom<$source>>::try_from(t_max as $source) - .unwrap(), - t_max as $target); - assert_eq!(<$target as TryFrom<$source>>::try_from(t_min as $source) - .unwrap(), - t_min as $target); + assert_eq!(<$target as TryFrom<$source>>::try_from(zero).unwrap(), zero as $target); + assert_eq!( + <$target as TryFrom<$source>>::try_from(t_max as $source).unwrap(), + t_max as $target + ); + assert_eq!( + <$target as TryFrom<$source>>::try_from(t_min as $source).unwrap(), + t_min as $target + ); } - } + }; } test_impl_try_from_same_sign_err! { test_try_u16u8, u16, u8 } @@ -589,16 +585,17 @@ macro_rules! test_impl_try_from_signed_to_unsigned_err { let t_min = <$target>::min_value(); assert!(<$target as TryFrom<$source>>::try_from(max).is_err()); assert!(<$target as TryFrom<$source>>::try_from(min).is_err()); - assert_eq!(<$target as TryFrom<$source>>::try_from(zero).unwrap(), - zero as $target); - assert_eq!(<$target as TryFrom<$source>>::try_from(t_max as $source) - .unwrap(), - t_max as $target); - assert_eq!(<$target as TryFrom<$source>>::try_from(t_min as $source) - .unwrap(), - t_min as $target); + assert_eq!(<$target as TryFrom<$source>>::try_from(zero).unwrap(), zero as $target); + assert_eq!( + <$target as TryFrom<$source>>::try_from(t_max as $source).unwrap(), + t_max as $target + ); + assert_eq!( + <$target as TryFrom<$source>>::try_from(t_min as $source).unwrap(), + t_min as $target + ); } - } + }; } test_impl_try_from_signed_to_unsigned_err! { test_try_i16u8, i16, u8 } @@ -637,72 +634,74 @@ assume_usize_width! { } macro_rules! test_float { - ($modname: ident, $fty: ty, $inf: expr, $neginf: expr, $nan: expr) => { mod $modname { - // FIXME(nagisa): these tests should test for sign of -0.0 - #[test] - fn min() { - assert_eq!((0.0 as $fty).min(0.0), 0.0); - assert_eq!((-0.0 as $fty).min(-0.0), -0.0); - assert_eq!((9.0 as $fty).min(9.0), 9.0); - assert_eq!((-9.0 as $fty).min(0.0), -9.0); - assert_eq!((0.0 as $fty).min(9.0), 0.0); - assert_eq!((-0.0 as $fty).min(-9.0), -9.0); - assert_eq!(($inf as $fty).min(9.0), 9.0); - assert_eq!((9.0 as $fty).min($inf), 9.0); - assert_eq!(($inf as $fty).min(-9.0), -9.0); - assert_eq!((-9.0 as $fty).min($inf), -9.0); - assert_eq!(($neginf as $fty).min(9.0), $neginf); - assert_eq!((9.0 as $fty).min($neginf), $neginf); - assert_eq!(($neginf as $fty).min(-9.0), $neginf); - assert_eq!((-9.0 as $fty).min($neginf), $neginf); - assert_eq!(($nan as $fty).min(9.0), 9.0); - assert_eq!(($nan as $fty).min(-9.0), -9.0); - assert_eq!((9.0 as $fty).min($nan), 9.0); - assert_eq!((-9.0 as $fty).min($nan), -9.0); - assert!(($nan as $fty).min($nan).is_nan()); - } - #[test] - fn max() { - assert_eq!((0.0 as $fty).max(0.0), 0.0); - assert_eq!((-0.0 as $fty).max(-0.0), -0.0); - assert_eq!((9.0 as $fty).max(9.0), 9.0); - assert_eq!((-9.0 as $fty).max(0.0), 0.0); - assert_eq!((0.0 as $fty).max(9.0), 9.0); - assert_eq!((-0.0 as $fty).max(-9.0), -0.0); - assert_eq!(($inf as $fty).max(9.0), $inf); - assert_eq!((9.0 as $fty).max($inf), $inf); - assert_eq!(($inf as $fty).max(-9.0), $inf); - assert_eq!((-9.0 as $fty).max($inf), $inf); - assert_eq!(($neginf as $fty).max(9.0), 9.0); - assert_eq!((9.0 as $fty).max($neginf), 9.0); - assert_eq!(($neginf as $fty).max(-9.0), -9.0); - assert_eq!((-9.0 as $fty).max($neginf), -9.0); - assert_eq!(($nan as $fty).max(9.0), 9.0); - assert_eq!(($nan as $fty).max(-9.0), -9.0); - assert_eq!((9.0 as $fty).max($nan), 9.0); - assert_eq!((-9.0 as $fty).max($nan), -9.0); - assert!(($nan as $fty).max($nan).is_nan()); - } - #[test] - fn rem_euclid() { - let a: $fty = 42.0; - assert!($inf.rem_euclid(a).is_nan()); - assert_eq!(a.rem_euclid($inf), a); - assert!(a.rem_euclid($nan).is_nan()); - assert!($inf.rem_euclid($inf).is_nan()); - assert!($inf.rem_euclid($nan).is_nan()); - assert!($nan.rem_euclid($inf).is_nan()); - } - #[test] - fn div_euclid() { - let a: $fty = 42.0; - assert_eq!(a.div_euclid($inf), 0.0); - assert!(a.div_euclid($nan).is_nan()); - assert!($inf.div_euclid($inf).is_nan()); - assert!($inf.div_euclid($nan).is_nan()); - assert!($nan.div_euclid($inf).is_nan()); + ($modname: ident, $fty: ty, $inf: expr, $neginf: expr, $nan: expr) => { + mod $modname { + // FIXME(nagisa): these tests should test for sign of -0.0 + #[test] + fn min() { + assert_eq!((0.0 as $fty).min(0.0), 0.0); + assert_eq!((-0.0 as $fty).min(-0.0), -0.0); + assert_eq!((9.0 as $fty).min(9.0), 9.0); + assert_eq!((-9.0 as $fty).min(0.0), -9.0); + assert_eq!((0.0 as $fty).min(9.0), 0.0); + assert_eq!((-0.0 as $fty).min(-9.0), -9.0); + assert_eq!(($inf as $fty).min(9.0), 9.0); + assert_eq!((9.0 as $fty).min($inf), 9.0); + assert_eq!(($inf as $fty).min(-9.0), -9.0); + assert_eq!((-9.0 as $fty).min($inf), -9.0); + assert_eq!(($neginf as $fty).min(9.0), $neginf); + assert_eq!((9.0 as $fty).min($neginf), $neginf); + assert_eq!(($neginf as $fty).min(-9.0), $neginf); + assert_eq!((-9.0 as $fty).min($neginf), $neginf); + assert_eq!(($nan as $fty).min(9.0), 9.0); + assert_eq!(($nan as $fty).min(-9.0), -9.0); + assert_eq!((9.0 as $fty).min($nan), 9.0); + assert_eq!((-9.0 as $fty).min($nan), -9.0); + assert!(($nan as $fty).min($nan).is_nan()); + } + #[test] + fn max() { + assert_eq!((0.0 as $fty).max(0.0), 0.0); + assert_eq!((-0.0 as $fty).max(-0.0), -0.0); + assert_eq!((9.0 as $fty).max(9.0), 9.0); + assert_eq!((-9.0 as $fty).max(0.0), 0.0); + assert_eq!((0.0 as $fty).max(9.0), 9.0); + assert_eq!((-0.0 as $fty).max(-9.0), -0.0); + assert_eq!(($inf as $fty).max(9.0), $inf); + assert_eq!((9.0 as $fty).max($inf), $inf); + assert_eq!(($inf as $fty).max(-9.0), $inf); + assert_eq!((-9.0 as $fty).max($inf), $inf); + assert_eq!(($neginf as $fty).max(9.0), 9.0); + assert_eq!((9.0 as $fty).max($neginf), 9.0); + assert_eq!(($neginf as $fty).max(-9.0), -9.0); + assert_eq!((-9.0 as $fty).max($neginf), -9.0); + assert_eq!(($nan as $fty).max(9.0), 9.0); + assert_eq!(($nan as $fty).max(-9.0), -9.0); + assert_eq!((9.0 as $fty).max($nan), 9.0); + assert_eq!((-9.0 as $fty).max($nan), -9.0); + assert!(($nan as $fty).max($nan).is_nan()); + } + #[test] + fn rem_euclid() { + let a: $fty = 42.0; + assert!($inf.rem_euclid(a).is_nan()); + assert_eq!(a.rem_euclid($inf), a); + assert!(a.rem_euclid($nan).is_nan()); + assert!($inf.rem_euclid($inf).is_nan()); + assert!($inf.rem_euclid($nan).is_nan()); + assert!($nan.rem_euclid($inf).is_nan()); + } + #[test] + fn div_euclid() { + let a: $fty = 42.0; + assert_eq!(a.div_euclid($inf), 0.0); + assert!(a.div_euclid($nan).is_nan()); + assert!($inf.div_euclid($inf).is_nan()); + assert!($inf.div_euclid($nan).is_nan()); + assert!($nan.div_euclid($inf).is_nan()); + } } - } } + }; } test_float!(f32, f32, ::core::f32::INFINITY, ::core::f32::NEG_INFINITY, ::core::f32::NAN); diff --git a/src/libcore/tests/pattern.rs b/src/libcore/tests/pattern.rs index 06c3a78c169..6ec61cc97c9 100644 --- a/src/libcore/tests/pattern.rs +++ b/src/libcore/tests/pattern.rs @@ -18,7 +18,7 @@ enum Step { Matches(usize, usize), Rejects(usize, usize), InRange(usize, usize), - Done + Done, } use self::Step::*; @@ -28,7 +28,7 @@ impl From<SearchStep> for Step { match x { SearchStep::Match(a, b) => Matches(a, b), SearchStep::Reject(a, b) => Rejects(a, b), - SearchStep::Done => Done + SearchStep::Done => Done, } } } @@ -37,7 +37,7 @@ impl From<Option<(usize, usize)>> for Step { fn from(x: Option<(usize, usize)>) -> Self { match x { Some((a, b)) => InRange(a, b), - None => Done + None => Done, } } } @@ -52,57 +52,146 @@ impl From<Option<(usize, usize)>> for Step { #[test] fn test_simple_iteration() { - search_asserts! ("abcdeabcd", 'a', "forward iteration for ASCII string", + search_asserts!( + "abcdeabcd", + 'a', + "forward iteration for ASCII string", // a b c d e a b c d EOF - [next, next, next, next, next, next, next, next, next, next], - [Matches(0, 1), Rejects(1, 2), Rejects(2, 3), Rejects(3, 4), Rejects(4, 5), Matches(5, 6), Rejects(6, 7), Rejects(7, 8), Rejects(8, 9), Done] - ); - - search_asserts! ("abcdeabcd", 'a', "reverse iteration for ASCII string", + [next, next, next, next, next, next, next, next, next, next], + [ + Matches(0, 1), + Rejects(1, 2), + Rejects(2, 3), + Rejects(3, 4), + Rejects(4, 5), + Matches(5, 6), + Rejects(6, 7), + Rejects(7, 8), + Rejects(8, 9), + Done + ] + ); + + search_asserts!( + "abcdeabcd", + 'a', + "reverse iteration for ASCII string", // d c b a e d c b a EOF - [next_back, next_back, next_back, next_back, next_back, next_back, next_back, next_back, next_back, next_back], - [Rejects(8, 9), Rejects(7, 8), Rejects(6, 7), Matches(5, 6), Rejects(4, 5), Rejects(3, 4), Rejects(2, 3), Rejects(1, 2), Matches(0, 1), Done] - ); - - search_asserts! ("我爱我的猫", '我', "forward iteration for Chinese string", + [ + next_back, next_back, next_back, next_back, next_back, next_back, next_back, next_back, + next_back, next_back + ], + [ + Rejects(8, 9), + Rejects(7, 8), + Rejects(6, 7), + Matches(5, 6), + Rejects(4, 5), + Rejects(3, 4), + Rejects(2, 3), + Rejects(1, 2), + Matches(0, 1), + Done + ] + ); + + search_asserts!( + "我爱我的猫", + '我', + "forward iteration for Chinese string", // 我 愛 我 的 貓 EOF - [next, next, next, next, next, next], + [next, next, next, next, next, next], [Matches(0, 3), Rejects(3, 6), Matches(6, 9), Rejects(9, 12), Rejects(12, 15), Done] ); - search_asserts! ("我的猫说meow", 'm', "forward iteration for mixed string", + search_asserts!( + "我的猫说meow", + 'm', + "forward iteration for mixed string", // 我 的 猫 说 m e o w EOF - [next, next, next, next, next, next, next, next, next], - [Rejects(0, 3), Rejects(3, 6), Rejects(6, 9), Rejects(9, 12), Matches(12, 13), Rejects(13, 14), Rejects(14, 15), Rejects(15, 16), Done] - ); - - search_asserts! ("我的猫说meow", '猫', "reverse iteration for mixed string", + [next, next, next, next, next, next, next, next, next], + [ + Rejects(0, 3), + Rejects(3, 6), + Rejects(6, 9), + Rejects(9, 12), + Matches(12, 13), + Rejects(13, 14), + Rejects(14, 15), + Rejects(15, 16), + Done + ] + ); + + search_asserts!( + "我的猫说meow", + '猫', + "reverse iteration for mixed string", // w o e m 说 猫 的 我 EOF - [next_back, next_back, next_back, next_back, next_back, next_back, next_back, next_back, next_back], - [Rejects(15, 16), Rejects(14, 15), Rejects(13, 14), Rejects(12, 13), Rejects(9, 12), Matches(6, 9), Rejects(3, 6), Rejects(0, 3), Done] + [ + next_back, next_back, next_back, next_back, next_back, next_back, next_back, next_back, + next_back + ], + [ + Rejects(15, 16), + Rejects(14, 15), + Rejects(13, 14), + Rejects(12, 13), + Rejects(9, 12), + Matches(6, 9), + Rejects(3, 6), + Rejects(0, 3), + Done + ] ); } #[test] fn test_simple_search() { - search_asserts!("abcdeabcdeabcde", 'a', "next_match for ASCII string", - [next_match, next_match, next_match, next_match], + search_asserts!( + "abcdeabcdeabcde", + 'a', + "next_match for ASCII string", + [next_match, next_match, next_match, next_match], [InRange(0, 1), InRange(5, 6), InRange(10, 11), Done] ); - search_asserts!("abcdeabcdeabcde", 'a', "next_match_back for ASCII string", + search_asserts!( + "abcdeabcdeabcde", + 'a', + "next_match_back for ASCII string", [next_match_back, next_match_back, next_match_back, next_match_back], - [InRange(10, 11), InRange(5, 6), InRange(0, 1), Done] + [InRange(10, 11), InRange(5, 6), InRange(0, 1), Done] ); - search_asserts!("abcdeab", 'a', "next_reject for ASCII string", - [next_reject, next_reject, next_match, next_reject, next_reject], + search_asserts!( + "abcdeab", + 'a', + "next_reject for ASCII string", + [next_reject, next_reject, next_match, next_reject, next_reject], [InRange(1, 2), InRange(2, 3), InRange(5, 6), InRange(6, 7), Done] ); - search_asserts!("abcdeabcdeabcde", 'a', "next_reject_back for ASCII string", - [next_reject_back, next_reject_back, next_match_back, next_reject_back, next_reject_back, next_reject_back], - [InRange(14, 15), InRange(13, 14), InRange(10, 11), InRange(9, 10), InRange(8, 9), InRange(7, 8)] + search_asserts!( + "abcdeabcdeabcde", + 'a', + "next_reject_back for ASCII string", + [ + next_reject_back, + next_reject_back, + next_match_back, + next_reject_back, + next_reject_back, + next_reject_back + ], + [ + InRange(14, 15), + InRange(13, 14), + InRange(10, 11), + InRange(9, 10), + InRange(8, 9), + InRange(7, 8) + ] ); } @@ -121,134 +210,234 @@ const STRESS: &str = "Áa🁀bÁꁁfg😁각กᘀ각aÁ각ꁁก😁a"; fn test_stress_indices() { // this isn't really a test, more of documentation on the indices of each character in the stresstest string - search_asserts!(STRESS, 'x', "Indices of characters in stress test", - [next, next, next, next, next, next, next, next, next, next, next, next, next, next, next, next, next, next, next, next, next], - [Rejects(0, 2), // Á - Rejects(2, 3), // a - Rejects(3, 7), // 🁀 - Rejects(7, 8), // b - Rejects(8, 10), // Á - Rejects(10, 13), // ꁁ - Rejects(13, 14), // f - Rejects(14, 15), // g - Rejects(15, 19), // 😀 - Rejects(19, 22), // 각 - Rejects(22, 25), // ก - Rejects(25, 28), // ᘀ - Rejects(28, 31), // 각 - Rejects(31, 32), // a - Rejects(32, 34), // Á - Rejects(34, 37), // 각 - Rejects(37, 40), // ꁁ - Rejects(40, 43), // ก - Rejects(43, 47), // 😀 - Rejects(47, 48), // a - Done] + search_asserts!( + STRESS, + 'x', + "Indices of characters in stress test", + [ + next, next, next, next, next, next, next, next, next, next, next, next, next, next, + next, next, next, next, next, next, next + ], + [ + Rejects(0, 2), // Á + Rejects(2, 3), // a + Rejects(3, 7), // 🁀 + Rejects(7, 8), // b + Rejects(8, 10), // Á + Rejects(10, 13), // ꁁ + Rejects(13, 14), // f + Rejects(14, 15), // g + Rejects(15, 19), // 😀 + Rejects(19, 22), // 각 + Rejects(22, 25), // ก + Rejects(25, 28), // ᘀ + Rejects(28, 31), // 각 + Rejects(31, 32), // a + Rejects(32, 34), // Á + Rejects(34, 37), // 각 + Rejects(37, 40), // ꁁ + Rejects(40, 43), // ก + Rejects(43, 47), // 😀 + Rejects(47, 48), // a + Done + ] ); } #[test] fn test_forward_search_shared_bytes() { - search_asserts!(STRESS, 'Á', "Forward search for two-byte Latin character", - [next_match, next_match, next_match, next_match], + search_asserts!( + STRESS, + 'Á', + "Forward search for two-byte Latin character", + [next_match, next_match, next_match, next_match], [InRange(0, 2), InRange(8, 10), InRange(32, 34), Done] ); - search_asserts!(STRESS, 'Á', "Forward search for two-byte Latin character; check if next() still works", - [next_match, next, next_match, next, next_match, next, next_match], - [InRange(0, 2), Rejects(2, 3), InRange(8, 10), Rejects(10, 13), InRange(32, 34), Rejects(34, 37), Done] - ); - - search_asserts!(STRESS, '각', "Forward search for three-byte Hangul character", - [next_match, next, next_match, next_match, next_match], + search_asserts!( + STRESS, + 'Á', + "Forward search for two-byte Latin character; check if next() still works", + [next_match, next, next_match, next, next_match, next, next_match], + [ + InRange(0, 2), + Rejects(2, 3), + InRange(8, 10), + Rejects(10, 13), + InRange(32, 34), + Rejects(34, 37), + Done + ] + ); + + search_asserts!( + STRESS, + '각', + "Forward search for three-byte Hangul character", + [next_match, next, next_match, next_match, next_match], [InRange(19, 22), Rejects(22, 25), InRange(28, 31), InRange(34, 37), Done] ); - search_asserts!(STRESS, '각', "Forward search for three-byte Hangul character; check if next() still works", - [next_match, next, next_match, next, next_match, next, next_match], - [InRange(19, 22), Rejects(22, 25), InRange(28, 31), Rejects(31, 32), InRange(34, 37), Rejects(37, 40), Done] - ); - - search_asserts!(STRESS, 'ก', "Forward search for three-byte Thai character", - [next_match, next, next_match, next, next_match], + search_asserts!( + STRESS, + '각', + "Forward search for three-byte Hangul character; check if next() still works", + [next_match, next, next_match, next, next_match, next, next_match], + [ + InRange(19, 22), + Rejects(22, 25), + InRange(28, 31), + Rejects(31, 32), + InRange(34, 37), + Rejects(37, 40), + Done + ] + ); + + search_asserts!( + STRESS, + 'ก', + "Forward search for three-byte Thai character", + [next_match, next, next_match, next, next_match], [InRange(22, 25), Rejects(25, 28), InRange(40, 43), Rejects(43, 47), Done] ); - search_asserts!(STRESS, 'ก', "Forward search for three-byte Thai character; check if next() still works", - [next_match, next, next_match, next, next_match], + search_asserts!( + STRESS, + 'ก', + "Forward search for three-byte Thai character; check if next() still works", + [next_match, next, next_match, next, next_match], [InRange(22, 25), Rejects(25, 28), InRange(40, 43), Rejects(43, 47), Done] ); - search_asserts!(STRESS, '😁', "Forward search for four-byte emoji", - [next_match, next, next_match, next, next_match], + search_asserts!( + STRESS, + '😁', + "Forward search for four-byte emoji", + [next_match, next, next_match, next, next_match], [InRange(15, 19), Rejects(19, 22), InRange(43, 47), Rejects(47, 48), Done] ); - search_asserts!(STRESS, '😁', "Forward search for four-byte emoji; check if next() still works", - [next_match, next, next_match, next, next_match], + search_asserts!( + STRESS, + '😁', + "Forward search for four-byte emoji; check if next() still works", + [next_match, next, next_match, next, next_match], [InRange(15, 19), Rejects(19, 22), InRange(43, 47), Rejects(47, 48), Done] ); - search_asserts!(STRESS, 'ꁁ', "Forward search for three-byte Yi character with repeated bytes", - [next_match, next, next_match, next, next_match], + search_asserts!( + STRESS, + 'ꁁ', + "Forward search for three-byte Yi character with repeated bytes", + [next_match, next, next_match, next, next_match], [InRange(10, 13), Rejects(13, 14), InRange(37, 40), Rejects(40, 43), Done] ); - search_asserts!(STRESS, 'ꁁ', "Forward search for three-byte Yi character with repeated bytes; check if next() still works", - [next_match, next, next_match, next, next_match], + search_asserts!( + STRESS, + 'ꁁ', + "Forward search for three-byte Yi character with repeated bytes; check if next() still works", + [next_match, next, next_match, next, next_match], [InRange(10, 13), Rejects(13, 14), InRange(37, 40), Rejects(40, 43), Done] ); } #[test] fn test_reverse_search_shared_bytes() { - search_asserts!(STRESS, 'Á', "Reverse search for two-byte Latin character", + search_asserts!( + STRESS, + 'Á', + "Reverse search for two-byte Latin character", [next_match_back, next_match_back, next_match_back, next_match_back], - [InRange(32, 34), InRange(8, 10), InRange(0, 2), Done] - ); - - search_asserts!(STRESS, 'Á', "Reverse search for two-byte Latin character; check if next_back() still works", - [next_match_back, next_back, next_match_back, next_back, next_match_back, next_back], - [InRange(32, 34), Rejects(31, 32), InRange(8, 10), Rejects(7, 8), InRange(0, 2), Done] - ); - - search_asserts!(STRESS, '각', "Reverse search for three-byte Hangul character", - [next_match_back, next_back, next_match_back, next_match_back, next_match_back], - [InRange(34, 37), Rejects(32, 34), InRange(28, 31), InRange(19, 22), Done] - ); - - search_asserts!(STRESS, '각', "Reverse search for three-byte Hangul character; check if next_back() still works", - [next_match_back, next_back, next_match_back, next_back, next_match_back, next_back, next_match_back], - [InRange(34, 37), Rejects(32, 34), InRange(28, 31), Rejects(25, 28), InRange(19, 22), Rejects(15, 19), Done] - ); - - search_asserts!(STRESS, 'ก', "Reverse search for three-byte Thai character", - [next_match_back, next_back, next_match_back, next_back, next_match_back], + [InRange(32, 34), InRange(8, 10), InRange(0, 2), Done] + ); + + search_asserts!( + STRESS, + 'Á', + "Reverse search for two-byte Latin character; check if next_back() still works", + [next_match_back, next_back, next_match_back, next_back, next_match_back, next_back], + [InRange(32, 34), Rejects(31, 32), InRange(8, 10), Rejects(7, 8), InRange(0, 2), Done] + ); + + search_asserts!( + STRESS, + '각', + "Reverse search for three-byte Hangul character", + [next_match_back, next_back, next_match_back, next_match_back, next_match_back], + [InRange(34, 37), Rejects(32, 34), InRange(28, 31), InRange(19, 22), Done] + ); + + search_asserts!( + STRESS, + '각', + "Reverse search for three-byte Hangul character; check if next_back() still works", + [ + next_match_back, + next_back, + next_match_back, + next_back, + next_match_back, + next_back, + next_match_back + ], + [ + InRange(34, 37), + Rejects(32, 34), + InRange(28, 31), + Rejects(25, 28), + InRange(19, 22), + Rejects(15, 19), + Done + ] + ); + + search_asserts!( + STRESS, + 'ก', + "Reverse search for three-byte Thai character", + [next_match_back, next_back, next_match_back, next_back, next_match_back], [InRange(40, 43), Rejects(37, 40), InRange(22, 25), Rejects(19, 22), Done] ); - search_asserts!(STRESS, 'ก', "Reverse search for three-byte Thai character; check if next_back() still works", - [next_match_back, next_back, next_match_back, next_back, next_match_back], + search_asserts!( + STRESS, + 'ก', + "Reverse search for three-byte Thai character; check if next_back() still works", + [next_match_back, next_back, next_match_back, next_back, next_match_back], [InRange(40, 43), Rejects(37, 40), InRange(22, 25), Rejects(19, 22), Done] ); - search_asserts!(STRESS, '😁', "Reverse search for four-byte emoji", - [next_match_back, next_back, next_match_back, next_back, next_match_back], + search_asserts!( + STRESS, + '😁', + "Reverse search for four-byte emoji", + [next_match_back, next_back, next_match_back, next_back, next_match_back], [InRange(43, 47), Rejects(40, 43), InRange(15, 19), Rejects(14, 15), Done] ); - search_asserts!(STRESS, '😁', "Reverse search for four-byte emoji; check if next_back() still works", - [next_match_back, next_back, next_match_back, next_back, next_match_back], + search_asserts!( + STRESS, + '😁', + "Reverse search for four-byte emoji; check if next_back() still works", + [next_match_back, next_back, next_match_back, next_back, next_match_back], [InRange(43, 47), Rejects(40, 43), InRange(15, 19), Rejects(14, 15), Done] ); - search_asserts!(STRESS, 'ꁁ', "Reverse search for three-byte Yi character with repeated bytes", - [next_match_back, next_back, next_match_back, next_back, next_match_back], + search_asserts!( + STRESS, + 'ꁁ', + "Reverse search for three-byte Yi character with repeated bytes", + [next_match_back, next_back, next_match_back, next_back, next_match_back], [InRange(37, 40), Rejects(34, 37), InRange(10, 13), Rejects(8, 10), Done] ); - search_asserts!(STRESS, 'ꁁ', "Reverse search for three-byte Yi character with repeated bytes; check if next_back() still works", - [next_match_back, next_back, next_match_back, next_back, next_match_back], + search_asserts!( + STRESS, + 'ꁁ', + "Reverse search for three-byte Yi character with repeated bytes; check if next_back() still works", + [next_match_back, next_back, next_match_back, next_back, next_match_back], [InRange(37, 40), Rejects(34, 37), InRange(10, 13), Rejects(8, 10), Done] ); } @@ -257,36 +446,60 @@ fn test_reverse_search_shared_bytes() { fn double_ended_regression_test() { // https://github.com/rust-lang/rust/issues/47175 // Ensures that double ended searching comes to a convergence - search_asserts!("abcdeabcdeabcde", 'a', "alternating double ended search", - [next_match, next_match_back, next_match, next_match_back], + search_asserts!( + "abcdeabcdeabcde", + 'a', + "alternating double ended search", + [next_match, next_match_back, next_match, next_match_back], [InRange(0, 1), InRange(10, 11), InRange(5, 6), Done] ); - search_asserts!("abcdeabcdeabcde", 'a', "triple double ended search for a", - [next_match, next_match_back, next_match_back, next_match_back], + search_asserts!( + "abcdeabcdeabcde", + 'a', + "triple double ended search for a", + [next_match, next_match_back, next_match_back, next_match_back], [InRange(0, 1), InRange(10, 11), InRange(5, 6), Done] ); - search_asserts!("abcdeabcdeabcde", 'd', "triple double ended search for d", - [next_match, next_match_back, next_match_back, next_match_back], + search_asserts!( + "abcdeabcdeabcde", + 'd', + "triple double ended search for d", + [next_match, next_match_back, next_match_back, next_match_back], [InRange(3, 4), InRange(13, 14), InRange(8, 9), Done] ); - search_asserts!(STRESS, 'Á', "Double ended search for two-byte Latin character", - [next_match, next_match_back, next_match, next_match_back], + search_asserts!( + STRESS, + 'Á', + "Double ended search for two-byte Latin character", + [next_match, next_match_back, next_match, next_match_back], [InRange(0, 2), InRange(32, 34), InRange(8, 10), Done] ); - search_asserts!(STRESS, '각', "Reverse double ended search for three-byte Hangul character", - [next_match_back, next_back, next_match, next, next_match_back, next_match], + search_asserts!( + STRESS, + '각', + "Reverse double ended search for three-byte Hangul character", + [next_match_back, next_back, next_match, next, next_match_back, next_match], [InRange(34, 37), Rejects(32, 34), InRange(19, 22), Rejects(22, 25), InRange(28, 31), Done] ); - search_asserts!(STRESS, 'ก', "Double ended search for three-byte Thai character", - [next_match, next_back, next, next_match_back, next_match], + search_asserts!( + STRESS, + 'ก', + "Double ended search for three-byte Thai character", + [next_match, next_back, next, next_match_back, next_match], [InRange(22, 25), Rejects(47, 48), Rejects(25, 28), InRange(40, 43), Done] ); - search_asserts!(STRESS, '😁', "Double ended search for four-byte emoji", - [next_match_back, next, next_match, next_back, next_match], + search_asserts!( + STRESS, + '😁', + "Double ended search for four-byte emoji", + [next_match_back, next, next_match, next_back, next_match], [InRange(43, 47), Rejects(0, 2), InRange(15, 19), Rejects(40, 43), Done] ); - search_asserts!(STRESS, 'ꁁ', "Double ended search for three-byte Yi character with repeated bytes", - [next_match, next, next_match_back, next_back, next_match], + search_asserts!( + STRESS, + 'ꁁ', + "Double ended search for three-byte Yi character with repeated bytes", + [next_match, next, next_match_back, next_back, next_match], [InRange(10, 13), Rejects(13, 14), InRange(37, 40), Rejects(34, 37), Done] ); } diff --git a/src/libcore/tests/ptr.rs b/src/libcore/tests/ptr.rs index 473bc881d29..a008b3319f3 100644 --- a/src/libcore/tests/ptr.rs +++ b/src/libcore/tests/ptr.rs @@ -8,7 +8,7 @@ fn test_const_from_raw_parts() { assert_eq!(SLICE, FROM_RAW); let slice = &[1, 2, 3, 4, 5]; - let from_raw = unsafe { &*slice_from_raw_parts(slice.as_ptr(), 2) } ; + let from_raw = unsafe { &*slice_from_raw_parts(slice.as_ptr(), 2) }; assert_eq!(&slice[..2], from_raw); } diff --git a/src/libcore/tests/result.rs b/src/libcore/tests/result.rs index 163f8d0ab37..499a5613bd2 100644 --- a/src/libcore/tests/result.rs +++ b/src/libcore/tests/result.rs @@ -1,31 +1,30 @@ -use core::option::*; use core::array::FixedSizeArray; use core::ops::DerefMut; +use core::option::*; -fn op1() -> Result<isize, &'static str> { Ok(666) } -fn op2() -> Result<isize, &'static str> { Err("sadface") } +fn op1() -> Result<isize, &'static str> { + Ok(666) +} +fn op2() -> Result<isize, &'static str> { + Err("sadface") +} #[test] fn test_and() { assert_eq!(op1().and(Ok(667)).unwrap(), 667); - assert_eq!(op1().and(Err::<i32, &'static str>("bad")).unwrap_err(), - "bad"); + assert_eq!(op1().and(Err::<i32, &'static str>("bad")).unwrap_err(), "bad"); assert_eq!(op2().and(Ok(667)).unwrap_err(), "sadface"); - assert_eq!(op2().and(Err::<i32,&'static str>("bad")).unwrap_err(), - "sadface"); + assert_eq!(op2().and(Err::<i32, &'static str>("bad")).unwrap_err(), "sadface"); } #[test] fn test_and_then() { assert_eq!(op1().and_then(|i| Ok::<isize, &'static str>(i + 1)).unwrap(), 667); - assert_eq!(op1().and_then(|_| Err::<isize, &'static str>("bad")).unwrap_err(), - "bad"); + assert_eq!(op1().and_then(|_| Err::<isize, &'static str>("bad")).unwrap_err(), "bad"); - assert_eq!(op2().and_then(|i| Ok::<isize, &'static str>(i + 1)).unwrap_err(), - "sadface"); - assert_eq!(op2().and_then(|_| Err::<isize, &'static str>("bad")).unwrap_err(), - "sadface"); + assert_eq!(op2().and_then(|i| Ok::<isize, &'static str>(i + 1)).unwrap_err(), "sadface"); + assert_eq!(op2().and_then(|_| Err::<isize, &'static str>("bad")).unwrap_err(), "sadface"); } #[test] @@ -43,8 +42,7 @@ fn test_or_else() { assert_eq!(op1().or_else(|e| Err::<isize, &'static str>(e)).unwrap(), 666); assert_eq!(op2().or_else(|_| Ok::<isize, &'static str>(667)).unwrap(), 667); - assert_eq!(op2().or_else(|e| Err::<isize, &'static str>(e)).unwrap_err(), - "sadface"); + assert_eq!(op2().or_else(|e| Err::<isize, &'static str>(e)).unwrap_err(), "sadface"); } #[test] @@ -67,9 +65,7 @@ fn test_collect() { let v: Result<Vec<isize>, ()> = (0..3).map(|x| Ok::<isize, ()>(x)).collect(); assert!(v == Ok(vec![0, 1, 2])); - let v: Result<Vec<isize>, isize> = (0..3).map(|x| { - if x > 1 { Err(x) } else { Ok(x) } - }).collect(); + let v: Result<Vec<isize>, isize> = (0..3).map(|x| if x > 1 { Err(x) } else { Ok(x) }).collect(); assert!(v == Err(2)); // test that it does not take more elements than it needs @@ -103,11 +99,7 @@ fn test_unwrap_or() { #[test] fn test_unwrap_or_else() { fn handler(msg: &'static str) -> isize { - if msg == "I got this." { - 50 - } else { - panic!("BadBad") - } + if msg == "I got this." { 50 } else { panic!("BadBad") } } let ok: Result<isize, &'static str> = Ok(100); @@ -121,38 +113,32 @@ fn test_unwrap_or_else() { #[should_panic] pub fn test_unwrap_or_else_panic() { fn handler(msg: &'static str) -> isize { - if msg == "I got this." { - 50 - } else { - panic!("BadBad") - } + if msg == "I got this." { 50 } else { panic!("BadBad") } } let bad_err: Result<isize, &'static str> = Err("Unrecoverable mess."); - let _ : isize = bad_err.unwrap_or_else(handler); + let _: isize = bad_err.unwrap_or_else(handler); } - #[test] pub fn test_expect_ok() { let ok: Result<isize, &'static str> = Ok(100); assert_eq!(ok.expect("Unexpected error"), 100); } #[test] -#[should_panic(expected="Got expected error: \"All good\"")] +#[should_panic(expected = "Got expected error: \"All good\"")] pub fn test_expect_err() { let err: Result<isize, &'static str> = Err("All good"); err.expect("Got expected error"); } - #[test] pub fn test_expect_err_err() { let ok: Result<&'static str, isize> = Err(100); assert_eq!(ok.expect_err("Unexpected ok"), 100); } #[test] -#[should_panic(expected="Got expected ok: \"All good\"")] +#[should_panic(expected = "Got expected ok: \"All good\"")] pub fn test_expect_err_ok() { let err: Result<&'static str, isize> = Ok("All good"); err.expect_err("Got expected ok"); |
