}
}
-#[cfg(not(stage0))]
#[stable(feature = "rust1", since = "1.0.0")]
impl BoxAny for Box<Any+Send> {
#[inline]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[cfg(stage0)]
-#[cfg(not(test))]
-use core::ptr::PtrExt;
-
// FIXME: #13996: mark the `allocate` and `reallocate` return value as `noalias`
/// Return a pointer to `size` bytes of memory aligned to `align`.
use core::ops::{Deref, Drop};
use core::option::Option;
use core::option::Option::{Some, None};
-#[cfg(stage0)]
-use core::ptr::{self, PtrExt};
-#[cfg(not(stage0))]
use core::ptr;
use core::result::Result;
use core::result::Result::{Ok, Err};
use std::cell::{Cell, RefCell};
use std::cmp;
use std::intrinsics;
-#[cfg(stage0)] // SNAP 270a677
-use std::intrinsics::{get_tydesc, TyDesc};
use std::marker;
use std::mem;
-#[cfg(stage0)]
-use std::num::{Int, UnsignedInt};
use std::ptr;
use std::rc::Rc;
use std::rt::heap::{allocate, deallocate};
// HACK(eddyb) TyDesc replacement using a trait object vtable.
// This could be replaced in the future with a custom DST layout,
// or `&'static (drop_glue, size, align)` created by a `const fn`.
-#[cfg(not(stage0))] // SNAP 270a677
struct TyDesc {
drop_glue: fn(*const i8),
size: usize,
align: usize
}
-#[cfg(not(stage0))] // SNAP 270a677
unsafe fn get_tydesc<T>() -> *const TyDesc {
use std::raw::TraitObject;
/// Fails if `target_alignment` is not a power of two.
#[inline]
fn round_up_to_next(unrounded: usize, target_alignment: usize) -> usize {
- #[cfg(stage0)]
- use core::num::UnsignedInt;
-
assert!(target_alignment.is_power_of_two());
(unrounded + target_alignment - 1) & !(target_alignment - 1)
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[cfg(stage0)]
-/// Creates a `Vec` containing the arguments.
-///
-/// `vec!` allows `Vec`s to be defined with the same syntax as array expressions.
-/// There are two forms of this macro:
-///
-/// - Create a `Vec` containing a given list of elements:
-///
-/// ```
-/// let v = vec![1, 2, 3];
-/// assert_eq!(v[0], 1);
-/// assert_eq!(v[1], 2);
-/// assert_eq!(v[2], 3);
-/// ```
-///
-/// - Create a `Vec` from a given element and size:
-///
-/// ```
-/// let v = vec![1; 3];
-/// assert_eq!(v, [1, 1, 1]);
-/// ```
-///
-/// Note that unlike array expressions this syntax supports all elements
-/// which implement `Clone` and the number of elements doesn't have to be
-/// a constant.
-#[macro_export]
-#[stable(feature = "rust1", since = "1.0.0")]
-macro_rules! vec {
- ($elem:expr; $n:expr) => (
- $crate::vec::from_elem($elem, $n)
- );
- ($($x:expr),*) => (
- <[_] as $crate::slice::SliceExt>::into_vec(
- $crate::boxed::Box::new([$($x),*]))
- );
- ($($x:expr,)*) => (vec![$($x),*])
-}
-
-#[cfg(not(stage0))]
/// Creates a `Vec` containing the arguments.
///
/// `vec!` allows `Vec`s to be defined with the same syntax as array expressions.
($($x:expr,)*) => (vec![$($x),*])
}
-// HACK(japaric): with cfg(test) the inherent `[T]::into_vec` method, which is required for this
-// macro definition, is not available. Instead use the `slice::into_vec` function which is only
-// available with cfg(test)
+// HACK(japaric): with cfg(test) the inherent `[T]::into_vec` method, which is
+// required for this macro definition, is not available. Instead use the
+// `slice::into_vec` function which is only available with cfg(test)
// NB see the slice::hack module in slice.rs for more information
-#[cfg(not(stage0))]
#[cfg(test)]
macro_rules! vec {
($elem:expr; $n:expr) => (
use core::num::wrapping::WrappingOps;
use core::ops::FnMut;
use core::option::Option::{self, Some, None};
-#[cfg(stage0)]
-use core::ptr::PtrExt;
use core::ptr;
use core::result::Result;
use core::slice as core_slice;
// Basic slice extension methods
////////////////////////////////////////////////////////////////////////////////
-#[cfg(stage0)]
-/// Allocating extension methods for slices.
-#[stable(feature = "rust1", since = "1.0.0")]
-pub trait SliceExt {
- #[stable(feature = "rust1", since = "1.0.0")]
- type Item;
-
- /// Sorts the slice, in place, using `compare` to compare
- /// elements.
- ///
- /// This sort is `O(n log n)` worst-case and stable, but allocates
- /// approximately `2 * n`, where `n` is the length of `self`.
- ///
- /// # Examples
- ///
- /// ```
- /// let mut v = [5, 4, 1, 3, 2];
- /// v.sort_by(|a, b| a.cmp(b));
- /// assert!(v == [1, 2, 3, 4, 5]);
- ///
- /// // reverse sorting
- /// v.sort_by(|a, b| b.cmp(a));
- /// assert!(v == [5, 4, 3, 2, 1]);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn sort_by<F>(&mut self, compare: F) where F: FnMut(&Self::Item, &Self::Item) -> Ordering;
-
- /// Consumes `src` and moves as many elements as it can into `self`
- /// from the range [start,end).
- ///
- /// Returns the number of elements copied (the shorter of `self.len()`
- /// and `end - start`).
- ///
- /// # Arguments
- ///
- /// * src - A mutable vector of `T`
- /// * start - The index into `src` to start copying from
- /// * end - The index into `src` to stop copying from
- ///
- /// # Examples
- ///
- /// ```
- /// let mut a = [1, 2, 3, 4, 5];
- /// let b = vec![6, 7, 8];
- /// let num_moved = a.move_from(b, 0, 3);
- /// assert_eq!(num_moved, 3);
- /// assert!(a == [6, 7, 8, 4, 5]);
- /// ```
- #[unstable(feature = "collections",
- reason = "uncertain about this API approach")]
- fn move_from(&mut self, src: Vec<Self::Item>, start: usize, end: usize) -> usize;
-
- /// Deprecated: use `&s[start .. end]` notation instead.
- #[unstable(feature = "collections",
- reason = "will be replaced by slice syntax")]
- #[deprecated(since = "1.0.0", reason = "use &s[start .. end] instead")]
- fn slice(&self, start: usize, end: usize) -> &[Self::Item];
-
- /// Deprecated: use `&s[start..]` notation instead.
- #[unstable(feature = "collections",
- reason = "will be replaced by slice syntax")]
- #[deprecated(since = "1.0.0", reason = "use &s[start..] instead")]
- fn slice_from(&self, start: usize) -> &[Self::Item];
-
- /// Deprecated: use `&s[..end]` notation instead.
- #[unstable(feature = "collections",
- reason = "will be replaced by slice syntax")]
- #[deprecated(since = "1.0.0", reason = "use &s[..end] instead")]
- fn slice_to(&self, end: usize) -> &[Self::Item];
-
- /// Divides one slice into two at an index.
- ///
- /// The first will contain all indices from `[0, mid)` (excluding
- /// the index `mid` itself) and the second will contain all
- /// indices from `[mid, len)` (excluding the index `len` itself).
- ///
- /// Panics if `mid > len`.
- ///
- /// # Examples
- ///
- /// ```
- /// let v = [10, 40, 30, 20, 50];
- /// let (v1, v2) = v.split_at(2);
- /// assert_eq!([10, 40], v1);
- /// assert_eq!([30, 20, 50], v2);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn split_at(&self, mid: usize) -> (&[Self::Item], &[Self::Item]);
-
- /// Returns an iterator over the slice.
- #[stable(feature = "rust1", since = "1.0.0")]
- fn iter(&self) -> Iter<Self::Item>;
-
- /// Returns an iterator over subslices separated by elements that match
- /// `pred`. The matched element is not contained in the subslices.
- ///
- /// # Examples
- ///
- /// Print the slice split by numbers divisible by 3 (i.e. `[10, 40]`,
- /// `[20]`, `[50]`):
- ///
- /// ```
- /// let v = [10, 40, 30, 20, 60, 50];
- /// for group in v.split(|num| *num % 3 == 0) {
- /// println!("{:?}", group);
- /// }
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn split<F>(&self, pred: F) -> Split<Self::Item, F>
- where F: FnMut(&Self::Item) -> bool;
-
- /// Returns an iterator over subslices separated by elements that match
- /// `pred`, limited to splitting at most `n` times. The matched element is
- /// not contained in the subslices.
- ///
- /// # Examples
- ///
- /// Print the slice split once by numbers divisible by 3 (i.e. `[10, 40]`,
- /// `[20, 60, 50]`):
- ///
- /// ```
- /// let v = [10, 40, 30, 20, 60, 50];
- /// for group in v.splitn(1, |num| *num % 3 == 0) {
- /// println!("{:?}", group);
- /// }
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn splitn<F>(&self, n: usize, pred: F) -> SplitN<Self::Item, F>
- where F: FnMut(&Self::Item) -> bool;
-
- /// Returns an iterator over subslices separated by elements that match
- /// `pred` limited to splitting at most `n` times. This starts at the end of
- /// the slice and works backwards. The matched element is not contained in
- /// the subslices.
- ///
- /// # Examples
- ///
- /// Print the slice split once, starting from the end, by numbers divisible
- /// by 3 (i.e. `[50]`, `[10, 40, 30, 20]`):
- ///
- /// ```
- /// let v = [10, 40, 30, 20, 60, 50];
- /// for group in v.rsplitn(1, |num| *num % 3 == 0) {
- /// println!("{:?}", group);
- /// }
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<Self::Item, F>
- where F: FnMut(&Self::Item) -> bool;
-
- /// Returns an iterator over all contiguous windows of length
- /// `size`. The windows overlap. If the slice is shorter than
- /// `size`, the iterator returns no values.
- ///
- /// # Panics
- ///
- /// Panics if `size` is 0.
- ///
- /// # Examples
- ///
- /// Print the adjacent pairs of a slice (i.e. `[1,2]`, `[2,3]`,
- /// `[3,4]`):
- ///
- /// ```
- /// let v = &[1, 2, 3, 4];
- /// for win in v.windows(2) {
- /// println!("{:?}", win);
- /// }
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn windows(&self, size: usize) -> Windows<Self::Item>;
-
- /// Returns an iterator over `size` elements of the slice at a
- /// time. The chunks do not overlap. If `size` does not divide the
- /// length of the slice, then the last chunk will not have length
- /// `size`.
- ///
- /// # Panics
- ///
- /// Panics if `size` is 0.
- ///
- /// # Examples
- ///
- /// Print the slice two elements at a time (i.e. `[1,2]`,
- /// `[3,4]`, `[5]`):
- ///
- /// ```
- /// let v = &[1, 2, 3, 4, 5];
- /// for win in v.chunks(2) {
- /// println!("{:?}", win);
- /// }
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn chunks(&self, size: usize) -> Chunks<Self::Item>;
-
- /// Returns the element of a slice at the given index, or `None` if the
- /// index is out of bounds.
- ///
- /// # Examples
- ///
- /// ```
- /// let v = [10, 40, 30];
- /// assert_eq!(Some(&40), v.get(1));
- /// assert_eq!(None, v.get(3));
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn get(&self, index: usize) -> Option<&Self::Item>;
-
- /// Returns the first element of a slice, or `None` if it is empty.
- ///
- /// # Examples
- ///
- /// ```
- /// let v = [10, 40, 30];
- /// assert_eq!(Some(&10), v.first());
- ///
- /// let w: &[i32] = &[];
- /// assert_eq!(None, w.first());
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn first(&self) -> Option<&Self::Item>;
-
- /// Returns all but the first element of a slice.
- #[unstable(feature = "collections", reason = "likely to be renamed")]
- fn tail(&self) -> &[Self::Item];
-
- /// Returns all but the last element of a slice.
- #[unstable(feature = "collections", reason = "likely to be renamed")]
- fn init(&self) -> &[Self::Item];
-
- /// Returns the last element of a slice, or `None` if it is empty.
- ///
- /// # Examples
- ///
- /// ```
- /// let v = [10, 40, 30];
- /// assert_eq!(Some(&30), v.last());
- ///
- /// let w: &[i32] = &[];
- /// assert_eq!(None, w.last());
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn last(&self) -> Option<&Self::Item>;
-
- /// Returns a pointer to the element at the given index, without doing
- /// bounds checking.
- #[stable(feature = "rust1", since = "1.0.0")]
- unsafe fn get_unchecked(&self, index: usize) -> &Self::Item;
-
- /// Returns an unsafe pointer to the slice's buffer
- ///
- /// The caller must ensure that the slice outlives the pointer this
- /// function returns, or else it will end up pointing to garbage.
- ///
- /// Modifying the slice may cause its buffer to be reallocated, which
- /// would also make any pointers to it invalid.
- #[stable(feature = "rust1", since = "1.0.0")]
- fn as_ptr(&self) -> *const Self::Item;
-
- /// Binary search a sorted slice with a comparator function.
- ///
- /// The comparator function should implement an order consistent
- /// with the sort order of the underlying slice, returning an
- /// order code that indicates whether its argument is `Less`,
- /// `Equal` or `Greater` the desired target.
- ///
- /// If a matching value is found then returns `Ok`, containing
- /// the index for the matched element; if no match is found then
- /// `Err` is returned, containing the index where a matching
- /// element could be inserted while maintaining sorted order.
- ///
- /// # Examples
- ///
- /// Looks up a series of four elements. The first is found, with a
- /// uniquely determined position; the second and third are not
- /// found; the fourth could match any position in `[1,4]`.
- ///
- /// ```
- /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
- /// let s = s.as_slice();
- ///
- /// let seek = 13;
- /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
- /// let seek = 4;
- /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
- /// let seek = 100;
- /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
- /// let seek = 1;
- /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
- /// assert!(match r { Ok(1...4) => true, _ => false, });
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn binary_search_by<F>(&self, f: F) -> Result<usize, usize> where
- F: FnMut(&Self::Item) -> Ordering;
-
- /// Return the number of elements in the slice
- ///
- /// # Examples
- ///
- /// ```
- /// let a = [1, 2, 3];
- /// assert_eq!(a.len(), 3);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn len(&self) -> usize;
-
- /// Returns true if the slice has a length of 0
- ///
- /// # Examples
- ///
- /// ```
- /// let a = [1, 2, 3];
- /// assert!(!a.is_empty());
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn is_empty(&self) -> bool { self.len() == 0 }
- /// Returns a mutable reference to the element at the given index,
- /// or `None` if the index is out of bounds
- #[stable(feature = "rust1", since = "1.0.0")]
- fn get_mut(&mut self, index: usize) -> Option<&mut Self::Item>;
-
- /// Work with `self` as a mut slice.
- /// Primarily intended for getting a &mut [T] from a [T; N].
- #[stable(feature = "rust1", since = "1.0.0")]
- fn as_mut_slice(&mut self) -> &mut [Self::Item];
-
- /// Deprecated: use `&mut s[start .. end]` instead.
- #[unstable(feature = "collections",
- reason = "will be replaced by slice syntax")]
- #[deprecated(since = "1.0.0", reason = "use &mut s[start .. end] instead")]
- fn slice_mut(&mut self, start: usize, end: usize) -> &mut [Self::Item];
-
- /// Deprecated: use `&mut s[start ..]` instead.
- #[unstable(feature = "collections",
- reason = "will be replaced by slice syntax")]
- #[deprecated(since = "1.0.0", reason = "use &mut s[start ..] instead")]
- fn slice_from_mut(&mut self, start: usize) -> &mut [Self::Item];
-
- /// Deprecated: use `&mut s[.. end]` instead.
- #[unstable(feature = "collections",
- reason = "will be replaced by slice syntax")]
- #[deprecated(since = "1.0.0", reason = "use &mut s[.. end] instead")]
- fn slice_to_mut(&mut self, end: usize) -> &mut [Self::Item];
-
- /// Returns an iterator that allows modifying each value
- #[stable(feature = "rust1", since = "1.0.0")]
- fn iter_mut(&mut self) -> IterMut<Self::Item>;
-
- /// Returns a mutable pointer to the first element of a slice, or `None` if it is empty
- #[stable(feature = "rust1", since = "1.0.0")]
- fn first_mut(&mut self) -> Option<&mut Self::Item>;
-
- /// Returns all but the first element of a mutable slice
- #[unstable(feature = "collections",
- reason = "likely to be renamed or removed")]
- fn tail_mut(&mut self) -> &mut [Self::Item];
-
- /// Returns all but the last element of a mutable slice
- #[unstable(feature = "collections",
- reason = "likely to be renamed or removed")]
- fn init_mut(&mut self) -> &mut [Self::Item];
-
- /// Returns a mutable pointer to the last item in the slice.
- #[stable(feature = "rust1", since = "1.0.0")]
- fn last_mut(&mut self) -> Option<&mut Self::Item>;
-
- /// Returns an iterator over mutable subslices separated by elements that
- /// match `pred`. The matched element is not contained in the subslices.
- #[stable(feature = "rust1", since = "1.0.0")]
- fn split_mut<F>(&mut self, pred: F) -> SplitMut<Self::Item, F>
- where F: FnMut(&Self::Item) -> bool;
-
- /// Returns an iterator over subslices separated by elements that match
- /// `pred`, limited to splitting at most `n` times. The matched element is
- /// not contained in the subslices.
- #[stable(feature = "rust1", since = "1.0.0")]
- fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<Self::Item, F>
- where F: FnMut(&Self::Item) -> bool;
-
- /// Returns an iterator over subslices separated by elements that match
- /// `pred` limited to splitting at most `n` times. This starts at the end of
- /// the slice and works backwards. The matched element is not contained in
- /// the subslices.
- #[stable(feature = "rust1", since = "1.0.0")]
- fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<Self::Item, F>
- where F: FnMut(&Self::Item) -> bool;
-
- /// Returns an iterator over `chunk_size` elements of the slice at a time.
- /// The chunks are mutable and do not overlap. If `chunk_size` does
- /// not divide the length of the slice, then the last chunk will not
- /// have length `chunk_size`.
- ///
- /// # Panics
- ///
- /// Panics if `chunk_size` is 0.
- #[stable(feature = "rust1", since = "1.0.0")]
- fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<Self::Item>;
-
- /// Swaps two elements in a slice.
- ///
- /// # Arguments
- ///
- /// * a - The index of the first element
- /// * b - The index of the second element
- ///
- /// # Panics
- ///
- /// Panics if `a` or `b` are out of bounds.
- ///
- /// # Examples
- ///
- /// ```
- /// let mut v = ["a", "b", "c", "d"];
- /// v.swap(1, 3);
- /// assert!(v == ["a", "d", "c", "b"]);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn swap(&mut self, a: usize, b: usize);
-
- /// Divides one `&mut` into two at an index.
- ///
- /// The first will contain all indices from `[0, mid)` (excluding
- /// the index `mid` itself) and the second will contain all
- /// indices from `[mid, len)` (excluding the index `len` itself).
- ///
- /// # Panics
- ///
- /// Panics if `mid > len`.
- ///
- /// # Examples
- ///
- /// ```
- /// let mut v = [1, 2, 3, 4, 5, 6];
- ///
- /// // scoped to restrict the lifetime of the borrows
- /// {
- /// let (left, right) = v.split_at_mut(0);
- /// assert!(left == []);
- /// assert!(right == [1, 2, 3, 4, 5, 6]);
- /// }
- ///
- /// {
- /// let (left, right) = v.split_at_mut(2);
- /// assert!(left == [1, 2]);
- /// assert!(right == [3, 4, 5, 6]);
- /// }
- ///
- /// {
- /// let (left, right) = v.split_at_mut(6);
- /// assert!(left == [1, 2, 3, 4, 5, 6]);
- /// assert!(right == []);
- /// }
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn split_at_mut(&mut self, mid: usize) -> (&mut [Self::Item], &mut [Self::Item]);
-
- /// Reverse the order of elements in a slice, in place.
- ///
- /// # Examples
- ///
- /// ```
- /// let mut v = [1, 2, 3];
- /// v.reverse();
- /// assert!(v == [3, 2, 1]);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn reverse(&mut self);
-
- /// Returns an unsafe mutable pointer to the element in index
- #[stable(feature = "rust1", since = "1.0.0")]
- unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut Self::Item;
-
- /// Return an unsafe mutable pointer to the slice's buffer.
- ///
- /// The caller must ensure that the slice outlives the pointer this
- /// function returns, or else it will end up pointing to garbage.
- ///
- /// Modifying the slice may cause its buffer to be reallocated, which
- /// would also make any pointers to it invalid.
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn as_mut_ptr(&mut self) -> *mut Self::Item;
-
- /// Copies `self` into a new `Vec`.
- #[stable(feature = "rust1", since = "1.0.0")]
- fn to_vec(&self) -> Vec<Self::Item> where Self::Item: Clone;
-
- /// Creates an iterator that yields every possible permutation of the
- /// vector in succession.
- ///
- /// # Examples
- ///
- /// ```
- /// let v = [1, 2, 3];
- /// let mut perms = v.permutations();
- ///
- /// for p in perms {
- /// println!("{:?}", p);
- /// }
- /// ```
- ///
- /// Iterating through permutations one by one.
- ///
- /// ```
- /// let v = [1, 2, 3];
- /// let mut perms = v.permutations();
- ///
- /// assert_eq!(Some(vec![1, 2, 3]), perms.next());
- /// assert_eq!(Some(vec![1, 3, 2]), perms.next());
- /// assert_eq!(Some(vec![3, 1, 2]), perms.next());
- /// ```
- #[unstable(feature = "collections")]
- fn permutations(&self) -> Permutations<Self::Item> where Self::Item: Clone;
-
- /// Copies as many elements from `src` as it can into `self` (the
- /// shorter of `self.len()` and `src.len()`). Returns the number
- /// of elements copied.
- ///
- /// # Examples
- ///
- /// ```
- /// let mut dst = [0, 0, 0];
- /// let src = [1, 2];
- ///
- /// assert!(dst.clone_from_slice(&src) == 2);
- /// assert!(dst == [1, 2, 0]);
- ///
- /// let src2 = [3, 4, 5, 6];
- /// assert!(dst.clone_from_slice(&src2) == 3);
- /// assert!(dst == [3, 4, 5]);
- /// ```
- #[unstable(feature = "collections")]
- fn clone_from_slice(&mut self, &[Self::Item]) -> usize where Self::Item: Clone;
-
- /// Sorts the slice, in place.
- ///
- /// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`.
- ///
- /// # Examples
- ///
- /// ```
- /// let mut v = [-5, 4, 1, -3, 2];
- ///
- /// v.sort();
- /// assert!(v == [-5, -3, 1, 2, 4]);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn sort(&mut self) where Self::Item: Ord;
-
- /// Binary search a sorted slice for a given element.
- ///
- /// If the value is found then `Ok` is returned, containing the
- /// index of the matching element; if the value is not found then
- /// `Err` is returned, containing the index where a matching
- /// element could be inserted while maintaining sorted order.
- ///
- /// # Examples
- ///
- /// Looks up a series of four elements. The first is found, with a
- /// uniquely determined position; the second and third are not
- /// found; the fourth could match any position in `[1,4]`.
- ///
- /// ```
- /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
- /// let s = s.as_slice();
- ///
- /// assert_eq!(s.binary_search(&13), Ok(9));
- /// assert_eq!(s.binary_search(&4), Err(7));
- /// assert_eq!(s.binary_search(&100), Err(13));
- /// let r = s.binary_search(&1);
- /// assert!(match r { Ok(1...4) => true, _ => false, });
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn binary_search(&self, x: &Self::Item) -> Result<usize, usize> where Self::Item: Ord;
-
- /// Deprecated: use `binary_search` instead.
- #[unstable(feature = "collections")]
- #[deprecated(since = "1.0.0", reason = "use binary_search instead")]
- fn binary_search_elem(&self, x: &Self::Item) -> Result<usize, usize> where Self::Item: Ord {
- self.binary_search(x)
- }
-
- /// Mutates the slice to the next lexicographic permutation.
- ///
- /// Returns `true` if successful and `false` if the slice is at the
- /// last-ordered permutation.
- ///
- /// # Examples
- ///
- /// ```
- /// let v: &mut [_] = &mut [0, 1, 2];
- /// v.next_permutation();
- /// let b: &mut [_] = &mut [0, 2, 1];
- /// assert!(v == b);
- /// v.next_permutation();
- /// let b: &mut [_] = &mut [1, 0, 2];
- /// assert!(v == b);
- /// ```
- #[unstable(feature = "collections",
- reason = "uncertain if this merits inclusion in std")]
- fn next_permutation(&mut self) -> bool where Self::Item: Ord;
-
- /// Mutates the slice to the previous lexicographic permutation.
- ///
- /// Returns `true` if successful and `false` if the slice is at the
- /// first-ordered permutation.
- ///
- /// # Examples
- ///
- /// ```
- /// let v: &mut [_] = &mut [1, 0, 2];
- /// v.prev_permutation();
- /// let b: &mut [_] = &mut [0, 2, 1];
- /// assert!(v == b);
- /// v.prev_permutation();
- /// let b: &mut [_] = &mut [0, 1, 2];
- /// assert!(v == b);
- /// ```
- #[unstable(feature = "collections",
- reason = "uncertain if this merits inclusion in std")]
- fn prev_permutation(&mut self) -> bool where Self::Item: Ord;
-
- /// Find the first index containing a matching value.
- #[unstable(feature = "collections")]
- fn position_elem(&self, t: &Self::Item) -> Option<usize> where Self::Item: PartialEq;
-
- /// Find the last index containing a matching value.
- #[unstable(feature = "collections")]
- fn rposition_elem(&self, t: &Self::Item) -> Option<usize> where Self::Item: PartialEq;
-
- /// Returns true if the slice contains an element with the given value.
- ///
- /// # Examples
- ///
- /// ```
- /// let v = [10, 40, 30];
- /// assert!(v.contains(&30));
- /// assert!(!v.contains(&50));
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn contains(&self, x: &Self::Item) -> bool where Self::Item: PartialEq;
-
- /// Returns true if `needle` is a prefix of the slice.
- ///
- /// # Examples
- ///
- /// ```
- /// let v = [10, 40, 30];
- /// assert!(v.starts_with(&[10]));
- /// assert!(v.starts_with(&[10, 40]));
- /// assert!(!v.starts_with(&[50]));
- /// assert!(!v.starts_with(&[10, 50]));
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn starts_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
-
- /// Returns true if `needle` is a suffix of the slice.
- ///
- /// # Examples
- ///
- /// ```
- /// let v = [10, 40, 30];
- /// assert!(v.ends_with(&[30]));
- /// assert!(v.ends_with(&[40, 30]));
- /// assert!(!v.ends_with(&[50]));
- /// assert!(!v.ends_with(&[50, 30]));
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn ends_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
-
- /// Convert `self` into a vector without clones or allocation.
- #[stable(feature = "rust1", since = "1.0.0")]
- fn into_vec(self: Box<Self>) -> Vec<Self::Item>;
-}
-
-#[cfg(stage0)]
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<T> SliceExt for [T] {
- type Item = T;
-
- #[inline]
- fn sort_by<F>(&mut self, compare: F) where F: FnMut(&T, &T) -> Ordering {
- merge_sort(self, compare)
- }
-
- #[inline]
- fn move_from(&mut self, mut src: Vec<T>, start: usize, end: usize) -> usize {
- for (a, b) in self.iter_mut().zip(src[start .. end].iter_mut()) {
- mem::swap(a, b);
- }
- cmp::min(self.len(), end-start)
- }
-
- #[inline]
- fn slice(&self, start: usize, end: usize) -> &[T] {
- &self[start .. end]
- }
-
- #[inline]
- fn slice_from(&self, start: usize) -> &[T] {
- &self[start ..]
- }
-
- #[inline]
- fn slice_to(&self, end: usize) -> &[T] {
- &self[.. end]
- }
-
- #[inline]
- fn split_at(&self, mid: usize) -> (&[T], &[T]) {
- core_slice::SliceExt::split_at(self, mid)
- }
-
- #[inline]
- fn iter(&self) -> Iter<T> {
- core_slice::SliceExt::iter(self)
- }
-
- #[inline]
- fn split<F>(&self, pred: F) -> Split<T, F>
- where F: FnMut(&T) -> bool {
- core_slice::SliceExt::split(self, pred)
- }
-
- #[inline]
- fn splitn<F>(&self, n: usize, pred: F) -> SplitN<T, F>
- where F: FnMut(&T) -> bool {
- core_slice::SliceExt::splitn(self, n, pred)
- }
-
- #[inline]
- fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<T, F>
- where F: FnMut(&T) -> bool {
- core_slice::SliceExt::rsplitn(self, n, pred)
- }
-
- #[inline]
- fn windows(&self, size: usize) -> Windows<T> {
- core_slice::SliceExt::windows(self, size)
- }
-
- #[inline]
- fn chunks(&self, size: usize) -> Chunks<T> {
- core_slice::SliceExt::chunks(self, size)
- }
-
- #[inline]
- fn get(&self, index: usize) -> Option<&T> {
- core_slice::SliceExt::get(self, index)
- }
-
- #[inline]
- fn first(&self) -> Option<&T> {
- core_slice::SliceExt::first(self)
- }
-
- #[inline]
- fn tail(&self) -> &[T] {
- core_slice::SliceExt::tail(self)
- }
-
- #[inline]
- fn init(&self) -> &[T] {
- core_slice::SliceExt::init(self)
- }
-
- #[inline]
- fn last(&self) -> Option<&T> {
- core_slice::SliceExt::last(self)
- }
-
- #[inline]
- unsafe fn get_unchecked(&self, index: usize) -> &T {
- core_slice::SliceExt::get_unchecked(self, index)
- }
-
- #[inline]
- fn as_ptr(&self) -> *const T {
- core_slice::SliceExt::as_ptr(self)
- }
-
- #[inline]
- fn binary_search_by<F>(&self, f: F) -> Result<usize, usize>
- where F: FnMut(&T) -> Ordering {
- core_slice::SliceExt::binary_search_by(self, f)
- }
-
- #[inline]
- fn len(&self) -> usize {
- core_slice::SliceExt::len(self)
- }
-
- #[inline]
- fn is_empty(&self) -> bool {
- core_slice::SliceExt::is_empty(self)
- }
-
- #[inline]
- fn get_mut(&mut self, index: usize) -> Option<&mut T> {
- core_slice::SliceExt::get_mut(self, index)
- }
-
- #[inline]
- fn as_mut_slice(&mut self) -> &mut [T] {
- core_slice::SliceExt::as_mut_slice(self)
- }
-
- #[inline]
- fn slice_mut(&mut self, start: usize, end: usize) -> &mut [T] {
- &mut self[start .. end]
- }
-
- #[inline]
- fn slice_from_mut(&mut self, start: usize) -> &mut [T] {
- &mut self[start ..]
- }
-
- #[inline]
- fn slice_to_mut(&mut self, end: usize) -> &mut [T] {
- &mut self[.. end]
- }
-
- #[inline]
- fn iter_mut(&mut self) -> IterMut<T> {
- core_slice::SliceExt::iter_mut(self)
- }
-
- #[inline]
- fn first_mut(&mut self) -> Option<&mut T> {
- core_slice::SliceExt::first_mut(self)
- }
-
- #[inline]
- fn tail_mut(&mut self) -> &mut [T] {
- core_slice::SliceExt::tail_mut(self)
- }
-
- #[inline]
- fn init_mut(&mut self) -> &mut [T] {
- core_slice::SliceExt::init_mut(self)
- }
-
- #[inline]
- fn last_mut(&mut self) -> Option<&mut T> {
- core_slice::SliceExt::last_mut(self)
- }
-
- #[inline]
- fn split_mut<F>(&mut self, pred: F) -> SplitMut<T, F>
- where F: FnMut(&T) -> bool {
- core_slice::SliceExt::split_mut(self, pred)
- }
-
- #[inline]
- fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<T, F>
- where F: FnMut(&T) -> bool {
- core_slice::SliceExt::splitn_mut(self, n, pred)
- }
-
- #[inline]
- fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<T, F>
- where F: FnMut(&T) -> bool {
- core_slice::SliceExt::rsplitn_mut(self, n, pred)
- }
-
- #[inline]
- fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
- core_slice::SliceExt::chunks_mut(self, chunk_size)
- }
-
- #[inline]
- fn swap(&mut self, a: usize, b: usize) {
- core_slice::SliceExt::swap(self, a, b)
- }
-
- #[inline]
- fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
- core_slice::SliceExt::split_at_mut(self, mid)
- }
-
- #[inline]
- fn reverse(&mut self) {
- core_slice::SliceExt::reverse(self)
- }
-
- #[inline]
- unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
- core_slice::SliceExt::get_unchecked_mut(self, index)
- }
-
- #[inline]
- fn as_mut_ptr(&mut self) -> *mut T {
- core_slice::SliceExt::as_mut_ptr(self)
- }
-
- /// Returns a copy of `v`.
- #[inline]
- fn to_vec(&self) -> Vec<T> where T: Clone {
- let mut vector = Vec::with_capacity(self.len());
- vector.push_all(self);
- vector
- }
-
- /// Returns an iterator over all permutations of a vector.
- fn permutations(&self) -> Permutations<T> where T: Clone {
- Permutations{
- swaps: ElementSwaps::new(self.len()),
- v: self.to_vec(),
- }
- }
-
- fn clone_from_slice(&mut self, src: &[T]) -> usize where T: Clone {
- core_slice::SliceExt::clone_from_slice(self, src)
- }
-
- #[inline]
- fn sort(&mut self) where T: Ord {
- self.sort_by(|a, b| a.cmp(b))
- }
-
- fn binary_search(&self, x: &T) -> Result<usize, usize> where T: Ord {
- core_slice::SliceExt::binary_search(self, x)
- }
-
- fn next_permutation(&mut self) -> bool where T: Ord {
- core_slice::SliceExt::next_permutation(self)
- }
-
- fn prev_permutation(&mut self) -> bool where T: Ord {
- core_slice::SliceExt::prev_permutation(self)
- }
-
- fn position_elem(&self, t: &T) -> Option<usize> where T: PartialEq {
- core_slice::SliceExt::position_elem(self, t)
- }
-
- fn rposition_elem(&self, t: &T) -> Option<usize> where T: PartialEq {
- core_slice::SliceExt::rposition_elem(self, t)
- }
-
- fn contains(&self, x: &T) -> bool where T: PartialEq {
- core_slice::SliceExt::contains(self, x)
- }
-
- fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq {
- core_slice::SliceExt::starts_with(self, needle)
- }
-
- fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq {
- core_slice::SliceExt::ends_with(self, needle)
- }
-
- fn into_vec(mut self: Box<Self>) -> Vec<T> {
- unsafe {
- let xs = Vec::from_raw_parts(self.as_mut_ptr(), self.len(), self.len());
- mem::forget(self);
- xs
- }
- }
-}
-
// HACK(japaric) needed for the implementation of `vec!` macro during testing
// NB see the hack module in this file for more details
-#[cfg(not(stage0))]
#[cfg(test)]
pub use self::hack::into_vec;
// HACK(japaric) needed for the implementation of `Vec::clone` during testing
// NB see the hack module in this file for more details
-#[cfg(not(stage0))]
#[cfg(test)]
pub use self::hack::to_vec;
-// HACK(japaric): With cfg(test) `impl [T]` is not available, these three functions are actually
-// methods that are in `impl [T]` but not in `core::slice::SliceExt` - we need to supply these
-// functions for the `test_permutations` test
-#[cfg(not(stage0))]
+// HACK(japaric): With cfg(test) `impl [T]` is not available, these three
+// functions are actually methods that are in `impl [T]` but not in
+// `core::slice::SliceExt` - we need to supply these functions for the
+// `test_permutations` test
mod hack {
use alloc::boxed::Box;
use core::clone::Clone;
vector
}
- // NB we can remove this hack if we move this test to libcollectionstest - but that can't be
- // done right now because the test needs access to the private fields of Permutations
+ // NB we can remove this hack if we move this test to libcollectionstest -
+ // but that can't be done right now because the test needs access to the
+ // private fields of Permutations
#[test]
fn test_permutations() {
{
}
}
-#[cfg(not(stage0))]
/// Allocating extension methods for slices.
#[lang = "slice"]
#[cfg(not(test))]
use core::clone::Clone;
use core::iter::AdditiveIterator;
use core::iter::{Iterator, IteratorExt, Extend};
-#[cfg(stage0)]
-use core::ops::Index;
-#[cfg(stage0)]
-use core::ops::RangeFull;
use core::option::Option::{self, Some, None};
use core::result::Result;
use core::slice::AsSlice;
use core::str as core_str;
-#[cfg(stage0)]
-use unicode::char::CharExt;
use unicode::str::{UnicodeStr, Utf16Encoder};
use vec_deque::VecDeque;
use borrow::{Borrow, ToOwned};
-#[cfg(stage0)]
-use slice::SliceExt;
use string::String;
use unicode;
use vec::Vec;
Section: Trait implementations
*/
-#[cfg(stage0)]
-/// Any string that can be represented as a slice.
-#[stable(feature = "rust1", since = "1.0.0")]
-pub trait StrExt: Index<RangeFull, Output = str> {
- /// Escapes each char in `s` with `char::escape_default`.
- #[unstable(feature = "collections",
- reason = "return type may change to be an iterator")]
- fn escape_default(&self) -> String {
- self.chars().flat_map(|c| c.escape_default()).collect()
- }
-
- /// Escapes each char in `s` with `char::escape_unicode`.
- #[unstable(feature = "collections",
- reason = "return type may change to be an iterator")]
- fn escape_unicode(&self) -> String {
- self.chars().flat_map(|c| c.escape_unicode()).collect()
- }
-
- /// Replaces all occurrences of one string with another.
- ///
- /// `replace` takes two arguments, a sub-`&str` to find in `self`, and a second `&str` to
- /// replace it with. If the original `&str` isn't found, no change occurs.
- ///
- /// # Examples
- ///
- /// ```
- /// let s = "this is old";
- ///
- /// assert_eq!(s.replace("old", "new"), "this is new");
- /// ```
- ///
- /// When a `&str` isn't found:
- ///
- /// ```
- /// let s = "this is old";
- /// assert_eq!(s.replace("cookie monster", "little lamb"), s);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn replace(&self, from: &str, to: &str) -> String {
- let mut result = String::new();
- let mut last_end = 0;
- for (start, end) in self.match_indices(from) {
- result.push_str(unsafe { self.slice_unchecked(last_end, start) });
- result.push_str(to);
- last_end = end;
- }
- result.push_str(unsafe { self.slice_unchecked(last_end, self.len()) });
- result
- }
-
- /// Returns an iterator over the string in Unicode Normalization Form D
- /// (canonical decomposition).
- #[inline]
- #[unstable(feature = "unicode",
- reason = "this functionality may be replaced with a more generic \
- unicode crate on crates.io")]
- fn nfd_chars(&self) -> Decompositions {
- Decompositions {
- iter: self[..].chars(),
- buffer: Vec::new(),
- sorted: false,
- kind: Canonical
- }
- }
-
- /// Returns an iterator over the string in Unicode Normalization Form KD
- /// (compatibility decomposition).
- #[inline]
- #[unstable(feature = "unicode",
- reason = "this functionality may be replaced with a more generic \
- unicode crate on crates.io")]
- fn nfkd_chars(&self) -> Decompositions {
- Decompositions {
- iter: self[..].chars(),
- buffer: Vec::new(),
- sorted: false,
- kind: Compatible
- }
- }
-
- /// An Iterator over the string in Unicode Normalization Form C
- /// (canonical decomposition followed by canonical composition).
- #[inline]
- #[unstable(feature = "unicode",
- reason = "this functionality may be replaced with a more generic \
- unicode crate on crates.io")]
- fn nfc_chars(&self) -> Recompositions {
- Recompositions {
- iter: self.nfd_chars(),
- state: Composing,
- buffer: VecDeque::new(),
- composee: None,
- last_ccc: None
- }
- }
-
- /// An Iterator over the string in Unicode Normalization Form KC
- /// (compatibility decomposition followed by canonical composition).
- #[inline]
- #[unstable(feature = "unicode",
- reason = "this functionality may be replaced with a more generic \
- unicode crate on crates.io")]
- fn nfkc_chars(&self) -> Recompositions {
- Recompositions {
- iter: self.nfkd_chars(),
- state: Composing,
- buffer: VecDeque::new(),
- composee: None,
- last_ccc: None
- }
- }
-
- /// Returns `true` if `self` contains another `&str`.
- ///
- /// # Examples
- ///
- /// ```
- /// assert!("bananas".contains("nana"));
- ///
- /// assert!(!"bananas".contains("foobar"));
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn contains<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
- core_str::StrExt::contains(&self[..], pat)
- }
-
- /// Returns `true` if `self` contains a `char`.
- ///
- /// # Examples
- ///
- /// ```
- /// assert!("hello".contains_char('e'));
- ///
- /// assert!(!"hello".contains_char('z'));
- /// ```
- #[unstable(feature = "collections")]
- #[deprecated(since = "1.0.0", reason = "use `contains()` with a char")]
- fn contains_char<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
- core_str::StrExt::contains_char(&self[..], pat)
- }
-
- /// An iterator over the codepoints of `self`.
- ///
- /// # Examples
- ///
- /// ```
- /// let v: Vec<char> = "abc åäö".chars().collect();
- ///
- /// assert_eq!(v, ['a', 'b', 'c', ' ', 'å', 'ä', 'ö']);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn chars(&self) -> Chars {
- core_str::StrExt::chars(&self[..])
- }
-
- /// An iterator over the bytes of `self`.
- ///
- /// # Examples
- ///
- /// ```
- /// let v: Vec<u8> = "bors".bytes().collect();
- ///
- /// assert_eq!(v, b"bors".to_vec());
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn bytes(&self) -> Bytes {
- core_str::StrExt::bytes(&self[..])
- }
-
- /// An iterator over the characters of `self` and their byte offsets.
- ///
- /// # Examples
- ///
- /// ```
- /// let v: Vec<(usize, char)> = "abc".char_indices().collect();
- /// let b = vec![(0, 'a'), (1, 'b'), (2, 'c')];
- ///
- /// assert_eq!(v, b);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn char_indices(&self) -> CharIndices {
- core_str::StrExt::char_indices(&self[..])
- }
-
- /// An iterator over substrings of `self`, separated by characters
- /// matched by a pattern.
- ///
- /// The pattern can be a simple `&str`, or a closure that determines
- /// the split.
- ///
- /// # Examples
- ///
- /// Simple `&str` patterns:
- ///
- /// ```
- /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
- /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
- ///
- /// let v: Vec<&str> = "".split('X').collect();
- /// assert_eq!(v, [""]);
- /// ```
- ///
- /// More complex patterns with a lambda:
- ///
- /// ```
- /// let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_numeric()).collect();
- /// assert_eq!(v, ["abc", "def", "ghi"]);
- ///
- /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
- /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> {
- core_str::StrExt::split(&self[..], pat)
- }
-
- /// An iterator over substrings of `self`, separated by characters matched by a pattern,
- /// restricted to splitting at most `count` times.
- ///
- /// The pattern can be a simple `&str`, or a closure that determines
- /// the split.
- ///
- /// # Examples
- ///
- /// Simple `&str` patterns:
- ///
- /// ```
- /// let v: Vec<&str> = "Mary had a little lambda".splitn(2, ' ').collect();
- /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
- ///
- /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(2, 'X').collect();
- /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
- ///
- /// let v: Vec<&str> = "abcXdef".splitn(0, 'X').collect();
- /// assert_eq!(v, ["abcXdef"]);
- ///
- /// let v: Vec<&str> = "".splitn(1, 'X').collect();
- /// assert_eq!(v, [""]);
- /// ```
- ///
- /// More complex patterns with a lambda:
- ///
- /// ```
- /// let v: Vec<&str> = "abc1def2ghi".splitn(1, |c: char| c.is_numeric()).collect();
- /// assert_eq!(v, ["abc", "def2ghi"]);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P> {
- core_str::StrExt::splitn(&self[..], count, pat)
- }
-
- /// An iterator over substrings of `self`, separated by characters
- /// matched by a pattern.
- ///
- /// Equivalent to `split`, except that the trailing substring is skipped if empty.
- ///
- /// The pattern can be a simple `&str`, or a closure that determines
- /// the split.
- ///
- /// # Examples
- ///
- /// Simple `&str` patterns:
- ///
- /// ```
- /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
- /// assert_eq!(v, ["A", "B"]);
- ///
- /// let v: Vec<&str> = "A..B..".split_terminator('.').collect();
- /// assert_eq!(v, ["A", "", "B", ""]);
- /// ```
- ///
- /// More complex patterns with a lambda:
- ///
- /// ```
- /// let v: Vec<&str> = "abc1def2ghi3".split_terminator(|c: char| c.is_numeric()).collect();
- /// assert_eq!(v, ["abc", "def", "ghi"]);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P> {
- core_str::StrExt::split_terminator(&self[..], pat)
- }
-
- /// An iterator over substrings of `self`, separated by characters matched by a pattern,
- /// starting from the end of the string.
- ///
- /// Restricted to splitting at most `count` times.
- ///
- /// The pattern can be a simple `&str`, or a closure that determines the split.
- ///
- /// # Examples
- ///
- /// Simple `&str` patterns:
- ///
- /// ```
- /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(2, ' ').collect();
- /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
- ///
- /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(2, 'X').collect();
- /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
- /// ```
- ///
- /// More complex patterns with a lambda:
- ///
- /// ```
- /// let v: Vec<&str> = "abc1def2ghi".rsplitn(1, |c: char| c.is_numeric()).collect();
- /// assert_eq!(v, ["ghi", "abc1def"]);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P> {
- core_str::StrExt::rsplitn(&self[..], count, pat)
- }
-
- /// An iterator over the start and end indices of the disjoint matches of a `&str` within
- /// `self`.
- ///
- /// That is, each returned value `(start, end)` satisfies `self.slice(start, end) == sep`. For
- /// matches of `sep` within `self` that overlap, only the indices corresponding to the first
- /// match are returned.
- ///
- /// # Examples
- ///
- /// ```
- /// let v: Vec<(usize, usize)> = "abcXXXabcYYYabc".match_indices("abc").collect();
- /// assert_eq!(v, [(0,3), (6,9), (12,15)]);
- ///
- /// let v: Vec<(usize, usize)> = "1abcabc2".match_indices("abc").collect();
- /// assert_eq!(v, [(1,4), (4,7)]);
- ///
- /// let v: Vec<(usize, usize)> = "ababa".match_indices("aba").collect();
- /// assert_eq!(v, [(0, 3)]); // only the first `aba`
- /// ```
- #[unstable(feature = "collections",
- reason = "might have its iterator type changed")]
- // NB: Right now MatchIndices yields `(usize, usize)`,
- // but it would be more consistent and useful to return `(usize, &str)`
- fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
- core_str::StrExt::match_indices(&self[..], pat)
- }
-
- /// An iterator over the substrings of `self` separated by a `&str`.
- ///
- /// # Examples
- ///
- /// ```
- /// let v: Vec<&str> = "abcXXXabcYYYabc".split_str("abc").collect();
- /// assert_eq!(v, ["", "XXX", "YYY", ""]);
- ///
- /// let v: Vec<&str> = "1abcabc2".split_str("abc").collect();
- /// assert_eq!(v, ["1", "", "2"]);
- /// ```
- #[unstable(feature = "collections")]
- #[deprecated(since = "1.0.0", reason = "use `split()` with a `&str`")]
- #[allow(deprecated) /* for SplitStr */]
- fn split_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitStr<'a, P> {
- core_str::StrExt::split_str(&self[..], pat)
- }
-
- /// An iterator over the lines of a string, separated by `\n`.
- ///
- /// This does not include the empty string after a trailing `\n`.
- ///
- /// # Examples
- ///
- /// ```
- /// let four_lines = "foo\nbar\n\nbaz";
- /// let v: Vec<&str> = four_lines.lines().collect();
- ///
- /// assert_eq!(v, ["foo", "bar", "", "baz"]);
- /// ```
- ///
- /// Leaving off the trailing character:
- ///
- /// ```
- /// let four_lines = "foo\nbar\n\nbaz\n";
- /// let v: Vec<&str> = four_lines.lines().collect();
- ///
- /// assert_eq!(v, ["foo", "bar", "", "baz"]);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn lines(&self) -> Lines {
- core_str::StrExt::lines(&self[..])
- }
-
- /// An iterator over the lines of a string, separated by either `\n` or `\r\n`.
- ///
- /// As with `.lines()`, this does not include an empty trailing line.
- ///
- /// # Examples
- ///
- /// ```
- /// let four_lines = "foo\r\nbar\n\r\nbaz";
- /// let v: Vec<&str> = four_lines.lines_any().collect();
- ///
- /// assert_eq!(v, ["foo", "bar", "", "baz"]);
- /// ```
- ///
- /// Leaving off the trailing character:
- ///
- /// ```
- /// let four_lines = "foo\r\nbar\n\r\nbaz\n";
- /// let v: Vec<&str> = four_lines.lines_any().collect();
- ///
- /// assert_eq!(v, ["foo", "bar", "", "baz"]);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn lines_any(&self) -> LinesAny {
- core_str::StrExt::lines_any(&self[..])
- }
-
- /// Deprecated: use `s[a .. b]` instead.
- #[unstable(feature = "collections",
- reason = "use slice notation [a..b] instead")]
- #[deprecated(since = "1.0.0", reason = "use slice notation [a..b] instead")]
- fn slice(&self, begin: usize, end: usize) -> &str;
-
- /// Deprecated: use `s[a..]` instead.
- #[unstable(feature = "collections",
- reason = "use slice notation [a..b] instead")]
- #[deprecated(since = "1.0.0", reason = "use slice notation [a..] instead")]
- fn slice_from(&self, begin: usize) -> &str;
-
- /// Deprecated: use `s[..a]` instead.
- #[unstable(feature = "collections",
- reason = "use slice notation [a..b] instead")]
- #[deprecated(since = "1.0.0", reason = "use slice notation [..a] instead")]
- fn slice_to(&self, end: usize) -> &str;
-
- /// Returns a slice of the string from the character range [`begin`..`end`).
- ///
- /// That is, start at the `begin`-th code point of the string and continue
- /// to the `end`-th code point. This does not detect or handle edge cases
- /// such as leaving a combining character as the first code point of the
- /// string.
- ///
- /// Due to the design of UTF-8, this operation is `O(end)`. See `slice`,
- /// `slice_to` and `slice_from` for `O(1)` variants that use byte indices
- /// rather than code point indices.
- ///
- /// # Panics
- ///
- /// Panics if `begin` > `end` or the either `begin` or `end` are beyond the
- /// last character of the string.
- ///
- /// # Examples
- ///
- /// ```
- /// let s = "Löwe 老虎 Léopard";
- ///
- /// assert_eq!(s.slice_chars(0, 4), "Löwe");
- /// assert_eq!(s.slice_chars(5, 7), "老虎");
- /// ```
- #[unstable(feature = "collections",
- reason = "may have yet to prove its worth")]
- fn slice_chars(&self, begin: usize, end: usize) -> &str {
- core_str::StrExt::slice_chars(&self[..], begin, end)
- }
-
- /// Takes a bytewise slice from a string.
- ///
- /// Returns the substring from [`begin`..`end`).
- ///
- /// # Unsafety
- ///
- /// Caller must check both UTF-8 character boundaries and the boundaries of
- /// the entire slice as well.
- ///
- /// # Examples
- ///
- /// ```
- /// let s = "Löwe 老虎 Léopard";
- ///
- /// unsafe {
- /// assert_eq!(s.slice_unchecked(0, 21), "Löwe 老虎 Léopard");
- /// }
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
- core_str::StrExt::slice_unchecked(&self[..], begin, end)
- }
-
- /// Returns `true` if the given `&str` is a prefix of the string.
- ///
- /// # Examples
- ///
- /// ```
- /// assert!("banana".starts_with("ba"));
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn starts_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool {
- core_str::StrExt::starts_with(&self[..], pat)
- }
-
- /// Returns true if the given `&str` is a suffix of the string.
- ///
- /// # Examples
- ///
- /// ```
- /// assert!("banana".ends_with("nana"));
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn ends_with<'a, P: Pattern<'a>>(&'a self, pat: P) -> bool
- where P::Searcher: ReverseSearcher<'a>
- {
- core_str::StrExt::ends_with(&self[..], pat)
- }
-
- /// Returns a string with all pre- and suffixes that match a pattern repeatedly removed.
- ///
- /// The pattern can be any `DoubleEndedSearcher`, including a closure that determines the split.
- ///
- /// # Examples
- ///
- /// Simple `char` patterns:
- ///
- /// ```
- /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
- ///
- /// let x: &[_] = &['1', '2'];
- /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
- /// ```
- ///
- /// More complex patterns with a lambda:
- ///
- /// ```
- /// assert_eq!("123foo1bar123".trim_matches(|c: char| c.is_numeric()), "foo1bar");
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn trim_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
- where P::Searcher: DoubleEndedSearcher<'a>
- {
- core_str::StrExt::trim_matches(&self[..], pat)
- }
-
- /// Returns a string with all prefixes that match a pattern repeatedly removed.
- ///
- /// The pattern can be a simple `&str`, or a closure that determines the split.
- ///
- /// # Examples
- ///
- /// Simple `&str` patterns:
- ///
- /// ```
- /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
- ///
- /// let x: &[_] = &['1', '2'];
- /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
- /// ```
- ///
- /// More complex patterns with a lambda:
- ///
- /// ```
- /// assert_eq!("123foo1bar123".trim_left_matches(|c: char| c.is_numeric()), "foo1bar123");
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn trim_left_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str {
- core_str::StrExt::trim_left_matches(&self[..], pat)
- }
-
- /// Returns a string with all suffixes that match a pattern repeatedly removed.
- ///
- /// The pattern can be a simple `&str`, or a closure that determines the split.
- ///
- /// # Examples
- ///
- /// Simple `&str` patterns:
- ///
- /// ```
- /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
- /// let x: &[_] = &['1', '2'];
- /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
- /// ```
- ///
- /// More complex patterns with a lambda:
- ///
- /// ```
- /// assert_eq!("123foo1bar123".trim_right_matches(|c: char| c.is_numeric()), "123foo1bar");
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
- where P::Searcher: ReverseSearcher<'a>
- {
- core_str::StrExt::trim_right_matches(&self[..], pat)
- }
-
- /// Check that `index`-th byte lies at the start and/or end of a UTF-8 code point sequence.
- ///
- /// The start and end of the string (when `index == self.len()`) are considered to be
- /// boundaries.
- ///
- /// # Panics
- ///
- /// Panics if `index` is greater than `self.len()`.
- ///
- /// # Examples
- ///
- /// ```
- /// let s = "Löwe 老虎 Léopard";
- /// assert!(s.is_char_boundary(0));
- /// // start of `老`
- /// assert!(s.is_char_boundary(6));
- /// assert!(s.is_char_boundary(s.len()));
- ///
- /// // second byte of `ö`
- /// assert!(!s.is_char_boundary(2));
- ///
- /// // third byte of `老`
- /// assert!(!s.is_char_boundary(8));
- /// ```
- #[unstable(feature = "str_char",
- reason = "it is unclear whether this method pulls its weight \
- with the existence of the char_indices iterator or \
- this method may want to be replaced with checked \
- slicing")]
- fn is_char_boundary(&self, index: usize) -> bool {
- core_str::StrExt::is_char_boundary(&self[..], index)
- }
-
- /// Given a byte position, return the next char and its index.
- ///
- /// This can be used to iterate over the Unicode characters of a string.
- ///
- /// # Panics
- ///
- /// If `i` is greater than or equal to the length of the string.
- /// If `i` is not the index of the beginning of a valid UTF-8 character.
- ///
- /// # Examples
- ///
- /// This example manually iterates through the characters of a string; this should normally be
- /// done by `.chars()` or `.char_indices()`.
- ///
- /// ```
- /// use std::str::CharRange;
- ///
- /// let s = "中华Việt Nam";
- /// let mut i = 0;
- /// while i < s.len() {
- /// let CharRange {ch, next} = s.char_range_at(i);
- /// println!("{}: {}", i, ch);
- /// i = next;
- /// }
- /// ```
- ///
- /// This outputs:
- ///
- /// ```text
- /// 0: 中
- /// 3: 华
- /// 6: V
- /// 7: i
- /// 8: ệ
- /// 11: t
- /// 12:
- /// 13: N
- /// 14: a
- /// 15: m
- /// ```
- #[unstable(feature = "str_char",
- reason = "often replaced by char_indices, this method may \
- be removed in favor of just char_at() or eventually \
- removed altogether")]
- fn char_range_at(&self, start: usize) -> CharRange {
- core_str::StrExt::char_range_at(&self[..], start)
- }
-
- /// Given a byte position, return the previous `char` and its position.
- ///
- /// This function can be used to iterate over a Unicode string in reverse.
- ///
- /// Returns 0 for next index if called on start index 0.
- ///
- /// # Panics
- ///
- /// If `i` is greater than the length of the string.
- /// If `i` is not an index following a valid UTF-8 character.
- ///
- /// # Examples
- ///
- /// This example manually iterates through the characters of a string; this should normally be
- /// done by `.chars().rev()` or `.char_indices()`.
- ///
- /// ```
- /// use std::str::CharRange;
- ///
- /// let s = "中华Việt Nam";
- /// let mut i = s.len();
- /// while i > 0 {
- /// let CharRange {ch, next} = s.char_range_at_reverse(i);
- /// println!("{}: {}", i, ch);
- /// i = next;
- /// }
- /// ```
- ///
- /// This outputs:
- ///
- /// ```text
- /// 16: m
- /// 15: a
- /// 14: N
- /// 13:
- /// 12: t
- /// 11: ệ
- /// 8: i
- /// 7: V
- /// 6: 华
- /// 3: 中
- /// ```
- #[unstable(feature = "str_char",
- reason = "often replaced by char_indices, this method may \
- be removed in favor of just char_at() or eventually \
- removed altogether")]
- fn char_range_at_reverse(&self, start: usize) -> CharRange {
- core_str::StrExt::char_range_at_reverse(&self[..], start)
- }
-
- /// Given a byte position, return the `char` at that position.
- ///
- /// # Panics
- ///
- /// If `i` is greater than or equal to the length of the string.
- /// If `i` is not the index of the beginning of a valid UTF-8 character.
- ///
- /// # Examples
- ///
- /// ```
- /// let s = "abπc";
- /// assert_eq!(s.char_at(1), 'b');
- /// assert_eq!(s.char_at(2), 'π');
- /// ```
- #[unstable(feature = "str_char",
- reason = "frequently replaced by the chars() iterator, this \
- method may be removed or possibly renamed in the \
- future; it is normally replaced by chars/char_indices \
- iterators or by getting the first char from a \
- subslice")]
- fn char_at(&self, i: usize) -> char {
- core_str::StrExt::char_at(&self[..], i)
- }
-
- /// Given a byte position, return the `char` at that position, counting from the end.
- ///
- /// # Panics
- ///
- /// If `i` is greater than the length of the string.
- /// If `i` is not an index following a valid UTF-8 character.
- ///
- /// # Examples
- ///
- /// ```
- /// let s = "abπc";
- /// assert_eq!(s.char_at_reverse(1), 'a');
- /// assert_eq!(s.char_at_reverse(2), 'b');
- /// ```
- #[unstable(feature = "str_char",
- reason = "see char_at for more details, but reverse semantics \
- are also somewhat unclear, especially with which \
- cases generate panics")]
- fn char_at_reverse(&self, i: usize) -> char {
- core_str::StrExt::char_at_reverse(&self[..], i)
- }
-
- /// Convert `self` to a byte slice.
- ///
- /// # Examples
- ///
- /// ```
- /// assert_eq!("bors".as_bytes(), b"bors");
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn as_bytes(&self) -> &[u8] {
- core_str::StrExt::as_bytes(&self[..])
- }
-
- /// Returns the byte index of the first character of `self` that matches the pattern, if it
- /// exists.
- ///
- /// Returns `None` if it doesn't exist.
- ///
- /// The pattern can be a simple `&str`, or a closure that determines the split.
- ///
- /// # Examples
- ///
- /// Simple `&str` patterns:
- ///
- /// ```
- /// let s = "Löwe 老虎 Léopard";
- ///
- /// assert_eq!(s.find('L'), Some(0));
- /// assert_eq!(s.find('é'), Some(14));
- ///
- /// ```
- ///
- /// More complex patterns with a lambda:
- ///
- /// ```
- /// let s = "Löwe 老虎 Léopard";
- ///
- /// assert_eq!(s.find(|c: char| c.is_whitespace()), Some(5));
- /// ```
- ///
- /// Not finding the pattern:
- ///
- /// ```
- /// let s = "Löwe 老虎 Léopard";
- /// let x: &[_] = &['1', '2'];
- ///
- /// assert_eq!(s.find(x), None);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize> {
- core_str::StrExt::find(&self[..], pat)
- }
-
- /// Returns the byte index of the last character of `self` that matches the pattern, if it
- /// exists.
- ///
- /// Returns `None` if it doesn't exist.
- ///
- /// The pattern can be a simple `&str`, or a closure that determines the split.
- ///
- /// # Examples
- ///
- /// Simple `&str` patterns:
- ///
- /// ```
- /// let s = "Löwe 老虎 Léopard";
- ///
- /// assert_eq!(s.rfind('L'), Some(13));
- /// assert_eq!(s.rfind('é'), Some(14));
- /// ```
- ///
- /// More complex patterns with a lambda:
- ///
- /// ```
- /// let s = "Löwe 老虎 Léopard";
- ///
- /// assert_eq!(s.rfind(|c: char| c.is_whitespace()), Some(12));
- /// ```
- ///
- /// Not finding the pattern:
- ///
- /// ```
- /// let s = "Löwe 老虎 Léopard";
- /// let x: &[_] = &['1', '2'];
- ///
- /// assert_eq!(s.rfind(x), None);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn rfind<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option<usize>
- where P::Searcher: ReverseSearcher<'a>
- {
- core_str::StrExt::rfind(&self[..], pat)
- }
-
- /// Returns the byte index of the first matching substring if it exists.
- ///
- /// Returns `None` if it doesn't exist.
- ///
- /// The pattern can be a simple `&str`, or a closure that determines the split.
- ///
- /// # Examples
- ///
- /// ```
- /// let s = "Löwe 老虎 Léopard";
- ///
- /// assert_eq!(s.find_str("老虎 L"), Some(6));
- /// assert_eq!(s.find_str("muffin man"), None);
- /// ```
- #[unstable(feature = "collections")]
- #[deprecated(since = "1.0.0", reason = "use `find()` with a `&str`")]
- fn find_str<'a, P: Pattern<'a>>(&'a self, needle: P) -> Option<usize> {
- core_str::StrExt::find_str(&self[..], needle)
- }
-
- /// Retrieves the first character from a `&str` and returns it.
- ///
- /// This does not allocate a new string; instead, it returns a slice that points one character
- /// beyond the character that was shifted.
- ///
- /// If the slice does not contain any characters, None is returned instead.
- ///
- /// # Examples
- ///
- /// ```
- /// let s = "Löwe 老虎 Léopard";
- /// let (c, s1) = s.slice_shift_char().unwrap();
- ///
- /// assert_eq!(c, 'L');
- /// assert_eq!(s1, "öwe 老虎 Léopard");
- ///
- /// let (c, s2) = s1.slice_shift_char().unwrap();
- ///
- /// assert_eq!(c, 'ö');
- /// assert_eq!(s2, "we 老虎 Léopard");
- /// ```
- #[unstable(feature = "str_char",
- reason = "awaiting conventions about shifting and slices and \
- may not be warranted with the existence of the chars \
- and/or char_indices iterators")]
- fn slice_shift_char(&self) -> Option<(char, &str)> {
- core_str::StrExt::slice_shift_char(&self[..])
- }
-
- /// Returns the byte offset of an inner slice relative to an enclosing outer slice.
- ///
- /// # Panics
- ///
- /// Panics if `inner` is not a direct slice contained within self.
- ///
- /// # Examples
- ///
- /// ```
- /// let string = "a\nb\nc";
- /// let lines: Vec<&str> = string.lines().collect();
- ///
- /// assert!(string.subslice_offset(lines[0]) == 0); // &"a"
- /// assert!(string.subslice_offset(lines[1]) == 2); // &"b"
- /// assert!(string.subslice_offset(lines[2]) == 4); // &"c"
- /// ```
- #[unstable(feature = "collections",
- reason = "awaiting convention about comparability of arbitrary slices")]
- fn subslice_offset(&self, inner: &str) -> usize {
- core_str::StrExt::subslice_offset(&self[..], inner)
- }
-
- /// Return an unsafe pointer to the `&str`'s buffer.
- ///
- /// The caller must ensure that the string outlives this pointer, and that it is not
- /// reallocated (e.g. by pushing to the string).
- ///
- /// # Examples
- ///
- /// ```
- /// let s = "Hello";
- /// let p = s.as_ptr();
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- fn as_ptr(&self) -> *const u8 {
- core_str::StrExt::as_ptr(&self[..])
- }
-
- /// Return an iterator of `u16` over the string encoded as UTF-16.
- #[unstable(feature = "collections",
- reason = "this functionality may only be provided by libunicode")]
- fn utf16_units(&self) -> Utf16Units {
- Utf16Units { encoder: Utf16Encoder::new(self[..].chars()) }
- }
-
- /// Returns the length of `self` in bytes.
- ///
- /// # Examples
- ///
- /// ```
- /// assert_eq!("foo".len(), 3);
- /// assert_eq!("ƒoo".len(), 4); // fancy f!
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- fn len(&self) -> usize {
- core_str::StrExt::len(&self[..])
- }
-
- /// Returns true if this slice has a length of zero bytes.
- ///
- /// # Examples
- ///
- /// ```
- /// assert!("".is_empty());
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn is_empty(&self) -> bool {
- core_str::StrExt::is_empty(&self[..])
- }
-
- /// Parses `self` into the specified type.
- ///
- /// # Failure
- ///
- /// Will return `Err` if it's not possible to parse `self` into the type.
- ///
- /// # Examples
- ///
- /// ```
- /// assert_eq!("4".parse::<u32>(), Ok(4));
- /// ```
- ///
- /// Failing:
- ///
- /// ```
- /// assert!("j".parse::<u32>().is_err());
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
- core_str::StrExt::parse(&self[..])
- }
-
- /// Returns an iterator over the [grapheme clusters][graphemes] of `self`.
- ///
- /// [graphemes]: http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries
- ///
- /// If `is_extended` is true, the iterator is over the *extended grapheme clusters*;
- /// otherwise, the iterator is over the *legacy grapheme clusters*.
- /// [UAX#29](http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries)
- /// recommends extended grapheme cluster boundaries for general processing.
- ///
- /// # Examples
- ///
- /// ```
- /// let gr1 = "a\u{310}e\u{301}o\u{308}\u{332}".graphemes(true).collect::<Vec<&str>>();
- /// let b: &[_] = &["a\u{310}", "e\u{301}", "o\u{308}\u{332}"];
- ///
- /// assert_eq!(gr1.as_slice(), b);
- ///
- /// let gr2 = "a\r\nb🇷🇺🇸🇹".graphemes(true).collect::<Vec<&str>>();
- /// let b: &[_] = &["a", "\r\n", "b", "🇷🇺🇸🇹"];
- ///
- /// assert_eq!(gr2.as_slice(), b);
- /// ```
- #[unstable(feature = "unicode",
- reason = "this functionality may be replaced with a more generic \
- unicode crate on crates.io")]
- fn graphemes(&self, is_extended: bool) -> Graphemes {
- UnicodeStr::graphemes(&self[..], is_extended)
- }
-
- /// Returns an iterator over the grapheme clusters of `self` and their byte offsets. See
- /// `graphemes()` for more information.
- ///
- /// # Examples
- ///
- /// ```
- /// let gr_inds = "a̐éö̲\r\n".grapheme_indices(true).collect::<Vec<(usize, &str)>>();
- /// let b: &[_] = &[(0, "a̐"), (3, "é"), (6, "ö̲"), (11, "\r\n")];
- ///
- /// assert_eq!(gr_inds.as_slice(), b);
- /// ```
- #[unstable(feature = "unicode",
- reason = "this functionality may be replaced with a more generic \
- unicode crate on crates.io")]
- fn grapheme_indices(&self, is_extended: bool) -> GraphemeIndices {
- UnicodeStr::grapheme_indices(&self[..], is_extended)
- }
-
- /// An iterator over the non-empty words of `self`.
- ///
- /// A 'word' is a subsequence separated by any sequence of whitespace. Sequences of whitespace
- /// are collapsed, so empty "words" are not included.
- ///
- /// # Examples
- ///
- /// ```
- /// let some_words = " Mary had\ta little \n\t lamb";
- /// let v: Vec<&str> = some_words.words().collect();
- ///
- /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
- /// ```
- #[unstable(feature = "str_words",
- reason = "the precise algorithm to use is unclear")]
- fn words(&self) -> Words {
- UnicodeStr::words(&self[..])
- }
-
- /// Returns a string's displayed width in columns.
- ///
- /// Control characters have zero width.
- ///
- /// `is_cjk` determines behavior for characters in the Ambiguous category:
- /// if `is_cjk` is `true`, these are 2 columns wide; otherwise, they are 1.
- /// In CJK locales, `is_cjk` should be `true`, else it should be `false`.
- /// [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/)
- /// recommends that these characters be treated as 1 column (i.e., `is_cjk =
- /// false`) if the locale is unknown.
- #[unstable(feature = "unicode",
- reason = "this functionality may be replaced with a more generic \
- unicode crate on crates.io")]
- fn width(&self, is_cjk: bool) -> usize {
- UnicodeStr::width(&self[..], is_cjk)
- }
-
- /// Returns a `&str` with leading and trailing whitespace removed.
- ///
- /// # Examples
- ///
- /// ```
- /// let s = " Hello\tworld\t";
- /// assert_eq!(s.trim(), "Hello\tworld");
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn trim(&self) -> &str {
- UnicodeStr::trim(&self[..])
- }
-
- /// Returns a `&str` with leading whitespace removed.
- ///
- /// # Examples
- ///
- /// ```
- /// let s = " Hello\tworld\t";
- /// assert_eq!(s.trim_left(), "Hello\tworld\t");
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn trim_left(&self) -> &str {
- UnicodeStr::trim_left(&self[..])
- }
-
- /// Returns a `&str` with trailing whitespace removed.
- ///
- /// # Examples
- ///
- /// ```
- /// let s = " Hello\tworld\t";
- /// assert_eq!(s.trim_right(), " Hello\tworld");
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn trim_right(&self) -> &str {
- UnicodeStr::trim_right(&self[..])
- }
-
- /// Returns the lowercase equivalent of this string.
- ///
- /// # Examples
- ///
- /// let s = "HELLO";
- /// assert_eq!(s.to_lowercase(), "hello");
- #[unstable(feature = "collections")]
- fn to_lowercase(&self) -> String {
- let mut s = String::with_capacity(self.len());
- s.extend(self[..].chars().flat_map(|c| c.to_lowercase()));
- return s;
- }
-
- /// Returns the uppercase equivalent of this string.
- ///
- /// # Examples
- ///
- /// let s = "hello";
- /// assert_eq!(s.to_uppercase(), "HELLO");
- #[unstable(feature = "collections")]
- fn to_uppercase(&self) -> String {
- let mut s = String::with_capacity(self.len());
- s.extend(self[..].chars().flat_map(|c| c.to_uppercase()));
- return s;
- }
-}
-
-#[cfg(stage0)]
-#[stable(feature = "rust1", since = "1.0.0")]
-impl StrExt for str {
- fn slice(&self, begin: usize, end: usize) -> &str {
- &self[begin..end]
- }
-
- fn slice_from(&self, begin: usize) -> &str {
- &self[begin..]
- }
-
- fn slice_to(&self, end: usize) -> &str {
- &self[..end]
- }
-}
-#[cfg(not(stage0))]
/// Any string that can be represented as a slice.
#[lang = "str"]
#[cfg(not(test))]
}
}
- #[cfg(stage0)]
- /// Creates a new string buffer from the given string.
- ///
- /// # Examples
- ///
- /// ```
- /// let s = String::from_str("hello");
- /// assert_eq!(s.as_slice(), "hello");
- /// ```
- #[inline]
- #[unstable(feature = "collections",
- reason = "needs investigation to see if to_string() can match perf")]
- pub fn from_str(string: &str) -> String {
- String { vec: ::slice::SliceExt::to_vec(string.as_bytes()) }
- }
-
- #[cfg(not(stage0))]
/// Creates a new string buffer from the given string.
///
/// # Examples
String { vec: <[_]>::to_vec(string.as_bytes()) }
}
- // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is required for this
- // method definition, is not available. Since we don't require this method for testing
- // purposes, I'll just stub it
+ // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
+ // required for this method definition, is not available. Since we don't
+ // require this method for testing purposes, I'll just stub it
// NB see the slice::hack module in slice.rs for more information
#[inline]
#[cfg(test)]
use core::iter::{repeat, FromIterator, IntoIterator};
use core::marker::PhantomData;
use core::mem;
-#[cfg(stage0)]
-use core::num::{Int, UnsignedInt};
use core::ops::{Index, IndexMut, Deref, Add};
use core::ops;
use core::ptr;
#[unstable(feature = "collections")]
impl<T:Clone> Clone for Vec<T> {
- #[cfg(stage0)]
- fn clone(&self) -> Vec<T> { ::slice::SliceExt::to_vec(&**self) }
-
- #[cfg(not(stage0))]
#[cfg(not(test))]
fn clone(&self) -> Vec<T> { <[T]>::to_vec(&**self) }
- // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is required for this
- // method definition, is not available. Instead use the `slice::to_vec` function which is only
- // available with cfg(test)
+ // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
+ // required for this method definition, is not available. Instead use the
+ // `slice::to_vec` function which is only available with cfg(test)
// NB see the slice::hack module in slice.rs for more information
- #[cfg(not(stage0))]
#[cfg(test)]
fn clone(&self) -> Vec<T> {
::slice::to_vec(&**self)
use core::fmt;
use core::iter::{self, repeat, FromIterator, IntoIterator, RandomAccessIterator};
use core::mem;
-#[cfg(stage0)]
-use core::num::{Int, UnsignedInt};
use core::num::wrapping::WrappingOps;
use core::ops::{Index, IndexMut};
use core::ptr::{self, Unique};
}
}
-#[cfg(not(stage0))]
impl Any+Send {
/// Forwards to the method defined on the type `Any`.
#[stable(feature = "rust1", since = "1.0.0")]
use marker::Sized;
-#[cfg(stage0)] // SNAP 270a677
-pub type GlueFn = extern "Rust" fn(*const i8);
-
-#[lang="ty_desc"]
-#[derive(Copy)]
-#[cfg(stage0)] // SNAP 270a677
-pub struct TyDesc {
- // sizeof(T)
- pub size: usize,
-
- // alignof(T)
- pub align: usize,
-
- // Called when a value of type `T` is no longer needed
- pub drop_glue: GlueFn,
-
- // Name corresponding to the type
- pub name: &'static str,
-}
-
extern "rust-intrinsic" {
// NB: These intrinsics take unsafe pointers because they mutate aliased
pub fn min_align_of<T>() -> usize;
pub fn pref_align_of<T>() -> usize;
- /// Get a static pointer to a type descriptor.
- #[cfg(stage0)] // SNAP 270a677
- pub fn get_tydesc<T: ?Sized>() -> *const TyDesc;
-
/// Gets a static string slice containing the name of a type.
- #[cfg(not(stage0))] // SNAP 270a677
+ #[cfg(not(stage0))]
pub fn type_name<T: ?Sized>() -> &'static str;
/// Gets an identifier which is globally unique to the specified type. This
fn max_value() -> $T { -1 }
#[inline]
- fn count_ones(self) -> u32 { unsafe { $ctpop(self as $ActualT) as u32 } }
+ fn count_ones(self) -> u32 {
+ unsafe { $ctpop(self as $ActualT) as u32 }
+ }
#[inline]
- fn leading_zeros(self) -> u32 { unsafe { $ctlz(self as $ActualT) as u32 } }
+ fn leading_zeros(self) -> u32 {
+ unsafe { $ctlz(self as $ActualT) as u32 }
+ }
#[inline]
- fn trailing_zeros(self) -> u32 { unsafe { $cttz(self as $ActualT) as u32 } }
+ fn trailing_zeros(self) -> u32 {
+ unsafe { $cttz(self as $ActualT) as u32 }
+ }
#[inline]
fn rotate_left(self, n: u32) -> $T {
}
#[inline]
- fn swap_bytes(self) -> $T { unsafe { $bswap(self as $ActualT) as $T } }
+ fn swap_bytes(self) -> $T {
+ unsafe { $bswap(self as $ActualT) as $T }
+ }
#[inline]
fn checked_add(self, other: $T) -> Option<$T> {
fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
#[inline]
- fn leading_zeros(self) -> u32 { (self as $UnsignedT).leading_zeros() }
+ fn leading_zeros(self) -> u32 {
+ (self as $UnsignedT).leading_zeros()
+ }
#[inline]
- fn trailing_zeros(self) -> u32 { (self as $UnsignedT).trailing_zeros() }
+ fn trailing_zeros(self) -> u32 {
+ (self as $UnsignedT).trailing_zeros()
+ }
#[inline]
- fn rotate_left(self, n: u32) -> $T { (self as $UnsignedT).rotate_left(n) as $T }
+ fn rotate_left(self, n: u32) -> $T {
+ (self as $UnsignedT).rotate_left(n) as $T
+ }
#[inline]
- fn rotate_right(self, n: u32) -> $T { (self as $UnsignedT).rotate_right(n) as $T }
+ fn rotate_right(self, n: u32) -> $T {
+ (self as $UnsignedT).rotate_right(n) as $T
+ }
#[inline]
- fn swap_bytes(self) -> $T { (self as $UnsignedT).swap_bytes() as $T }
+ fn swap_bytes(self) -> $T {
+ (self as $UnsignedT).swap_bytes() as $T
+ }
#[inline]
fn checked_add(self, other: $T) -> Option<$T> {
signed_int_impl! { i64 }
signed_int_impl! { int }
-#[cfg(stage0)]
-/// A built-in unsigned integer.
-#[stable(feature = "rust1", since = "1.0.0")]
-pub trait UnsignedInt: Int + WrappingOps {
- /// Returns `true` iff `self == 2^k` for some `k`.
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- fn is_power_of_two(self) -> bool {
- (self.wrapping_sub(Int::one())) & self == Int::zero() && !(self == Int::zero())
- }
-
- /// Returns the smallest power of two greater than or equal to `self`.
- /// Unspecified behavior on overflow.
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- fn next_power_of_two(self) -> Self {
- let bits = size_of::<Self>() * 8;
- let one: Self = Int::one();
- one << ((bits - self.wrapping_sub(one).leading_zeros() as usize) % bits)
- }
-
- /// Returns the smallest power of two greater than or equal to `n`. If the
- /// next power of two is greater than the type's maximum value, `None` is
- /// returned, otherwise the power of two is wrapped in `Some`.
- #[stable(feature = "rust1", since = "1.0.0")]
- fn checked_next_power_of_two(self) -> Option<Self> {
- let npot = self.next_power_of_two();
- if npot >= self {
- Some(npot)
- } else {
- None
+// `Int` + `SignedInt` implemented for signed integers
+macro_rules! int_impl {
+ ($T:ty = $ActualT:ty, $UnsignedT:ty, $BITS:expr,
+ $add_with_overflow:path,
+ $sub_with_overflow:path,
+ $mul_with_overflow:path) => {
+ /// Returns the `0` value of this integer type.
+ // FIXME (#5527): Should be an associated constant
+ #[unstable(feature = "core",
+ reason = "unsure about its place in the world")]
+ #[inline]
+ pub fn zero() -> $T { 0 }
+
+ /// Returns the `1` value of this integer type.
+ // FIXME (#5527): Should be an associated constant
+ #[unstable(feature = "core",
+ reason = "unsure about its place in the world")]
+ #[inline]
+ pub fn one() -> $T { 1 }
+
+ /// Returns the smallest value that can be represented by this integer
+ /// type.
+ // FIXME (#5527): Should be and associated constant
+ #[unstable(feature = "core",
+ reason = "unsure about its place in the world")]
+ #[inline]
+ pub fn min_value() -> $T { (-1 as $T) << ($BITS - 1) }
+
+ /// Returns the largest value that can be represented by this integer
+ /// type.
+ // FIXME (#5527): Should be and associated constant
+ #[unstable(feature = "core",
+ reason = "unsure about its place in the world")]
+ #[inline]
+ pub fn max_value() -> $T { let min: $T = <$T>::min_value(); !min }
+
+ /// Returns the number of ones in the binary representation of `self`.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// let n = 0b01001100u8;
+ ///
+ /// assert_eq!(n.count_ones(), 3);
+ /// ```
+ #[unstable(feature = "core",
+ reason = "pending integer conventions")]
+ #[inline]
+ pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
+
+ /// Returns the number of zeros in the binary representation of `self`.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// let n = 0b01001100u8;
+ ///
+ /// assert_eq!(n.count_zeros(), 5);
+ /// ```
+ #[unstable(feature = "core",
+ reason = "pending integer conventions")]
+ #[inline]
+ pub fn count_zeros(self) -> u32 {
+ (!self).count_ones()
}
- }
-}
-
-#[cfg(stage0)]
-#[stable(feature = "rust1", since = "1.0.0")]
-impl UnsignedInt for uint {}
-
-#[cfg(stage0)]
-#[stable(feature = "rust1", since = "1.0.0")]
-impl UnsignedInt for u8 {}
-
-#[cfg(stage0)]
-#[stable(feature = "rust1", since = "1.0.0")]
-impl UnsignedInt for u16 {}
-#[cfg(stage0)]
-#[stable(feature = "rust1", since = "1.0.0")]
-impl UnsignedInt for u32 {}
-
-#[cfg(stage0)]
-#[stable(feature = "rust1", since = "1.0.0")]
-impl UnsignedInt for u64 {}
-
-// NB(japaric) I added this module to avoid adding several `cfg(not(stage0))`, and avoid name
-// clashes between macros. We should move all the items inside this module into the outer scope
-// once the `Int` trait is removed
-#[cfg(not(stage0))]
-mod inherent {
- use intrinsics;
- use mem::size_of;
- use option::Option::{self, Some, None};
-
- use super::wrapping::{OverflowingOps, WrappingOps};
-
- // `Int` + `SignedInt` implemented for signed integers
- macro_rules! int_impl {
- ($T:ty = $ActualT:ty, $UnsignedT:ty, $BITS:expr,
- $add_with_overflow:path,
- $sub_with_overflow:path,
- $mul_with_overflow:path) => {
- /// Returns the `0` value of this integer type.
- // FIXME (#5527): Should be an associated constant
- #[unstable(feature = "core",
- reason = "unsure about its place in the world")]
- #[inline]
- pub fn zero() -> $T { 0 }
-
- /// Returns the `1` value of this integer type.
- // FIXME (#5527): Should be an associated constant
- #[unstable(feature = "core",
- reason = "unsure about its place in the world")]
- #[inline]
- pub fn one() -> $T { 1 }
-
- /// Returns the smallest value that can be represented by this integer type.
- // FIXME (#5527): Should be and associated constant
- #[unstable(feature = "core",
- reason = "unsure about its place in the world")]
- #[inline]
- pub fn min_value() -> $T { (-1 as $T) << ($BITS - 1) }
-
- /// Returns the largest value that can be represented by this integer type.
- // FIXME (#5527): Should be and associated constant
- #[unstable(feature = "core",
- reason = "unsure about its place in the world")]
- #[inline]
- pub fn max_value() -> $T { let min: $T = <$T>::min_value(); !min }
-
- /// Returns the number of ones in the binary representation of `self`.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// let n = 0b01001100u8;
- ///
- /// assert_eq!(n.count_ones(), 3);
- /// ```
- #[unstable(feature = "core",
- reason = "pending integer conventions")]
- #[inline]
- pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
-
- /// Returns the number of zeros in the binary representation of `self`.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// let n = 0b01001100u8;
- ///
- /// assert_eq!(n.count_zeros(), 5);
- /// ```
- #[unstable(feature = "core",
- reason = "pending integer conventions")]
- #[inline]
- pub fn count_zeros(self) -> u32 {
- (!self).count_ones()
- }
-
- /// Returns the number of leading zeros in the binary representation
- /// of `self`.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// let n = 0b0101000u16;
- ///
- /// assert_eq!(n.leading_zeros(), 10);
- /// ```
- #[unstable(feature = "core",
- reason = "pending integer conventions")]
- #[inline]
- pub fn leading_zeros(self) -> u32 { (self as $UnsignedT).leading_zeros() }
+ /// Returns the number of leading zeros in the binary representation
+ /// of `self`.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// let n = 0b0101000u16;
+ ///
+ /// assert_eq!(n.leading_zeros(), 10);
+ /// ```
+ #[unstable(feature = "core",
+ reason = "pending integer conventions")]
+ #[inline]
+ pub fn leading_zeros(self) -> u32 {
+ (self as $UnsignedT).leading_zeros()
+ }
- /// Returns the number of trailing zeros in the binary representation
- /// of `self`.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// let n = 0b0101000u16;
- ///
- /// assert_eq!(n.trailing_zeros(), 3);
- /// ```
- #[unstable(feature = "core",
- reason = "pending integer conventions")]
- #[inline]
- pub fn trailing_zeros(self) -> u32 { (self as $UnsignedT).trailing_zeros() }
+ /// Returns the number of trailing zeros in the binary representation
+ /// of `self`.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// let n = 0b0101000u16;
+ ///
+ /// assert_eq!(n.trailing_zeros(), 3);
+ /// ```
+ #[unstable(feature = "core",
+ reason = "pending integer conventions")]
+ #[inline]
+ pub fn trailing_zeros(self) -> u32 {
+ (self as $UnsignedT).trailing_zeros()
+ }
- /// Shifts the bits to the left by a specified amount amount, `n`, wrapping
- /// the truncated bits to the end of the resulting integer.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// let n = 0x0123456789ABCDEFu64;
- /// let m = 0x3456789ABCDEF012u64;
- ///
- /// assert_eq!(n.rotate_left(12), m);
- /// ```
- #[unstable(feature = "core",
- reason = "pending integer conventions")]
- #[inline]
- pub fn rotate_left(self, n: u32) -> $T { (self as $UnsignedT).rotate_left(n) as $T }
+ /// Shifts the bits to the left by a specified amount amount, `n`,
+ /// wrapping the truncated bits to the end of the resulting integer.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// let n = 0x0123456789ABCDEFu64;
+ /// let m = 0x3456789ABCDEF012u64;
+ ///
+ /// assert_eq!(n.rotate_left(12), m);
+ /// ```
+ #[unstable(feature = "core",
+ reason = "pending integer conventions")]
+ #[inline]
+ pub fn rotate_left(self, n: u32) -> $T {
+ (self as $UnsignedT).rotate_left(n) as $T
+ }
- /// Shifts the bits to the right by a specified amount amount, `n`, wrapping
- /// the truncated bits to the beginning of the resulting integer.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// let n = 0x0123456789ABCDEFu64;
- /// let m = 0xDEF0123456789ABCu64;
- ///
- /// assert_eq!(n.rotate_right(12), m);
- /// ```
- #[unstable(feature = "core",
- reason = "pending integer conventions")]
- #[inline]
- pub fn rotate_right(self, n: u32) -> $T { (self as $UnsignedT).rotate_right(n) as $T }
+ /// Shifts the bits to the right by a specified amount amount, `n`,
+ /// wrapping the truncated bits to the beginning of the resulting
+ /// integer.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// let n = 0x0123456789ABCDEFu64;
+ /// let m = 0xDEF0123456789ABCu64;
+ ///
+ /// assert_eq!(n.rotate_right(12), m);
+ /// ```
+ #[unstable(feature = "core",
+ reason = "pending integer conventions")]
+ #[inline]
+ pub fn rotate_right(self, n: u32) -> $T {
+ (self as $UnsignedT).rotate_right(n) as $T
+ }
- /// Reverses the byte order of the integer.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// let n = 0x0123456789ABCDEFu64;
- /// let m = 0xEFCDAB8967452301u64;
- ///
- /// assert_eq!(n.swap_bytes(), m);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- pub fn swap_bytes(self) -> $T { (self as $UnsignedT).swap_bytes() as $T }
+ /// Reverses the byte order of the integer.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// let n = 0x0123456789ABCDEFu64;
+ /// let m = 0xEFCDAB8967452301u64;
+ ///
+ /// assert_eq!(n.swap_bytes(), m);
+ /// ```
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[inline]
+ pub fn swap_bytes(self) -> $T {
+ (self as $UnsignedT).swap_bytes() as $T
+ }
- /// Convert an integer from big endian to the target's endianness.
- ///
- /// On big endian this is a no-op. On little endian the bytes are swapped.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// let n = 0x0123456789ABCDEFu64;
- ///
- /// if cfg!(target_endian = "big") {
- /// assert_eq!(Int::from_be(n), n)
- /// } else {
- /// assert_eq!(Int::from_be(n), n.swap_bytes())
- /// }
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- pub fn from_be(x: $T) -> $T {
- if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
- }
+ /// Convert an integer from big endian to the target's endianness.
+ ///
+ /// On big endian this is a no-op. On little endian the bytes are
+ /// swapped.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// let n = 0x0123456789ABCDEFu64;
+ ///
+ /// if cfg!(target_endian = "big") {
+ /// assert_eq!(Int::from_be(n), n)
+ /// } else {
+ /// assert_eq!(Int::from_be(n), n.swap_bytes())
+ /// }
+ /// ```
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[inline]
+ pub fn from_be(x: $T) -> $T {
+ if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
+ }
- /// Convert an integer from little endian to the target's endianness.
- ///
- /// On little endian this is a no-op. On big endian the bytes are swapped.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// let n = 0x0123456789ABCDEFu64;
- ///
- /// if cfg!(target_endian = "little") {
- /// assert_eq!(Int::from_le(n), n)
- /// } else {
- /// assert_eq!(Int::from_le(n), n.swap_bytes())
- /// }
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- pub fn from_le(x: $T) -> $T {
- if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
- }
+ /// Convert an integer from little endian to the target's endianness.
+ ///
+ /// On little endian this is a no-op. On big endian the bytes are
+ /// swapped.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// let n = 0x0123456789ABCDEFu64;
+ ///
+ /// if cfg!(target_endian = "little") {
+ /// assert_eq!(Int::from_le(n), n)
+ /// } else {
+ /// assert_eq!(Int::from_le(n), n.swap_bytes())
+ /// }
+ /// ```
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[inline]
+ pub fn from_le(x: $T) -> $T {
+ if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
+ }
- /// Convert `self` to big endian from the target's endianness.
- ///
- /// On big endian this is a no-op. On little endian the bytes are swapped.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// let n = 0x0123456789ABCDEFu64;
- ///
- /// if cfg!(target_endian = "big") {
- /// assert_eq!(n.to_be(), n)
- /// } else {
- /// assert_eq!(n.to_be(), n.swap_bytes())
- /// }
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- pub fn to_be(self) -> $T { // or not to be?
- if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
- }
+ /// Convert `self` to big endian from the target's endianness.
+ ///
+ /// On big endian this is a no-op. On little endian the bytes are
+ /// swapped.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// let n = 0x0123456789ABCDEFu64;
+ ///
+ /// if cfg!(target_endian = "big") {
+ /// assert_eq!(n.to_be(), n)
+ /// } else {
+ /// assert_eq!(n.to_be(), n.swap_bytes())
+ /// }
+ /// ```
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[inline]
+ pub fn to_be(self) -> $T { // or not to be?
+ if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
+ }
- /// Convert `self` to little endian from the target's endianness.
- ///
- /// On little endian this is a no-op. On big endian the bytes are swapped.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// let n = 0x0123456789ABCDEFu64;
- ///
- /// if cfg!(target_endian = "little") {
- /// assert_eq!(n.to_le(), n)
- /// } else {
- /// assert_eq!(n.to_le(), n.swap_bytes())
- /// }
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- pub fn to_le(self) -> $T {
- if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
- }
+ /// Convert `self` to little endian from the target's endianness.
+ ///
+ /// On little endian this is a no-op. On big endian the bytes are
+ /// swapped.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// let n = 0x0123456789ABCDEFu64;
+ ///
+ /// if cfg!(target_endian = "little") {
+ /// assert_eq!(n.to_le(), n)
+ /// } else {
+ /// assert_eq!(n.to_le(), n.swap_bytes())
+ /// }
+ /// ```
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[inline]
+ pub fn to_le(self) -> $T {
+ if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
+ }
- /// Checked integer addition. Computes `self + other`, returning `None` if
- /// overflow occurred.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// assert_eq!(5u16.checked_add(65530), Some(65535));
- /// assert_eq!(6u16.checked_add(65530), None);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- pub fn checked_add(self, other: $T) -> Option<$T> {
- checked_op!($T, $ActualT, $add_with_overflow, self, other)
- }
+ /// Checked integer addition. Computes `self + other`, returning `None`
+ /// if overflow occurred.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// assert_eq!(5u16.checked_add(65530), Some(65535));
+ /// assert_eq!(6u16.checked_add(65530), None);
+ /// ```
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[inline]
+ pub fn checked_add(self, other: $T) -> Option<$T> {
+ checked_op!($T, $ActualT, $add_with_overflow, self, other)
+ }
- /// Checked integer subtraction. Computes `self - other`, returning `None`
- /// if underflow occurred.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// assert_eq!((-127i8).checked_sub(1), Some(-128));
- /// assert_eq!((-128i8).checked_sub(1), None);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- pub fn checked_sub(self, other: $T) -> Option<$T> {
- checked_op!($T, $ActualT, $sub_with_overflow, self, other)
- }
+ /// Checked integer subtraction. Computes `self - other`, returning
+ /// `None` if underflow occurred.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// assert_eq!((-127i8).checked_sub(1), Some(-128));
+ /// assert_eq!((-128i8).checked_sub(1), None);
+ /// ```
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[inline]
+ pub fn checked_sub(self, other: $T) -> Option<$T> {
+ checked_op!($T, $ActualT, $sub_with_overflow, self, other)
+ }
- /// Checked integer multiplication. Computes `self * other`, returning
- /// `None` if underflow or overflow occurred.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// assert_eq!(5u8.checked_mul(51), Some(255));
- /// assert_eq!(5u8.checked_mul(52), None);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- pub fn checked_mul(self, other: $T) -> Option<$T> {
- checked_op!($T, $ActualT, $mul_with_overflow, self, other)
- }
+ /// Checked integer multiplication. Computes `self * other`, returning
+ /// `None` if underflow or overflow occurred.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// assert_eq!(5u8.checked_mul(51), Some(255));
+ /// assert_eq!(5u8.checked_mul(52), None);
+ /// ```
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[inline]
+ pub fn checked_mul(self, other: $T) -> Option<$T> {
+ checked_op!($T, $ActualT, $mul_with_overflow, self, other)
+ }
- /// Checked integer division. Computes `self / other`, returning `None` if
- /// `other == 0` or the operation results in underflow or overflow.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// assert_eq!((-127i8).checked_div(-1), Some(127));
- /// assert_eq!((-128i8).checked_div(-1), None);
- /// assert_eq!((1i8).checked_div(0), None);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- pub fn checked_div(self, v: $T) -> Option<$T> {
- match v {
- 0 => None,
- -1 if self == <$T>::min_value()
- => None,
- v => Some(self / v),
- }
+ /// Checked integer division. Computes `self / other`, returning `None`
+ /// if `other == 0` or the operation results in underflow or overflow.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// assert_eq!((-127i8).checked_div(-1), Some(127));
+ /// assert_eq!((-128i8).checked_div(-1), None);
+ /// assert_eq!((1i8).checked_div(0), None);
+ /// ```
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[inline]
+ pub fn checked_div(self, v: $T) -> Option<$T> {
+ match v {
+ 0 => None,
+ -1 if self == <$T>::min_value()
+ => None,
+ v => Some(self / v),
}
+ }
- /// Saturating integer addition. Computes `self + other`, saturating at
- /// the numeric bounds instead of overflowing.
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- pub fn saturating_add(self, other: $T) -> $T {
- match self.checked_add(other) {
- Some(x) => x,
- None if other >= <$T>::zero() => <$T>::max_value(),
- None => <$T>::min_value(),
- }
+ /// Saturating integer addition. Computes `self + other`, saturating at
+ /// the numeric bounds instead of overflowing.
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[inline]
+ pub fn saturating_add(self, other: $T) -> $T {
+ match self.checked_add(other) {
+ Some(x) => x,
+ None if other >= <$T>::zero() => <$T>::max_value(),
+ None => <$T>::min_value(),
}
+ }
- /// Saturating integer subtraction. Computes `self - other`, saturating at
- /// the numeric bounds instead of overflowing.
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- pub fn saturating_sub(self, other: $T) -> $T {
- match self.checked_sub(other) {
- Some(x) => x,
- None if other >= <$T>::zero() => <$T>::min_value(),
- None => <$T>::max_value(),
- }
+ /// Saturating integer subtraction. Computes `self - other`, saturating
+ /// at the numeric bounds instead of overflowing.
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[inline]
+ pub fn saturating_sub(self, other: $T) -> $T {
+ match self.checked_sub(other) {
+ Some(x) => x,
+ None if other >= <$T>::zero() => <$T>::min_value(),
+ None => <$T>::max_value(),
}
+ }
- /// Raises self to the power of `exp`, using exponentiation by squaring.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// assert_eq!(2.pow(4), 16);
- /// ```
- #[unstable(feature = "core",
- reason = "pending integer conventions")]
- #[inline]
- pub fn pow(self, mut exp: u32) -> $T {
- let mut base = self;
- let mut acc = <$T>::one();
-
- let mut prev_base = self;
- let mut base_oflo = false;
- while exp > 0 {
- if (exp & 1) == 1 {
- if base_oflo {
- // ensure overflow occurs in the same manner it
- // would have otherwise (i.e. signal any exception
- // it would have otherwise).
- acc = acc * (prev_base * prev_base);
- } else {
- acc = acc * base;
- }
+ /// Raises self to the power of `exp`, using exponentiation by squaring.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// assert_eq!(2.pow(4), 16);
+ /// ```
+ #[unstable(feature = "core",
+ reason = "pending integer conventions")]
+ #[inline]
+ pub fn pow(self, mut exp: u32) -> $T {
+ let mut base = self;
+ let mut acc = <$T>::one();
+
+ let mut prev_base = self;
+ let mut base_oflo = false;
+ while exp > 0 {
+ if (exp & 1) == 1 {
+ if base_oflo {
+ // ensure overflow occurs in the same manner it
+ // would have otherwise (i.e. signal any exception
+ // it would have otherwise).
+ acc = acc * (prev_base * prev_base);
+ } else {
+ acc = acc * base;
}
- prev_base = base;
- let (new_base, new_base_oflo) = base.overflowing_mul(base);
- base = new_base;
- base_oflo = new_base_oflo;
- exp /= 2;
}
- acc
+ prev_base = base;
+ let (new_base, new_base_oflo) = base.overflowing_mul(base);
+ base = new_base;
+ base_oflo = new_base_oflo;
+ exp /= 2;
}
+ acc
+ }
- /// Computes the absolute value of `self`. `Int::min_value()` will be
- /// returned if the number is `Int::min_value()`.
- #[unstable(feature = "core", reason = "overflow in debug builds?")]
- #[inline]
- pub fn abs(self) -> $T {
- if self.is_negative() { -self } else { self }
- }
+ /// Computes the absolute value of `self`. `Int::min_value()` will be
+ /// returned if the number is `Int::min_value()`.
+ #[unstable(feature = "core", reason = "overflow in debug builds?")]
+ #[inline]
+ pub fn abs(self) -> $T {
+ if self.is_negative() { -self } else { self }
+ }
- /// Returns a number representing sign of `self`.
- ///
- /// - `0` if the number is zero
- /// - `1` if the number is positive
- /// - `-1` if the number is negative
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- pub fn signum(self) -> $T {
- match self {
- n if n > 0 => 1,
- 0 => 0,
- _ => -1,
- }
+ /// Returns a number representing sign of `self`.
+ ///
+ /// - `0` if the number is zero
+ /// - `1` if the number is positive
+ /// - `-1` if the number is negative
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[inline]
+ pub fn signum(self) -> $T {
+ match self {
+ n if n > 0 => 1,
+ 0 => 0,
+ _ => -1,
}
+ }
- /// Returns `true` if `self` is positive and `false` if the number
- /// is zero or negative.
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- pub fn is_positive(self) -> bool { self > 0 }
+ /// Returns `true` if `self` is positive and `false` if the number
+ /// is zero or negative.
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[inline]
+ pub fn is_positive(self) -> bool { self > 0 }
- /// Returns `true` if `self` is negative and `false` if the number
- /// is zero or positive.
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- pub fn is_negative(self) -> bool { self < 0 }
- }
+ /// Returns `true` if `self` is negative and `false` if the number
+ /// is zero or positive.
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[inline]
+ pub fn is_negative(self) -> bool { self < 0 }
}
+}
- #[lang = "i8"]
- impl i8 {
- int_impl! { i8 = i8, u8, 8,
- intrinsics::i8_add_with_overflow,
- intrinsics::i8_sub_with_overflow,
- intrinsics::i8_mul_with_overflow }
- }
+#[lang = "i8"]
+impl i8 {
+ int_impl! { i8 = i8, u8, 8,
+ intrinsics::i8_add_with_overflow,
+ intrinsics::i8_sub_with_overflow,
+ intrinsics::i8_mul_with_overflow }
+}
- #[lang = "i16"]
- impl i16 {
- int_impl! { i16 = i16, u16, 16,
- intrinsics::i16_add_with_overflow,
- intrinsics::i16_sub_with_overflow,
- intrinsics::i16_mul_with_overflow }
- }
+#[lang = "i16"]
+impl i16 {
+ int_impl! { i16 = i16, u16, 16,
+ intrinsics::i16_add_with_overflow,
+ intrinsics::i16_sub_with_overflow,
+ intrinsics::i16_mul_with_overflow }
+}
- #[lang = "i32"]
- impl i32 {
- int_impl! { i32 = i32, u32, 32,
- intrinsics::i32_add_with_overflow,
- intrinsics::i32_sub_with_overflow,
- intrinsics::i32_mul_with_overflow }
- }
+#[lang = "i32"]
+impl i32 {
+ int_impl! { i32 = i32, u32, 32,
+ intrinsics::i32_add_with_overflow,
+ intrinsics::i32_sub_with_overflow,
+ intrinsics::i32_mul_with_overflow }
+}
- #[lang = "i64"]
- impl i64 {
- int_impl! { i64 = i64, u64, 64,
- intrinsics::i64_add_with_overflow,
- intrinsics::i64_sub_with_overflow,
- intrinsics::i64_mul_with_overflow }
- }
+#[lang = "i64"]
+impl i64 {
+ int_impl! { i64 = i64, u64, 64,
+ intrinsics::i64_add_with_overflow,
+ intrinsics::i64_sub_with_overflow,
+ intrinsics::i64_mul_with_overflow }
+}
- #[cfg(target_pointer_width = "32")]
- #[lang = "isize"]
- impl isize {
- int_impl! { int = i32, u32, 32,
- intrinsics::i32_add_with_overflow,
- intrinsics::i32_sub_with_overflow,
- intrinsics::i32_mul_with_overflow }
- }
+#[cfg(target_pointer_width = "32")]
+#[lang = "isize"]
+impl isize {
+ int_impl! { int = i32, u32, 32,
+ intrinsics::i32_add_with_overflow,
+ intrinsics::i32_sub_with_overflow,
+ intrinsics::i32_mul_with_overflow }
+}
- #[cfg(target_pointer_width = "64")]
- #[lang = "isize"]
- impl isize {
- int_impl! { int = i64, u64, 64,
- intrinsics::i64_add_with_overflow,
- intrinsics::i64_sub_with_overflow,
- intrinsics::i64_mul_with_overflow }
- }
+#[cfg(target_pointer_width = "64")]
+#[lang = "isize"]
+impl isize {
+ int_impl! { int = i64, u64, 64,
+ intrinsics::i64_add_with_overflow,
+ intrinsics::i64_sub_with_overflow,
+ intrinsics::i64_mul_with_overflow }
+}
- // `Int` + `UnsignedInt` implemented for signed integers
- macro_rules! uint_impl {
- ($T:ty = $ActualT:ty, $BITS:expr,
- $ctpop:path,
- $ctlz:path,
- $cttz:path,
- $bswap:path,
- $add_with_overflow:path,
- $sub_with_overflow:path,
- $mul_with_overflow:path) => {
- /// Returns the `0` value of this integer type.
- // FIXME (#5527): Should be an associated constant
- #[unstable(feature = "core",
- reason = "unsure about its place in the world")]
- #[inline]
- pub fn zero() -> $T { 0 }
-
- /// Returns the `1` value of this integer type.
- // FIXME (#5527): Should be an associated constant
- #[unstable(feature = "core",
- reason = "unsure about its place in the world")]
- #[inline]
- pub fn one() -> $T { 1 }
-
- /// Returns the smallest value that can be represented by this integer type.
- // FIXME (#5527): Should be and associated constant
- #[unstable(feature = "core",
- reason = "unsure about its place in the world")]
- #[inline]
- pub fn min_value() -> $T { 0 }
-
- /// Returns the largest value that can be represented by this integer type.
- // FIXME (#5527): Should be and associated constant
- #[unstable(feature = "core",
- reason = "unsure about its place in the world")]
- #[inline]
- pub fn max_value() -> $T { -1 }
-
- /// Returns the number of ones in the binary representation of `self`.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// let n = 0b01001100u8;
- ///
- /// assert_eq!(n.count_ones(), 3);
- /// ```
- #[unstable(feature = "core",
- reason = "pending integer conventions")]
- #[inline]
- pub fn count_ones(self) -> u32 { unsafe { $ctpop(self as $ActualT) as u32 } }
+// `Int` + `UnsignedInt` implemented for signed integers
+macro_rules! uint_impl {
+ ($T:ty = $ActualT:ty, $BITS:expr,
+ $ctpop:path,
+ $ctlz:path,
+ $cttz:path,
+ $bswap:path,
+ $add_with_overflow:path,
+ $sub_with_overflow:path,
+ $mul_with_overflow:path) => {
+ /// Returns the `0` value of this integer type.
+ // FIXME (#5527): Should be an associated constant
+ #[unstable(feature = "core",
+ reason = "unsure about its place in the world")]
+ #[inline]
+ pub fn zero() -> $T { 0 }
+
+ /// Returns the `1` value of this integer type.
+ // FIXME (#5527): Should be an associated constant
+ #[unstable(feature = "core",
+ reason = "unsure about its place in the world")]
+ #[inline]
+ pub fn one() -> $T { 1 }
+
+ /// Returns the smallest value that can be represented by this integer
+ /// type.
+ // FIXME (#5527): Should be and associated constant
+ #[unstable(feature = "core",
+ reason = "unsure about its place in the world")]
+ #[inline]
+ pub fn min_value() -> $T { 0 }
+
+ /// Returns the largest value that can be represented by this integer
+ /// type.
+ // FIXME (#5527): Should be and associated constant
+ #[unstable(feature = "core",
+ reason = "unsure about its place in the world")]
+ #[inline]
+ pub fn max_value() -> $T { -1 }
+
+ /// Returns the number of ones in the binary representation of `self`.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// let n = 0b01001100u8;
+ ///
+ /// assert_eq!(n.count_ones(), 3);
+ /// ```
+ #[unstable(feature = "core",
+ reason = "pending integer conventions")]
+ #[inline]
+ pub fn count_ones(self) -> u32 {
+ unsafe { $ctpop(self as $ActualT) as u32 }
+ }
- /// Returns the number of zeros in the binary representation of `self`.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// let n = 0b01001100u8;
- ///
- /// assert_eq!(n.count_zeros(), 5);
- /// ```
- #[unstable(feature = "core",
- reason = "pending integer conventions")]
- #[inline]
- pub fn count_zeros(self) -> u32 {
- (!self).count_ones()
- }
+ /// Returns the number of zeros in the binary representation of `self`.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// let n = 0b01001100u8;
+ ///
+ /// assert_eq!(n.count_zeros(), 5);
+ /// ```
+ #[unstable(feature = "core",
+ reason = "pending integer conventions")]
+ #[inline]
+ pub fn count_zeros(self) -> u32 {
+ (!self).count_ones()
+ }
- /// Returns the number of leading zeros in the binary representation
- /// of `self`.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// let n = 0b0101000u16;
- ///
- /// assert_eq!(n.leading_zeros(), 10);
- /// ```
- #[unstable(feature = "core",
- reason = "pending integer conventions")]
- #[inline]
- pub fn leading_zeros(self) -> u32 { unsafe { $ctlz(self as $ActualT) as u32 } }
+ /// Returns the number of leading zeros in the binary representation
+ /// of `self`.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// let n = 0b0101000u16;
+ ///
+ /// assert_eq!(n.leading_zeros(), 10);
+ /// ```
+ #[unstable(feature = "core",
+ reason = "pending integer conventions")]
+ #[inline]
+ pub fn leading_zeros(self) -> u32 {
+ unsafe { $ctlz(self as $ActualT) as u32 }
+ }
- /// Returns the number of trailing zeros in the binary representation
- /// of `self`.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// let n = 0b0101000u16;
- ///
- /// assert_eq!(n.trailing_zeros(), 3);
- /// ```
- #[unstable(feature = "core",
- reason = "pending integer conventions")]
- #[inline]
- pub fn trailing_zeros(self) -> u32 { unsafe { $cttz(self as $ActualT) as u32 } }
+ /// Returns the number of trailing zeros in the binary representation
+ /// of `self`.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// let n = 0b0101000u16;
+ ///
+ /// assert_eq!(n.trailing_zeros(), 3);
+ /// ```
+ #[unstable(feature = "core",
+ reason = "pending integer conventions")]
+ #[inline]
+ pub fn trailing_zeros(self) -> u32 {
+ unsafe { $cttz(self as $ActualT) as u32 }
+ }
- /// Shifts the bits to the left by a specified amount amount, `n`, wrapping
- /// the truncated bits to the end of the resulting integer.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// let n = 0x0123456789ABCDEFu64;
- /// let m = 0x3456789ABCDEF012u64;
- ///
- /// assert_eq!(n.rotate_left(12), m);
- /// ```
- #[unstable(feature = "core",
- reason = "pending integer conventions")]
- #[inline]
- pub fn rotate_left(self, n: u32) -> $T {
- // Protect against undefined behaviour for over-long bit shifts
- let n = n % $BITS;
- (self << n) | (self >> (($BITS - n) % $BITS))
- }
+ /// Shifts the bits to the left by a specified amount amount, `n`,
+ /// wrapping the truncated bits to the end of the resulting integer.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// let n = 0x0123456789ABCDEFu64;
+ /// let m = 0x3456789ABCDEF012u64;
+ ///
+ /// assert_eq!(n.rotate_left(12), m);
+ /// ```
+ #[unstable(feature = "core",
+ reason = "pending integer conventions")]
+ #[inline]
+ pub fn rotate_left(self, n: u32) -> $T {
+ // Protect against undefined behaviour for over-long bit shifts
+ let n = n % $BITS;
+ (self << n) | (self >> (($BITS - n) % $BITS))
+ }
- /// Shifts the bits to the right by a specified amount amount, `n`, wrapping
- /// the truncated bits to the beginning of the resulting integer.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// let n = 0x0123456789ABCDEFu64;
- /// let m = 0xDEF0123456789ABCu64;
- ///
- /// assert_eq!(n.rotate_right(12), m);
- /// ```
- #[unstable(feature = "core",
- reason = "pending integer conventions")]
- #[inline]
- pub fn rotate_right(self, n: u32) -> $T {
- // Protect against undefined behaviour for over-long bit shifts
- let n = n % $BITS;
- (self >> n) | (self << (($BITS - n) % $BITS))
- }
+ /// Shifts the bits to the right by a specified amount amount, `n`,
+ /// wrapping the truncated bits to the beginning of the resulting
+ /// integer.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// let n = 0x0123456789ABCDEFu64;
+ /// let m = 0xDEF0123456789ABCu64;
+ ///
+ /// assert_eq!(n.rotate_right(12), m);
+ /// ```
+ #[unstable(feature = "core",
+ reason = "pending integer conventions")]
+ #[inline]
+ pub fn rotate_right(self, n: u32) -> $T {
+ // Protect against undefined behaviour for over-long bit shifts
+ let n = n % $BITS;
+ (self >> n) | (self << (($BITS - n) % $BITS))
+ }
- /// Reverses the byte order of the integer.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// let n = 0x0123456789ABCDEFu64;
- /// let m = 0xEFCDAB8967452301u64;
- ///
- /// assert_eq!(n.swap_bytes(), m);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- pub fn swap_bytes(self) -> $T { unsafe { $bswap(self as $ActualT) as $T } }
+ /// Reverses the byte order of the integer.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// let n = 0x0123456789ABCDEFu64;
+ /// let m = 0xEFCDAB8967452301u64;
+ ///
+ /// assert_eq!(n.swap_bytes(), m);
+ /// ```
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[inline]
+ pub fn swap_bytes(self) -> $T {
+ unsafe { $bswap(self as $ActualT) as $T }
+ }
- /// Convert an integer from big endian to the target's endianness.
- ///
- /// On big endian this is a no-op. On little endian the bytes are swapped.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// let n = 0x0123456789ABCDEFu64;
- ///
- /// if cfg!(target_endian = "big") {
- /// assert_eq!(Int::from_be(n), n)
- /// } else {
- /// assert_eq!(Int::from_be(n), n.swap_bytes())
- /// }
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- pub fn from_be(x: $T) -> $T {
- if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
- }
+ /// Convert an integer from big endian to the target's endianness.
+ ///
+ /// On big endian this is a no-op. On little endian the bytes are
+ /// swapped.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// let n = 0x0123456789ABCDEFu64;
+ ///
+ /// if cfg!(target_endian = "big") {
+ /// assert_eq!(Int::from_be(n), n)
+ /// } else {
+ /// assert_eq!(Int::from_be(n), n.swap_bytes())
+ /// }
+ /// ```
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[inline]
+ pub fn from_be(x: $T) -> $T {
+ if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
+ }
- /// Convert an integer from little endian to the target's endianness.
- ///
- /// On little endian this is a no-op. On big endian the bytes are swapped.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// let n = 0x0123456789ABCDEFu64;
- ///
- /// if cfg!(target_endian = "little") {
- /// assert_eq!(Int::from_le(n), n)
- /// } else {
- /// assert_eq!(Int::from_le(n), n.swap_bytes())
- /// }
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- pub fn from_le(x: $T) -> $T {
- if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
- }
+ /// Convert an integer from little endian to the target's endianness.
+ ///
+ /// On little endian this is a no-op. On big endian the bytes are
+ /// swapped.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// let n = 0x0123456789ABCDEFu64;
+ ///
+ /// if cfg!(target_endian = "little") {
+ /// assert_eq!(Int::from_le(n), n)
+ /// } else {
+ /// assert_eq!(Int::from_le(n), n.swap_bytes())
+ /// }
+ /// ```
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[inline]
+ pub fn from_le(x: $T) -> $T {
+ if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
+ }
- /// Convert `self` to big endian from the target's endianness.
- ///
- /// On big endian this is a no-op. On little endian the bytes are swapped.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// let n = 0x0123456789ABCDEFu64;
- ///
- /// if cfg!(target_endian = "big") {
- /// assert_eq!(n.to_be(), n)
- /// } else {
- /// assert_eq!(n.to_be(), n.swap_bytes())
- /// }
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- pub fn to_be(self) -> $T { // or not to be?
- if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
- }
+ /// Convert `self` to big endian from the target's endianness.
+ ///
+ /// On big endian this is a no-op. On little endian the bytes are
+ /// swapped.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// let n = 0x0123456789ABCDEFu64;
+ ///
+ /// if cfg!(target_endian = "big") {
+ /// assert_eq!(n.to_be(), n)
+ /// } else {
+ /// assert_eq!(n.to_be(), n.swap_bytes())
+ /// }
+ /// ```
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[inline]
+ pub fn to_be(self) -> $T { // or not to be?
+ if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
+ }
- /// Convert `self` to little endian from the target's endianness.
- ///
- /// On little endian this is a no-op. On big endian the bytes are swapped.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// let n = 0x0123456789ABCDEFu64;
- ///
- /// if cfg!(target_endian = "little") {
- /// assert_eq!(n.to_le(), n)
- /// } else {
- /// assert_eq!(n.to_le(), n.swap_bytes())
- /// }
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- pub fn to_le(self) -> $T {
- if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
- }
+ /// Convert `self` to little endian from the target's endianness.
+ ///
+ /// On little endian this is a no-op. On big endian the bytes are
+ /// swapped.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// let n = 0x0123456789ABCDEFu64;
+ ///
+ /// if cfg!(target_endian = "little") {
+ /// assert_eq!(n.to_le(), n)
+ /// } else {
+ /// assert_eq!(n.to_le(), n.swap_bytes())
+ /// }
+ /// ```
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[inline]
+ pub fn to_le(self) -> $T {
+ if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
+ }
- /// Checked integer addition. Computes `self + other`, returning `None` if
- /// overflow occurred.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// assert_eq!(5u16.checked_add(65530), Some(65535));
- /// assert_eq!(6u16.checked_add(65530), None);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- pub fn checked_add(self, other: $T) -> Option<$T> {
- checked_op!($T, $ActualT, $add_with_overflow, self, other)
- }
+ /// Checked integer addition. Computes `self + other`, returning `None`
+ /// if overflow occurred.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// assert_eq!(5u16.checked_add(65530), Some(65535));
+ /// assert_eq!(6u16.checked_add(65530), None);
+ /// ```
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[inline]
+ pub fn checked_add(self, other: $T) -> Option<$T> {
+ checked_op!($T, $ActualT, $add_with_overflow, self, other)
+ }
- /// Checked integer subtraction. Computes `self - other`, returning `None`
- /// if underflow occurred.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// assert_eq!((-127i8).checked_sub(1), Some(-128));
- /// assert_eq!((-128i8).checked_sub(1), None);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- pub fn checked_sub(self, other: $T) -> Option<$T> {
- checked_op!($T, $ActualT, $sub_with_overflow, self, other)
- }
+ /// Checked integer subtraction. Computes `self - other`, returning
+ /// `None` if underflow occurred.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// assert_eq!((-127i8).checked_sub(1), Some(-128));
+ /// assert_eq!((-128i8).checked_sub(1), None);
+ /// ```
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[inline]
+ pub fn checked_sub(self, other: $T) -> Option<$T> {
+ checked_op!($T, $ActualT, $sub_with_overflow, self, other)
+ }
- /// Checked integer multiplication. Computes `self * other`, returning
- /// `None` if underflow or overflow occurred.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// assert_eq!(5u8.checked_mul(51), Some(255));
- /// assert_eq!(5u8.checked_mul(52), None);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- pub fn checked_mul(self, other: $T) -> Option<$T> {
- checked_op!($T, $ActualT, $mul_with_overflow, self, other)
- }
+ /// Checked integer multiplication. Computes `self * other`, returning
+ /// `None` if underflow or overflow occurred.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// assert_eq!(5u8.checked_mul(51), Some(255));
+ /// assert_eq!(5u8.checked_mul(52), None);
+ /// ```
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[inline]
+ pub fn checked_mul(self, other: $T) -> Option<$T> {
+ checked_op!($T, $ActualT, $mul_with_overflow, self, other)
+ }
- /// Checked integer division. Computes `self / other`, returning `None` if
- /// `other == 0` or the operation results in underflow or overflow.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// assert_eq!((-127i8).checked_div(-1), Some(127));
- /// assert_eq!((-128i8).checked_div(-1), None);
- /// assert_eq!((1i8).checked_div(0), None);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- pub fn checked_div(self, v: $T) -> Option<$T> {
- match v {
- 0 => None,
- v => Some(self / v),
- }
+ /// Checked integer division. Computes `self / other`, returning `None`
+ /// if `other == 0` or the operation results in underflow or overflow.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// assert_eq!((-127i8).checked_div(-1), Some(127));
+ /// assert_eq!((-128i8).checked_div(-1), None);
+ /// assert_eq!((1i8).checked_div(0), None);
+ /// ```
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[inline]
+ pub fn checked_div(self, v: $T) -> Option<$T> {
+ match v {
+ 0 => None,
+ v => Some(self / v),
}
+ }
- /// Saturating integer addition. Computes `self + other`, saturating at
- /// the numeric bounds instead of overflowing.
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- pub fn saturating_add(self, other: $T) -> $T {
- match self.checked_add(other) {
- Some(x) => x,
- None if other >= <$T>::zero() => <$T>::max_value(),
- None => <$T>::min_value(),
- }
+ /// Saturating integer addition. Computes `self + other`, saturating at
+ /// the numeric bounds instead of overflowing.
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[inline]
+ pub fn saturating_add(self, other: $T) -> $T {
+ match self.checked_add(other) {
+ Some(x) => x,
+ None if other >= <$T>::zero() => <$T>::max_value(),
+ None => <$T>::min_value(),
}
+ }
- /// Saturating integer subtraction. Computes `self - other`, saturating at
- /// the numeric bounds instead of overflowing.
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- pub fn saturating_sub(self, other: $T) -> $T {
- match self.checked_sub(other) {
- Some(x) => x,
- None if other >= <$T>::zero() => <$T>::min_value(),
- None => <$T>::max_value(),
- }
+ /// Saturating integer subtraction. Computes `self - other`, saturating
+ /// at the numeric bounds instead of overflowing.
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[inline]
+ pub fn saturating_sub(self, other: $T) -> $T {
+ match self.checked_sub(other) {
+ Some(x) => x,
+ None if other >= <$T>::zero() => <$T>::min_value(),
+ None => <$T>::max_value(),
}
+ }
- /// Raises self to the power of `exp`, using exponentiation by squaring.
- ///
- /// # Examples
- ///
- /// ```rust
- /// use std::num::Int;
- ///
- /// assert_eq!(2.pow(4), 16);
- /// ```
- #[unstable(feature = "core",
- reason = "pending integer conventions")]
- #[inline]
- pub fn pow(self, mut exp: u32) -> $T {
- let mut base = self;
- let mut acc = <$T>::one();
-
- let mut prev_base = self;
- let mut base_oflo = false;
- while exp > 0 {
- if (exp & 1) == 1 {
- if base_oflo {
- // ensure overflow occurs in the same manner it
- // would have otherwise (i.e. signal any exception
- // it would have otherwise).
- acc = acc * (prev_base * prev_base);
- } else {
- acc = acc * base;
- }
+ /// Raises self to the power of `exp`, using exponentiation by squaring.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use std::num::Int;
+ ///
+ /// assert_eq!(2.pow(4), 16);
+ /// ```
+ #[unstable(feature = "core",
+ reason = "pending integer conventions")]
+ #[inline]
+ pub fn pow(self, mut exp: u32) -> $T {
+ let mut base = self;
+ let mut acc = <$T>::one();
+
+ let mut prev_base = self;
+ let mut base_oflo = false;
+ while exp > 0 {
+ if (exp & 1) == 1 {
+ if base_oflo {
+ // ensure overflow occurs in the same manner it
+ // would have otherwise (i.e. signal any exception
+ // it would have otherwise).
+ acc = acc * (prev_base * prev_base);
+ } else {
+ acc = acc * base;
}
- prev_base = base;
- let (new_base, new_base_oflo) = base.overflowing_mul(base);
- base = new_base;
- base_oflo = new_base_oflo;
- exp /= 2;
}
- acc
+ prev_base = base;
+ let (new_base, new_base_oflo) = base.overflowing_mul(base);
+ base = new_base;
+ base_oflo = new_base_oflo;
+ exp /= 2;
}
+ acc
+ }
- /// Returns `true` iff `self == 2^k` for some `k`.
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- pub fn is_power_of_two(self) -> bool {
- (self.wrapping_sub(<$T>::one())) & self == <$T>::zero() && !(self == <$T>::zero())
- }
+ /// Returns `true` iff `self == 2^k` for some `k`.
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[inline]
+ pub fn is_power_of_two(self) -> bool {
+ (self.wrapping_sub(<$T>::one())) & self == <$T>::zero() &&
+ !(self == <$T>::zero())
+ }
- /// Returns the smallest power of two greater than or equal to `self`.
- /// Unspecified behavior on overflow.
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- pub fn next_power_of_two(self) -> $T {
- let bits = size_of::<$T>() * 8;
- let one: $T = <$T>::one();
- one << ((bits - self.wrapping_sub(one).leading_zeros() as usize) % bits)
- }
+ /// Returns the smallest power of two greater than or equal to `self`.
+ /// Unspecified behavior on overflow.
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[inline]
+ pub fn next_power_of_two(self) -> $T {
+ let bits = size_of::<$T>() * 8;
+ let one: $T = <$T>::one();
+ one << ((bits - self.wrapping_sub(one).leading_zeros() as usize) % bits)
+ }
- /// Returns the smallest power of two greater than or equal to `n`. If the
- /// next power of two is greater than the type's maximum value, `None` is
- /// returned, otherwise the power of two is wrapped in `Some`.
- #[stable(feature = "rust1", since = "1.0.0")]
- pub fn checked_next_power_of_two(self) -> Option<$T> {
- let npot = self.next_power_of_two();
- if npot >= self {
- Some(npot)
- } else {
- None
- }
+ /// Returns the smallest power of two greater than or equal to `n`. If
+ /// the next power of two is greater than the type's maximum value,
+ /// `None` is returned, otherwise the power of two is wrapped in `Some`.
+ #[stable(feature = "rust1", since = "1.0.0")]
+ pub fn checked_next_power_of_two(self) -> Option<$T> {
+ let npot = self.next_power_of_two();
+ if npot >= self {
+ Some(npot)
+ } else {
+ None
}
}
}
+}
- /// Swapping a single byte is a no-op. This is marked as `unsafe` for
- /// consistency with the other `bswap` intrinsics.
- unsafe fn bswap8(x: u8) -> u8 { x }
-
- #[lang = "u8"]
- impl u8 {
- uint_impl! { u8 = u8, 8,
- intrinsics::ctpop8,
- intrinsics::ctlz8,
- intrinsics::cttz8,
- bswap8,
- intrinsics::u8_add_with_overflow,
- intrinsics::u8_sub_with_overflow,
- intrinsics::u8_mul_with_overflow }
- }
+#[lang = "u8"]
+impl u8 {
+ uint_impl! { u8 = u8, 8,
+ intrinsics::ctpop8,
+ intrinsics::ctlz8,
+ intrinsics::cttz8,
+ bswap8,
+ intrinsics::u8_add_with_overflow,
+ intrinsics::u8_sub_with_overflow,
+ intrinsics::u8_mul_with_overflow }
+}
- #[lang = "u16"]
- impl u16 {
- uint_impl! { u16 = u16, 16,
- intrinsics::ctpop16,
- intrinsics::ctlz16,
- intrinsics::cttz16,
- intrinsics::bswap16,
- intrinsics::u16_add_with_overflow,
- intrinsics::u16_sub_with_overflow,
- intrinsics::u16_mul_with_overflow }
- }
+#[lang = "u16"]
+impl u16 {
+ uint_impl! { u16 = u16, 16,
+ intrinsics::ctpop16,
+ intrinsics::ctlz16,
+ intrinsics::cttz16,
+ intrinsics::bswap16,
+ intrinsics::u16_add_with_overflow,
+ intrinsics::u16_sub_with_overflow,
+ intrinsics::u16_mul_with_overflow }
+}
- #[lang = "u32"]
- impl u32 {
- uint_impl! { u32 = u32, 32,
- intrinsics::ctpop32,
- intrinsics::ctlz32,
- intrinsics::cttz32,
- intrinsics::bswap32,
- intrinsics::u32_add_with_overflow,
- intrinsics::u32_sub_with_overflow,
- intrinsics::u32_mul_with_overflow }
- }
+#[lang = "u32"]
+impl u32 {
+ uint_impl! { u32 = u32, 32,
+ intrinsics::ctpop32,
+ intrinsics::ctlz32,
+ intrinsics::cttz32,
+ intrinsics::bswap32,
+ intrinsics::u32_add_with_overflow,
+ intrinsics::u32_sub_with_overflow,
+ intrinsics::u32_mul_with_overflow }
+}
- #[lang = "u64"]
- impl u64 {
- uint_impl! { u64 = u64, 64,
- intrinsics::ctpop64,
- intrinsics::ctlz64,
- intrinsics::cttz64,
- intrinsics::bswap64,
- intrinsics::u64_add_with_overflow,
- intrinsics::u64_sub_with_overflow,
- intrinsics::u64_mul_with_overflow }
- }
+#[lang = "u64"]
+impl u64 {
+ uint_impl! { u64 = u64, 64,
+ intrinsics::ctpop64,
+ intrinsics::ctlz64,
+ intrinsics::cttz64,
+ intrinsics::bswap64,
+ intrinsics::u64_add_with_overflow,
+ intrinsics::u64_sub_with_overflow,
+ intrinsics::u64_mul_with_overflow }
+}
- #[cfg(target_pointer_width = "32")]
- #[lang = "usize"]
- impl usize {
- uint_impl! { uint = u32, 32,
- intrinsics::ctpop32,
- intrinsics::ctlz32,
- intrinsics::cttz32,
- intrinsics::bswap32,
- intrinsics::u32_add_with_overflow,
- intrinsics::u32_sub_with_overflow,
- intrinsics::u32_mul_with_overflow }
- }
+#[cfg(target_pointer_width = "32")]
+#[lang = "usize"]
+impl usize {
+ uint_impl! { uint = u32, 32,
+ intrinsics::ctpop32,
+ intrinsics::ctlz32,
+ intrinsics::cttz32,
+ intrinsics::bswap32,
+ intrinsics::u32_add_with_overflow,
+ intrinsics::u32_sub_with_overflow,
+ intrinsics::u32_mul_with_overflow }
+}
- #[cfg(target_pointer_width = "64")]
- #[lang = "usize"]
- impl usize {
- uint_impl! { uint = u64, 64,
- intrinsics::ctpop64,
- intrinsics::ctlz64,
- intrinsics::cttz64,
- intrinsics::bswap64,
- intrinsics::u64_add_with_overflow,
- intrinsics::u64_sub_with_overflow,
- intrinsics::u64_mul_with_overflow }
- }
+#[cfg(target_pointer_width = "64")]
+#[lang = "usize"]
+impl usize {
+ uint_impl! { uint = u64, 64,
+ intrinsics::ctpop64,
+ intrinsics::ctlz64,
+ intrinsics::cttz64,
+ intrinsics::bswap64,
+ intrinsics::u64_add_with_overflow,
+ intrinsics::u64_sub_with_overflow,
+ intrinsics::u64_mul_with_overflow }
}
/// A generic trait for converting a value to a number.
pub use iter::{Iterator, DoubleEndedIterator};
pub use iter::{ExactSizeIterator};
pub use option::Option::{self, Some, None};
-#[cfg(stage0)]
-pub use ptr::{PtrExt, MutPtrExt};
pub use result::Result::{self, Ok, Err};
pub use slice::{AsSlice, SliceExt};
pub use str::{Str, StrExt};
intrinsics::move_val_init(&mut *dst, src)
}
-#[cfg(stage0)]
-/// Methods on raw pointers
-#[stable(feature = "rust1", since = "1.0.0")]
-pub trait PtrExt {
- /// The type which is being pointed at
- type Target: ?Sized;
-
- /// Returns true if the pointer is null.
- #[stable(feature = "rust1", since = "1.0.0")]
- fn is_null(self) -> bool;
-
- /// Returns `None` if the pointer is null, or else returns a reference to
- /// the value wrapped in `Some`.
- ///
- /// # Safety
- ///
- /// While this method and its mutable counterpart are useful for
- /// null-safety, it is important to note that this is still an unsafe
- /// operation because the returned value could be pointing to invalid
- /// memory.
- #[unstable(feature = "core",
- reason = "Option is not clearly the right return type, and we may want \
- to tie the return lifetime to a borrow of the raw pointer")]
- unsafe fn as_ref<'a>(&self) -> Option<&'a Self::Target>;
-
- /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
- /// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.
- ///
- /// # Safety
- ///
- /// The offset must be in-bounds of the object, or one-byte-past-the-end.
- /// Otherwise `offset` invokes Undefined Behaviour, regardless of whether
- /// the pointer is used.
- #[stable(feature = "rust1", since = "1.0.0")]
- unsafe fn offset(self, count: isize) -> Self where Self::Target: Sized;
-}
-
-#[cfg(stage0)]
-/// Methods on mutable raw pointers
-#[stable(feature = "rust1", since = "1.0.0")]
-pub trait MutPtrExt {
- /// The type which is being pointed at
- type Target: ?Sized;
-
- /// Returns `None` if the pointer is null, or else returns a mutable
- /// reference to the value wrapped in `Some`.
- ///
- /// # Safety
- ///
- /// As with `as_ref`, this is unsafe because it cannot verify the validity
- /// of the returned pointer.
- #[unstable(feature = "core",
- reason = "Option is not clearly the right return type, and we may want \
- to tie the return lifetime to a borrow of the raw pointer")]
- unsafe fn as_mut<'a>(&self) -> Option<&'a mut Self::Target>;
-}
-
-#[cfg(stage0)]
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<T: ?Sized> PtrExt for *const T {
- type Target = T;
-
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn is_null(self) -> bool { self == 0 as *const T }
-
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- unsafe fn offset(self, count: isize) -> *const T where T: Sized {
- intrinsics::offset(self, count)
- }
-
- #[inline]
- #[unstable(feature = "core",
- reason = "return value does not necessarily convey all possible \
- information")]
- unsafe fn as_ref<'a>(&self) -> Option<&'a T> {
- if self.is_null() {
- None
- } else {
- Some(&**self)
- }
- }
-}
-
-#[cfg(stage0)]
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<T: ?Sized> PtrExt for *mut T {
- type Target = T;
-
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn is_null(self) -> bool { self == 0 as *mut T }
-
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- unsafe fn offset(self, count: isize) -> *mut T where T: Sized {
- intrinsics::offset(self, count) as *mut T
- }
-
- #[inline]
- #[unstable(feature = "core",
- reason = "return value does not necessarily convey all possible \
- information")]
- unsafe fn as_ref<'a>(&self) -> Option<&'a T> {
- if self.is_null() {
- None
- } else {
- Some(&**self)
- }
- }
-}
-
-#[cfg(stage0)]
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<T: ?Sized> MutPtrExt for *mut T {
- type Target = T;
-
- #[inline]
- #[unstable(feature = "core",
- reason = "return value does not necessarily convey all possible \
- information")]
- unsafe fn as_mut<'a>(&self) -> Option<&'a mut T> {
- if self.is_null() {
- None
- } else {
- Some(&mut **self)
- }
- }
-}
-
-#[cfg(not(stage0))]
#[stable(feature = "rust1", since = "1.0.0")]
#[lang = "const_ptr"]
impl<T: ?Sized> *const T {
/// Returns true if the pointer is null.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
- pub fn is_null(self) -> bool {
+ pub fn is_null(self) -> bool where T: Sized {
self == 0 as *const T
}
reason = "Option is not clearly the right return type, and we may want \
to tie the return lifetime to a borrow of the raw pointer")]
#[inline]
- pub unsafe fn as_ref<'a>(&self) -> Option<&'a T> {
+ pub unsafe fn as_ref<'a>(&self) -> Option<&'a T> where T: Sized {
if self.is_null() {
None
} else {
}
}
-#[cfg(not(stage0))]
#[stable(feature = "rust1", since = "1.0.0")]
#[lang = "mut_ptr"]
impl<T: ?Sized> *mut T {
/// Returns true if the pointer is null.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
- pub fn is_null(self) -> bool {
+ pub fn is_null(self) -> bool where T: Sized {
self == 0 as *mut T
}
reason = "Option is not clearly the right return type, and we may want \
to tie the return lifetime to a borrow of the raw pointer")]
#[inline]
- pub unsafe fn as_ref<'a>(&self) -> Option<&'a T> {
+ pub unsafe fn as_ref<'a>(&self) -> Option<&'a T> where T: Sized {
if self.is_null() {
None
} else {
reason = "return value does not necessarily convey all possible \
information")]
#[inline]
- pub unsafe fn as_mut<'a>(&self) -> Option<&'a mut T> {
+ pub unsafe fn as_mut<'a>(&self) -> Option<&'a mut T> where T: Sized {
if self.is_null() {
None
} else {
use result::Result;
use result::Result::{Ok, Err};
use ptr;
-#[cfg(stage0)]
-use ptr::PtrExt;
use mem;
use mem::size_of;
use marker::{Send, Sized, Sync, self};
use num::Int;
use ops::{Fn, FnMut};
use option::Option::{self, None, Some};
-#[cfg(stage0)]
-use ptr::PtrExt;
use raw::{Repr, Slice};
use result::Result::{self, Ok, Err};
use slice::{self, SliceExt};
use std::cmp::Ordering;
use std::fmt;
use std::iter::{range_inclusive, AdditiveIterator, FromIterator, IntoIterator, repeat};
-#[cfg(stage0)]
-use std::num::Float;
use std::slice;
use syntax::ast::{self, DUMMY_NODE_ID, NodeId, Pat};
use syntax::ast_util;
use std::io;
use std::mem::{swap};
use std::num::FpCategory as Fp;
-#[cfg(stage0)]
-use std::num::{Float, Int};
use std::ops::Index;
use std::str::FromStr;
use std::string;
use iter::{self, Iterator, ExactSizeIterator, IntoIterator, IteratorExt, FromIterator, Extend, Map};
use marker::Sized;
use mem::{self, replace};
-#[cfg(stage0)]
-use num::{Int, UnsignedInt};
use ops::{Deref, FnMut, Index, IndexMut};
use option::Option::{self, Some, None};
use rand::{self, Rng};
use marker::{Copy, Send, Sync, Sized, self};
use mem::{min_align_of, size_of};
use mem;
-#[cfg(stage0)]
-use num::{Int, UnsignedInt};
use num::wrapping::{OverflowingOps, WrappingOps};
use ops::{Deref, DerefMut, Drop};
use option::Option;
use option::Option::{Some, None};
-#[cfg(stage0)]
-use ptr::{self, PtrExt, Unique};
-#[cfg(not(stage0))]
use ptr::{self, Unique};
use rt::heap::{allocate, deallocate, EMPTY};
use collections::hash_state::HashState;
use ptr;
use result::Result;
use result::Result::{Ok, Err};
- #[cfg(stage0)]
- use slice::SliceExt;
- #[cfg(stage0)]
- use str::StrExt;
use str;
use string::String;
use vec::Vec;
let err = os::errno();
if err as libc::c_int == ERROR_CALL_NOT_IMPLEMENTED {
use_thread_mode = false;
- // SetThreadErrorMode not found. use fallback solution: SetErrorMode()
- // Note that SetErrorMode is process-wide so this can cause race condition!
- // However, since even Windows APIs do not care of such problem (#20650),
- // we just assume SetErrorMode race is not a great deal.
+ // SetThreadErrorMode not found. use fallback solution:
+ // SetErrorMode() Note that SetErrorMode is process-wide so
+ // this can cause race condition! However, since even
+ // Windows APIs do not care of such problem (#20650), we
+ // just assume SetErrorMode race is not a great deal.
prev_error_mode = SetErrorMode(new_error_mode);
}
}
use ops::Deref;
use option::Option::{self, Some, None};
use result::Result::{self, Ok, Err};
-#[cfg(stage0)]
-use slice::{self, SliceExt};
-#[cfg(not(stage0))]
use slice;
-#[cfg(stage0)]
-use str::StrExt;
use string::String;
use vec::Vec;
use marker::Sized;
use ops::{Drop, FnOnce};
use option::Option::{self, Some, None};
-#[cfg(stage0)]
-use ptr::PtrExt;
use result::Result::{Ok, Err};
use result;
-#[cfg(stage0)]
-use slice::{self, SliceExt};
-#[cfg(not(stage0))]
use slice;
use string::String;
-#[cfg(stage0)]
-use str::{self, StrExt};
-#[cfg(not(stage0))]
use str;
use vec::Vec;
}
}
-#[cfg(not(stage0))]
#[cfg(not(test))]
#[lang = "f32"]
#[stable(feature = "rust1", since = "1.0.0")]
}
}
-#[cfg(not(stage0))]
#[cfg(not(test))]
#[lang = "f64"]
#[stable(feature = "rust1", since = "1.0.0")]
#![unstable(feature = "std_misc")]
#![doc(hidden)]
-#[cfg(stage0)]
-macro_rules! assert_approx_eq {
- ($a:expr, $b:expr) => ({
- use num::Float;
- let (a, b) = (&$a, &$b);
- assert!((*a - *b).abs() < 1.0e-6,
- "{} is not approximately equal to {}", *a, *b);
- })
-}
-
-#[cfg(not(stage0))]
macro_rules! assert_approx_eq {
($a:expr, $b:expr) => ({
let (a, b) = (&$a, &$b);
use clone::Clone;
use cmp::{PartialOrd, PartialEq};
-#[cfg(stage0)]
-pub use core::num::{Int, SignedInt, UnsignedInt};
-#[cfg(not(stage0))]
pub use core::num::{Int, SignedInt};
pub use core::num::{cast, FromPrimitive, NumCast, ToPrimitive};
pub use core::num::{from_int, from_i8, from_i16, from_i32, from_i64};
use self::SignificantDigits::*;
use self::SignFormat::*;
-#[cfg(stage0)]
-use char::{self, CharExt};
-#[cfg(not(stage0))]
use char;
use num::{self, Int, Float, ToPrimitive};
use num::FpCategory as Fp;
use ops::FnMut;
-#[cfg(stage0)]
-use slice::SliceExt;
-#[cfg(stage0)]
-use str::StrExt;
use string::String;
use vec::Vec;
use option::Option;
use option::Option::{Some, None};
use result::Result::Ok;
-#[cfg(stage0)]
-use slice::{SliceExt};
use slice;
use vec::Vec;
use old_io;
use option::Option::{None, Some};
use result::Result::{Ok, Err};
-#[cfg(stage0)]
-use slice::{bytes, SliceExt};
-#[cfg(not(stage0))]
use slice::bytes;
use super::{Buffer, Reader, Writer, IoResult};
use vec::Vec;
use ops::FnOnce;
use option::Option;
use option::Option::{Some, None};
-#[cfg(stage0)]
-use ptr::PtrExt;
use result::Result::{Ok, Err};
-#[cfg(stage0)]
-use slice::SliceExt;
/// An iterator that reads a single byte on each iteration,
/// until `.read_byte()` returns `EndOfFile`.
/// 32-bit value is parsed.
pub fn u64_from_be_bytes(data: &[u8], start: uint, size: uint) -> u64 {
use ptr::{copy_nonoverlapping_memory};
- #[cfg(stage0)]
- use slice::SliceExt;
assert!(size <= 8);
use old_path::{Path, GenericPath};
use old_path;
use result::Result::{Err, Ok};
-#[cfg(stage0)]
-use slice::SliceExt;
use string::String;
use vec::Vec;
use result::Result::{Err, Ok};
use old_io;
use old_io::{Reader, Writer, Seek, Buffer, IoError, SeekStyle, IoResult};
-#[cfg(stage0)]
-use slice::{self, SliceExt};
-#[cfg(not(stage0))]
use slice;
use vec::Vec;
pub use self::FileAccess::*;
pub use self::IoErrorKind::*;
-#[cfg(stage0)]
-use char::CharExt;
use default::Default;
use error::Error;
use fmt;
use result::Result;
use result::Result::{Ok, Err};
use sys;
-#[cfg(stage0)]
-use slice::SliceExt;
-#[cfg(stage0)]
-use str::StrExt;
use str;
use string::String;
use usize;
// API yet. If so, it should be a method on Vec.
unsafe fn slice_vec_capacity<'a, T>(v: &'a mut Vec<T>, start: uint, end: uint) -> &'a mut [T] {
use slice;
- #[cfg(stage0)]
- use ptr::PtrExt;
assert!(start <= end);
assert!(end <= v.capacity());
use option::Option;
use option::Option::{None, Some};
use result::Result::{self, Ok, Err};
-#[cfg(stage0)]
-use slice::SliceExt;
-#[cfg(stage0)]
-use str::{FromStr, StrExt};
-#[cfg(not(stage0))]
use str::FromStr;
use vec::Vec;
use ptr;
use result::Result::{Ok, Err};
use rt;
-#[cfg(stage0)]
-use slice::SliceExt;
-#[cfg(stage0)]
-use str::StrExt;
use string::String;
use sys::{fs, tty};
use sync::{Arc, Mutex, MutexGuard, Once, ONCE_INIT};
use old_path::{Path, GenericPath};
use rand::{Rng, thread_rng};
use result::Result::{Ok, Err};
-#[cfg(stage0)]
-use str::StrExt;
use string::String;
/// A wrapper for a path to temporary directory implementing automatic
use option::Option;
use option::Option::{None, Some};
use str;
-#[cfg(stage0)]
-use str::StrExt;
use string::{String, CowString};
-#[cfg(stage0)]
-use slice::SliceExt;
use vec::Vec;
/// Typedef for POSIX file paths.
use marker::Sized;
use option::Option::{self, Some, None};
use result::Result::{self, Ok, Err};
-#[cfg(stage0)]
-use slice::{AsSlice, Split, SliceExt, SliceConcatExt};
-#[cfg(not(stage0))]
use slice::{AsSlice, Split, SliceConcatExt};
-#[cfg(stage0)]
-use str::{self, FromStr, StrExt};
-#[cfg(not(stage0))]
use str::{self, FromStr};
use vec::Vec;
use self::PathPrefix::*;
use ascii::AsciiExt;
-#[cfg(stage0)]
-use char::CharExt;
use clone::Clone;
use cmp::{Ordering, Eq, Ord, PartialEq, PartialOrd};
use fmt;
use mem;
use option::Option::{self, Some, None};
use result::Result::{self, Ok, Err};
-#[cfg(stage0)]
-use slice::{SliceExt, SliceConcatExt};
-#[cfg(not(stage0))]
use slice::SliceConcatExt;
-#[cfg(stage0)]
-use str::{SplitTerminator, FromStr, StrExt};
-#[cfg(not(stage0))]
use str::{SplitTerminator, FromStr};
use string::{String, ToString};
use vec::Vec;
use option::Option;
use old_path::{Path, GenericPath, BytesContainer};
use path::{self, PathBuf};
-#[cfg(stage0)]
-use ptr::PtrExt;
use ptr;
use result::Result::{Err, Ok};
use result::Result;
-#[cfg(stage0)]
-use slice::{AsSlice, SliceExt};
-#[cfg(not(stage0))]
use slice::AsSlice;
-#[cfg(stage0)]
-use str::{Str, StrExt};
-#[cfg(not(stage0))]
use str::Str;
use str;
use string::{String, ToString};
use core::prelude::*;
use ascii::*;
- #[cfg(stage0)]
- use char::CharExt as UnicodeCharExt;
use super::{os_str_as_u8_slice, u8_slice_as_os_str, Prefix};
use ffi::OsStr;
// Reexported types and traits
#[stable(feature = "rust1", since = "1.0.0")]
#[doc(no_inline)] pub use boxed::Box;
-#[cfg(stage0)]
-#[stable(feature = "rust1", since = "1.0.0")]
-#[doc(no_inline)] pub use char::CharExt;
#[stable(feature = "rust1", since = "1.0.0")]
#[doc(no_inline)] pub use clone::Clone;
#[stable(feature = "rust1", since = "1.0.0")]
#[doc(no_inline)] pub use iter::{Iterator, IteratorExt, Extend};
#[stable(feature = "rust1", since = "1.0.0")]
#[doc(no_inline)] pub use option::Option::{self, Some, None};
-#[cfg(stage0)]
-#[stable(feature = "rust1", since = "1.0.0")]
-#[doc(no_inline)] pub use ptr::{PtrExt, MutPtrExt};
#[stable(feature = "rust1", since = "1.0.0")]
#[doc(no_inline)] pub use result::Result::{self, Ok, Err};
-#[cfg(stage0)]
-#[stable(feature = "rust1", since = "1.0.0")]
-#[doc(no_inline)] pub use slice::{SliceExt, SliceConcatExt, AsSlice};
-#[cfg(not(stage0))]
#[stable(feature = "rust1", since = "1.0.0")]
#[doc(no_inline)] pub use slice::{SliceConcatExt, AsSlice};
-#[cfg(stage0)]
-#[stable(feature = "rust1", since = "1.0.0")]
-#[doc(no_inline)] pub use str::{Str, StrExt};
-#[cfg(not(stage0))]
#[stable(feature = "rust1", since = "1.0.0")]
#[doc(no_inline)] pub use str::Str;
#[stable(feature = "rust1", since = "1.0.0")]
use rand::Rng;
use rand::reader::ReaderRng;
use result::Result::Ok;
- #[cfg(stage0)]
- use slice::SliceExt;
use mem;
use os::errno;
use rand::Rng;
use result::Result::{Ok};
use self::libc::{c_int, size_t};
- #[cfg(stage0)]
- use slice::SliceExt;
/// A random number generator that retrieves randomness straight from
/// the operating system. Platform sources:
use result::Result::{Ok, Err};
use self::libc::{DWORD, BYTE, LPCSTR, BOOL};
use self::libc::types::os::arch::extra::{LONG_PTR};
- #[cfg(stage0)]
- use slice::SliceExt;
type HCRYPTPROV = LONG_PTR;
use old_io::Reader;
use rand::Rng;
use result::Result::{Ok, Err};
-#[cfg(stage0)]
-use slice::SliceExt;
/// An RNG that reads random bytes straight from a `Reader`. This will
/// work best with an infinite reader, but this is not required.
//!
//! Documentation can be found on the `rt::at_exit` function.
-#[cfg(stage0)]
-use core::prelude::*;
-
use boxed;
use boxed::Box;
use vec::Vec;
Wtf8Buf { bytes: string.into_bytes() }
}
- #[cfg(stage0)]
- /// Create a WTF-8 string from an UTF-8 `&str` slice.
- ///
- /// This copies the content of the slice.
- ///
- /// Since WTF-8 is a superset of UTF-8, this always succeeds.
- #[inline]
- pub fn from_str(str: &str) -> Wtf8Buf {
- Wtf8Buf { bytes: slice::SliceExt::to_vec(str.as_bytes()) }
- }
-
- #[cfg(not(stage0))]
/// Create a WTF-8 string from an UTF-8 `&str` slice.
///
/// This copies the content of the slice.
use borrow::Cow;
use fmt::{self, Debug};
use vec::Vec;
-#[cfg(stage0)]
-use slice::SliceExt as StdSliceExt;
use str;
use string::String;
use mem;
use env::split_paths;
use mem;
use iter::IteratorExt;
- #[cfg(stage0)]
- use str::StrExt;
// To have the spawning semantics of unix/windows stay the same, we need to
// read the *child's* PATH if one is provided. See #15149 for more details.
use std::collections::HashSet;
use std::io::prelude::*;
use std::mem;
-#[cfg(stage0)]
-use std::num::Float;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::slice;
None
}
- // HACK(eddyb) staging required for `quote_item!`.
- #[cfg(stage0)] // SNAP 270a677
- pub fn parse_item_with_outer_attributes(&mut self) -> Option<P<Item>> {
- self.parse_item()
- }
-
pub fn parse_item(&mut self) -> Option<P<Item>> {
let attrs = self.parse_outer_attributes();
self.parse_item_(attrs, true)
pub use tables::normalization::canonical_combining_class;
pub use tables::UNICODE_VERSION;
-#[cfg(stage0)]
-/// Functionality for manipulating `char`.
-#[stable(feature = "rust1", since = "1.0.0")]
-pub trait CharExt {
- /// Checks if a `char` parses as a numeric digit in the given radix.
- ///
- /// Compared to `is_numeric()`, this function only recognizes the characters
- /// `0-9`, `a-z` and `A-Z`.
- ///
- /// # Return value
- ///
- /// Returns `true` if `c` is a valid digit under `radix`, and `false`
- /// otherwise.
- ///
- /// # Panics
- ///
- /// Panics if given a radix > 36.
- ///
- /// # Examples
- ///
- /// ```
- /// let c = '1';
- ///
- /// assert!(c.is_digit(10));
- ///
- /// assert!('f'.is_digit(16));
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn is_digit(self, radix: u32) -> bool;
-
- /// Converts a character to the corresponding digit.
- ///
- /// # Return value
- ///
- /// If `c` is between '0' and '9', the corresponding value between 0 and
- /// 9. If `c` is 'a' or 'A', 10. If `c` is 'b' or 'B', 11, etc. Returns
- /// none if the character does not refer to a digit in the given radix.
- ///
- /// # Panics
- ///
- /// Panics if given a radix outside the range [0..36].
- ///
- /// # Examples
- ///
- /// ```
- /// let c = '1';
- ///
- /// assert_eq!(c.to_digit(10), Some(1));
- ///
- /// assert_eq!('f'.to_digit(16), Some(15));
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn to_digit(self, radix: u32) -> Option<u32>;
-
- /// Returns an iterator that yields the hexadecimal Unicode escape of a
- /// character, as `char`s.
- ///
- /// All characters are escaped with Rust syntax of the form `\\u{NNNN}`
- /// where `NNNN` is the shortest hexadecimal representation of the code
- /// point.
- ///
- /// # Examples
- ///
- /// ```
- /// for i in '❤'.escape_unicode() {
- /// println!("{}", i);
- /// }
- /// ```
- ///
- /// This prints:
- ///
- /// ```text
- /// \
- /// u
- /// {
- /// 2
- /// 7
- /// 6
- /// 4
- /// }
- /// ```
- ///
- /// Collecting into a `String`:
- ///
- /// ```
- /// let heart: String = '❤'.escape_unicode().collect();
- ///
- /// assert_eq!(heart, r"\u{2764}");
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn escape_unicode(self) -> EscapeUnicode;
-
- /// Returns an iterator that yields the 'default' ASCII and
- /// C++11-like literal escape of a character, as `char`s.
- ///
- /// The default is chosen with a bias toward producing literals that are
- /// legal in a variety of languages, including C++11 and similar C-family
- /// languages. The exact rules are:
- ///
- /// * Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively.
- /// * Single-quote, double-quote and backslash chars are backslash-
- /// escaped.
- /// * Any other chars in the range [0x20,0x7e] are not escaped.
- /// * Any other chars are given hex Unicode escapes; see `escape_unicode`.
- ///
- /// # Examples
- ///
- /// ```
- /// for i in '"'.escape_default() {
- /// println!("{}", i);
- /// }
- /// ```
- ///
- /// This prints:
- ///
- /// ```text
- /// \
- /// "
- /// ```
- ///
- /// Collecting into a `String`:
- ///
- /// ```
- /// let quote: String = '"'.escape_default().collect();
- ///
- /// assert_eq!(quote, "\\\"");
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn escape_default(self) -> EscapeDefault;
-
- /// Returns the number of bytes this character would need if encoded in
- /// UTF-8.
- ///
- /// # Examples
- ///
- /// ```
- /// let n = 'ß'.len_utf8();
- ///
- /// assert_eq!(n, 2);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn len_utf8(self) -> usize;
-
- /// Returns the number of 16-bit code units this character would need if
- /// encoded in UTF-16.
- ///
- /// # Examples
- ///
- /// ```
- /// let n = 'ß'.len_utf16();
- ///
- /// assert_eq!(n, 1);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn len_utf16(self) -> usize;
-
- /// Encodes this character as UTF-8 into the provided byte buffer, and then
- /// returns the number of bytes written.
- ///
- /// If the buffer is not large enough, nothing will be written into it and a
- /// `None` will be returned. A buffer of length four is large enough to
- /// encode any `char`.
- ///
- /// # Examples
- ///
- /// In both of these examples, 'ß' takes two bytes to encode.
- ///
- /// ```
- /// let mut b = [0; 2];
- ///
- /// let result = 'ß'.encode_utf8(&mut b);
- ///
- /// assert_eq!(result, Some(2));
- /// ```
- ///
- /// A buffer that's too small:
- ///
- /// ```
- /// let mut b = [0; 1];
- ///
- /// let result = 'ß'.encode_utf8(&mut b);
- ///
- /// assert_eq!(result, None);
- /// ```
- #[unstable(feature = "unicode",
- reason = "pending decision about Iterator/Writer/Reader")]
- fn encode_utf8(self, dst: &mut [u8]) -> Option<usize>;
-
- /// Encodes this character as UTF-16 into the provided `u16` buffer, and
- /// then returns the number of `u16`s written.
- ///
- /// If the buffer is not large enough, nothing will be written into it and a
- /// `None` will be returned. A buffer of length 2 is large enough to encode
- /// any `char`.
- ///
- /// # Examples
- ///
- /// In both of these examples, 'ß' takes one `u16` to encode.
- ///
- /// ```
- /// let mut b = [0; 1];
- ///
- /// let result = 'ß'.encode_utf16(&mut b);
- ///
- /// assert_eq!(result, Some(1));
- /// ```
- ///
- /// A buffer that's too small:
- ///
- /// ```
- /// let mut b = [0; 0];
- ///
- /// let result = 'ß'.encode_utf8(&mut b);
- ///
- /// assert_eq!(result, None);
- /// ```
- #[unstable(feature = "unicode",
- reason = "pending decision about Iterator/Writer/Reader")]
- fn encode_utf16(self, dst: &mut [u16]) -> Option<usize>;
-
- /// Returns whether the specified character is considered a Unicode
- /// alphabetic code point.
- #[stable(feature = "rust1", since = "1.0.0")]
- fn is_alphabetic(self) -> bool;
-
- /// Returns whether the specified character satisfies the 'XID_Start'
- /// Unicode property.
- ///
- /// 'XID_Start' is a Unicode Derived Property specified in
- /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications),
- /// mostly similar to ID_Start but modified for closure under NFKx.
- #[unstable(feature = "unicode",
- reason = "mainly needed for compiler internals")]
- fn is_xid_start(self) -> bool;
-
- /// Returns whether the specified `char` satisfies the 'XID_Continue'
- /// Unicode property.
- ///
- /// 'XID_Continue' is a Unicode Derived Property specified in
- /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications),
- /// mostly similar to 'ID_Continue' but modified for closure under NFKx.
- #[unstable(feature = "unicode",
- reason = "mainly needed for compiler internals")]
- fn is_xid_continue(self) -> bool;
-
- /// Indicates whether a character is in lowercase.
- ///
- /// This is defined according to the terms of the Unicode Derived Core
- /// Property `Lowercase`.
- #[stable(feature = "rust1", since = "1.0.0")]
- fn is_lowercase(self) -> bool;
-
- /// Indicates whether a character is in uppercase.
- ///
- /// This is defined according to the terms of the Unicode Derived Core
- /// Property `Uppercase`.
- #[stable(feature = "rust1", since = "1.0.0")]
- fn is_uppercase(self) -> bool;
-
- /// Indicates whether a character is whitespace.
- ///
- /// Whitespace is defined in terms of the Unicode Property `White_Space`.
- #[stable(feature = "rust1", since = "1.0.0")]
- fn is_whitespace(self) -> bool;
-
- /// Indicates whether a character is alphanumeric.
- ///
- /// Alphanumericness is defined in terms of the Unicode General Categories
- /// 'Nd', 'Nl', 'No' and the Derived Core Property 'Alphabetic'.
- #[stable(feature = "rust1", since = "1.0.0")]
- fn is_alphanumeric(self) -> bool;
-
- /// Indicates whether a character is a control code point.
- ///
- /// Control code points are defined in terms of the Unicode General
- /// Category `Cc`.
- #[stable(feature = "rust1", since = "1.0.0")]
- fn is_control(self) -> bool;
-
- /// Indicates whether the character is numeric (Nd, Nl, or No).
- #[stable(feature = "rust1", since = "1.0.0")]
- fn is_numeric(self) -> bool;
-
- /// Converts a character to its lowercase equivalent.
- ///
- /// The case-folding performed is the common or simple mapping. See
- /// `to_uppercase()` for references and more information.
- ///
- /// # Return value
- ///
- /// Returns an iterator which yields the characters corresponding to the
- /// lowercase equivalent of the character. If no conversion is possible then
- /// the input character is returned.
- #[stable(feature = "rust1", since = "1.0.0")]
- fn to_lowercase(self) -> ToLowercase;
-
- /// Converts a character to its uppercase equivalent.
- ///
- /// The case-folding performed is the common or simple mapping: it maps
- /// one Unicode codepoint to its uppercase equivalent according to the
- /// Unicode database [1]. The additional [`SpecialCasing.txt`] is not yet
- /// considered here, but the iterator returned will soon support this form
- /// of case folding.
- ///
- /// A full reference can be found here [2].
- ///
- /// # Return value
- ///
- /// Returns an iterator which yields the characters corresponding to the
- /// uppercase equivalent of the character. If no conversion is possible then
- /// the input character is returned.
- ///
- /// [1]: ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt
- ///
- /// [`SpecialCasing`.txt`]: ftp://ftp.unicode.org/Public/UNIDATA/SpecialCasing.txt
- ///
- /// [2]: http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G33992
- #[stable(feature = "rust1", since = "1.0.0")]
- fn to_uppercase(self) -> ToUppercase;
-
- /// Returns this character's displayed width in columns, or `None` if it is a
- /// control character other than `'\x00'`.
- ///
- /// `is_cjk` determines behavior for characters in the Ambiguous category:
- /// if `is_cjk` is `true`, these are 2 columns wide; otherwise, they are 1.
- /// In CJK contexts, `is_cjk` should be `true`, else it should be `false`.
- /// [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/)
- /// recommends that these characters be treated as 1 column (i.e.,
- /// `is_cjk` = `false`) if the context cannot be reliably determined.
- #[unstable(feature = "unicode",
- reason = "needs expert opinion. is_cjk flag stands out as ugly")]
- fn width(self, is_cjk: bool) -> Option<usize>;
-}
-
-#[cfg(stage0)]
-#[stable(feature = "rust1", since = "1.0.0")]
-impl CharExt for char {
- fn is_digit(self, radix: u32) -> bool { C::is_digit(self, radix) }
- fn to_digit(self, radix: u32) -> Option<u32> { C::to_digit(self, radix) }
- fn escape_unicode(self) -> EscapeUnicode { C::escape_unicode(self) }
- fn escape_default(self) -> EscapeDefault { C::escape_default(self) }
- fn len_utf8(self) -> usize { C::len_utf8(self) }
- fn len_utf16(self) -> usize { C::len_utf16(self) }
- fn encode_utf8(self, dst: &mut [u8]) -> Option<usize> { C::encode_utf8(self, dst) }
- fn encode_utf16(self, dst: &mut [u16]) -> Option<usize> { C::encode_utf16(self, dst) }
-
- fn is_alphabetic(self) -> bool {
- match self {
- 'a' ... 'z' | 'A' ... 'Z' => true,
- c if c > '\x7f' => derived_property::Alphabetic(c),
- _ => false
- }
- }
-
- fn is_xid_start(self) -> bool { derived_property::XID_Start(self) }
-
- fn is_xid_continue(self) -> bool { derived_property::XID_Continue(self) }
-
- fn is_lowercase(self) -> bool {
- match self {
- 'a' ... 'z' => true,
- c if c > '\x7f' => derived_property::Lowercase(c),
- _ => false
- }
- }
-
- fn is_uppercase(self) -> bool {
- match self {
- 'A' ... 'Z' => true,
- c if c > '\x7f' => derived_property::Uppercase(c),
- _ => false
- }
- }
-
- fn is_whitespace(self) -> bool {
- match self {
- ' ' | '\x09' ... '\x0d' => true,
- c if c > '\x7f' => property::White_Space(c),
- _ => false
- }
- }
-
- fn is_alphanumeric(self) -> bool {
- self.is_alphabetic() || self.is_numeric()
- }
-
- fn is_control(self) -> bool { general_category::Cc(self) }
-
- fn is_numeric(self) -> bool {
- match self {
- '0' ... '9' => true,
- c if c > '\x7f' => general_category::N(c),
- _ => false
- }
- }
-
- fn to_lowercase(self) -> ToLowercase {
- ToLowercase(Some(conversions::to_lower(self)))
- }
-
- fn to_uppercase(self) -> ToUppercase {
- ToUppercase(Some(conversions::to_upper(self)))
- }
-
- fn width(self, is_cjk: bool) -> Option<usize> { charwidth::width(self, is_cjk) }
-}
-
/// An iterator over the lowercase mapping of a given character, returned from
/// the `lowercase` method on characters.
#[stable(feature = "rust1", since = "1.0.0")]
fn next(&mut self) -> Option<char> { self.0.take() }
}
-#[cfg(not(stage0))]
#[stable(feature = "rust1", since = "1.0.0")]
#[lang = "char"]
impl char {
use core::slice;
use core::str::Split;
-#[cfg(stage0)]
-use char::CharExt as UCharExt; // conflicts with core::prelude::CharExt
use tables::grapheme::GraphemeCat;
/// An iterator over the words of a string, separated by a sequence of whitespace
}
self.cat = if take_curr {
- idx = idx + len_utf8(self.string.char_at(idx));
+ idx = idx + self.string.char_at(idx).len_utf8();
None
} else {
Some(cat)
}
}
-#[cfg(stage0)]
-fn len_utf8(c: char) -> usize { UCharExt::len_utf8(c) }
-#[cfg(not(stage0))]
-fn len_utf8(c: char) -> usize { c.len_utf8() }
-
impl<'a> DoubleEndedIterator for Graphemes<'a> {
#[inline]
fn next_back(&mut self) -> Option<&'a str> {
#![feature(exit_status)]
#![feature(rustdoc)]
#![feature(rustc_private)]
+#![feature(path_relative_from)]
extern crate rustdoc;
extern crate rustc_back;
+S 2015-03-17 c64d671
+ bitrig-x86_64 4b2f11a96b1b5b3782d74bda707aca33bc179880
+ freebsd-x86_64 14ced24e1339a4dd8baa9db69995daa52a948d54
+ linux-i386 200450ad3cc56bc715ca105b9acae35204bf7351
+ linux-x86_64 a54f50fee722ba6bc7281dec3e4d5121af7c15e3
+ macos-i386 e33fd692f3808a0265e7b02fbc40e403080cdd4f
+ macos-x86_64 9a89ed364ae71aeb9d659ad223eae5f5986fc03f
+ winnt-i386 8911a28581e490d413b56467a6184545633ca04a
+ winnt-x86_64 38ce4556b19472c23ccce28685e3a2ebefb9bfbc
+
S 2015-03-07 270a677
bitrig-x86_64 4b2f11a96b1b5b3782d74bda707aca33bc179880
freebsd-x86_64 3c147d8e4cfdcb02c2569f5aca689a1d8920d17b