rust/src/libcore/array.rs

297 lines
9.9 KiB
Rust
Raw Normal View History

// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Implementations of things like `Eq` for fixed-length arrays
//! up to a certain length. Eventually we should able to generalize
//! to all lengths.
//!
//! *[See also the array primitive type](../../std/primitive.array.html).*
#![unstable(feature = "fixed_size_array",
reason = "traits and impls are better expressed through generic \
integer constants",
issue = "27778")]
use borrow::{Borrow, BorrowMut};
2016-08-22 05:02:28 -05:00
use cmp::Ordering;
use convert::TryFrom;
use fmt;
use hash::{Hash, self};
2016-08-22 05:02:28 -05:00
use marker::Unsize;
use slice::{Iter, IterMut};
/// Utility trait implemented only on arrays of fixed size
///
/// This trait can be used to implement other traits on fixed-size arrays
/// without causing much metadata bloat.
///
/// The trait is marked unsafe in order to restrict implementors to fixed-size
/// arrays. User of this trait can assume that implementors have the exact
/// layout in memory of a fixed size array (for example, for unsafe
/// initialization).
///
/// Note that the traits AsRef and AsMut provide similar methods for types that
/// may not be fixed-size arrays. Implementors should prefer those traits
/// instead.
2015-09-19 14:33:34 -05:00
pub unsafe trait FixedSizeArray<T> {
/// Converts the array to immutable slice
fn as_slice(&self) -> &[T];
/// Converts the array to mutable slice
fn as_mut_slice(&mut self) -> &mut [T];
}
2015-09-19 14:33:34 -05:00
unsafe impl<T, A: Unsize<[T]>> FixedSizeArray<T> for A {
#[inline]
fn as_slice(&self) -> &[T] {
self
}
#[inline]
fn as_mut_slice(&mut self) -> &mut [T] {
self
}
}
/// The error type returned when a conversion from a slice to an array fails.
#[unstable(feature = "try_from", issue = "33417")]
#[derive(Debug, Copy, Clone)]
pub struct TryFromSliceError(());
impl fmt::Display for TryFromSliceError {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self.__description(), f)
}
}
impl TryFromSliceError {
#[unstable(feature = "array_error_internals",
reason = "available through Error trait and this method should not \
be exposed publicly",
issue = "0")]
#[inline]
#[doc(hidden)]
pub fn __description(&self) -> &str {
"could not convert slice to array"
}
}
std: Stabilize APIs for the 1.6 release This commit is the standard API stabilization commit for the 1.6 release cycle. The list of issues and APIs below have all been through their cycle-long FCP and the libs team decisions are listed below Stabilized APIs * `Read::read_exact` * `ErrorKind::UnexpectedEof` (renamed from `UnexpectedEOF`) * libcore -- this was a bit of a nuanced stabilization, the crate itself is now marked as `#[stable]` and the methods appearing via traits for primitives like `char` and `str` are now also marked as stable. Note that the extension traits themeselves are marked as unstable as they're imported via the prelude. The `try!` macro was also moved from the standard library into libcore to have the same interface. Otherwise the functions all have copied stability from the standard library now. * The `#![no_std]` attribute * `fs::DirBuilder` * `fs::DirBuilder::new` * `fs::DirBuilder::recursive` * `fs::DirBuilder::create` * `os::unix::fs::DirBuilderExt` * `os::unix::fs::DirBuilderExt::mode` * `vec::Drain` * `vec::Vec::drain` * `string::Drain` * `string::String::drain` * `vec_deque::Drain` * `vec_deque::VecDeque::drain` * `collections::hash_map::Drain` * `collections::hash_map::HashMap::drain` * `collections::hash_set::Drain` * `collections::hash_set::HashSet::drain` * `collections::binary_heap::Drain` * `collections::binary_heap::BinaryHeap::drain` * `Vec::extend_from_slice` (renamed from `push_all`) * `Mutex::get_mut` * `Mutex::into_inner` * `RwLock::get_mut` * `RwLock::into_inner` * `Iterator::min_by_key` (renamed from `min_by`) * `Iterator::max_by_key` (renamed from `max_by`) Deprecated APIs * `ErrorKind::UnexpectedEOF` (renamed to `UnexpectedEof`) * `OsString::from_bytes` * `OsStr::to_cstring` * `OsStr::to_bytes` * `fs::walk_dir` and `fs::WalkDir` * `path::Components::peek` * `slice::bytes::MutableByteVector` * `slice::bytes::copy_memory` * `Vec::push_all` (renamed to `extend_from_slice`) * `Duration::span` * `IpAddr` * `SocketAddr::ip` * `Read::tee` * `io::Tee` * `Write::broadcast` * `io::Broadcast` * `Iterator::min_by` (renamed to `min_by_key`) * `Iterator::max_by` (renamed to `max_by_key`) * `net::lookup_addr` New APIs (still unstable) * `<[T]>::sort_by_key` (added to mirror `min_by_key`) Closes #27585 Closes #27704 Closes #27707 Closes #27710 Closes #27711 Closes #27727 Closes #27740 Closes #27744 Closes #27799 Closes #27801 cc #27801 (doesn't close as `Chars` is still unstable) Closes #28968
2015-12-02 19:31:49 -06:00
macro_rules! __impl_slice_eq1 {
($Lhs: ty, $Rhs: ty) => {
__impl_slice_eq1! { $Lhs, $Rhs, Sized }
};
($Lhs: ty, $Rhs: ty, $Bound: ident) => {
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
#[inline]
fn eq(&self, other: &$Rhs) -> bool { self[..] == other[..] }
#[inline]
fn ne(&self, other: &$Rhs) -> bool { self[..] != other[..] }
}
}
}
macro_rules! __impl_slice_eq2 {
($Lhs: ty, $Rhs: ty) => {
__impl_slice_eq2! { $Lhs, $Rhs, Sized }
};
($Lhs: ty, $Rhs: ty, $Bound: ident) => {
__impl_slice_eq1!($Lhs, $Rhs, $Bound);
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, 'b, A: $Bound, B> PartialEq<$Lhs> for $Rhs where B: PartialEq<A> {
#[inline]
fn eq(&self, other: &$Lhs) -> bool { self[..] == other[..] }
#[inline]
fn ne(&self, other: &$Lhs) -> bool { self[..] != other[..] }
}
}
}
2017-08-20 03:04:02 -05:00
// macro for implementing n-element array functions and operations
macro_rules! array_impls {
($($N:expr)+) => {
$(
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> AsRef<[T]> for [T; $N] {
#[inline]
fn as_ref(&self) -> &[T] {
&self[..]
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> AsMut<[T]> for [T; $N] {
#[inline]
fn as_mut(&mut self) -> &mut [T] {
&mut self[..]
}
}
#[stable(feature = "array_borrow", since = "1.4.0")]
impl<T> Borrow<[T]> for [T; $N] {
fn borrow(&self) -> &[T] {
self
}
}
#[stable(feature = "array_borrow", since = "1.4.0")]
impl<T> BorrowMut<[T]> for [T; $N] {
fn borrow_mut(&mut self) -> &mut [T] {
self
}
}
#[unstable(feature = "try_from", issue = "33417")]
impl<'a, T> TryFrom<&'a [T]> for [T; $N] where T: Copy {
type Error = TryFromSliceError;
fn try_from(slice: &[T]) -> Result<[T; $N], TryFromSliceError> {
<&Self>::try_from(slice).map(|r| *r)
}
}
#[unstable(feature = "try_from", issue = "33417")]
impl<'a, T> TryFrom<&'a [T]> for &'a [T; $N] {
type Error = TryFromSliceError;
fn try_from(slice: &[T]) -> Result<&[T; $N], TryFromSliceError> {
if slice.len() == $N {
let ptr = slice.as_ptr() as *const [T; $N];
unsafe { Ok(&*ptr) }
} else {
Err(TryFromSliceError(()))
}
}
}
#[unstable(feature = "try_from", issue = "33417")]
impl<'a, T> TryFrom<&'a mut [T]> for &'a mut [T; $N] {
type Error = TryFromSliceError;
fn try_from(slice: &mut [T]) -> Result<&mut [T; $N], TryFromSliceError> {
if slice.len() == $N {
let ptr = slice.as_mut_ptr() as *mut [T; $N];
unsafe { Ok(&mut *ptr) }
} else {
Err(TryFromSliceError(()))
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Hash> Hash for [T; $N] {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
2015-02-18 17:58:07 -06:00
Hash::hash(&self[..], state)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
std: Rename Show/String to Debug/Display This commit is an implementation of [RFC 565][rfc] which is a stabilization of the `std::fmt` module and the implementations of various formatting traits. Specifically, the following changes were performed: [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0565-show-string-guidelines.md * The `Show` trait is now deprecated, it was renamed to `Debug` * The `String` trait is now deprecated, it was renamed to `Display` * Many `Debug` and `Display` implementations were audited in accordance with the RFC and audited implementations now have the `#[stable]` attribute * Integers and floats no longer print a suffix * Smart pointers no longer print details that they are a smart pointer * Paths with `Debug` are now quoted and escape characters * The `unwrap` methods on `Result` now require `Display` instead of `Debug` * The `Error` trait no longer has a `detail` method and now requires that `Display` must be implemented. With the loss of `String`, this has moved into libcore. * `impl<E: Error> FromError<E> for Box<Error>` now exists * `derive(Show)` has been renamed to `derive(Debug)`. This is not currently warned about due to warnings being emitted on stage1+ While backwards compatibility is attempted to be maintained with a blanket implementation of `Display` for the old `String` trait (and the same for `Show`/`Debug`) this is still a breaking change due to primitives no longer implementing `String` as well as modifications such as `unwrap` and the `Error` trait. Most code is fairly straightforward to update with a rename or tweaks of method calls. [breaking-change] Closes #21436
2015-01-20 17:45:07 -06:00
impl<T: fmt::Debug> fmt::Debug for [T; $N] {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&&self[..], f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T> IntoIterator for &'a [T; $N] {
type Item = &'a T;
type IntoIter = Iter<'a, T>;
fn into_iter(self) -> Iter<'a, T> {
self.iter()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
2015-01-07 21:01:05 -06:00
impl<'a, T> IntoIterator for &'a mut [T; $N] {
type Item = &'a mut T;
type IntoIter = IterMut<'a, T>;
2015-01-07 21:01:05 -06:00
fn into_iter(self) -> IterMut<'a, T> {
self.iter_mut()
}
}
// NOTE: some less important impls are omitted to reduce code bloat
__impl_slice_eq1! { [A; $N], [B; $N] }
__impl_slice_eq2! { [A; $N], [B] }
__impl_slice_eq2! { [A; $N], &'b [B] }
__impl_slice_eq2! { [A; $N], &'b mut [B] }
// __impl_slice_eq2! { [A; $N], &'b [B; $N] }
// __impl_slice_eq2! { [A; $N], &'b mut [B; $N] }
2015-01-23 23:48:20 -06:00
#[stable(feature = "rust1", since = "1.0.0")]
2014-12-31 22:40:24 -06:00
impl<T:Eq> Eq for [T; $N] { }
2015-01-23 23:48:20 -06:00
#[stable(feature = "rust1", since = "1.0.0")]
2014-12-31 22:40:24 -06:00
impl<T:PartialOrd> PartialOrd for [T; $N] {
#[inline]
2014-12-31 22:40:24 -06:00
fn partial_cmp(&self, other: &[T; $N]) -> Option<Ordering> {
PartialOrd::partial_cmp(&&self[..], &&other[..])
}
#[inline]
2014-12-31 22:40:24 -06:00
fn lt(&self, other: &[T; $N]) -> bool {
PartialOrd::lt(&&self[..], &&other[..])
}
#[inline]
2014-12-31 22:40:24 -06:00
fn le(&self, other: &[T; $N]) -> bool {
PartialOrd::le(&&self[..], &&other[..])
}
#[inline]
2014-12-31 22:40:24 -06:00
fn ge(&self, other: &[T; $N]) -> bool {
PartialOrd::ge(&&self[..], &&other[..])
}
#[inline]
2014-12-31 22:40:24 -06:00
fn gt(&self, other: &[T; $N]) -> bool {
PartialOrd::gt(&&self[..], &&other[..])
}
}
2015-01-23 23:48:20 -06:00
#[stable(feature = "rust1", since = "1.0.0")]
2014-12-31 22:40:24 -06:00
impl<T:Ord> Ord for [T; $N] {
#[inline]
2014-12-31 22:40:24 -06:00
fn cmp(&self, other: &[T; $N]) -> Ordering {
Ord::cmp(&&self[..], &&other[..])
}
}
)+
}
}
array_impls! {
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32
}
// The Default impls cannot be generated using the array_impls! macro because
// they require array literals.
macro_rules! array_impl_default {
{$n:expr, $t:ident $($ts:ident)*} => {
#[stable(since = "1.4.0", feature = "array_default")]
impl<T> Default for [T; $n] where T: Default {
fn default() -> [T; $n] {
[$t::default(), $($ts::default()),*]
}
}
array_impl_default!{($n - 1), $($ts)*}
};
{$n:expr,} => {
#[stable(since = "1.4.0", feature = "array_default")]
impl<T> Default for [T; $n] {
fn default() -> [T; $n] { [] }
}
};
}
array_impl_default!{32, T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T}