Skip to main content

c_support/memory/
manipulation.rs

1use core::{
2    cmp::Ordering,
3    ffi::{c_int, c_void},
4    ptr::{copy, copy_nonoverlapping, write_bytes},
5    slice,
6};
7
8/// Copy memory from source to destination
9///
10/// # Safety
11/// This function is unsafe because it dereferences raw pointers.
12pub unsafe fn memory_copy(
13    destination: *mut c_void,
14    source: *const c_void,
15    size: usize,
16) -> *mut c_void {
17    if destination.is_null() || source.is_null() || size == 0 {
18        return destination;
19    }
20
21    // Use Rust's efficient copy_nonoverlapping
22    unsafe {
23        copy_nonoverlapping(source as *const u8, destination as *mut u8, size);
24    }
25    destination
26}
27
28/// Compare memory blocks
29///
30/// # Safety
31/// This function is unsafe because it dereferences raw pointers.
32pub unsafe fn memory_compare(ptr1: *const c_void, ptr2: *const c_void, num: usize) -> c_int {
33    if ptr1.is_null() || ptr2.is_null() || num == 0 {
34        return 0;
35    }
36
37    // Use Rust's slice comparison which is optimized
38    let bytes1 = unsafe { slice::from_raw_parts(ptr1 as *const u8, num) };
39    let bytes2 = unsafe { slice::from_raw_parts(ptr2 as *const u8, num) };
40
41    // Use Rust's cmp which returns Ordering
42    match bytes1.cmp(bytes2) {
43        Ordering::Less => -1,
44        Ordering::Equal => 0,
45        Ordering::Greater => 1,
46    }
47}
48
49/// Move memory from source to destination (handles overlapping regions)
50///
51/// # Safety
52/// This function is unsafe because it dereferences raw pointers.
53pub unsafe fn memory_move(
54    destination: *mut c_void,
55    source: *const c_void,
56    size: usize,
57) -> *mut c_void {
58    if destination.is_null() || source.is_null() || size == 0 {
59        return destination;
60    }
61
62    // Use Rust's copy which handles overlapping memory correctly
63    unsafe {
64        copy(source as *const u8, destination as *mut u8, size);
65    }
66    destination
67}
68
69/// Set memory to a specific value
70///
71/// # Safety
72/// This function is unsafe because it dereferences raw pointers.
73pub unsafe fn memory_set(ptr: *mut c_void, value: c_int, num: usize) -> *mut c_void {
74    if ptr.is_null() || num == 0 {
75        return ptr;
76    }
77
78    // Use Rust's efficient write_bytes
79    unsafe {
80        write_bytes(ptr as *mut u8, value as u8, num);
81    }
82    ptr
83}