nstd_collections 0.5.0

NSTD collections crate.
Documentation
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
use nstd_alloc::deps::nstd_core;
use nstd_core::slice::NSTDSlice;
use std::{
    mem::ManuallyDrop,
    os::raw::{c_int, c_void},
    ptr::{self, addr_of_mut},
};

/// Represents an array of dynamic length.
#[repr(C)]
#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct NSTDVec {
    pub size: usize,
    pub capacity: usize,
    pub element_size: usize,
    pub data: *mut u8,
}
impl NSTDVec {
    /// Gets the total number of bytes allocated for this vec.
    #[inline]
    pub fn total_byte_count(&self) -> usize {
        self.capacity * self.element_size
    }

    /// Gets the number of used bytes for this vec.
    #[inline]
    pub fn byte_count(&self) -> usize {
        self.size * self.element_size
    }

    /// Returns a pointer to the end of the vector.
    #[inline]
    pub unsafe fn end_unchecked(&self) -> *mut u8 {
        self.data.add(self.byte_count())
    }

    /// Drops elements aquired from a [`Vec`].
    pub unsafe fn drop_from_vec<T>(&mut self) -> c_int {
        let data_ptr = self.data as *mut ManuallyDrop<T>;
        let data_slice = std::slice::from_raw_parts_mut(data_ptr, self.size);
        for element in data_slice {
            ManuallyDrop::<T>::drop(element);
        }
        nstd_collections_vec_free(self)
    }
}
impl Default for NSTDVec {
    #[inline]
    fn default() -> Self {
        Self {
            size: 0,
            capacity: 0,
            element_size: 0,
            data: ptr::null_mut(),
        }
    }
}
impl Clone for NSTDVec {
    fn clone(&self) -> Self {
        unsafe {
            let mut new_vec =
                nstd_collections_vec_new_with_capacity(self.element_size, self.capacity);
            if !new_vec.data.is_null() {
                let byte_count = self.byte_count();
                let data = std::slice::from_raw_parts(self.data, byte_count);
                let new_data = std::slice::from_raw_parts_mut(new_vec.data, byte_count);
                new_data.copy_from_slice(data);
                new_vec.size = self.size;
            }
            new_vec
        }
    }
}
impl<T> From<Vec<T>> for NSTDVec {
    /// Creates an `NSTDVec` from a [`Vec`]. The only way to free memory allocated by this
    /// function is to call `drop_from_vec`.
    fn from(vec: Vec<T>) -> Self {
        unsafe {
            let element_size = std::mem::size_of::<ManuallyDrop<T>>();
            let mut nstd_vec = nstd_collections_vec_new_with_capacity(element_size, vec.len());
            if !nstd_vec.data.is_null() {
                for element in vec {
                    let element = ManuallyDrop::new(element);
                    let element = &element as *const ManuallyDrop<T> as *const c_void;
                    nstd_collections_vec_push(&mut nstd_vec, element);
                }
            }
            nstd_vec
        }
    }
}

/// Creates a new vector.
/// Parameters:
///     `const NSTDUSize element_size` - The size of each element in the vector.
/// Returns: `NSTDVec vec` - The new vector.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_collections_vec_new(element_size: usize) -> NSTDVec {
    const INITIAL_CAPACITY: usize = 1;
    NSTDVec {
        size: 0,
        capacity: INITIAL_CAPACITY,
        element_size,
        data: nstd_alloc::nstd_alloc_allocate(INITIAL_CAPACITY * element_size).cast(),
    }
}

/// Creates a new vector with the specified capacity.
/// Parameters:
///     `const NSTDUSize element_size` - The size of each element in the vector.
///     `const NSTDUSize capacity` - The capacity to give the vector, must be greater than 0.
/// Returns: `NSTDVec vec` - The new vector.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_collections_vec_new_with_capacity(
    element_size: usize,
    capacity: usize,
) -> NSTDVec {
    NSTDVec {
        size: 0,
        capacity,
        element_size,
        data: nstd_alloc::nstd_alloc_allocate(capacity * element_size).cast(),
    }
}

/// Creates an `NSTDSlice` from an `NSTDVec`.
/// Parameters:
///     `const NSTDVec *const vec` - The vector.
/// Returns: `NSTDSlice slice` - The new slice.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_collections_vec_as_slice(vec: &NSTDVec) -> NSTDSlice {
    nstd_core::slice::nstd_core_slice_new(vec.size, vec.element_size, vec.data as *mut c_void)
}

