abi_definitions/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.
12#[unsafe(no_mangle)]
13pub unsafe extern "C" fn xila_memory_copy(
14    destination: *mut c_void,
15    source: *const c_void,
16    size: usize,
17) -> *mut c_void {
18    if destination.is_null() || source.is_null() || size == 0 {
19        return destination;
20    }
21
22    // Use Rust's efficient copy_nonoverlapping
23    unsafe {
24        copy_nonoverlapping(source as *const u8, destination as *mut u8, size);
25    }
26    destination
27}
28
29/// Compare memory blocks
30///
31/// # Safety
32/// This function is unsafe because it dereferences raw pointers.
33#[unsafe(no_mangle)]
34pub unsafe extern "C" fn xila_memory_compare(
35    ptr1: *const c_void,
36    ptr2: *const c_void,
37    num: usize,
38) -> c_int {
39    if ptr1.is_null() || ptr2.is_null() || num == 0 {
40        return 0;
41    }
42
43    // Use Rust's slice comparison which is optimized
44    let bytes1 = unsafe { slice::from_raw_parts(ptr1 as *const u8, num) };
45    let bytes2 = unsafe { slice::from_raw_parts(ptr2 as *const u8, num) };
46
47    // Use Rust's cmp which returns Ordering
48    match bytes1.cmp(bytes2) {
49        Ordering::Less => -1,
50        Ordering::Equal => 0,
51        Ordering::Greater => 1,
52    }
53}
54
55/// Move memory from source to destination (handles overlapping regions)
56///
57/// # Safety
58/// This function is unsafe because it dereferences raw pointers.
59#[unsafe(no_mangle)]
60pub unsafe extern "C" fn xila_memory_move(
61    destination: *mut c_void,
62    source: *const c_void,
63    size: usize,
64) -> *mut c_void {
65    if destination.is_null() || source.is_null() || size == 0 {
66        return destination;
67    }
68
69    // Use Rust's copy which handles overlapping memory correctly
70    unsafe {
71        copy(source as *const u8, destination as *mut u8, size);
72    }
73    destination
74}
75
76/// Set memory to a specific value
77///
78/// # Safety
79/// This function is unsafe because it dereferences raw pointers.
80#[unsafe(no_mangle)]
81pub unsafe extern "C" fn xila_memory_set(
82    ptr: *mut c_void,
83    value: c_int,
84    num: usize,
85) -> *mut c_void {
86    if ptr.is_null() || num == 0 {
87        return ptr;
88    }
89
90    // Use Rust's efficient write_bytes
91    unsafe {
92        write_bytes(ptr as *mut u8, value as u8, num);
93    }
94    ptr
95}