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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License..

use core::intrinsics::assume;
use core::marker::PhantomData;
use core::mem;

// no relocate
#[repr(C)]
pub union Slice<T> {
    rust: *const [T],
    rust_mut: *mut [T],
    raw: FatPtr<T>,
}

#[repr(C)]
struct FatPtr<T> {
    data: *const T,
    len: usize,
}

impl<T> Clone for FatPtr<T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T> Copy for FatPtr<T> {}

pub trait AsSlice<T> {
    fn as_slice(&self) -> Slice<T>;
}

impl<T> AsSlice<T> for [T] {
    #[inline(always)]
    fn as_slice(&self) -> Slice<T> {
        Slice { rust: self }
    }
}

impl<T> Slice<T> {
    pub const fn as_ptr(&self) -> *const T {
        unsafe { self.rust as *const T }
    }

    pub fn as_mut_ptr(&mut self) -> *mut T {
        unsafe { self.rust_mut as *mut T }
    }

    pub const fn len(&self) -> usize {
        unsafe { self.raw.len }
    }

    pub fn get(&self, idx: usize) -> Option<&T> {
        if idx < self.len() {
            Some(unsafe { self.get_unchecked(idx) })
        } else {
            None
        }
    }

    pub fn get_mut(&mut self, idx: usize) -> Option<&mut T> {
        if idx < self.len() {
            Some(unsafe { self.get_mut_unchecked(idx) })
        } else {
            None
        }
    }

    pub unsafe fn get_unchecked(&self, idx: usize) -> &T {
        let size = if mem::size_of::<T>() == 0 {
            1
        } else {
            mem::size_of::<T>()
        };
        &*((self.as_ptr() as usize + size * idx) as *const T)
    }

    pub unsafe fn get_mut_unchecked(&mut self, idx: usize) -> &mut T {
        let size = if mem::size_of::<T>() == 0 {
            1
        } else {
            mem::size_of::<T>()
        };
        &mut *((self.as_mut_ptr() as usize + size * idx) as *mut T)
    }

    pub fn into_slice<'a>(self, rang: (usize, usize)) -> Option<&'a [T]> {
        if rang.1 > rang.0 && rang.1 < self.len() {
            Some(unsafe { self.into_slice_unchecked(rang) })
        } else {
            None
        }
    }

    pub fn into_mut_slice<'a>(self, rang: (usize, usize)) -> Option<&'a mut [T]> {
        if rang.1 > rang.0 && rang.1 < self.len() {
            Some(unsafe { self.into_mut_slice_unchecked(rang) })
        } else {
            None
        }
    }

    pub unsafe fn into_slice_unchecked<'a>(self, rang: (usize, usize)) -> &'a [T] {
        let start = self.as_ptr() as usize + rang.0;
        let len = rang.1 - rang.0;
        let size = if mem::size_of::<T>() == 0 {
            1
        } else {
            mem::size_of::<T>()
        };
        from_raw_parts(start as *const T, len * size)
    }

    pub unsafe fn into_mut_slice_unchecked<'a>(mut self, rang: (usize, usize)) -> &'a mut [T] {
        let start = self.as_mut_ptr() as usize + rang.0;
        let len = rang.1 - rang.0;
        let size = if mem::size_of::<T>() == 0 {
            1
        } else {
            mem::size_of::<T>()
        };
        from_raw_parts_mut(start as *mut T, len * size)
    }

    pub fn eq(&self, other: &[T]) -> bool {
        let t_len = self.len();
        let other = other.as_slice();
        if t_len != other.len() {
            return false;
        }

        unsafe {
            memcmp(
                self.as_ptr() as *const u8,
                other.as_ptr() as *const u8,
                mem::size_of::<T>() * t_len,
            )
        }
    }

    #[inline]
    pub fn iter(&self) -> Iter<'_, T> {
        Iter::new(self)
    }
}

pub unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T] {
    // SAFETY: Accessing the value from the `Repr` union is safe since *const [T]
    // and FatPtr have the same memory layouts. Only std can make this
    // guarantee.
    &*(Slice {
        raw: FatPtr { data, len },
    }
    .rust)
}

pub unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T] {
    // SAFETY: Accessing the value from the `Repr` union is safe since *mut [T]
    // and FatPtr have the same memory layouts
    &mut *(Slice {
        raw: FatPtr { data, len },
    }
    .rust_mut)
}

pub fn eq<T>(src: &[T], other: &[T]) -> bool {
    let t_len = src.as_slice().len();
    if t_len != other.as_slice().len() {
        return false;
    }

    unsafe {
        memcmp(
            src.as_slice().as_ptr() as *const u8,
            other.as_slice().as_ptr() as *const u8,
            mem::size_of::<T>() * t_len,
        )
    }
}

unsafe fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> bool {
    if n != 0 {
        let mut i = 0;
        let mut src_ptr = s1 as usize;
        let mut other_ptr = s2 as usize;
        while i < n {
            if *(src_ptr as *const u8) != *(other_ptr as *const u8) {
                return false;
            }
            src_ptr += 1;
            other_ptr += 1;
            i += 1;
        }
    }
    true
}

pub struct Iter<'a, T: 'a> {
    ptr: *const T,
    end: *const T,
    _marker: PhantomData<&'a T>,
}

impl<'a, T> Iter<'a, T> {
    pub fn new(slice: &'a Slice<T>) -> Self {
        let ptr = slice.as_ptr();
        unsafe {
            assume((ptr as usize) != 0);

            let end = if mem::size_of::<T>() == 0 {
                ((ptr as usize) + slice.len()) as *const T
            } else {
                ((ptr as usize) + slice.len() * mem::size_of::<T>()) as *const T
            };

            Self {
                ptr,
                end,
                _marker: PhantomData,
            }
        }
    }

    #[inline]
    #[allow(clippy::while_let_on_iterator)]
    pub fn for_each<F>(mut self, mut f: F)
    where
        Self: Sized,
        F: FnMut(&'a T),
    {
        while let Some(x) = self.next() {
            f(x);
        }
    }

    #[inline]
    #[allow(clippy::while_let_on_iterator)]
    pub fn all<F>(mut self, mut f: F) -> bool
    where
        Self: Sized,
        F: FnMut(&'a T) -> bool,
    {
        while let Some(x) = self.next() {
            if !f(x) {
                return false;
            }
        }
        true
    }

    #[inline]
    #[allow(clippy::while_let_on_iterator)]
    pub fn any<F>(mut self, mut f: F) -> bool
    where
        Self: Sized,
        F: FnMut(&'a T) -> bool,
    {
        while let Some(x) = self.next() {
            if f(x) {
                return true;
            }
        }
        false
    }

    #[inline]
    fn next(&mut self) -> Option<&'a T> {
        unsafe {
            assume((self.ptr as usize) != 0);
            if mem::size_of::<T>() != 0 {
                assume((self.end as usize) != 0);
            }

            if self.ptr as usize == self.end as usize {
                None
            } else {
                let old = self.ptr;
                if mem::size_of::<T>() == 0 {
                    self.ptr = (self.ptr as usize + 1) as *const T;
                } else {
                    self.ptr = (self.ptr as usize + mem::size_of::<T>()) as *const T;
                }
                Some(&*old)
            }
        }
    }
}