Function nstd_sys::vec::nstd_vec_insert

source ·
#[no_mangle]
pub unsafe extern "C" fn nstd_vec_insert(
    vec: &mut NSTDVec,
    value: NSTDAny,
    index: NSTDUInt
) -> NSTDErrorCode
Available on crate feature nstd_vec only.
Expand description

Attempts to insert a value into a vector at index.

Parameters:

  • NSTDVec *vec - The vector.

  • NSTDAny value - A pointer to the value to insert into the vector.

  • NSTDUInt index - The index at which to insert the value.

Returns

NSTDErrorCode errc - Nonzero on error.

Possible errors

  • 1 - index is greater than the vector’s length.

  • 2 - Reserving space for the vector failed.

Panics

This function will panic if index multiplied by vec’s stride exceeds NSTDInt’s max value.

Safety

This operation is unsafe because undefined behavior can occur if the size of the value being inserted into the vector is not equal to vec’s stride.

Example

use core::ptr::addr_of;
use nstd_sys::{
    core::slice::nstd_core_slice_new,
    vec::{nstd_vec_from_slice, nstd_vec_get, nstd_vec_insert},
};

const SIZE: usize = core::mem::size_of::<u32>();

let slice: [u32; 4] = [1, 2, 3, 5];
let slice = nstd_core_slice_new(slice.as_ptr().cast(), SIZE, 4);
unsafe {
    let mut vec = nstd_vec_from_slice(&slice);
    let four = 4u32;
    assert!(nstd_vec_insert(&mut vec, addr_of!(four).cast(), 3) == 0);
    for i in 1..=5 {
        let v = nstd_vec_get(&vec, i - 1);
        assert!(!v.is_null());
        assert!(*v.cast::<u32>() == i as u32);
    }
}