File: issue-61936.rs

package info (click to toggle)
rustc-web 1.85.0%2Bdfsg3-1~deb12u3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bookworm-proposed-updates
  • size: 1,759,988 kB
  • sloc: xml: 158,127; python: 35,830; javascript: 19,497; cpp: 19,002; sh: 17,245; ansic: 13,127; asm: 4,376; makefile: 1,056; lisp: 29; perl: 29; ruby: 19; sql: 11
file content (47 lines) | stat: -rw-r--r-- 1,303 bytes parent folder | download | duplicates (10)
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
//@ run-pass

trait SliceExt<T: Clone> {
    fn array_windows_example<'a, const N: usize>(&'a self) -> ArrayWindowsExample<'a, T, N>;
}

impl <T: Clone> SliceExt<T> for [T] {
   fn array_windows_example<'a, const N: usize>(&'a self) -> ArrayWindowsExample<'a, T, N> {
       ArrayWindowsExample{ idx: 0, slice: &self }
   }
}

struct ArrayWindowsExample<'a, T, const N: usize> {
    slice: &'a [T],
    idx: usize,
}

impl <'a, T: Clone, const N: usize> Iterator for ArrayWindowsExample<'a, T, N> {
    type Item = [T; N];
    fn next(&mut self) -> Option<Self::Item> {
        // Note: this is unsound for some `T` and not meant as an example
        // on how to implement `ArrayWindows`.
        let mut res = unsafe{ std::mem::zeroed() };
        let mut ptr = &mut res as *mut [T; N] as *mut T;

        for i in 0..N {
            match self.slice[self.idx..].get(i) {
                None => return None,
                Some(elem) => unsafe { std::ptr::write_volatile(ptr, elem.clone())},
            };
            ptr = ptr.wrapping_add(1);
            self.idx += 1;
        }

        Some(res)
    }
}

const FOUR: usize = 4;

fn main() {
    let v: Vec<usize> = vec![0; 100];

    for array in v.as_slice().array_windows_example::<FOUR>() {
        assert_eq!(array, [0, 0, 0, 0])
    }
}