Skip to main content

osom_lib_arrays/const_helpers/
slice_helpers.rs

1use core::ops::Range;
2
3use osom_lib_macros::debug_check_or_release_hint;
4
5/// A const variant of `&slice[range]`.
6///
7/// # Panics
8///
9/// This function will panic if the range is invalid. This check
10/// is only performed in debug mode.
11///
12/// # Safety
13///
14/// This function does not verify the out-of-bounds access.
15/// It is up to the caller to ensure that the range is valid.
16pub const unsafe fn subslice_const<T>(slice: &[T], range: Range<usize>) -> &[T] {
17    let start = range.start;
18    let end = range.end;
19    let len = slice.len();
20    debug_check_or_release_hint!((start <= end) && (start < len) && (end <= len));
21    unsafe { core::slice::from_raw_parts(slice.as_ptr().add(start), end - start) }
22}
23
24/// A const variant of `&mut slice[range]`.
25///
26/// # Panics
27///
28/// This function will panic if the range is invalid. This check
29/// is only performed in debug mode.
30///
31/// # Safety
32///
33/// This function does not verify the out-of-bounds access.
34/// It is up to the caller to ensure that the range is valid.
35pub const unsafe fn subslice_mut_const<T>(slice: &mut [T], range: Range<usize>) -> &mut [T] {
36    let start = range.start;
37    let end = range.end;
38    let len = slice.len();
39    debug_check_or_release_hint!((start <= end) && (start < len) && (end <= len));
40    unsafe { core::slice::from_raw_parts_mut(slice.as_mut_ptr().add(start), end - start) }
41}
42
43/// Fills the given slice with the given, copyable value.
44///
45/// # Notes
46///
47/// This requires `T: Copy` constraint, because it is const.
48#[inline(always)]
49pub const fn fill_const<T: Copy>(slice: &mut [T], value: T) {
50    let mut index = 0;
51    let end = slice.len();
52    while index < end {
53        slice[index] = value;
54        index += 1;
55    }
56}