]> git.lizzy.rs Git - rust.git/blob - tests/ui/array-slice-vec/slice-of-zero-size-elements.rs
Rollup merge of #106715 - BoxyUwU:new_solver_triagebot, r=lcnr
[rust.git] / tests / ui / array-slice-vec / slice-of-zero-size-elements.rs
1 // run-pass
2 #![allow(stable_features)]
3
4 // compile-flags: -C debug-assertions
5
6 #![feature(iter_to_slice)]
7
8 use std::slice;
9
10 fn foo<T>(v: &[T]) -> Option<&[T]> {
11     let mut it = v.iter();
12     for _ in 0..5 {
13         let _ = it.next();
14     }
15     Some(it.as_slice())
16 }
17
18 fn foo_mut<T>(v: &mut [T]) -> Option<&mut [T]> {
19     let mut it = v.iter_mut();
20     for _ in 0..5 {
21         let _ = it.next();
22     }
23     Some(it.into_slice())
24 }
25
26 pub fn main() {
27     // In a slice of zero-size elements the pointer is meaningless.
28     // Ensure iteration still works even if the pointer is at the end of the address space.
29     let slice: &[()] = unsafe { slice::from_raw_parts(-5isize as *const (), 10) };
30     assert_eq!(slice.len(), 10);
31     assert_eq!(slice.iter().count(), 10);
32
33     // .nth() on the iterator should also behave correctly
34     let mut it = slice.iter();
35     assert!(it.nth(5).is_some());
36     assert_eq!(it.count(), 4);
37
38     // Converting Iter to a slice should never have a null pointer
39     assert!(foo(slice).is_some());
40
41     // Test mutable iterators as well
42     let slice: &mut [()] = unsafe { slice::from_raw_parts_mut(-5isize as *mut (), 10) };
43     assert_eq!(slice.len(), 10);
44     assert_eq!(slice.iter_mut().count(), 10);
45
46     {
47         let mut it = slice.iter_mut();
48         assert!(it.nth(5).is_some());
49         assert_eq!(it.count(), 4);
50     }
51
52     assert!(foo_mut(slice).is_some())
53 }