Files
alloc
core
alloc
array
char
convert
fmt
future
hash
iter
macros
mem
num
ops
panic
portable-simd
prelude
ptr
slice
stdarch
str
stream
sync
task
unicode
std
backtrace
collections
ffi
io
net
os
prelude
sync
sys
sys_common
thread
time
  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
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
//! 固定长度数组的辅助函数和类型。
//!
//! *[See also the array primitive type](array).*

#![stable(feature = "core_array", since = "1.36.0")]

use crate::borrow::{Borrow, BorrowMut};
use crate::cmp::Ordering;
use crate::convert::{Infallible, TryFrom};
use crate::fmt;
use crate::hash::{self, Hash};
use crate::iter::TrustedLen;
use crate::mem::{self, MaybeUninit};
use crate::ops::{
    ChangeOutputType, ControlFlow, FromResidual, Index, IndexMut, NeverShortCircuit, Residual, Try,
};
use crate::slice::{Iter, IterMut};

mod equality;
mod iter;

#[stable(feature = "array_value_iter", since = "1.51.0")]
pub use iter::IntoIter;

/// 创建一个数组 `[T; N]`,其中每个数组元素 `T` 都由 `cb` 调用返回。
///
/// # Arguments
///
/// * `cb`: 回调,其中传入的参数是当前数组索引。
///
/// # Example
///
/// ```rust
/// #![feature(array_from_fn)]
///
/// let array = core::array::from_fn(|i| i);
/// assert_eq!(array, [0, 1, 2, 3, 4]);
/// ```
#[inline]
#[unstable(feature = "array_from_fn", issue = "89379")]
pub fn from_fn<F, T, const N: usize>(mut cb: F) -> [T; N]
where
    F: FnMut(usize) -> T,
{
    let mut idx = 0;
    [(); N].map(|_| {
        let res = cb(idx);
        idx += 1;
        res
    })
}

/// 创建一个数组 `[T; N]`,其中每个易出错的数组元素 `T` 由 `cb` 调用返回。
/// 与 [`from_fn`] 的元素创建不能失败不同,如果任何元素创建失败,此版本将返回错误。
///
///
/// 这个函数的返回类型取决于闭包的返回类型。
/// 如果您从闭包返回 `Result<T, E>`,您会得到一个 `Result<[T; N]; E>`。
/// 如果您从闭包中返回 `Option<T>`,您会得到一个 `Option<[T; N]>`.
///
/// # Arguments
///
/// * `cb`: 回调,其中传入的参数是当前数组索引。
///
/// # Example
///
/// ```rust
/// #![feature(array_from_fn)]
/// # // 显然,这些文档测试仍在 2018 版上
/// # use std::convert::TryInto;
///
/// let array: Result<[u8; 5], _> = std::array::try_from_fn(|i| i.try_into());
/// assert_eq!(array, Ok([0, 1, 2, 3, 4]));
///
/// let array: Result<[i8; 200], _> = std::array::try_from_fn(|i| i.try_into());
/// assert!(array.is_err());
///
/// let array: Option<[_; 4]> = std::array::try_from_fn(|i| i.checked_add(100));
/// assert_eq!(array, Some([100, 101, 102, 103]));
///
/// let array: Option<[_; 4]> = std::array::try_from_fn(|i| i.checked_sub(100));
/// assert_eq!(array, None);
/// ```
#[inline]
#[unstable(feature = "array_from_fn", issue = "89379")]
pub fn try_from_fn<F, R, const N: usize>(cb: F) -> ChangeOutputType<R, [R::Output; N]>
where
    F: FnMut(usize) -> R,
    R: Try,
    R::Residual: Residual<[R::Output; N]>,
{
    // SAFETY: 我们肯定知道该迭代器将产生完全 `N` 项。
    //
    unsafe { try_collect_into_array_unchecked(&mut (0..N).map(cb)) }
}

