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
#![deny(missing_docs)]

//! Provides types that assist with byte order conversions of primitive data
//! types.
//!
//! # Example
//!
//! ```
//! # extern crate pod;
//! # extern crate byteorder_pod;
//! use pod::Pod;
//! use byteorder_pod::unaligned::{Le, Be};
//!
//! unsafe impl Pod for Data { }
//!
//! #[repr(C)]
//! struct Data(u8, Le<u16>, Be<u32>);
//!
//! # fn main() {
//! let data = Data(1, From::from(0x2055), From::from(0xdeadbeef));
//!
//! let cmp = &[
//!     0x01,
//!     0x55, 0x20,
//!     0xde, 0xad, 0xbe, 0xef,
//! ];
//!
//! assert_eq!(cmp, data.as_bytes());
//! # }
//!
//! ```

extern crate byteorder;
extern crate pod;
#[cfg(feature = "uninitialized")]
extern crate uninitialized;

use std::marker::PhantomData;
use std::fmt;
use std::cmp::Ordering;
use std::hash::{Hash, Hasher};
use byteorder::ByteOrder;
use pod::packed::{Unaligned, Aligned, Packed};
use pod::Pod;

#[cfg(feature = "uninitialized")]
use uninitialized::uninitialized;
#[cfg(not(feature = "uninitialized"))]
use std::mem::zeroed as uninitialized;

/// Aligned type aliases
pub mod aligned {
    use byteorder;
    use super::EndianPrimitive;

    /// A type alias for little endian primitives
    pub type Le<T> = EndianPrimitive<byteorder::LittleEndian, T, T>;

    /// A type alias for big endian primitives
    pub type Be<T> = EndianPrimitive<byteorder::BigEndian, T, T>;

    /// A type alias for native endian primitives
    pub type Native<T> = EndianPrimitive<byteorder::NativeEndian, T, T>;
}

/// Unaligned type aliases
pub mod unaligned {
    use byteorder;
    use super::EndianPrimitive;

    /// A type alias for unaligned little endian primitives
    pub type Le<T> = EndianPrimitive<byteorder::LittleEndian, T, ()>;

    /// A type alias for unaligned big endian primitives
    pub type Be<T> = EndianPrimitive<byteorder::BigEndian, T, ()>;

    /// A type alias for unaligned native endian primitives
    pub type Native<T> = EndianPrimitive<byteorder::NativeEndian, T, ()>;
}

/// A POD container for a primitive that stores a value in the specified endianness
/// in memory, and transforms on `get`/`set`
#[repr(C)]
pub struct EndianPrimitive<B, T: EndianConvert, Alignment = ()> {
    _alignment: [Alignment; 0],
    value: T::Unaligned,
    _phantom: PhantomData<*const B>,
}

impl<B: ByteOrder, T: EndianConvert, A> EndianPrimitive<B, T, A> {
    /// Creates a new value
    #[inline]
    pub fn new(v: T) -> Self {
        EndianPrimitive {
            _alignment: [],
            value: EndianConvert::to::<B>(v),
            _phantom: PhantomData,
        }
    }

    /// Transforms to the native value
    #[inline]
    pub fn get(&self) -> T {
        EndianConvert::from::<B>(&self.value)
    }

    /// Transforms from a native value
    #[inline]
    pub fn set(&mut self, v: T) {
        self.value = EndianConvert::to::<B>(v)
    }

    /// Gets the inner untransformed value
    #[inline]
    pub fn raw(&self) -> &T::Unaligned {
        &self.value
    }

    /// A mutable reference to the inner untransformed value
    #[inline]
    pub fn raw_mut(&mut self) -> &mut T::Unaligned {
        &mut self.value
    }
}

unsafe impl<B: Pod, T: EndianConvert, A> Pod for EndianPrimitive<B, T, A> { }
unsafe impl<B, T: EndianConvert, A: Unaligned> Unaligned for EndianPrimitive<B, T, A> { }
unsafe impl<B, T: EndianConvert, A: Unaligned> Packed for EndianPrimitive<B, T, A> { }

impl<B: ByteOrder, T: Default + EndianConvert, A> Default for EndianPrimitive<B, T, A> {
    #[inline]
    fn default() -> Self {
        Self::new(Default::default())
    }
}

impl<B: ByteOrder, T: EndianConvert, A> From<T> for EndianPrimitive<B, T, A> {
    #[inline]
    fn from(v: T) -> Self {
        Self::new(v)
    }
}

impl<B: ByteOrder, T: fmt::Debug + EndianConvert, A> fmt::Debug for EndianPrimitive<B, T, A> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        <T as fmt::Debug>::fmt(&self.get(), f)
    }
}

impl<ARHS, A, BRHS: ByteOrder, RHS: EndianConvert, B: ByteOrder, T: EndianConvert + PartialEq<RHS>> PartialEq<EndianPrimitive<BRHS, RHS, ARHS>> for EndianPrimitive<B, T, A> {
    #[inline]
    fn eq(&self, other: &EndianPrimitive<BRHS, RHS, ARHS>) -> bool {
        self.get().eq(&other.get())
    }
}

impl<A, B: ByteOrder, T: EndianConvert + Eq> Eq for EndianPrimitive<B, T, A> { }

impl<ARHS, A, BRHS: ByteOrder, RHS: EndianConvert, B: ByteOrder, T: EndianConvert + PartialOrd<RHS>> PartialOrd<EndianPrimitive<BRHS, RHS, ARHS>> for EndianPrimitive<B, T, A> {
    #[inline]
    fn partial_cmp(&self, other: &EndianPrimitive<BRHS, RHS, ARHS>) -> Option<Ordering> {
        self.get().partial_cmp(&other.get())
    }
}

