1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
//! Contains mostly unsafe functions for interacting with raw memory.
use crate::{core::def::NSTDByte, NSTDBool, NSTDUInt, NSTD_FALSE, NSTD_TRUE};

/// Compares two memory buffers of `num` bytes.
///
/// # Note
///
/// This will always return false if `num` is greater than `NSTDInt`'s max value.
///
/// # Parameters:
///
/// - `const NSTDByte *buf1` - A pointer to the first memory buffer.
///
/// - `const NSTDByte *buf2` - A pointer to the second memory buffer.
///
/// - `NSTDUInt num` - The number of bytes to compare.
///
/// # Returns
///
/// `NSTDBool is_eq` - `NSTD_TRUE` if the memory buffers carry the same data.
///
/// # Safety
///
/// This function is highly unsafe as it does not know how large either of the memory buffers
/// actually are, which can lead to undefined behavior if either of the buffers' length are less
/// than `num`.
///
/// # Example
///
/// ```
/// use nstd_sys::{
///     core::mem::{nstd_core_mem_compare, nstd_core_mem_copy},
///     NSTD_TRUE,
/// };
///
/// let buf1 = [0u32; 12];
/// let mut buf2 = [u32::MAX; 12];
///
/// let num = core::mem::size_of::<[u32; 12]>();
/// let ptr1 = buf1.as_ptr().cast();
/// let ptr2 = buf2.as_mut_ptr().cast();
///
/// unsafe {
///     nstd_core_mem_copy(ptr2, ptr1, num);
///     assert!(nstd_core_mem_compare(ptr1, ptr2, num) == NSTD_TRUE);
/// }
/// ```
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_core_mem_compare(
    buf1: *const NSTDByte,
    buf2: *const NSTDByte,
    num: NSTDUInt,
) -> NSTDBool {
    // If the two pointers point to the same buffer, or `num` is 0, return true.
    if buf1 == buf2 || num == 0 {
        return NSTD_TRUE;
    }
    // Check if `num` exceeds `isize::MAX`.
    if num > isize::MAX as usize {
        return NSTD_FALSE;
    }
    // Otherwise compare them manually.
    let buf1 = core::slice::from_raw_parts(buf1, num);
    let buf2 = core::slice::from_raw_parts(buf2, num);
    buf1 == buf2
}

/// Iterates through each byte in a raw memory buffer until `delim` is reached, returning a pointer
/// to the delimiter byte if it is found.
///
/// # Note
///
/// This will always return null if `size` is greater than `NSTDInt`'s max value.
///
/// # Parameters:
///
/// - `const NSTDByte *buf` - The memory buffer to search.
///
/// - `NSTDUInt size` - The number of bytes to search.
///
/// - `NSTDByte delim` - The delimiter byte.
///
/// # Returns
///
/// `const NSTDByte *delim_ptr` - A pointer to the delimiter byte, or null if it was not found.
///
/// # Safety
///
/// This operation makes access to raw pointer data, leading to undefined behavior if `buf`'s
/// data is invalid.
///
/// # Example
///
/// ```
/// use nstd_sys::core::mem::nstd_core_mem_search;
///
/// let buffer = b"Hello, world!\0";
/// let ptr = buffer.as_ptr().cast();
/// unsafe {
///     assert!(nstd_core_mem_search(ptr, buffer.len(), b'H') == ptr);
///     assert!(nstd_core_mem_search(ptr, buffer.len(), b' ') == ptr.add(6));
///     assert!(nstd_core_mem_search(ptr, buffer.len(), 0) == ptr.add(13));
/// }
/// ```
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_core_mem_search(
    buf: *const NSTDByte,
    size: NSTDUInt,
    delim: NSTDByte,
) -> *const NSTDByte {
    // Check if `size` is greater than `NSTDInt`'s max size.
    if size > isize::MAX as usize {
        return core::ptr::null();
    }
    // Search the buffer for `delim`.
    #[cfg(not(all(
        feature = "asm",
        any(
            target_arch = "arm",
            target_arch = "aarch64",
            target_arch = "x86",
            target_arch = "x86_64"
        )
    )))]
    {
        let mut i = 0;
        while i < size {
            if *buf.add(i) == delim {
                return buf.add(i);
            }
            i += 1;
        }
        core::ptr::null()
    }
    #[cfg(all(feature = "asm", any(target_arch = "x86", target_arch = "x86_64")))]
    {
        use core::arch::asm;
        let mut end = buf.add(size);
        asm!(
            include_str!("mem/x86/search.asm"),
            buf = inout(reg) buf => end,
            delim = in(reg_byte) delim,
            end = in(reg) end
        );
        end
    }
    #[cfg(all(feature = "asm", target_arch = "arm"))]
    {
        use core::arch::asm;
        let mut end = buf.add(size);
        asm!(
            include_str!("mem/arm/search.asm"),
            buf = inout(reg) buf => end,
            delim = in(reg) delim as usize,
            end = in(reg) end,
            byte = out(reg) _
        );
        end
    }
    #[cfg(all(feature = "asm", target_arch = "aarch64"))]
    {
        use core::arch::asm;
        let mut end = buf.add(size);
        asm!(
            include_str!("mem/arm64/search.asm"),
            buf = inout(reg) buf => end,
            delim = in(reg) delim as usize,
            end = in(reg) end,
            byte = out(reg) _
        );
        end
    }
}