/// 将 quotes 转换为 `T`,将 quotes 转换为长度为 1 的数组 (不进行复制)。
#[stable(feature = "array_from_ref", since = "1.53.0")]
#[rustc_const_unstable(feature = "const_array_from_ref", issue = "90206")]
pub const fn from_ref<T>(s: &T) -> &[T; 1] {
    // SAFETY: 将 `&T` 转换为 `&[T; 1]` 是声音。
    unsafe { &*(s as *const T).cast::<[T; 1]>() }
}

/// 将变量引用转换为 `T`,将变量引用转换为长度为 1 的数组 (不进行复制)。
#[stable(feature = "array_from_ref", since = "1.53.0")]
#[rustc_const_unstable(feature = "const_array_from_ref", issue = "90206")]
pub const fn from_mut<T>(s: &mut T) -> &mut [T; 1] {
    // SAFETY: 将 `&mut T` 转换为 `&mut [T; 1]` 是声音。
    unsafe { &mut *(s as *mut T).cast::<[T; 1]>() }
}

/// 从切片到数组的转换失败时返回的错误类型。
#[stable(feature = "try_from", since = "1.34.0")]
#[derive(Debug, Copy, Clone)]
pub struct TryFromSliceError(());

#[stable(feature = "core_array", since = "1.36.0")]
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 = "none"
    )]
    #[inline]
    #[doc(hidden)]
    pub fn __description(&self) -> &str {
        "could not convert slice to array"
    }
}

#[stable(feature = "try_from_slice_error", since = "1.36.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "88674")]
impl const From<Infallible> for TryFromSliceError {
    fn from(x: Infallible) -> TryFromSliceError {
        match x {}
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T, const N: usize> AsRef<[T]> for [T; N] {
    #[inline]
    fn as_ref(&self) -> &[T] {
        &self[..]
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T, const N: usize> AsMut<[T]> for [T; N] {
    #[inline]
    fn as_mut(&mut self) -> &mut [T] {
        &mut self[..]
    }
}

#[stable(feature = "array_borrow", since = "1.4.0")]
#[rustc_const_unstable(feature = "const_borrow", issue = "91522")]
impl<T, const N: usize> const Borrow<[T]> for [T; N] {
    fn borrow(&self) -> &[T] {
        self
    }
}

#[stable(feature = "array_borrow", since = "1.4.0")]
#[rustc_const_unstable(feature = "const_borrow", issue = "91522")]
impl<T, const N: usize> const BorrowMut<[T]> for [T; N] {
    fn borrow_mut(&mut self) -> &mut [T] {
        self
    }
}

#[stable(feature = "try_from", since = "1.34.0")]
impl<T, const N: usize> TryFrom<&[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)
    }
}

#[stable(feature = "try_from_mut_slice_to_array", since = "1.59.0")]
impl<T, const N: usize> TryFrom<&mut [T]> for [T; N]
where
    T: Copy,
{
    type Error = TryFromSliceError;

    fn try_from(slice: &mut [T]) -> Result<[T; N], TryFromSliceError> {
        <Self>::try_from(&*slice)
    }
}

#[stable(feature = "try_from", since = "1.34.0")]
impl<'a, T, const N: usize> 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];
            // SAFETY: 好的,因为我们只是检查了长度是否合适
            unsafe { Ok(&*ptr) }
        } else {
            Err(TryFromSliceError(()))
        }
    }
}

#[stable(feature = "try_from", since = "1.34.0")]
impl<'a, T, const N: usize> 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];
            // SAFETY: 好的,因为我们只是检查了长度是否合适
            unsafe { Ok(&mut *ptr) }
        } else {
            Err(TryFromSliceError(()))
        }
    }
}

/// 数组的哈希值与对应的 X 像素的哈希值相同,符合实现的要求。
///
///
/// ```
/// #![feature(build_hasher_simple_hash_one)]
/// use std::hash::BuildHasher;
///
/// let b = std::collections::hash_map::RandomState::new();
/// let a: [u8; 3] = [0xa8, 0x3c, 0x09];
/// let s: &[u8] = &[0xa8, 0x3c, 0x09];
/// assert_eq!(b.hash_one(a), b.hash_one(s));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Hash, const N: usize> Hash for [T; N] {
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        Hash::hash(&self[..], state)
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Debug, const N: usize> 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, const N: usize> 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")]
impl<'a, T, const N: usize> IntoIterator for &'a mut [T; N] {
    type Item = &'a mut T;
    type IntoIter = IterMut<'a, T>;

