Skip to main content

c_support/
string.rs

1use core::{
2    cmp::{Ordering, min},
3    ffi::{c_char, c_int},
4    ptr::null_mut,
5    slice,
6};
7
8use crate::memory::memory_allocate_core;
9
10/// Get the length of a null-terminated string
11///
12/// # Safety
13/// This function is unsafe because it dereferences raw pointers.
14pub unsafe fn string_get_length(str: *const c_char) -> usize {
15    unsafe {
16        if str.is_null() {
17            return 0;
18        }
19
20        let mut len = 0;
21        let mut ptr = str;
22        while *ptr != 0 {
23            len += 1;
24            ptr = ptr.add(1);
25        }
26        len
27    }
28}
29
30/// Get the length of a null-terminated string with maximum length
31///
32/// # Safety
33/// This function is unsafe because it dereferences raw pointers.
34pub unsafe fn string_get_length_bounded(str: *const c_char, maxlen: usize) -> usize {
35    unsafe {
36        if str.is_null() {
37            return 0;
38        }
39
40        let mut len = 0;
41        let mut ptr = str;
42        while len < maxlen && *ptr != 0 {
43            len += 1;
44            ptr = ptr.add(1);
45        }
46        len
47    }
48}
49
50/// Compare two null-terminated strings
51///
52/// # Safety
53/// This function is unsafe because it dereferences raw pointers.
54pub unsafe fn string_compare(str1: *const c_char, str2: *const c_char) -> c_int {
55    unsafe {
56        if str1.is_null() || str2.is_null() {
57            return if str1.is_null() && str2.is_null() {
58                0
59            } else if str1.is_null() {
60                -1
61            } else {
62                1
63            };
64        }
65
66        let len1 = string_get_length(str1);
67        let len2 = string_get_length(str2);
68
69        // Use Rust's slice comparison for efficiency
70        let slice1 = slice::from_raw_parts(str1 as *const u8, len1);
71        let slice2 = slice::from_raw_parts(str2 as *const u8, len2);
72
73        match slice1.cmp(slice2) {
74            Ordering::Less => -1,
75            Ordering::Equal => 0,
76            Ordering::Greater => 1,
77        }
78    }
79}
80
81/// Compare two strings up to n characters
82///
83/// # Safety
84/// This function is unsafe because it dereferences raw pointers.
85pub unsafe fn string_compare_bounded(
86    str1: *const c_char,
87    str2: *const c_char,
88    num: usize,
89) -> c_int {
90    unsafe {
91        if str1.is_null() || str2.is_null() || num == 0 {
92            return if str1.is_null() && str2.is_null() {
93                0
94            } else if str1.is_null() {
95                -1
96            } else {
97                1
98            };
99        }
100
101        let len1 = min(string_get_length(str1), num);
102        let len2 = min(string_get_length(str2), num);
103        let min_len = min(len1, len2);
104
105        // Use Rust's slice comparison for the overlapping part
106        let slice1 = slice::from_raw_parts(str1 as *const u8, min_len);
107        let slice2 = slice::from_raw_parts(str2 as *const u8, min_len);
108
109        use core::cmp::Ordering;
110        match slice1.cmp(slice2) {
111            Ordering::Less => -1,
112            Ordering::Greater => 1,
113            Ordering::Equal => {
114                // If the compared parts are equal, compare lengths
115                match len1.cmp(&len2) {
116                    Ordering::Less => -1,
117                    Ordering::Equal => 0,
118                    Ordering::Greater => 1,
119                }
120            }
121        }
122    }
123}
124
125/// Copy string from source to destination
126///
127/// # Safety
128/// This function is unsafe because it dereferences raw pointers.
129pub unsafe fn string_copy(destination: *mut c_char, source: *const c_char) -> *mut c_char {
130    if destination.is_null() || source.is_null() {
131        return destination;
132    }
133
134    let mut dst_ptr = destination;
135    let mut src_ptr = source;
136
137    unsafe {
138        // Copy characters until null terminator
139        while *src_ptr != 0 {
140            *dst_ptr = *src_ptr;
141            dst_ptr = dst_ptr.add(1);
142            src_ptr = src_ptr.add(1);
143        }
144
145        // Null-terminate the destination string
146        *dst_ptr = 0;
147    }
148
149    destination
150}
151
152/// Copy string from source to destination with maximum length
153///
154/// # Safety
155/// This function is unsafe because it dereferences raw pointers.
156pub unsafe fn string_copy_bounded(
157    destination: *mut c_char,
158    source: *const c_char,
159    num: usize,
160) -> *mut c_char {
161    unsafe {
162        if destination.is_null() || source.is_null() || num == 0 {
163            return destination;
164        }
165
166        let mut dst_ptr = destination;
167        let mut src_ptr = source;
168        let mut count = 0;
169
170        // Copy characters until null terminator or num reached
171        while count < num && *src_ptr != 0 {
172            *dst_ptr = *src_ptr;
173            dst_ptr = dst_ptr.add(1);
174            src_ptr = src_ptr.add(1);
175            count += 1;
176        }
177
178        // Pad with null bytes if necessary
179        while count < num {
180            *dst_ptr = 0;
181            dst_ptr = dst_ptr.add(1);
182            count += 1;
183        }
184
185        destination
186    }
187}
188
189/// Duplicate a string
190///
191/// # Safety
192/// This function is unsafe because it dereferences raw pointers.
193pub unsafe fn string_duplicate(string: *const c_char) -> *mut c_char {
194    if string.is_null() {
195        return null_mut();
196    }
197
198    let new_string = unsafe {
199        let length = string_get_length(string);
200        memory_allocate_core(length + 1)
201    };
202
203    if new_string.is_null() {
204        return null_mut();
205    }
206
207    // Copy the string into the newly allocated memory
208    unsafe {
209        string_copy(new_string as *mut c_char, string);
210    }
211
212    new_string as *mut c_char
213}
214
215/// Duplicate a string up to a maximum length
216///
217/// # Safety
218/// This function is unsafe because it dereferences raw pointers.
219pub unsafe fn string_duplicate_bounded(string: *const c_char, max_length: usize) -> *mut c_char {
220    if string.is_null() {
221        return null_mut();
222    }
223
224    // Like `strndup`, a zero bound yields an empty string, not a null pointer.
225    let length = unsafe { string_get_length_bounded(string, max_length) };
226    let new_string = unsafe { memory_allocate_core(length + 1) } as *mut c_char;
227
228    if new_string.is_null() {
229        return null_mut();
230    }
231
232    // The bounded copy stops after `length` bytes without a terminator when
233    // the source is longer, so the terminator is always written here.
234    unsafe {
235        string_copy_bounded(new_string, string, length);
236        *new_string.add(length) = 0;
237    }
238
239    new_string
240}
241
242/// Concatenate source string to destination string
243///
244/// # Safety
245/// This function is unsafe because it dereferences raw pointers.
246pub unsafe fn string_concatenate(
247    destination: *mut c_char,
248    mut source: *const c_char,
249) -> *mut c_char {
250    if destination.is_null() || source.is_null() {
251        return destination;
252    }
253
254    // Find the end of dest string
255    let mut destination_end = destination;
256    unsafe {
257        while *destination_end != 0 {
258            destination_end = destination_end.add(1);
259        }
260    }
261
262    unsafe {
263        // Copy src to the end of dest (including null terminator)
264        while *source != 0 {
265            *destination_end = *source;
266            destination_end = destination_end.add(1);
267            source = source.add(1);
268        }
269        // Add null terminator
270        *destination_end = 0;
271    }
272
273    destination
274}
275
276#[cfg(test)]
277mod tests {
278    use super::*;
279    use crate::memory_deallocate;
280    use core::ffi::CStr;
281
282    #[test]
283    fn bounded_duplicate_is_always_terminated() {
284        // Poison the heap so that a missing terminator cannot hide behind
285        // freshly zeroed memory.
286        unsafe {
287            for _ in 0..8 {
288                let poison = memory_allocate_core(8) as *mut u8;
289                if !poison.is_null() {
290                    poison.write_bytes(b'X', 8);
291                    memory_deallocate(poison as *mut _);
292                }
293            }
294            for (source, bound, expected) in [
295                (c"abcdefg", 3, c"abc"),
296                (c"abcdefg", 7, c"abcdefg"),
297                (c"abc", 16, c"abc"),
298                (c"abc", 0, c""),
299            ] {
300                let copy = string_duplicate_bounded(source.as_ptr(), bound);
301                if copy.is_null() {
302                    panic!("duplicate of {source:?} bounded to {bound} is null");
303                }
304                assert_eq!(CStr::from_ptr(copy), expected);
305                memory_deallocate(copy as *mut _);
306            }
307            assert!(string_duplicate_bounded(core::ptr::null(), 4).is_null());
308        }
309    }
310}