impl<B: ByteOrder, T: EndianConvert + Ord, A> Ord for EndianPrimitive<B, T, A> {
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        self.get().cmp(&other.get())
    }
}

impl<B, T: EndianConvert + Hash, A> Hash for EndianPrimitive<B, T, A> where T::Unaligned: Hash {
    #[inline]
    fn hash<H: Hasher>(&self, h: &mut H) {
        self.value.hash(h)
    }
}

impl<B, T: EndianConvert, A> Clone for EndianPrimitive<B, T, A> {
    #[inline]
    fn clone(&self) -> Self {
        EndianPrimitive {
            _alignment: [],
            value: self.value.clone(),
            _phantom: PhantomData,
        }
    }
}

impl<B, T: EndianConvert, A: Copy> Copy for EndianPrimitive<B, T, A> { }

/// Describes a value that can be converted to and from a specified byte order.
pub trait EndianConvert: Aligned {
    /// Converts a value from `B`
    fn from<B: ByteOrder>(&Self::Unaligned) -> Self;

    /// Converts a value to `B`
    fn to<B: ByteOrder>(self) -> Self::Unaligned;
}

macro_rules! endian_impl {
    ($(($($tt:tt)*)),*) => {
        $(
            endian_impl! { $($tt)* }
        )*
    };
    ($t:ty: $s:expr => $r:ident, $w:ident) => {
        impl EndianConvert for $t {
            #[inline]
            fn from<B: ByteOrder>(s: &Self::Unaligned) -> Self {
                B::$r(s) as _
            }

            #[inline]
            fn to<B: ByteOrder>(self) -> Self::Unaligned {
                let mut s: Self::Unaligned = unsafe { uninitialized() };
                B::$w(&mut s, self as _);
                s
            }
        }

        impl<B: ByteOrder, A> Into<$t> for EndianPrimitive<B, $t, A> {
            #[inline]
            fn into(self) -> $t {
                self.get()
            }
        }
    };
}

endian_impl! {
    (u16: 2 => read_u16, write_u16),
    (i16: 2 => read_i16, write_i16),
    (i32: 4 => read_i32, write_i32),
    (u32: 4 => read_u32, write_u32),
    (i64: 8 => read_i64, write_i64),
    (u64: 8 => read_u64, write_u64),
    (f32: 4 => read_f32, write_f32),
    (f64: 8 => read_f64, write_f64)
}

#[cfg(target_pointer_width = "32")]
endian_impl! {
    (usize: 4 => read_u32, write_u32),
    (isize: 4 => read_i32, write_i32)
}

#[cfg(target_pointer_width = "64")]
endian_impl! {
    (usize: 8 => read_u64, write_u64),
    (isize: 8 => read_i64, write_i64)
}

impl<T> EndianConvert for *const T {
    #[inline]
    fn from<B: ByteOrder>(s: &Self::Unaligned) -> Self {
        <usize as EndianConvert>::from::<B>(s) as _
    }

    #[inline]
    fn to<B: ByteOrder>(self) -> Self::Unaligned {
        <usize as EndianConvert>::to::<B>(self as _)
    }
}

impl<T> EndianConvert for *mut T {
    #[inline]
    fn from<B: ByteOrder>(s: &Self::Unaligned) -> Self {
        <usize as EndianConvert>::from::<B>(s) as _
    }

    #[inline]
    fn to<B: ByteOrder>(self) -> Self::Unaligned {
        <usize as EndianConvert>::to::<B>(self as _)
    }
}

impl<T, B: ByteOrder, A> Into<*const T> for EndianPrimitive<B, *const T, A> {
    #[inline]
    fn into(self) -> *const T {
        self.get()
    }
}

impl<T, B: ByteOrder, A> Into<*mut T> for EndianPrimitive<B, *mut T, A> {
    #[inline]
    fn into(self) -> *mut T {
        self.get()
    }
}

impl EndianConvert for bool {
    #[inline]
    fn from<B: ByteOrder>(s: &Self::Unaligned) -> Self {
        *s as u8 != 0
    }

    #[inline]
    fn to<B: ByteOrder>(self) -> Self::Unaligned {
        if self as u8 != 0 { true } else { false }
    }
}

impl<B: ByteOrder, A> Into<bool> for EndianPrimitive<B, bool, A> {
    #[inline]
    fn into(self) -> bool {
        self.get()
    }
}

#[cfg(test)]
mod tests {
    use byteorder;
    use super::*;

    fn align_size<B: byteorder::ByteOrder>() {
        fn f<B: byteorder::ByteOrder, T: EndianConvert>() {
            use std::mem::{size_of, align_of};

            assert_eq!(size_of::<EndianPrimitive<B, T, T>>(), size_of::<T>());
            assert_eq!(size_of::<EndianPrimitive<B, T, ()>>(), size_of::<T>());

            assert_eq!(align_of::<EndianPrimitive<B, T, T>>(), align_of::<T>());
            assert_eq!(align_of::<EndianPrimitive<B, T, ()>>(), 1);
        }

        f::<B, *const u32>();
        f::<B, *mut u32>();

        f::<B, isize>();
        f::<B, usize>();

        f::<B, i16>();
        f::<B, i32>();
        f::<B, i64>();

        f::<B, u16>();
        f::<B, u32>();
        f::<B, u64>();

        f::<B, f32>();
        f::<B, f64>();

        f::<B, bool>();
    }

    #[test]
    fn align_size_ne() {
        align_size::<byteorder::NativeEndian>();
        align_size::<byteorder::LittleEndian>();
        align_size::<byteorder::BigEndian>();
    }
}