| 1 |
// { dg-additional-options "-w" } |
| 2 |
#![feature(intrinsics)] |
| 3 |
|
| 4 |
#[lang = "sized"] |
| 5 |
pub trait Sized {} |
| 6 |
|
| 7 |
extern "rust-intrinsic" { |
| 8 |
#[rustc_const_stable(feature = "const_ptr_offset", since = "1.61.0")] |
| 9 |
pub fn offset<T>(dst: *const T, offset: isize) -> *const T; |
| 10 |
} |
| 11 |
|
| 12 |
struct FatPtr<T> { |
| 13 |
data: *const T, |
| 14 |
len: usize, |
| 15 |
} |
| 16 |
|
| 17 |
union Repr<T> { |
| 18 |
rust: *const [T], |
| 19 |
rust_mut: *mut [T], |
| 20 |
raw: FatPtr<T>, |
| 21 |
} |
| 22 |
|
| 23 |
#[lang = "Range"] |
| 24 |
pub struct Range<Idx> { |
| 25 |
pub start: Idx, |
| 26 |
pub end: Idx, |
| 27 |
} |
| 28 |
|
| 29 |
#[lang = "const_slice_ptr"] |
| 30 |
impl<T> *const [T] { |
| 31 |
pub const fn len(self) -> usize { |
| 32 |
unsafe { Repr { rust: self }.raw.len } |
| 33 |
} |
| 34 |
|
| 35 |
pub const fn as_ptr(self) -> *const T { |
| 36 |
self as *const T |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
#[lang = "const_ptr"] |
| 41 |
impl<T> *const T { |
| 42 |
pub const unsafe fn offset(self, count: isize) -> *const T { |
| 43 |
unsafe { offset(self, count) } |
| 44 |
} |
| 45 |
|
| 46 |
pub const unsafe fn add(self, count: usize) -> Self { |
| 47 |
unsafe { self.offset(count as isize) } |
| 48 |
} |
| 49 |
|
| 50 |
pub const fn as_ptr(self) -> *const T { |
| 51 |
self as *const T |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
const fn slice_from_raw_parts<T>(data: *const T, len: usize) -> *const [T] { |
| 56 |
unsafe { |
| 57 |
Repr { |
| 58 |
raw: FatPtr { data, len }, |
| 59 |
} |
| 60 |
.rust |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
#[lang = "index"] |
| 65 |
trait Index<Idx> { |
| 66 |
type Output; |
| 67 |
|
| 68 |
fn index(&self, index: Idx) -> &Self::Output; |
| 69 |
} |
| 70 |
|
| 71 |
pub unsafe trait SliceIndex<T> { |
| 72 |
type Output; |
| 73 |
|
| 74 |
unsafe fn get_unchecked(self, slice: *const T) -> *const Self::Output; |
| 75 |
|
| 76 |
fn index(self, slice: &T) -> &Self::Output; |
| 77 |
} |
| 78 |
|
| 79 |
unsafe impl<T> SliceIndex<[T]> for Range<usize> { |
| 80 |
type Output = [T]; |
| 81 |
|
| 82 |
unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] { |
| 83 |
unsafe { |
| 84 |
let a: *const T = slice.as_ptr(); |
| 85 |
let b: *const T = a.add(self.start); |
| 86 |
slice_from_raw_parts(b, self.end - self.start) |
| 87 |
} |
| 88 |
} |
| 89 |
|
| 90 |
fn index(self, slice: &[T]) -> &[T] { |
| 91 |
unsafe { &*self.get_unchecked(slice) } |
| 92 |
} |
| 93 |
} |
| 94 |
|
| 95 |
impl<T, I> Index<I> for [T] |
| 96 |
where |
| 97 |
I: SliceIndex<[T]>, |
| 98 |
{ |
| 99 |
type Output = I::Output; |
| 100 |
|
| 101 |
fn index(&self, index: I) -> &I::Output { |
| 102 |
index.index(self) |
| 103 |
} |
| 104 |
} |
| 105 |
|
| 106 |
fn main() -> i32 { |
| 107 |
let a = [1, 2, 3, 4, 5]; |
| 108 |
let b = &a[1..3]; |
| 109 |
|
| 110 |
0 |
| 111 |
} |