/// Gets a pointer to an element from a vector.
/// NOTE: The returned element pointer can quickly become a dangling pointer if the vector's memory
/// gets reallocated or deallocated, so it is advised to create a copy of the element after
/// getting it.
/// Parameters:
///     `const NSTDVec *const vec` - The vector.
///     `const NSTDUSize pos` - The position of the element to get.
/// Returns: `void *element` - Pointer to the element.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_collections_vec_get(vec: &NSTDVec, pos: usize) -> *mut c_void {
    match vec.size > pos {
        true => vec.data.add(pos * vec.element_size) as *mut c_void,
        false => ptr::null_mut(),
    }
}

/// Gets the first element in the vector.
/// NOTE: This function follows the same behaviour rules as `nstd_collections_vec_get`.
/// Parameters:
///     `const NSTDVec *const vec` - The vector.
/// Returns: `void *element` - Pointer to the first element.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_collections_vec_first(vec: &NSTDVec) -> *mut c_void {
    match vec.size > 0 {
        true => vec.data as *mut c_void,
        false => ptr::null_mut(),
    }
}

/// Gets the last element in the vector.
/// NOTE: This function follows the same behaviour rules as `nstd_collections_vec_get`.
/// Parameters:
///     `const NSTDVec *const vec` - The vector.
/// Returns: `void *element` - Pointer to the last element.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_collections_vec_last(vec: &NSTDVec) -> *mut c_void {
    match vec.size > 0 {
        true => vec.end_unchecked().sub(vec.element_size) as *mut c_void,
        false => ptr::null_mut(),
    }
}

/// Pushes a new element onto the end of a vector.
/// Parameters:
///     `NSTDVec *const vec` - The vector.
///     `const void *const element` - Pointer to the new element.
/// Returns: `int errc` - Nonzero on error.
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_collections_vec_push(
    vec: &mut NSTDVec,
    element: *const c_void,
) -> c_int {
    // Checking if the vector has reached it's capacity.
    if vec.size == vec.capacity {
        let new_cap = (vec.capacity as f32 * 1.5).ceil() as usize;
        match nstd_collections_vec_reserve(vec, new_cap) {
            0 => (),
            errc => return errc,
        }
        vec.capacity = new_cap;
    }
    // Adding new element.
    let element = std::slice::from_raw_parts(element as *const u8, vec.element_size);
    let data = std::slice::from_raw_parts_mut(vec.end_unchecked(), vec.element_size);
    data.copy_from_slice(element);
    vec.size += 1;
    0
}

/// Pops a value off of the back of a vector and returns a pointer to it.
/// NOTE: This function follows the same behaviour rules as `nstd_collections_vec_get`.
/// Parameters:
///     `NSTDVec *const vec` - The vector.
/// Returns: `void *element` - The element that was removed.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_collections_vec_pop(vec: &mut NSTDVec) -> *mut c_void {
    match vec.size > 0 {
        true => {
            vec.size -= 1;
            vec.end_unchecked() as *mut c_void
        }
        false => ptr::null_mut(),
    }
}

/// Extends a vector from a slice. `vec` and `slice` must have the same element size.
/// Parameters:
///     `NSTDVec *const vec` - The vector.
///     `const NSTDSlice *const slice` - The slice to extend from.
/// Returns: `int errc` - Nonzero on error.
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_collections_vec_extend(
    vec: &mut NSTDVec,
    slice: &NSTDSlice,
) -> c_int {
    if vec.element_size == slice.ptr.size {
        if slice.size > 0 {
            nstd_collections_vec_reserve(vec, vec.size + slice.size);
            let mut ptr = slice.ptr.raw;
            for _ in 0..slice.size {
                nstd_collections_vec_push(vec, ptr);
                ptr = ptr.add(slice.ptr.size);
            }
        }
        return 0;
    }
    1
}

