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
use std::net::Ipv4Addr;

use byteorder::{NetworkEndian, NativeEndian, ByteOrder};

pub trait BytesAble {
    fn as_bytes(&self) -> Vec<u8>;

    #[inline]
    fn write_bytes(&self, dst: &mut [u8]) {
        dst.copy_from_slice(&self.as_bytes());
    }
}

pub trait BytesAbleNum {
    fn as_bytes_be(&self) -> Vec<u8>;
    fn as_bytes_le(&self) -> Vec<u8>;

    #[inline]
    fn write_bytes_be(&self, dst: &mut [u8]) {
        dst.copy_from_slice(&self.as_bytes_be());
    }

    #[inline]
    fn write_bytes_le(&self, dst: &mut [u8]) {
        dst.copy_from_slice(&self.as_bytes_le());
    }
}

impl BytesAble for Ipv4Addr {
    #[inline]
    fn as_bytes(&self) -> Vec<u8> {
        self.octets().to_vec()
    }
}

impl BytesAble for String {
    #[inline]
    fn as_bytes(&self) -> Vec<u8> {
        self.as_bytes().to_vec()
    }
}

macro_rules! impl_bytes_able_for_num_type {
    ($ty:ty, $size:expr) => (
        impl BytesAble for $ty {
            #[inline]
            fn as_bytes(&self) -> Vec<u8> {
                self.as_bytes_be().to_vec()
            }
        }

        impl BytesAbleNum for $ty {
            #[inline]
            fn as_bytes_be(&self) -> Vec<u8> {
                let mut bytes = [0u8; $size];
                NetworkEndian::write_uint(&mut bytes, u64::from(*self), $size);
                bytes.to_vec()
            }

            #[inline]
            fn as_bytes_le(&self) -> Vec<u8> {
                let mut bytes = [0u8; $size];
                NativeEndian::write_uint(&mut bytes, u64::from(*self), $size);
                bytes.to_vec()
            }
        }
    )
}

impl_bytes_able_for_num_type!(u64, 8);
impl_bytes_able_for_num_type!(u32, 4);
impl_bytes_able_for_num_type!(u16, 2);