Skip to main content

io_buffer/
utils.rs

1/// Only copy the 0..min(dst, src) of src to dst, return the bytes copied.
2#[inline]
3pub fn safe_copy(dst: &mut [u8], src: &[u8]) -> usize {
4    let dst_len = dst.len();
5    let src_len = src.len();
6    if src_len > dst_len {
7        dst.copy_from_slice(&src[0..dst_len]);
8        return dst_len;
9    } else if src_len < dst_len {
10        dst[0..src_len].copy_from_slice(src);
11        return src_len;
12    } else {
13        dst.copy_from_slice(src);
14        return dst_len;
15    }
16}
17
18/// Set a buffer to zero
19#[inline(always)]
20pub fn set_zero(dst: &mut [u8]) {
21    unsafe {
22        libc::memset(dst.as_mut_ptr() as *mut libc::c_void, 0, dst.len());
23    }
24}
25
26/// Produce ascii random string
27#[cfg(feature = "rand")]
28#[inline]
29pub fn rand_buffer<T: AsMut<[u8]>>(dst: &mut T) {
30    let s: &mut [u8] = dst.as_mut();
31    let len = s.len();
32    for i in 0..len {
33        s[i] = fastrand::alphanumeric() as u8;
34    }
35}
36
37/// Test whether a buffer is all set to zero
38#[inline(always)]
39pub fn is_all_zero(s: &[u8]) -> bool {
40    for c in s {
41        if *c != 0 {
42            return false;
43        }
44    }
45    true
46}
47
48#[cfg(test)]
49mod tests {
50
51    extern crate md5;
52    use super::*;
53
54    #[test]
55    fn test_safe_copy() {
56        let buf1: [u8; 10] = [0; 10];
57        let mut buf2: [u8; 10] = [1; 10];
58        let mut buf3: [u8; 10] = [2; 10];
59        let zero: usize = 0;
60        // dst zero size copy should be protected
61        assert_eq!(0, safe_copy(&mut buf2[0..zero], &buf3));
62        assert_eq!(&buf2, &[1; 10]);
63        assert_eq!(0, safe_copy(&mut buf2[10..], &buf3));
64        assert_eq!(&buf2, &[1; 10]);
65        // src zero size copy should be protected
66
67        // src zero size copy ?
68        assert_eq!(10, safe_copy(&mut buf2, &buf1));
69        assert_eq!(buf1, buf2);
70        assert_eq!(5, safe_copy(&mut buf2[5..], &buf3));
71        assert_eq!(buf1[0..5], buf2[0..5]);
72        assert_eq!(buf2[5..], buf3[5..]);
73        assert_eq!(5, safe_copy(&mut buf3[0..5], &buf1));
74        assert_eq!(buf2, buf3);
75    }
76
77    #[cfg(feature = "rand")]
78    #[test]
79    fn test_rand_buffer() {
80        let mut buf1: [u8; 10] = [0; 10];
81        let mut buf2: [u8; 10] = [0; 10];
82        rand_buffer(&mut buf1);
83        rand_buffer(&mut buf2);
84        assert!(md5::compute(&buf1) != md5::compute(&buf2));
85    }
86
87    #[test]
88    fn test_set_zero() {
89        let mut buf1: [u8; 10] = [1; 10];
90        set_zero(&mut buf1);
91        for i in &buf1 {
92            assert_eq!(*i, 0)
93        }
94    }
95}