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
//! A dynamically sized array.
use std::iter::FusedIterator;
use std::marker::PhantomData;
use std::{fmt, mem, ops, ptr, slice};

use super::IAllocator;
use crate::raw::root::RED4ext as red;
use crate::VoidPtr;

/// A dynamically sized array.
#[repr(transparent)]
pub struct RedArray<T>(red::DynArray<T>);

impl<T> RedArray<T> {
    /// Creates a new empty [`RedArray`].
    #[inline]
    pub const fn new() -> Self {
        Self(red::DynArray {
            entries: ptr::null_mut(),
            size: 0,
            capacity: 0,
            _phantom_0: PhantomData,
        })
    }

    /// Creates a new empty [`RedArray`] with the specified capacity.
    #[inline]
    pub fn with_capacity(capacity: u32) -> Self {
        let mut this = Self::new();
        this.realloc(capacity);
        this
    }

    /// Returns the number of elements in the array.
    #[inline]
    pub fn len(&self) -> u32 {
        self.0.size
    }

    /// Returns `true` if the array contains no elements.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns the number of elements the array can hold without reallocating.
    #[inline]
    pub fn capacity(&self) -> u32 {
        self.0.capacity
    }

    /// Clears the array, removing all values.
    #[inline]
    pub fn clear(&mut self) {
        let elems: *mut [T] = &mut **self;
        unsafe { ptr::drop_in_place(elems) }
        self.0.size = 0;
    }

    /// Adds an element to the end of the array.
    #[inline]
    pub fn push(&mut self, value: T) {
        let len = self.len();
        self.reserve(1);
        unsafe {
            ptr::write(self.0.entries.add(len as usize), value);
        }
        self.0.size = len + 1;
    }

    /// Reserve capacity for at least `additional` more elements to be inserted.
    pub fn reserve(&mut self, additional: u32) {
        let expected = self.len() + additional;
        if expected <= self.capacity() {
            return;
        }
        self.realloc(expected.max(self.capacity() + self.capacity() / 2));
    }

    /// Returns an iterator over the elements of the array.
    pub fn iter(&self) -> slice::Iter<'_, T> {
        self.into_iter()
    }

    fn realloc(&mut self, cap: u32) {
        let size = mem::size_of::<T>();
        let align = mem::align_of::<T>().max(8);
        unsafe {
            let realloc = crate::fn_from_hash!(
                DynArray_Realloc,
                unsafe extern "C" fn(VoidPtr, u32, u32, u32, usize)
            );
            realloc(self as *mut _ as VoidPtr, cap, size as u32, align as u32, 0);
        };
    }
}

impl<T: fmt::Debug> fmt::Debug for RedArray<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.iter()).finish()
    }
}

impl<T> Default for RedArray<T> {
    fn default() -> Self {
        Self(Default::default())
    }
}

impl<T> ops::Deref for RedArray<T> {
    type Target = [T];

    #[inline]
    fn deref(&self) -> &[T] {
        (!self.0.entries.is_null())
            .then(|| unsafe { slice::from_raw_parts(self.0.entries, self.len() as _) })
            .unwrap_or_default()
    }
}

impl<T> ops::DerefMut for RedArray<T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut [T] {
        (!self.0.entries.is_null())
            .then(|| unsafe { slice::from_raw_parts_mut(self.0.entries, self.len() as _) })
            .unwrap_or_default()
    }
}

impl<T> AsRef<[T]> for RedArray<T> {
    #[inline]
    fn as_ref(&self) -> &[T] {
        self
    }
}

impl<T> AsMut<[T]> for RedArray<T> {
    #[inline]
    fn as_mut(&mut self) -> &mut [T] {
        self
    }
}

impl<'a, T> IntoIterator for &'a RedArray<T> {
    type IntoIter = slice::Iter<'a, T>;
    type Item = &'a T;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        <[T]>::iter(self)
    }
}

impl<T> IntoIterator for RedArray<T> {
    type IntoIter = IntoIter<T>;
    type Item = T;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        let me = mem::ManuallyDrop::new(self);
        IntoIter {
            array: red::DynArray {
                entries: me.0.entries,
                size: me.len(),
                capacity: me.capacity(),
                ..Default::default()
            },
            ptr: me.0.entries,
            end: unsafe { me.0.entries.add(me.len() as _) },
        }
    }
}

impl<T> FromIterator<T> for RedArray<T> {
    #[inline]
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        let mut array = Self::new();
        array.extend(iter);
        array
    }
}

impl<T> Extend<T> for RedArray<T> {
    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        let iter = iter.into_iter();
        let (lower, _) = iter.size_hint();
        self.reserve(lower as u32);
        for item in iter {
            self.push(item);
        }
    }
}

impl<T> Drop for RedArray<T> {
    #[inline]
    fn drop(&mut self) {
        if self.capacity() == 0 {
            return;
        }
        let elems: *mut [T] = &mut **self;
        unsafe {
            ptr::drop_in_place(elems);
            (*get_allocator(&self.0)).free(self.0.entries);
        };
    }
}

#[derive(Debug)]
pub struct IntoIter<T> {
    array: red::DynArray<T>,
    ptr: *mut T,
    end: *mut T,
}

impl<T> Iterator for IntoIter<T> {
    type Item = T;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.ptr == self.end {
            None
        } else {
            let old = self.ptr;
            self.ptr = unsafe { old.add(1) };
            Some(unsafe { ptr::read(old) })
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = unsafe { self.end.offset_from(self.ptr) } as usize;
        (len, Some(len))
    }
}

impl<T> DoubleEndedIterator for IntoIter<T> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.ptr == self.end {
            None
        } else {
            self.end = unsafe { self.end.sub(1) };
            Some(unsafe { ptr::read(self.end) })
        }
    }
}

impl<T> ExactSizeIterator for IntoIter<T> {}

impl<T> FusedIterator for IntoIter<T> {}

impl<T> Drop for IntoIter<T> {
    #[inline]
    fn drop(&mut self) {
        if self.array.capacity == 0 {
            return;
        }
        unsafe {
            let elems = slice::from_raw_parts_mut(self.ptr, self.len());
            ptr::drop_in_place(elems);
            (*get_allocator(&self.array)).free(self.array.entries);
        };
    }
}

fn get_allocator<T>(arr: &red::DynArray<T>) -> *mut IAllocator {
    if arr.capacity == 0 {
        &arr.entries as *const _ as *mut _
    } else {
        let end = unsafe { arr.entries.add(arr.capacity as _) } as usize;
        let aligned = end.next_multiple_of(mem::size_of::<usize>());
        aligned as _
    }
}