/// Zeros out a memory buffer.
///
/// # Parameters:
///
/// - `NSTDByte *buf` - A pointer to the first byte in the memory buffer.
///
/// - `NSTDUInt size` - The number of bytes to set to 0.
///
/// # Panics
///
/// This operation will panic if `size` is greater than `NSTDInt`'s max value.
///
/// # Safety
///
/// This operation can cause undefined behavior if the caller does not ensure that the memory
/// buffer is at least `size` bytes in size.
///
/// # Example
///
/// ```
/// use nstd_sys::core::mem::nstd_core_mem_zero;
///
/// unsafe {
///     let mut buf = [i32::MAX; 10];
///     nstd_core_mem_zero(buf.as_mut_ptr().cast(), core::mem::size_of::<i32>() * 10);
///     assert!(buf == [0i32; 10]);
/// }
/// ```
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_core_mem_zero(buf: *mut NSTDByte, size: NSTDUInt) {
    assert!(size <= isize::MAX as usize);
    #[cfg(not(all(
        feature = "asm",
        any(
            target_arch = "arm",
            target_arch = "aarch64",
            target_arch = "x86",
            target_arch = "x86_64"
        )
    )))]
    {
        let mut i = 0;
        while i < size {
            *buf.add(i) = 0;
            i += 1;
        }
    }
    #[cfg(feature = "asm")]
    {
        use core::arch::asm;
        const REG_SIZE: NSTDUInt = core::mem::size_of::<&()>();
        let rem_bytes = size % REG_SIZE;
        let reg_end = buf.add(size - rem_bytes);
        let end = reg_end.add(rem_bytes);
        #[cfg(target_arch = "x86")]
        {
            asm!(
                include_str!("mem/x86/zero.asm"),
                buf = inout(reg) buf => _,
                reg_end = in(reg) reg_end,
                end = in(reg) end
            );
        }
        #[cfg(target_arch = "x86_64")]
        {
            asm!(
                include_str!("mem/x86_64/zero.asm"),
                buf = inout(reg) buf => _,
                reg_end = in(reg) reg_end,
                end = in(reg) end
            );
        }
        #[cfg(target_arch = "arm")]
        {
            asm!(
                include_str!("mem/arm/zero.asm"),
                buf = inout(reg) buf => _,
                reg_end = in(reg) reg_end,
                end = in(reg) end,
                zero = out(reg) _
            );
        }
        #[cfg(target_arch = "aarch64")]
        {
            asm!(
                include_str!("mem/arm64/zero.asm"),
                buf = inout(reg) buf => _,
                reg_end = in(reg) reg_end,
                end = in(reg) end,
                zero = out(reg) _
            );
        }
    }
}