    fn into_iter(self) -> IterMut<'a, T> {
        self.iter_mut()
    }
}

#[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
impl<T, I, const N: usize> Index<I> for [T; N]
where
    [T]: Index<I>,
{
    type Output = <[T] as Index<I>>::Output;

    #[inline]
    fn index(&self, index: I) -> &Self::Output {
        Index::index(self as &[T], index)
    }
}

#[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
impl<T, I, const N: usize> IndexMut<I> for [T; N]
where
    [T]: IndexMut<I>,
{
    #[inline]
    fn index_mut(&mut self, index: I) -> &mut Self::Output {
        IndexMut::index_mut(self as &mut [T], index)
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: PartialOrd, const N: usize> PartialOrd for [T; N] {
    #[inline]
    fn partial_cmp(&self, other: &[T; N]) -> Option<Ordering> {
        PartialOrd::partial_cmp(&&self[..], &&other[..])
    }
    #[inline]
    fn lt(&self, other: &[T; N]) -> bool {
        PartialOrd::lt(&&self[..], &&other[..])
    }
    #[inline]
    fn le(&self, other: &[T; N]) -> bool {
        PartialOrd::le(&&self[..], &&other[..])
    }
    #[inline]
    fn ge(&self, other: &[T; N]) -> bool {
        PartialOrd::ge(&&self[..], &&other[..])
    }
    #[inline]
    fn gt(&self, other: &[T; N]) -> bool {
        PartialOrd::gt(&&self[..], &&other[..])
    }
}

/// 实现数组 [按字典顺序](Ord#lexicographical-comparison) 的比较。
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Ord, const N: usize> Ord for [T; N] {
    #[inline]
    fn cmp(&self, other: &[T; N]) -> Ordering {
        Ord::cmp(&&self[..], &&other[..])
    }
}

#[stable(feature = "copy_clone_array_lib", since = "1.58.0")]
impl<T: Copy, const N: usize> Copy for [T; N] {}

#[stable(feature = "copy_clone_array_lib", since = "1.58.0")]
impl<T: Clone, const N: usize> Clone for [T; N] {
    #[inline]
    fn clone(&self) -> Self {
        SpecArrayClone::clone(self)
    }

    #[inline]
    fn clone_from(&mut self, other: &Self) {
        self.clone_from_slice(other);
    }
}

trait SpecArrayClone: Clone {
    fn clone<const N: usize>(array: &[Self; N]) -> [Self; N];
}

impl<T: Clone> SpecArrayClone for T {
    #[inline]
    default fn clone<const N: usize>(array: &[T; N]) -> [T; N] {
        // SAFETY: 我们肯定知道该迭代器将产生完全 `N` 项。
        //
        unsafe { collect_into_array_unchecked(&mut array.iter().cloned()) }
    }
}

impl<T: Copy> SpecArrayClone for T {
    #[inline]
    fn clone<const N: usize>(array: &[T; N]) -> [T; N] {
        *array
    }
}

// 不能使用 const 泛型来完成 Default impls,因为 `[T; 0]` 不需要实现 Default,并且尚不支持针对不同数字使用不同的 impl 块。
//
//

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")]
        #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
        impl<T> const 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}

#[lang = "array"]
impl<T, const N: usize> [T; N] {
    /// 返回大小与 `self` 相同的数组,并将函数 `f` 按顺序应用于每个元素。
    ///
    /// 如果您不一定需要新的固定大小的数组,请考虑改用 [`Iterator::map`]。
    ///
    /// # 关于性能和栈使用的注意事项
    ///
    /// 不幸的是,这种方法的使用目前并不总是像它们可能的那样优化。
    /// 这主要涉及大数组,因为小数组上的映射似乎优化得很好。
    /// 另请注意,在调试模式下 (即
    /// 没有任何优化),这种方法可以使用大量的栈空间 (数组大小的几倍或更多)。
    ///
    /// 因此,在性能关键的代码中,尽量避免在大型数组上使用此方法或检查发出的代码。
    /// 还要尽量避免链接 maps (例如
    /// `arr.map(...).map(...)`).
    ///
    /// 在许多情况下,您可以通过在阵列上调用 `.iter()` 或 `.into_iter()` 来代替使用 [`Iterator::map`]。
    /// 只有当您真的需要一个与结果大小相同的新数组时,才需要 `[T; N]::map`
    /// Rust 的惰性迭代器往往会得到很好的优化。
    ///
    /// # Examples
    ///
    /// ```
    /// let x = [1, 2, 3];
    /// let y = x.map(|v| v + 1);
    /// assert_eq!(y, [2, 3, 4]);
    ///
    /// let x = [1, 2, 3];
    /// let mut temp = 0;
    /// let y = x.map(|v| { temp += 1; v * temp });
    /// assert_eq!(y, [1, 4, 9]);
    ///
    /// let x = ["Ferris", "Bueller's", "Day", "Off"];
    /// let y = x.map(|v| v.len());
    /// assert_eq!(y, [6, 9, 3, 3]);
    /// ```
    ///
    ///
    ///
    ///
    ///
    ///
    #[stable(feature = "array_map", since = "1.55.0")]
    pub fn map<F, U>(self, f: F) -> [U; N]
    where
        F: FnMut(T) -> U,
    {
        // SAFETY: 我们肯定知道该迭代器将产生完全 `N` 项。
        //
        unsafe { collect_into_array_unchecked(&mut IntoIterator::into_iter(self).map(f)) }
    }

    /// 一个容易出错的函数 `f` 应用于数组 `self` 上的每个元素,以返回与 `self` 或遇到的第一个错误大小相同的数组。
    ///
    ///
    /// 这个函数的返回类型取决于闭包的返回类型。
    /// 如果您从闭包返回 `Result<T, E>`,您会得到一个 `Result<[T; N]; E>`。
    /// 如果您从闭包中返回 `Option<T>`,您会得到一个 `Option<[T; N]>`.
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(array_try_map)]
    /// let a = ["1", "2", "3"];
    /// let b = a.try_map(|v| v.parse::<u32>()).unwrap().map(|v| v + 1);
    /// assert_eq!(b, [2, 3, 4]);
    ///
    /// let a = ["1", "2a", "3"];
    /// let b = a.try_map(|v| v.parse::<u32>());
    /// assert!(b.is_err());
    ///
    /// use std::num::NonZeroU32;
    /// let z = [1, 2, 0, 3, 4];
    /// assert_eq!(z.try_map(NonZeroU32::new), None);
    /// let a = [1, 2, 3];
    /// let b = a.try_map(NonZeroU32::new);
    /// let c = b.map(|x| x.map(NonZeroU32::get));
    /// assert_eq!(c, Some(a));
    /// ```
    #[unstable(feature = "array_try_map", issue = "79711")]
    pub fn try_map<F, R>(self, f: F) -> ChangeOutputType<R, [R::Output; N]>
    where
        F: FnMut(T) -> R,
        R: Try,
        R::Residual: Residual<[R::Output; N]>,
    {
        // SAFETY: 我们肯定知道该迭代器将产生完全 `N` 项。
        //
        unsafe { try_collect_into_array_unchecked(&mut IntoIterator::into_iter(self).map(f)) }
    }

    /// 将两个阵列压缩为成对的单个阵列。
    ///
    /// `zip()` 返回一个新数组,其中每个元素都是一个元组,其中第一个元素来自第一个数组,第二个元素来自第二个数组。
    ///
    /// 换句话说,它将两个数组压缩在一起,成为一个数组。
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(array_zip)]
    /// let x = [1, 2, 3];
    /// let y = [4, 5, 6];
    /// let z = x.zip(y);
    /// assert_eq!(z, [(1, 4), (2, 5), (3, 6)]);
    /// ```
    ///
    #[unstable(feature = "array_zip", issue = "80094")]
    pub fn zip<U>(self, rhs: [U; N]) -> [(T, U); N] {
        let mut iter = IntoIterator::into_iter(self).zip(rhs);

        // SAFETY: 我们肯定知道该迭代器将产生完全 `N` 项。
        //
        unsafe { collect_into_array_unchecked(&mut iter) }
    }

    /// 返回包含整个数组的切片。等效于 `&s[..]`。
    #[stable(feature = "array_as_slice", since = "1.57.0")]
    pub const fn as_slice(&self) -> &[T] {
        self
    }

    /// 返回包含整个数组的可变切片。
    /// 等效于 `&mut s[..]`。
    #[stable(feature = "array_as_slice", since = "1.57.0")]
    pub fn as_mut_slice(&mut self) -> &mut [T] {
        self
    }

    /// 借用每个元素,并返回一个引用数组,其大小与 `self` 相同。
    ///
    /// # Example
    ///
    /// ```
    /// #![feature(array_methods)]
    ///
    /// let floats = [3.1, 2.7, -1.0];
    /// let float_refs: [&f64; 3] = floats.each_ref();
    /// assert_eq!(float_refs, [&3.1, &2.7, &-1.0]);
    /// ```
    ///
    /// 如果与其他方法 (例如 [`map`](#method.map)) 结合使用,则此方法特别有用。
    /// 这样,如果原始数组的元素不是 [`Copy`],则可以避免移动原始数组。
    ///
    /// ```
    /// #![feature(array_methods)]
    ///
    /// let strings = ["Ferris".to_string(), "♥".to_string(), "Rust".to_string()];
    /// let is_ascii = strings.each_ref().map(|s| s.is_ascii());
    /// assert_eq!(is_ascii, [true, false, true]);
    ///
    /// // 我们仍然可以访问原始数组:它尚未移动。
    /// assert_eq!(strings.len(), 3);
    /// ```
    ///
    ///
    ///
    #[unstable(feature = "array_methods", issue = "76118")]
    pub fn each_ref(&self) -> [&T; N] {
        // SAFETY: 我们肯定知道该迭代器将产生完全 `N` 项。
        //
        unsafe { collect_into_array_unchecked(&mut self.iter()) }
    }

    /// 借用每个元素,并返回与 `self` 相同大小的可变引用数组。
    ///
    ///
    /// # Example
    ///
    /// ```
    /// #![feature(array_methods)]
    ///
    /// let mut floats = [3.1, 2.7, -1.0];
    /// let float_refs: [&mut f64; 3] = floats.each_mut();
    /// *float_refs[0] = 0.0;
    /// assert_eq!(float_refs, [&mut 0.0, &mut 2.7, &mut -1.0]);
    /// assert_eq!(floats, [0.0, 2.7, -1.0]);
    /// ```
    ///
    #[unstable(feature = "array_methods", issue = "76118")]
    pub fn each_mut(&mut self) -> [&mut T; N] {
        // SAFETY: 我们肯定知道该迭代器将产生完全 `N` 项。
        //
        unsafe { collect_into_array_unchecked(&mut self.iter_mut()) }
    }

    /// 在一个索引处将一个数组的引用一分为二。
    ///
    /// 第一个将包含来自 `[0, M)` 的所有索引 (不包括索引 `M` 本身),第二个将包含来自 `[M, N)` 的所有索引 (不包括索引 `N` 本身)。
    ///
    ///
    /// # Panics
    ///
    /// 如果 `M > N`,就会出现 panics。
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(split_array)]
    ///
    /// let v = [1, 2, 3, 4, 5, 6];
    ///
    /// {
    ///    let (left, right) = v.split_array_ref::<0>();
    ///    assert_eq!(left, &[]);
    ///    assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
    /// }
    ///
    /// {
    ///     let (left, right) = v.split_array_ref::<2>();
    ///     assert_eq!(left, &[1, 2]);
    ///     assert_eq!(right, &[3, 4, 5, 6]);
    /// }
    ///
    /// {
    ///     let (left, right) = v.split_array_ref::<6>();
    ///     assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
    ///     assert_eq!(right, &[]);
    /// }
    /// ```
    ///
    #[unstable(
        feature = "split_array",
        reason = "return type should have array as 2nd element",
        issue = "90091"
    )]
    #[inline]
    pub fn split_array_ref<const M: usize>(&self) -> (&[T; M], &[T]) {
        (&self[..]).split_array_ref::<M>()
    }

    /// 在一个索引处将一个可变数组的引用一分为二。
    ///
    /// 第一个将包含来自 `[0, M)` 的所有索引 (不包括索引 `M` 本身),第二个将包含来自 `[M, N)` 的所有索引 (不包括索引 `N` 本身)。
    ///
    ///
    /// # Panics
    ///
    /// 如果 `M > N`,就会出现 panics。
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(split_array)]
    ///
    /// let mut v = [1, 0, 3, 0, 5, 6];
    /// let (left, right) = v.split_array_mut::<2>();
    /// assert_eq!(left, &mut [1, 0][..]);
    /// assert_eq!(right, &mut [3, 0, 5, 6]);
    /// left[1] = 2;
    /// right[1] = 4;
    /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
    /// ```
    ///
    #[unstable(
        feature = "split_array",
        reason = "return type should have array as 2nd element",
        issue = "90091"
    )]
    #[inline]
    pub fn split_array_mut<const M: usize>(&mut self) -> (&mut [T; M], &mut [T]) {
        (&mut self[..]).split_array_mut::<M>()
    }

    /// 将一个数组引用从末尾的一个索引处一分为二。
    ///
    /// 第一个将包含来自 `[0, N - M)` 的所有索引 (不包括索引 `N - M` 本身),第二个将包含来自 `[N - M, N)` 的所有索引 (不包括索引 `N` 本身)。
    ///
    ///
    /// # Panics
    ///
    /// 如果 `M > N`,就会出现 panics。
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(split_array)]
    ///
    /// let v = [1, 2, 3, 4, 5, 6];
    ///
    /// {
    ///    let (left, right) = v.rsplit_array_ref::<0>();
    ///    assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
    ///    assert_eq!(right, &[]);
    /// }
    ///
    /// {
    ///     let (left, right) = v.rsplit_array_ref::<2>();
    ///     assert_eq!(left, &[1, 2, 3, 4]);
    ///     assert_eq!(right, &[5, 6]);
    /// }
    ///
    /// {
    ///     let (left, right) = v.rsplit_array_ref::<6>();
    ///     assert_eq!(left, &[]);
    ///     assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
    /// }
    /// ```
    ///
    #[unstable(
        feature = "split_array",
        reason = "return type should have array as 2nd element",
        issue = "90091"
    )]
    #[inline]
    pub fn rsplit_array_ref<const M: usize>(&self) -> (&[T], &[T; M]) {
        (&self[..]).rsplit_array_ref::<M>()
    }

    /// 将一个附属数组引用从末尾的一个索引处一分为二。
    ///
    /// 第一个将包含来自 `[0, N - M)` 的所有索引 (不包括索引 `N - M` 本身),第二个将包含来自 `[N - M, N)` 的所有索引 (不包括索引 `N` 本身)。
    ///
    ///
    /// # Panics
    ///
    /// 如果 `M > N`,就会出现 panics。
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(split_array)]
    ///
    /// let mut v = [1, 0, 3, 0, 5, 6];
    /// let (left, right) = v.rsplit_array_mut::<4>();
    /// assert_eq!(left, &mut [1, 0]);
    /// assert_eq!(right, &mut [3, 0, 5, 6][..]);
    /// left[1] = 2;
    /// right[1] = 4;
    /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
    /// ```
    ///
    #[unstable(
        feature = "split_array",
        reason = "return type should have array as 2nd element",
        issue = "90091"
    )]
    #[inline]
    pub fn rsplit_array_mut<const M: usize>(&mut self) -> (&mut [T], &mut [T; M]) {
        (&mut self[..]).rsplit_array_mut::<M>()
    }
}

