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
#[repr(C)]
pub struct WireValue<T> {
value : T
}
impl<T:Endian> WireValue<T> {
#[inline]
pub fn get(&self) -> T { self.value.get() }
#[inline]
pub fn set(&mut self, value : T) { self.value.set(value) }
}
pub trait Endian : Sized {
fn get(&self) -> Self;
fn set(&mut self, value : Self);
}
macro_rules! endian_impl(
($typ:ty) => (
impl Endian for $typ {
#[inline]
fn get(&self) -> $typ { *self }
#[inline]
fn set(&mut self, value : $typ) {*self = value;}
}
);
($typ:ty, $swapper:ident) => (
impl Endian for $typ {
#[inline]
fn get(&self) -> $typ { self.$swapper() }
#[inline]
fn set(&mut self, value : $typ) {
*self = value.$swapper();
}
}
);
);
endian_impl!(());
endian_impl!(bool);
endian_impl!(u8);
endian_impl!(i8);
endian_impl!(u16, to_le);
endian_impl!(i16, to_le);
endian_impl!(u32, to_le);
endian_impl!(i32, to_le);
endian_impl!(u64, to_le);
endian_impl!(i64, to_le);
impl Endian for f32 {
fn get(&self) -> f32 {
unsafe { ::std::mem::transmute(::std::mem::transmute::<f32, u32>(*self).to_le()) }
}
fn set(&mut self, value : f32) {
*self = unsafe { ::std::mem::transmute(::std::mem::transmute::<f32, u32>(value).to_le()) };
}
}
impl Endian for f64 {
fn get(&self) -> f64 {
unsafe { ::std::mem::transmute(::std::mem::transmute::<f64, u64>(*self).to_le()) }
}
fn set(&mut self, value : f64) {
*self = unsafe { ::std::mem::transmute(::std::mem::transmute::<f64, u64>(value).to_le()) };
}
}