/// Fills the memory buffer `buf` with byte `fill`.
///
/// # Parameters:
///
/// - `NSTDByte *buf` - The memory buffer to fill.
///
/// - `NSTDUInt size` - The size of the memory buffer.
///
/// - `NSTDByte fill` - The byte value to fill the memory buffer with.
///
/// # Panics
///
/// This operation will panic if `size` is greater than `NSTDInt`'s max value.
///
/// # Safety
///
/// This operation can cause undefined behavior if the caller does not ensure that the memory
/// buffer is at least `size` bytes in size.
///
/// # Example
///
/// ```
/// use nstd_sys::core::mem::nstd_core_mem_fill;
///
/// unsafe {
///     let mut buf = [u8::MAX; 10];
///     nstd_core_mem_fill(buf.as_mut_ptr(), 10, 0);
///     assert!(buf == [0u8; 10]);
/// }
/// ```
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_core_mem_fill(buf: *mut NSTDByte, size: NSTDUInt, fill: NSTDByte) {
    assert!(size <= isize::MAX as usize);
    #[cfg(not(all(
        feature = "asm",
        any(
            target_arch = "arm",
            target_arch = "aarch64",
            target_arch = "x86",
            target_arch = "x86_64"
        )
    )))]
    {
        let mut i = 0;
        while i < size {
            *buf.add(i) = fill;
            i += 1;
        }
    }
    #[cfg(all(feature = "asm", any(target_arch = "x86", target_arch = "x86_64")))]
    {
        use core::arch::asm;
        asm!(
            include_str!("mem/x86/fill.asm"),
            buf = inout(reg) buf => _,
            fill = in(reg_byte) fill,
            end = in(reg) buf.add(size)
        );
    }
    #[cfg(all(feature = "asm", target_arch = "arm"))]
    {
        use core::arch::asm;
        asm!(
            include_str!("mem/arm/fill.asm"),
            buf = inout(reg) buf => _,
            fill = in(reg) fill as usize,
            end = in(reg) buf.add(size)
        );
    }
    #[cfg(all(feature = "asm", target_arch = "aarch64"))]
    {
        use core::arch::asm;
        asm!(
            include_str!("mem/arm64/fill.asm"),
            buf = inout(reg) buf => _,
            fill = in(reg) fill as usize,
            end = in(reg) buf.add(size)
        );
    }
}

/// Copies `num` bytes from `src` to `dest`.
///
/// # Parameters:
///
/// - `NSTDByte *dest` - A pointer to the memory buffer to copy `src`'s bytes to.
///
/// - `const NSTDByte *src` - A pointer to the memory buffer to copy from.
///
/// - `NSTDUInt num` - The number of bytes to copy from `src` to `dest`.
///
/// # Safety
///
/// This function is highly unsafe as it does not know how large either of the memory buffers are,
/// quickly leading to undefined behavior if this function ends up reading or writing past the end
/// of a buffer.
///
/// # Example
///
/// ```
/// use nstd_sys::core::mem::nstd_core_mem_copy;
///
/// unsafe {
///     let buf1 = [0u8; 25];
///     let mut buf2 = [u8::MAX; 25];
///     nstd_core_mem_copy(buf2.as_mut_ptr(), buf1.as_ptr(), 25);
///     assert!(buf1 == buf2);
/// }
/// ```
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_core_mem_copy(
    dest: *mut NSTDByte,
    src: *const NSTDByte,
    num: NSTDUInt,
) {
    core::ptr::copy_nonoverlapping(src, dest, num);
}

/// Copies `num` bytes from `src` to `dest`. Unlike `nstd_core_mem_copy` this operation can be used
/// when the two memory buffers overlap.
///
/// # Parameters:
///
/// - `NSTDByte *dest` - A pointer to the memory buffer to copy `src`'s bytes to.
///
/// - `const NSTDByte *src` - A pointer to the memory buffer to copy from.
///
/// - `NSTDUInt num` - The number of bytes to copy from `src` to `dest`.
///
/// # Safety
///
/// This function is highly unsafe as it does not know how large either of the memory buffers are,
/// quickly leading to undefined behavior if this function ends up reading or writing past the end
/// of a buffer.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_core_mem_copy_overlapping(
    dest: *mut NSTDByte,
    src: *const NSTDByte,
    num: NSTDUInt,
) {
    core::ptr::copy(src, dest, num);
}

/// Swaps `num` bytes between the memory buffers `x` and `y`.
///
/// # Parameters:
///
/// - `NSTDByte *x` - A pointer to the first memory buffer.
///
/// - `NSTDByte *y` - A pointer to the second memory buffer.
///
/// - `NSTDUInt num` - The number of bytes to swap.
///
/// # Safety
///
/// This function is highly unsafe as it does not know how large either of the memory buffers are,
/// quickly leading to undefined behavior if this function ends up reading or writing past the end
/// of a buffer.
///
/// # Example
///
/// ```
/// use nstd_sys::core::mem::nstd_core_mem_swap;
///
/// unsafe {
///     let mut buf1 = [0u8; 25];
///     let mut buf2 = [u8::MAX; 25];
///     nstd_core_mem_swap(buf1.as_mut_ptr(), buf2.as_mut_ptr(), 25);
///     assert!(buf1 == [u8::MAX; 25] && buf2 == [0u8; 25]);
/// }
/// ```
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_core_mem_swap(x: *mut NSTDByte, y: *mut NSTDByte, num: NSTDUInt) {
    core::ptr::swap_nonoverlapping(x, y, num);
}