/// 从 `iter` 中提取 `N` 项,并将它们作为数组返回。
/// 如果迭代器产生的结果少于 `N` 项,则此函数显示未定义的行为。
///
///
/// 有关详细信息,请参见 [`try_collect_into_array`]。
///
/// # Safety
///
/// 取决于调用者,以确保 `iter` 至少产生 `N` 项。
/// 违反此条件会导致未定义的行为。
unsafe fn try_collect_into_array_unchecked<I, T, R, const N: usize>(iter: &mut I) -> R::TryType
where
    // Note: `TrustedLen` 在这里有点实验。
    // 这只是一个内联函数,因此如果发现此绑定不是一个好主意,请随时删除。
    //
    // 在这种情况下,请记住还要移除下面的下限 `debug_assert!`!
    I: Iterator + TrustedLen,
    I::Item: Try<Output = T, Residual = R>,
    R: Residual<[T; N]>,
{
    debug_assert!(N <= iter.size_hint().1.unwrap_or(usize::MAX));
    debug_assert!(N <= iter.size_hint().0);

    // SAFETY: 函数契约涵盖的范围。
    unsafe { try_collect_into_array(iter).unwrap_unchecked() }
}

// `try_collect_into_array_unchecked` 的可靠版本。
unsafe fn collect_into_array_unchecked<I, const N: usize>(iter: &mut I) -> [I::Item; N]
where
    I: Iterator + TrustedLen,
{
    let mut map = iter.map(NeverShortCircuit);

    // SAFETY: 相同的安全注意事项
    // 迭代器长度适用于 `try_collect_into_array_unchecked` 和 `collect_into_array_unchecked`
    //
    match unsafe { try_collect_into_array_unchecked(&mut map) } {
        NeverShortCircuit(array) => array,
    }
}

