]> git.proxmox.com Git - rustc.git/blob - library/core/src/array/mod.rs
New upstream version 1.55.0+dfsg1
[rustc.git] / library / core / src / array / mod.rs
1 //! Helper functions and types for fixed-length arrays.
2 //!
3 //! *[See also the array primitive type](array).*
4
5 #![stable(feature = "core_array", since = "1.36.0")]
6
7 use crate::borrow::{Borrow, BorrowMut};
8 use crate::cmp::Ordering;
9 use crate::convert::{Infallible, TryFrom};
10 use crate::fmt;
11 use crate::hash::{self, Hash};
12 use crate::iter::TrustedLen;
13 use crate::mem::{self, MaybeUninit};
14 use crate::ops::{Index, IndexMut};
15 use crate::slice::{Iter, IterMut};
16
17 mod equality;
18 mod iter;
19
20 #[stable(feature = "array_value_iter", since = "1.51.0")]
21 pub use iter::IntoIter;
22
23 /// Converts a reference to `T` into a reference to an array of length 1 (without copying).
24 #[stable(feature = "array_from_ref", since = "1.53.0")]
25 pub fn from_ref<T>(s: &T) -> &[T; 1] {
26 // SAFETY: Converting `&T` to `&[T; 1]` is sound.
27 unsafe { &*(s as *const T).cast::<[T; 1]>() }
28 }
29
30 /// Converts a mutable reference to `T` into a mutable reference to an array of length 1 (without copying).
31 #[stable(feature = "array_from_ref", since = "1.53.0")]
32 pub fn from_mut<T>(s: &mut T) -> &mut [T; 1] {
33 // SAFETY: Converting `&mut T` to `&mut [T; 1]` is sound.
34 unsafe { &mut *(s as *mut T).cast::<[T; 1]>() }
35 }
36
37 /// The error type returned when a conversion from a slice to an array fails.
38 #[stable(feature = "try_from", since = "1.34.0")]
39 #[derive(Debug, Copy, Clone)]
40 pub struct TryFromSliceError(());
41
42 #[stable(feature = "core_array", since = "1.36.0")]
43 impl fmt::Display for TryFromSliceError {
44 #[inline]
45 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46 fmt::Display::fmt(self.__description(), f)
47 }
48 }
49
50 impl TryFromSliceError {
51 #[unstable(
52 feature = "array_error_internals",
53 reason = "available through Error trait and this method should not \
54 be exposed publicly",
55 issue = "none"
56 )]
57 #[inline]
58 #[doc(hidden)]
59 pub fn __description(&self) -> &str {
60 "could not convert slice to array"
61 }
62 }
63
64 #[stable(feature = "try_from_slice_error", since = "1.36.0")]
65 impl From<Infallible> for TryFromSliceError {
66 fn from(x: Infallible) -> TryFromSliceError {
67 match x {}
68 }
69 }
70
71 #[stable(feature = "rust1", since = "1.0.0")]
72 impl<T, const N: usize> AsRef<[T]> for [T; N] {
73 #[inline]
74 fn as_ref(&self) -> &[T] {
75 &self[..]
76 }
77 }
78
79 #[stable(feature = "rust1", since = "1.0.0")]
80 impl<T, const N: usize> AsMut<[T]> for [T; N] {
81 #[inline]
82 fn as_mut(&mut self) -> &mut [T] {
83 &mut self[..]
84 }
85 }
86
87 #[stable(feature = "array_borrow", since = "1.4.0")]
88 impl<T, const N: usize> Borrow<[T]> for [T; N] {
89 fn borrow(&self) -> &[T] {
90 self
91 }
92 }
93
94 #[stable(feature = "array_borrow", since = "1.4.0")]
95 impl<T, const N: usize> BorrowMut<[T]> for [T; N] {
96 fn borrow_mut(&mut self) -> &mut [T] {
97 self
98 }
99 }
100
101 #[stable(feature = "try_from", since = "1.34.0")]
102 impl<T, const N: usize> TryFrom<&[T]> for [T; N]
103 where
104 T: Copy,
105 {
106 type Error = TryFromSliceError;
107
108 fn try_from(slice: &[T]) -> Result<[T; N], TryFromSliceError> {
109 <&Self>::try_from(slice).map(|r| *r)
110 }
111 }
112
113 #[stable(feature = "try_from", since = "1.34.0")]
114 impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N] {
115 type Error = TryFromSliceError;
116
117 fn try_from(slice: &[T]) -> Result<&[T; N], TryFromSliceError> {
118 if slice.len() == N {
119 let ptr = slice.as_ptr() as *const [T; N];
120 // SAFETY: ok because we just checked that the length fits
121 unsafe { Ok(&*ptr) }
122 } else {
123 Err(TryFromSliceError(()))
124 }
125 }
126 }
127
128 #[stable(feature = "try_from", since = "1.34.0")]
129 impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N] {
130 type Error = TryFromSliceError;
131
132 fn try_from(slice: &mut [T]) -> Result<&mut [T; N], TryFromSliceError> {
133 if slice.len() == N {
134 let ptr = slice.as_mut_ptr() as *mut [T; N];
135 // SAFETY: ok because we just checked that the length fits
136 unsafe { Ok(&mut *ptr) }
137 } else {
138 Err(TryFromSliceError(()))
139 }
140 }
141 }
142
143 /// The hash of an array is the same as that of the corresponding slice,
144 /// as required by the `Borrow` implementation.
145 ///
146 /// ```
147 /// #![feature(build_hasher_simple_hash_one)]
148 /// use std::hash::BuildHasher;
149 ///
150 /// let b = std::collections::hash_map::RandomState::new();
151 /// let a: [u8; 3] = [0xa8, 0x3c, 0x09];
152 /// let s: &[u8] = &[0xa8, 0x3c, 0x09];
153 /// assert_eq!(b.hash_one(a), b.hash_one(s));
154 /// ```
155 #[stable(feature = "rust1", since = "1.0.0")]
156 impl<T: Hash, const N: usize> Hash for [T; N] {
157 fn hash<H: hash::Hasher>(&self, state: &mut H) {
158 Hash::hash(&self[..], state)
159 }
160 }
161
162 #[stable(feature = "rust1", since = "1.0.0")]
163 impl<T: fmt::Debug, const N: usize> fmt::Debug for [T; N] {
164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165 fmt::Debug::fmt(&&self[..], f)
166 }
167 }
168
169 // Note: the `#[rustc_skip_array_during_method_dispatch]` on `trait IntoIterator`
170 // hides this implementation from explicit `.into_iter()` calls on editions < 2021,
171 // so those calls will still resolve to the slice implementation, by reference.
172 #[stable(feature = "array_into_iter_impl", since = "1.53.0")]
173 impl<T, const N: usize> IntoIterator for [T; N] {
174 type Item = T;
175 type IntoIter = IntoIter<T, N>;
176
177 /// Creates a consuming iterator, that is, one that moves each value out of
178 /// the array (from start to end). The array cannot be used after calling
179 /// this unless `T` implements `Copy`, so the whole array is copied.
180 ///
181 /// Arrays have special behavior when calling `.into_iter()` prior to the
182 /// 2021 edition -- see the [array] Editions section for more information.
183 ///
184 /// [array]: prim@array
185 fn into_iter(self) -> Self::IntoIter {
186 IntoIter::new(self)
187 }
188 }
189
190 #[stable(feature = "rust1", since = "1.0.0")]
191 impl<'a, T, const N: usize> IntoIterator for &'a [T; N] {
192 type Item = &'a T;
193 type IntoIter = Iter<'a, T>;
194
195 fn into_iter(self) -> Iter<'a, T> {
196 self.iter()
197 }
198 }
199
200 #[stable(feature = "rust1", since = "1.0.0")]
201 impl<'a, T, const N: usize> IntoIterator for &'a mut [T; N] {
202 type Item = &'a mut T;
203 type IntoIter = IterMut<'a, T>;
204
205 fn into_iter(self) -> IterMut<'a, T> {
206 self.iter_mut()
207 }
208 }
209
210 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
211 impl<T, I, const N: usize> Index<I> for [T; N]
212 where
213 [T]: Index<I>,
214 {
215 type Output = <[T] as Index<I>>::Output;
216
217 #[inline]
218 fn index(&self, index: I) -> &Self::Output {
219 Index::index(self as &[T], index)
220 }
221 }
222
223 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
224 impl<T, I, const N: usize> IndexMut<I> for [T; N]
225 where
226 [T]: IndexMut<I>,
227 {
228 #[inline]
229 fn index_mut(&mut self, index: I) -> &mut Self::Output {
230 IndexMut::index_mut(self as &mut [T], index)
231 }
232 }
233
234 #[stable(feature = "rust1", since = "1.0.0")]
235 impl<T: PartialOrd, const N: usize> PartialOrd for [T; N] {
236 #[inline]
237 fn partial_cmp(&self, other: &[T; N]) -> Option<Ordering> {
238 PartialOrd::partial_cmp(&&self[..], &&other[..])
239 }
240 #[inline]
241 fn lt(&self, other: &[T; N]) -> bool {
242 PartialOrd::lt(&&self[..], &&other[..])
243 }
244 #[inline]
245 fn le(&self, other: &[T; N]) -> bool {
246 PartialOrd::le(&&self[..], &&other[..])
247 }
248 #[inline]
249 fn ge(&self, other: &[T; N]) -> bool {
250 PartialOrd::ge(&&self[..], &&other[..])
251 }
252 #[inline]
253 fn gt(&self, other: &[T; N]) -> bool {
254 PartialOrd::gt(&&self[..], &&other[..])
255 }
256 }
257
258 /// Implements comparison of arrays [lexicographically](Ord#lexicographical-comparison).
259 #[stable(feature = "rust1", since = "1.0.0")]
260 impl<T: Ord, const N: usize> Ord for [T; N] {
261 #[inline]
262 fn cmp(&self, other: &[T; N]) -> Ordering {
263 Ord::cmp(&&self[..], &&other[..])
264 }
265 }
266
267 // The Default impls cannot be done with const generics because `[T; 0]` doesn't
268 // require Default to be implemented, and having different impl blocks for
269 // different numbers isn't supported yet.
270
271 macro_rules! array_impl_default {
272 {$n:expr, $t:ident $($ts:ident)*} => {
273 #[stable(since = "1.4.0", feature = "array_default")]
274 impl<T> Default for [T; $n] where T: Default {
275 fn default() -> [T; $n] {
276 [$t::default(), $($ts::default()),*]
277 }
278 }
279 array_impl_default!{($n - 1), $($ts)*}
280 };
281 {$n:expr,} => {
282 #[stable(since = "1.4.0", feature = "array_default")]
283 impl<T> Default for [T; $n] {
284 fn default() -> [T; $n] { [] }
285 }
286 };
287 }
288
289 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}
290
291 #[lang = "array"]
292 impl<T, const N: usize> [T; N] {
293 /// Returns an array of the same size as `self`, with function `f` applied to each element
294 /// in order.
295 ///
296 /// # Examples
297 ///
298 /// ```
299 /// let x = [1, 2, 3];
300 /// let y = x.map(|v| v + 1);
301 /// assert_eq!(y, [2, 3, 4]);
302 ///
303 /// let x = [1, 2, 3];
304 /// let mut temp = 0;
305 /// let y = x.map(|v| { temp += 1; v * temp });
306 /// assert_eq!(y, [1, 4, 9]);
307 ///
308 /// let x = ["Ferris", "Bueller's", "Day", "Off"];
309 /// let y = x.map(|v| v.len());
310 /// assert_eq!(y, [6, 9, 3, 3]);
311 /// ```
312 #[stable(feature = "array_map", since = "1.55.0")]
313 pub fn map<F, U>(self, f: F) -> [U; N]
314 where
315 F: FnMut(T) -> U,
316 {
317 // SAFETY: we know for certain that this iterator will yield exactly `N`
318 // items.
319 unsafe { collect_into_array_unchecked(&mut IntoIterator::into_iter(self).map(f)) }
320 }
321
322 /// 'Zips up' two arrays into a single array of pairs.
323 ///
324 /// `zip()` returns a new array where every element is a tuple where the
325 /// first element comes from the first array, and the second element comes
326 /// from the second array. In other words, it zips two arrays together,
327 /// into a single one.
328 ///
329 /// # Examples
330 ///
331 /// ```
332 /// #![feature(array_zip)]
333 /// let x = [1, 2, 3];
334 /// let y = [4, 5, 6];
335 /// let z = x.zip(y);
336 /// assert_eq!(z, [(1, 4), (2, 5), (3, 6)]);
337 /// ```
338 #[unstable(feature = "array_zip", issue = "80094")]
339 pub fn zip<U>(self, rhs: [U; N]) -> [(T, U); N] {
340 let mut iter = IntoIterator::into_iter(self).zip(rhs);
341
342 // SAFETY: we know for certain that this iterator will yield exactly `N`
343 // items.
344 unsafe { collect_into_array_unchecked(&mut iter) }
345 }
346
347 /// Returns a slice containing the entire array. Equivalent to `&s[..]`.
348 #[unstable(feature = "array_methods", issue = "76118")]
349 pub fn as_slice(&self) -> &[T] {
350 self
351 }
352
353 /// Returns a mutable slice containing the entire array. Equivalent to
354 /// `&mut s[..]`.
355 #[unstable(feature = "array_methods", issue = "76118")]
356 pub fn as_mut_slice(&mut self) -> &mut [T] {
357 self
358 }
359
360 /// Borrows each element and returns an array of references with the same
361 /// size as `self`.
362 ///
363 ///
364 /// # Example
365 ///
366 /// ```
367 /// #![feature(array_methods)]
368 ///
369 /// let floats = [3.1, 2.7, -1.0];
370 /// let float_refs: [&f64; 3] = floats.each_ref();
371 /// assert_eq!(float_refs, [&3.1, &2.7, &-1.0]);
372 /// ```
373 ///
374 /// This method is particularly useful if combined with other methods, like
375 /// [`map`](#method.map). This way, you can avoid moving the original
376 /// array if its elements are not `Copy`.
377 ///
378 /// ```
379 /// #![feature(array_methods)]
380 ///
381 /// let strings = ["Ferris".to_string(), "♥".to_string(), "Rust".to_string()];
382 /// let is_ascii = strings.each_ref().map(|s| s.is_ascii());
383 /// assert_eq!(is_ascii, [true, false, true]);
384 ///
385 /// // We can still access the original array: it has not been moved.
386 /// assert_eq!(strings.len(), 3);
387 /// ```
388 #[unstable(feature = "array_methods", issue = "76118")]
389 pub fn each_ref(&self) -> [&T; N] {
390 // SAFETY: we know for certain that this iterator will yield exactly `N`
391 // items.
392 unsafe { collect_into_array_unchecked(&mut self.iter()) }
393 }
394
395 /// Borrows each element mutably and returns an array of mutable references
396 /// with the same size as `self`.
397 ///
398 ///
399 /// # Example
400 ///
401 /// ```
402 /// #![feature(array_methods)]
403 ///
404 /// let mut floats = [3.1, 2.7, -1.0];
405 /// let float_refs: [&mut f64; 3] = floats.each_mut();
406 /// *float_refs[0] = 0.0;
407 /// assert_eq!(float_refs, [&mut 0.0, &mut 2.7, &mut -1.0]);
408 /// assert_eq!(floats, [0.0, 2.7, -1.0]);
409 /// ```
410 #[unstable(feature = "array_methods", issue = "76118")]
411 pub fn each_mut(&mut self) -> [&mut T; N] {
412 // SAFETY: we know for certain that this iterator will yield exactly `N`
413 // items.
414 unsafe { collect_into_array_unchecked(&mut self.iter_mut()) }
415 }
416 }
417
418 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
419 /// yields fewer than `N` items, this function exhibits undefined behavior.
420 ///
421 /// See [`collect_into_array`] for more information.
422 ///
423 ///
424 /// # Safety
425 ///
426 /// It is up to the caller to guarantee that `iter` yields at least `N` items.
427 /// Violating this condition causes undefined behavior.
428 unsafe fn collect_into_array_unchecked<I, const N: usize>(iter: &mut I) -> [I::Item; N]
429 where
430 // Note: `TrustedLen` here is somewhat of an experiment. This is just an
431 // internal function, so feel free to remove if this bound turns out to be a
432 // bad idea. In that case, remember to also remove the lower bound
433 // `debug_assert!` below!
434 I: Iterator + TrustedLen,
435 {
436 debug_assert!(N <= iter.size_hint().1.unwrap_or(usize::MAX));
437 debug_assert!(N <= iter.size_hint().0);
438
439 match collect_into_array(iter) {
440 Some(array) => array,
441 // SAFETY: covered by the function contract.
442 None => unsafe { crate::hint::unreachable_unchecked() },
443 }
444 }
445
446 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
447 /// yields fewer than `N` items, `None` is returned and all already yielded
448 /// items are dropped.
449 ///
450 /// Since the iterator is passed as a mutable reference and this function calls
451 /// `next` at most `N` times, the iterator can still be used afterwards to
452 /// retrieve the remaining items.
453 ///
454 /// If `iter.next()` panicks, all items already yielded by the iterator are
455 /// dropped.
456 fn collect_into_array<I, const N: usize>(iter: &mut I) -> Option<[I::Item; N]>
457 where
458 I: Iterator,
459 {
460 if N == 0 {
461 // SAFETY: An empty array is always inhabited and has no validity invariants.
462 return unsafe { Some(mem::zeroed()) };
463 }
464
465 struct Guard<T, const N: usize> {
466 ptr: *mut T,
467 initialized: usize,
468 }
469
470 impl<T, const N: usize> Drop for Guard<T, N> {
471 fn drop(&mut self) {
472 debug_assert!(self.initialized <= N);
473
474 let initialized_part = crate::ptr::slice_from_raw_parts_mut(self.ptr, self.initialized);
475
476 // SAFETY: this raw slice will contain only initialized objects.
477 unsafe {
478 crate::ptr::drop_in_place(initialized_part);
479 }
480 }
481 }
482
483 let mut array = MaybeUninit::uninit_array::<N>();
484 let mut guard: Guard<_, N> =
485 Guard { ptr: MaybeUninit::slice_as_mut_ptr(&mut array), initialized: 0 };
486
487 while let Some(item) = iter.next() {
488 // SAFETY: `guard.initialized` starts at 0, is increased by one in the
489 // loop and the loop is aborted once it reaches N (which is
490 // `array.len()`).
491 unsafe {
492 array.get_unchecked_mut(guard.initialized).write(item);
493 }
494 guard.initialized += 1;
495
496 // Check if the whole array was initialized.
497 if guard.initialized == N {
498 mem::forget(guard);
499
500 // SAFETY: the condition above asserts that all elements are
501 // initialized.
502 let out = unsafe { MaybeUninit::array_assume_init(array) };
503 return Some(out);
504 }
505 }
506
507 // This is only reached if the iterator is exhausted before
508 // `guard.initialized` reaches `N`. Also note that `guard` is dropped here,
509 // dropping all already initialized elements.
510 None
511 }