eta_algorithms/data_structs/array/
mod.rs

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
use std::alloc::{realloc, Layout};
use std::cmp::min;
use std::marker::PhantomData;
use std::ops::{Index, IndexMut};
use std::ptr;
use std::ptr::{addr_of_mut, copy_nonoverlapping};

pub mod iterator;

pub struct Array<T>
where
    T: Copy + Sized,
{
    phantom_data: PhantomData<()>, // For compile time borrow checking correctness
    layout: Layout,
    data: *mut T,
    capacity: usize,
}

impl<T> Clone for Array<T>
where
    T: Copy + Sized,
{
    fn clone(&self) -> Self {
        let array = Self::new(self.capacity);
        unsafe { copy_nonoverlapping(self.data, array.data, self.capacity) }
        array
    }
}

impl<T> Array<T>
where
    T: Copy + Sized,
{
    #[inline(always)]
    pub fn capacity(&self) -> usize {
        self.capacity
    }
    pub fn extend(&mut self, new_capacity: usize) {
        let new_layout = Layout::array::<T>(new_capacity).expect("Failed to create layout");
        let new_ptr = unsafe { realloc(self.data as *mut u8, new_layout, new_layout.size()) };
        if new_ptr.is_null() {
            panic!("Failed to allocate memory");
        }
        self.data = new_ptr as *mut T;
        self.capacity = new_capacity;
        self.layout = new_layout;
    }
    #[inline(always)]
    pub fn extend_by(&mut self, additional_capacity: usize) {
        self.extend(self.capacity + additional_capacity);
    }

    pub fn as_ptr(&self) -> *const T {
        self.data
    }

    pub fn as_mut_ptr(&mut self) -> *mut T {
        self.data
    }

    pub fn new(capacity: usize) -> Self {
        let layout = Layout::array::<T>(capacity).expect("Failed to create layout");
        let data = unsafe { std::alloc::alloc(layout) as *mut T };
        if data.is_null() {
            panic!("Failed to allocate memory");
        }
        Array {
            phantom_data: PhantomData,
            layout,
            data,
            capacity,
        }
    }

    #[inline(always)]
    pub fn new_default_bytes(capacity: usize, default: u8) -> Self {
        let arr = Self::new(capacity);
        unsafe { ptr::write_bytes(arr.data, default, capacity) };
        arr
    }
    #[inline(always)]
    pub fn new_with_default(capacity: usize, default: T) -> Self
    where
        T: Copy,
    {
        let mut arr = Self::new(capacity);
        arr.fill(default);
        arr
    }

    pub fn fill(&mut self, value: T)
    where
        T: Copy,
    {
        for i in self.iter_mut() {
            *i = value;
        }
    }
    #[inline(always)]
    pub fn iter(&self) -> iterator::ArrayIterator<T> {
        iterator::ArrayIterator {
            phantom_data: &self.phantom_data,
            data: self.data,
            end: unsafe { self.data.add(self.capacity) },
        }
    }

    #[inline(always)]
    pub fn iter_mut(&mut self) -> iterator::ArrayIteratorMut<T> {
        iterator::ArrayIteratorMut {
            phantom_data: &mut self.phantom_data,
            data: self.data,
            end: unsafe { self.data.add(self.capacity) },
        }
    }

    #[inline(always)]
    pub fn iter_range(&self, start: usize, end: usize) -> iterator::ArrayIterator<T> {
        iterator::ArrayIterator {
            phantom_data: &self.phantom_data,
            data: unsafe { self.data.add(start) },
            end: unsafe { min(self.data.add(end), self.data.add(self.capacity)) },
        }
    }

    #[inline(always)]
    pub fn iter_range_mut(&mut self, start: usize, end: usize) -> iterator::ArrayIteratorMut<T> {
        iterator::ArrayIteratorMut {
            phantom_data: &mut self.phantom_data,
            data: unsafe { self.data.add(start) },
            end: unsafe { min(self.data.add(end), self.data.add(self.capacity)) },
        }
    }

    /// Extremely unsafe as it bypasses lifetime checks. Use if you know what you are doing.
    /// This is good for cases where you need dynamically retrieve multiple mutable iterators to chunks of non-overlapping data.
    #[inline(always)]
    pub unsafe fn iter_range_mut_unchecked(&mut self, start: usize, end: usize) -> iterator::ArrayIteratorMut<'static, T> {
        static mut PHANTOM: PhantomData<()> = PhantomData;
        iterator::ArrayIteratorMut {
            phantom_data: &mut *addr_of_mut!(PHANTOM),
            data: unsafe { self.data.add(start) },
            end: unsafe { min(self.data.add(end), self.data.add(self.capacity)) },
        }
    }

    /// Copies the contents of the vector into the array.
    pub fn from_vec(vec: Vec<T>) -> Self {
        let arr = Self::new(vec.len());
        unsafe {
            copy_nonoverlapping(vec.as_ptr(), arr.data, arr.capacity);
            arr
        }
    }
    /// Copies the contents of the slice into the array.
    pub fn from_slice(slice: &[T]) -> Self {
        let arr = Self::new(slice.len());
        unsafe {
            copy_nonoverlapping(slice.as_ptr(), arr.data, arr.capacity);
            arr
        }
    }

    pub fn as_slice(&self) -> &[T] {
        unsafe { std::slice::from_raw_parts(self.data, self.capacity) }
    }

    pub fn as_mut_slice(&mut self) -> &mut [T] {
        unsafe { std::slice::from_raw_parts_mut(self.data, self.capacity) }
    }

    pub fn split_at(&mut self, index: usize) -> (&[T], &[T]) {
        if index >= self.capacity {
            panic!("Index out of bounds");
        }
        let new_data = unsafe { self.data.add(index) };
        let left = unsafe { std::slice::from_raw_parts(self.data, index) };
        let right = unsafe { std::slice::from_raw_parts(new_data, self.capacity - index) };
        (left, right)
    }

    pub fn split_at_mut(&mut self, index: usize) -> (&mut [T], &mut [T]) {
        if index >= self.capacity {
            panic!("Index out of bounds");
        }
        let new_data = unsafe { self.data.add(index) };
        let left = unsafe { std::slice::from_raw_parts_mut(self.data, index) };
        let right = unsafe { std::slice::from_raw_parts_mut(new_data, self.capacity - index) };
        (left, right)
    }

    pub fn split_into_parts(&self, parts: usize) -> Array<&[T]> {
        if parts > self.capacity {
            panic!("Parts must be less than or equal to the capacity of the array");
        }

        if parts == 0 {
            panic!("Parts cannot be 0");
        }

        let chunk_size = self.capacity / parts;
        let remainder = self.capacity % parts;

        let mut arr = Array::<&[T]>::new(parts);
        let mut ptr = self.data as *const T;
        for i in 0..parts - 1 {
            arr[i] = unsafe { std::slice::from_raw_parts(ptr, chunk_size) };
            ptr = unsafe { ptr.add(chunk_size) };
        }

        arr[parts - 1] = unsafe { std::slice::from_raw_parts(ptr, chunk_size + remainder) };

        arr
    }
    pub fn split_into_parts_mut(&mut self, parts: usize) -> Vec<&mut [T]> {
        if parts >= self.capacity {
            panic!("Parts must be less than or equal to the capacity of the array");
        }

        if parts == 0 {
            panic!("Parts cannot be 0");
        }

        let chunk_size = self.capacity / parts;
        let remainder = self.capacity % parts;

        let mut arr = Vec::<&mut [T]>::with_capacity(parts);
        let mut ptr = self.data;
        for _ in 0..parts - 1 {
            arr.push(unsafe { std::slice::from_raw_parts_mut(ptr, chunk_size) });
            ptr = unsafe { ptr.add(chunk_size) };
        }

        arr.push(unsafe { std::slice::from_raw_parts_mut(ptr, chunk_size + remainder) });
        arr
    }
    #[inline(always)]
    pub unsafe fn index_unchecked(&self, index: usize) -> &T {
        self.data.add(index).as_ref().unwrap()
    }

    #[inline(always)]
    pub unsafe fn index_unchecked_mut(&mut self, index: usize) -> &mut T {
        self.data.add(index).as_mut().unwrap()
    }
}

impl<T> Drop for Array<T>
where
    T: Copy + Sized,
{
    fn drop(&mut self) {
        unsafe {
            std::alloc::dealloc(self.data as *mut u8, self.layout);
        }
    }
}

impl<T> Index<usize> for Array<T>
where
    T: Copy + Sized,
{
    type Output = T;

    #[inline(always)]
    fn index(&self, index: usize) -> &Self::Output {
        if index >= self.capacity {
            panic!("Index out of bounds");
        }

        unsafe { &*self.data.add(index) }
    }
}

impl<T> IndexMut<usize> for Array<T>
where
    T: Copy + Sized,
{
    #[inline(always)]
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        if index >= self.capacity {
            panic!("Index out of bounds");
        }
        unsafe { &mut *self.data.add(index) }
    }
}