/// 从 `iter` 中提取 `N` 项,并将它们作为数组返回。如果迭代器生成的项少于 `N`,则返回 `None`,并且丢弃所有已经生成的项。
///
/// 由于迭代器是作为变量引用传递的,并且此函数最多 `N` 次调用 `next`,因此以后仍然可以使用迭代器来检索剩余项。
///
///
/// 如果 `iter.next()` 出现 panic,则丢弃迭代器已经生成的所有项。
///
///
///
///
fn try_collect_into_array<I, T, R, const N: usize>(iter: &mut I) -> Option<R::TryType>
where
    I: Iterator,
    I::Item: Try<Output = T, Residual = R>,
    R: Residual<[T; N]>,
{
    if N == 0 {
        // SAFETY: 空数组始终有人居住,并且没有有效性不变量。
        return unsafe { Some(Try::from_output(mem::zeroed())) };
    }

    struct Guard<'a, T, const N: usize> {
        array_mut: &'a mut [MaybeUninit<T>; N],
        initialized: usize,
    }

    impl<T, const N: usize> Drop for Guard<'_, T, N> {
        fn drop(&mut self) {
            debug_assert!(self.initialized <= N);

            // SAFETY: 这个切片将只包含初始化的对象。
            unsafe {
                crate::ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(
                    &mut self.array_mut.get_unchecked_mut(..self.initialized),
                ));
            }
        }
    }

    let mut array = MaybeUninit::uninit_array::<N>();
    let mut guard = Guard { array_mut: &mut array, initialized: 0 };

    while let Some(item_rslt) = iter.next() {
        let item = match item_rslt.branch() {
            ControlFlow::Break(r) => {
                return Some(FromResidual::from_residual(r));
            }
            ControlFlow::Continue(elem) => elem,
        };

        // SAFETY: `guard.initialized` 从 0 开始,在循环中加 1,一旦到达 N (`array.len()`),循环就中止。
        //
        //
        unsafe {
            guard.array_mut.get_unchecked_mut(guard.initialized).write(item);
        }
        guard.initialized += 1;

        // 检查整个数组是否已初始化。
        if guard.initialized == N {
            mem::forget(guard);

            // SAFETY: 以上条件断言所有元素都已初始化。
            //
            let out = unsafe { MaybeUninit::array_assume_init(array) };
            return Some(Try::from_output(out));
        }
    }

    // 仅当 `guard.initialized` 到达 `N` 之前迭代器已耗尽时,才可以达到此目的。
    //
    // 还要注意的是,这里将 `guard` 放在了这里,丢弃了所有已经初始化的元素。
    None
}