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
use core::{ptr, mem};

macro_rules! write_slice {
    ($src:expr, $dst:expr, $ty:ty, $size:expr, $which:ident) => ({
        assert!($size == mem::size_of::<$ty>());
        assert_eq!($dst.len(), $size*$src.len());
        unsafe {
            ptr::copy_nonoverlapping(
                $src.as_ptr() as *const u8,
                $dst.as_mut_ptr(),
                $dst.len());
            let tmp: &mut [$ty] = mem::transmute($dst);
            for v in tmp[..$src.len()].iter_mut() {
                *v = v.$which();
            }
        }
    });
}

/// Write a vector of u32s into a vector of bytes. The values are written in
/// little-endian format.
#[inline]
pub fn write_u32v_le(dst: &mut [u8], src: &[u32]) {
    write_slice!(src, dst, u32, 4, to_le);
}

/// Write a vector of u32s into a vector of bytes. The values are written in
/// big-endian format.
#[inline]
pub fn write_u32v_be(dst: &mut [u8], src: &[u32]) {
    write_slice!(src, dst, u32, 4, to_be);
}

/// Write a vector of u64s into a vector of bytes. The values are written in
/// little-endian format.
#[inline]
pub fn write_u64v_le(dst: &mut [u8], src: &[u64]) {
    write_slice!(src, dst, u64, 8, to_le);
}

/// Write a vector of u64s into a vector of bytes. The values are written in
/// little-endian format.
#[inline]
pub fn write_u64v_be(dst: &mut [u8], src: &[u64]) {
    write_slice!(src, dst, u64, 8, to_be);
}