/// Inserts an element at `index` for a vector.
/// Parameters:
///     `NSTDVec *const vec` - The vector.
///     `const void *const element` - Pointer to the new element.
///     `const NSTDUSize index` - The index to insert an element.
/// Returns: `int errc` - Nonzero on error.
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_collections_vec_insert(
    vec: &mut NSTDVec,
    element: *const c_void,
    index: usize,
) -> c_int {
    // A value is being inserted.
    if vec.size > index {
        // Checking if the vector has reached it's capacity.
        if vec.size == vec.capacity {
            match nstd_collections_vec_reserve(vec, vec.capacity + 1) {
                0 => (),
                errc => return errc,
            }
        }
        // Moving data up by one element.
        let index_pointer = nstd_collections_vec_get(vec, index) as *mut u8;
        let next_index_pointer = index_pointer.add(vec.element_size);
        let copy_size = (vec.size - index) * vec.element_size;
        ptr::copy(index_pointer, next_index_pointer, copy_size);
        // Inserting data.
        let element = std::slice::from_raw_parts(element as *const u8, vec.element_size);
        let data = std::slice::from_raw_parts_mut(index_pointer, vec.element_size);
        data.copy_from_slice(element);
        vec.size += 1;
        0
    }
    // A value is being pushed.
    else if vec.size == index {
        nstd_collections_vec_push(vec, element)
    }
    // Invalid index.
    else {
        1
    }
}

/// Removes an element at `index` for a vector.
/// Parameters:
///     `NSTDVec *const vec` - The vector.
///     `const NSTDUSize index` - The index of the element to remove.
/// Returns: `int errc` - Nonzero on error.
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_collections_vec_remove(vec: &mut NSTDVec, index: usize) -> c_int {
    match vec.size > index {
        true => {
            // Moving data down by one element.
            let index_pointer = nstd_collections_vec_get(vec, index) as *mut u8;
            let next_index_pointer = index_pointer.add(vec.element_size);
            let copy_size = (vec.size - index - 1) * vec.element_size;
            ptr::copy(next_index_pointer, index_pointer, copy_size);
            vec.size -= 1;
            0
        }
        false => 1,
    }
}

/// Clears the contents of a vector.
/// Parameters:
///     `NSTDVec *const vec` - The vector.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_collections_vec_clear(vec: &mut NSTDVec) {
    vec.size = 0;
}

/// Resizes a vector.
/// Parameters:
///     `NSTDVec *const vec` - The vector.
///     `const NSTDUSize new_size` - The new vector size.
/// Returns: `int errc` - Nonzero on error.
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_collections_vec_resize(vec: &mut NSTDVec, new_size: usize) -> c_int {
    if vec.size < new_size {
        if vec.capacity < new_size {
            match nstd_collections_vec_reserve(vec, new_size) {
                0 => (),
                errc => return errc,
            }
        }
        let new_bytes = (new_size - vec.size) * vec.element_size;
        std::slice::from_raw_parts_mut(vec.end_unchecked(), new_bytes).fill(0);
    }
    vec.size = new_size;
    0
}

/// Reserves memory for the vector.
/// Parameters:
///     `NSTDVec *const vec` - The vector.
///     `const NSTDUSize new_cap` - The new, greater capacity for the vector.
/// Returns: `int errc` - Nonzero on error.
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_collections_vec_reserve(vec: &mut NSTDVec, new_cap: usize) -> c_int {
    if vec.capacity < new_cap {
        let old_byte_count = vec.total_byte_count();
        let new_byte_count = new_cap * vec.element_size;
        match nstd_alloc::nstd_alloc_reallocate(
            addr_of_mut!(vec.data).cast(),
            old_byte_count,
            new_byte_count,
        ) {
            0 => {
                vec.capacity = new_cap;
                0
            }
            errc => errc,
        }
    } else {
        1
    }
}

/// Shrinks a vector to free any unused memory.
/// Parameters:
///     `NSTDVec *const vec` - The vector.
/// Returns: `int errc` - Nonzero on error.
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_collections_vec_shrink(vec: &mut NSTDVec) -> c_int {
    if vec.size > 0 {
        let old_byte_count = vec.total_byte_count();
        let new_byte_count = vec.byte_count();
        match nstd_alloc::nstd_alloc_reallocate(
            addr_of_mut!(vec.data).cast(),
            old_byte_count,
            new_byte_count,
        ) {
            0 => {
                vec.capacity = vec.size;
                0
            }
            errc => errc,
        }
    } else {
        1
    }
}

/// Frees a vector.
/// Parameters:
///     `NSTDVec *const vec` - The vector.
/// Returns: `int errc` - Nonzero on error.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_collections_vec_free(vec: &mut NSTDVec) -> c_int {
    nstd_alloc::nstd_alloc_deallocate(addr_of_mut!(vec.data).cast(), vec.total_byte_count())
}