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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
#![warn(
    missing_docs, unused,
    trivial_numeric_casts,
    future_incompatible,
    rust_2018_compatibility,
    rust_2018_idioms,
    clippy::all
)]

#![doc(html_root_url = "https://docs.rs/lebe/0.5.0")]

//! Dead simple endianness conversions.
//! The following operations are implemented on
//! `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64`, `u128`, `i128`, `f32`, `f64`:
//!
//!
//! ### Read Numbers
//! ```rust
//! use lebe::prelude::*;
//! let mut reader: &[u8] = &[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
//!
//! let number : u64 = reader.read_from_little_endian()?;
//! let number = u64::read_from_big_endian(&mut reader)?;
//! # Ok::<(), std::io::Error>(())
//! ```
//!
//! ### Read Slices
//! ```rust
//! use std::io::Read;
//! use lebe::prelude::*;
//! let mut reader: &[u8] = &[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
//!
//! let mut numbers: &mut [u64] = &mut [0, 0];
//! reader.read_from_little_endian_into(numbers)?;
//! # Ok::<(), std::io::Error>(())
//! ```
//!
//! ### Write Numbers
//! ```rust
//! use std::io::Read;
//! use lebe::prelude::*;
//! let mut writer: Vec<u8> = Vec::new();
//!
//! let number: u64 = 1237691;
//! writer.write_as_big_endian(&number)?;
//! # Ok::<(), std::io::Error>(())
//! ```
//!
//! ### Write Slices
//! ```rust
//! use std::io::Write;
//! use lebe::prelude::*;
//! let mut writer: Vec<u8> = Vec::new();
//!
//! let numbers: &[u64] = &[1_u64, 234545_u64];
//! writer.write_as_little_endian(numbers)?;
//! # Ok::<(), std::io::Error>(())
//! ```
//!


/// Exports some of the most common types.
pub mod prelude {
    pub use super::Endian;
    pub use super::io::{ WriteEndian, ReadEndian, ReadPrimitive };
}

/// Represents values that can swap their bytes to reverse their endianness.
///
/// Supports converting values in-place using [`swap_bytes`] or [`convert_current_to_little_endian`]:
/// Supports converting while transferring ownership using
/// [`from_little_endian_into_current`] or [`from_current_into_little_endian`].
///
///
/// For the types `u8`, `i8`, `&[u8]` and `&[i8]`, this trait will never transform any data,
/// as they are just implemented for completeness.
pub trait Endian {

    /// Swaps all bytes in this value, inverting its endianness.
    fn swap_bytes(&mut self);

    /// On a little endian machine, this does nothing.
    /// On a big endian machine, the bytes of this value are reversed.
    #[inline] fn convert_current_to_little_endian(&mut self) {
        #[cfg(target_endian = "big")] {
            self.swap_bytes();
        }
    }

    /// On a big endian machine, this does nothing.
    /// On a little endian machine, the bytes of this value are reversed.
    #[inline] fn convert_current_to_big_endian(&mut self) {
        #[cfg(target_endian = "little")] {
            self.swap_bytes();
        }
    }

    /// On a little endian machine, this does nothing.
    /// On a big endian machine, the bytes of this value are reversed.
    #[inline] fn convert_little_endian_to_current(&mut self) {
        #[cfg(target_endian = "big")] {
            self.swap_bytes();
        }
    }

    /// On a big endian machine, this does nothing.
    /// On a little endian machine, the bytes of this value are reversed.
    #[inline] fn convert_big_endian_to_current(&mut self) {
        #[cfg(target_endian = "little")] {
            self.swap_bytes();
        }
    }

    /// On a little endian machine, this does nothing.
    /// On a big endian machine, the bytes of this value are reversed.
    #[inline] fn from_current_into_little_endian(mut self) -> Self where Self: Sized {
        self.convert_current_to_little_endian();
        self
    }

    /// On a big endian machine, this does nothing.
    /// On a little endian machine, the bytes of this value are reversed.
    #[inline] fn from_current_into_big_endian(mut self) -> Self where Self: Sized {
        self.convert_current_to_big_endian();
        self
    }

    /// On a little endian machine, this does nothing.
    /// On a big endian machine, the bytes of this value are reversed.
    #[inline] fn from_little_endian_into_current(mut self) -> Self where Self: Sized {
        self.convert_little_endian_to_current();
        self
    }

    /// On a big endian machine, this does nothing.
    /// On a little endian machine, the bytes of this value are reversed.
    #[inline] fn from_big_endian_into_current(mut self) -> Self where Self: Sized {
        self.convert_big_endian_to_current();
        self
    }
}


// call a macro for each argument
macro_rules! call_single_arg_macro_for_each {
    ($macro: ident, $( $arguments: ident ),* ) => {
        $( $macro! { $arguments }  )*
    };
}

// implement this interface for primitive signed and unsigned integers
macro_rules! implement_simple_primitive_endian {
    ($type: ident) => {
        impl Endian for $type {
            fn swap_bytes(&mut self) {
                *self = $type::swap_bytes(*self);
            }
        }
    };
}


call_single_arg_macro_for_each! {
    implement_simple_primitive_endian,
    u16, u32, u64, u128, i16, i32, i64, i128
}

// no-op implementations
impl Endian for u8 { fn swap_bytes(&mut self) {} }
impl Endian for i8 { fn swap_bytes(&mut self) {} }
impl Endian for [u8] { fn swap_bytes(&mut self) {} }
impl Endian for [i8] { fn swap_bytes(&mut self) {} }

// implement this interface for primitive floats, because they do not have a `swap_bytes()` in `std`
macro_rules! implement_float_primitive_by_bits {
    ($type: ident) => {
        impl Endian for $type {
            fn swap_bytes(&mut self) {
                *self = Self::from_bits(self.to_bits().swap_bytes());
            }
        }
    };
}


implement_float_primitive_by_bits!(f32);
implement_float_primitive_by_bits!(f64);

macro_rules! implement_slice_by_element {
    ($type: ident) => {
        impl Endian for [$type] {
            fn swap_bytes(&mut self) {
                for number in self.iter_mut() { // TODO SIMD?
                    number.swap_bytes();
                }
            }
        }
    };
}

call_single_arg_macro_for_each! {
    implement_slice_by_element,
    u16, u32, u64, u128,
    i16, i32, i64, i128,
    f64, f32
}

/// Easily write primitives and slices of primitives to
/// binary `std::io::Write` streams and easily read from binary `std::io::Read` streams.
///
/// Also contains the unsafe `bytes` module for reinterpreting values as byte slices and vice versa.
pub mod io {
    use super::Endian;
    use std::io::{Read, Write, Result};

    /// Reinterpret values as byte slices and byte slices as values unsafely.
    pub mod bytes {
        use std::io::{Read, Write, Result};

        /// View this slice of values as a slice of bytes.
        #[inline]
        pub unsafe fn slice_as_bytes<T>(value: &[T]) -> &[u8] {
            std::slice::from_raw_parts(
                value.as_ptr() as *const u8,
                value.len() * std::mem::size_of::<T>()
            )
        }

        /// View this slice of values as a mutable slice of bytes.
        #[inline]
        pub unsafe fn slice_as_bytes_mut<T>(value: &mut [T]) -> &mut [u8] {
            std::slice::from_raw_parts_mut(
                value.as_mut_ptr() as *mut u8,
                value.len() * std::mem::size_of::<T>()
            )
        }

        /// View this reference as a slice of bytes.
        #[inline]
        pub unsafe fn value_as_bytes<T: Sized>(value: &T) -> &[u8] {
            std::slice::from_raw_parts(
                value as *const T as *const u8,
                std::mem::size_of::<T>()
            )
        }

        /// View this reference as a mutable slice of bytes.
        #[inline]
        pub unsafe fn value_as_bytes_mut<T: Sized>(value: &mut T) ->&mut [u8] {
            std::slice::from_raw_parts_mut(
                value as *mut T as *mut u8,
                std::mem::size_of::<T>()
            )
        }

        /// View this slice as a mutable slice of bytes and write it.
        #[inline]
        pub unsafe fn write_slice<T>(write: &mut impl Write, value: &[T]) -> Result<()> {
            write.write_all(slice_as_bytes(value))
        }

        /// Read a slice of bytes into the specified slice.
        #[inline]
        pub unsafe fn read_slice<T>(read: &mut impl Read, value: &mut [T]) -> Result<()> {
            read.read_exact(slice_as_bytes_mut(value))
        }

        /// View this reference as a mutable slice of bytes and write it.
        #[inline]
        pub unsafe fn write_value<T: Sized>(write: &mut impl Write, value: &T) -> Result<()> {
            write.write_all(value_as_bytes(value))
        }

        /// Read a slice of bytes into the specified reference.
        #[inline]
        pub unsafe fn read_value<T: Sized>(read: &mut impl Read, value: &mut T) -> Result<()> {
            read.read_exact(value_as_bytes_mut(value))
        }
    }

    /// A `std::io::Write` output stream which supports writing any primitive values as bytes.
    /// Will encode the values to be either little endian or big endian, as desired.
    ///
    /// This extension trait is implemented for all `Write` types.
    /// Add `use lebe::io::WriteEndian;` to your code
    /// to automatically unlock this functionality for all types that implement `Write`.
    pub trait WriteEndian<T: ?Sized> {

        /// Write the byte value of the specified reference, converting it to little endianness
        fn write_as_little_endian(&mut self, value: &T) -> Result<()>;

        /// Write the byte value of the specified reference, converting it to big endianness
        fn write_as_big_endian(&mut self, value: &T) -> Result<()>;

        /// Write the byte value of the specified reference, not converting it
        fn write_as_native_endian(&mut self, value: &T) -> Result<()> {
            #[cfg(target_endian = "little")] { self.write_as_little_endian(value) }
            #[cfg(target_endian = "big")] { self.write_as_big_endian(value) }
        }
    }

    /// A `std::io::Read` input stream which supports reading any primitive values from bytes.
    /// Will decode the values from either little endian or big endian, as desired.
    ///
    /// This extension trait is implemented for all `Read` types.
    /// Add `use lebe::io::ReadEndian;` to your code
    /// to automatically unlock this functionality for all types that implement `Read`.
    pub trait ReadEndian<T: ?Sized> {

        /// Read into the supplied reference. Acts the same as `std::io::Read::read_exact`.
        fn read_from_little_endian_into(&mut self, value: &mut T) -> Result<()>;

        /// Read into the supplied reference. Acts the same as `std::io::Read::read_exact`.
        fn read_from_big_endian_into(&mut self, value: &mut T) -> Result<()>;

        /// Read into the supplied reference. Acts the same as `std::io::Read::read_exact`.
        fn read_from_native_endian_into(&mut self, value: &mut T) -> Result<()> {
            #[cfg(target_endian = "little")] { self.read_from_little_endian_into(value) }
            #[cfg(target_endian = "big")] { self.read_from_big_endian_into(value) }
        }

        /// Read the byte value of the inferred type
        #[inline]
        fn read_from_little_endian(&mut self) -> Result<T> where T: Sized + Default {
            let mut value = T::default();
            self.read_from_little_endian_into(&mut value)?;
            Ok(value)
        }

        /// Read the byte value of the inferred type
        #[inline]
        fn read_from_big_endian(&mut self) -> Result<T> where T: Sized + Default {
            let mut value = T::default();
            self.read_from_big_endian_into(&mut value)?;
            Ok(value)
        }

        /// Read the byte value of the inferred type
        #[inline]
        fn read_from_native_endian(&mut self) -> Result<T> where T: Sized + Default {
            #[cfg(target_endian = "little")] { self.read_from_little_endian() }
            #[cfg(target_endian = "big")] { self.read_from_big_endian() }
        }
    }

    // implement primitive for all types that are implemented by `Read`
    impl<R: Read + ReadEndian<P>, P: Default> ReadPrimitive<R> for P {}


    /// Offers a prettier versions of reading a primitive number.
    ///
    /// The default way of reading a value is:
    /// ```rust
    /// # use std::io::Read;
    /// # use lebe::prelude::*;
    /// # let mut reader : &[u8] = &[2, 1];
    ///
    /// let number: u16 = reader.read_from_little_endian()?;
    /// println!("{}", number);
    /// # Ok::<(), std::io::Error>(())
    ///
    /// ```
    ///
    /// This trait enables you to use expressions:
    /// ```rust
    /// # use std::io::Read;
    /// # use lebe::prelude::*;
    /// # let mut reader : &[u8] = &[2, 1];
    ///
    /// println!("{}", u16::read_from_little_endian(&mut reader)?);
    /// # Ok::<(), std::io::Error>(())
    /// ```
    /// .
    ///
    pub trait ReadPrimitive<R: Read + ReadEndian<Self>> : Sized + Default {
        /// Read this value from the supplied reader. Same as `ReadEndian::read_from_little_endian()`.
        fn read_from_little_endian(read: &mut R) -> Result<Self> {
            read.read_from_little_endian()
        }

        /// Read this value from the supplied reader. Same as `ReadEndian::read_from_big_endian()`.
        fn read_from_big_endian(read: &mut R) -> Result<Self> {
            read.read_from_big_endian()
        }

        /// Read this value from the supplied reader. Same as `ReadEndian::read_from_native_endian()`.
        fn read_from_native_endian(read: &mut R) -> Result<Self> {
            read.read_from_native_endian()
        }
    }

    macro_rules! implement_simple_primitive_write {
        ($type: ident) => {
            impl<W: Write> WriteEndian<$type> for W {
                fn write_as_little_endian(&mut self, value: &$type) -> Result<()> {
                    unsafe { bytes::write_value(self, &value.from_current_into_little_endian()) }
                }

                fn write_as_big_endian(&mut self, value: &$type) -> Result<()> {
                    unsafe { bytes::write_value(self, &value.from_current_into_big_endian()) }
                }
            }

            impl<R: Read> ReadEndian<$type> for R {
                #[inline]
                fn read_from_little_endian_into(&mut self, value: &mut $type) -> Result<()> {
                    unsafe { bytes::read_value(self, value)?; }
                    value.convert_little_endian_to_current();
                    Ok(())
                }

                #[inline]
                fn read_from_big_endian_into(&mut self, value: &mut $type) -> Result<()> {
                    unsafe { bytes::read_value(self, value)?; }
                    value.convert_big_endian_to_current();
                    Ok(())
                }
            }
        };
    }

    call_single_arg_macro_for_each! {
        implement_simple_primitive_write,
        u8, u16, u32, u64, u128,
        i8, i16, i32, i64, i128,
        f32, f64
    }


    macro_rules! implement_slice_io {
        ($type: ident) => {
            impl<W: Write> WriteEndian<[$type]> for W {
                fn write_as_little_endian(&mut self, value: &[$type]) -> Result<()> {
                    #[cfg(target_endian = "big")] {
                        for number in value { // TODO SIMD!
                            self.write_as_little_endian(number)?;
                        }
                    }

                    // else write whole slice
                    #[cfg(target_endian = "little")]
                    unsafe { bytes::write_slice(self, value)?; }

                    Ok(())
                }

                fn write_as_big_endian(&mut self, value: &[$type]) -> Result<()> {
                    #[cfg(target_endian = "little")] {
                        for number in value { // TODO SIMD!
                            self.write_as_big_endian(number)?;
                        }
                    }

                    // else write whole slice
                    #[cfg(target_endian = "big")]
                    unsafe { bytes::write_slice(self, value)?; }

                    Ok(())
                }
            }

            impl<R: Read> ReadEndian<[$type]> for R {
                fn read_from_little_endian_into(&mut self, value: &mut [$type]) -> Result<()> {
                    unsafe { bytes::read_slice(self, value)? };
                    value.convert_little_endian_to_current();
                    Ok(())
                }

                fn read_from_big_endian_into(&mut self, value: &mut [$type]) -> Result<()> {
                    unsafe { bytes::read_slice(self, value)? };
                    value.convert_big_endian_to_current();
                    Ok(())
                }
            }
        };
    }

    call_single_arg_macro_for_each! {
        implement_slice_io,
        u8, u16, u32, u64, u128,
        i8, i16, i32, i64, i128,
        f64, f32
    }



    // TODO: SIMD
    /*impl<R: Read> ReadEndian<[f32]> for R {
        fn read_from_little_endian_into(&mut self, value: &mut [f32]) -> Result<()> {
            unsafe { bytes::read_slice(self, value)? };
            value.convert_little_endian_to_current();
            Ok(())
        }

        fn read_from_big_endian_into(&mut self, value: &mut [f32]) -> Result<()> {
            unsafe { bytes::read_slice(self, value)? };
            value.convert_big_endian_to_current();
            Ok(())
        }
    }

    impl<W: Write> WriteEndian<[f32]> for W {
        fn write_as_big_endian(&mut self, value: &[f32]) -> Result<()> {
            if cfg!(target_endian = "little") {

                // FIX ME this SIMD optimization makes no difference ... why? like, ZERO difference, not even worse
//                #[cfg(feature = "simd")]
                #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
                unsafe {
                    if is_x86_feature_detected!("avx2") {
                        write_bytes_avx(self, value);
                        return Ok(());
                    }
                }

                // otherwise (no avx2 available)
//                for number in value {
//                    self.write_as_little_endian(number);
//                }
//
//                return Ok(());
                unimplemented!();

                #[target_feature(enable = "avx2")]
                #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
                unsafe fn write_bytes_avx(write: &mut impl Write, slice: &[f32]) -> Result<()> {
                    #[cfg(target_arch = "x86")] use std::arch::x86 as mm;
                    #[cfg(target_arch = "x86_64")] use std::arch::x86_64 as mm;

                    let bytes: &[u8] = crate::io::bytes::slice_as_bytes(slice);
                    let mut chunks = bytes.chunks_exact(32);

                    let indices = mm::_mm256_set_epi8(
                        0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
                        0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15
//                        3,2,1,0, 7,6,5,4, 11,10,9,8, 15,14,13,12,
//                        3,2,1,0, 7,6,5,4, 11,10,9,8, 15,14,13,12
                    );

                    for chunk in &mut chunks {
                        let data = mm::_mm256_loadu_si256(chunk.as_ptr() as _);
                        let result = mm::_mm256_shuffle_epi8(data, indices);
                        let mut out = [0_u8; 32];
                        mm::_mm256_storeu_si256(out.as_mut_ptr() as _, result);
                        write.write_all(&out)?;
                    }

                    let remainder = chunks.remainder();

                    { // copy remainder into larger slice, with zeroes at the end
                        let mut last_chunk = [0_u8; 32];
                        last_chunk[0..remainder.len()].copy_from_slice(remainder);
                        let data = mm::_mm256_loadu_si256(last_chunk.as_ptr() as _);
                        let result = mm::_mm256_shuffle_epi8(data, indices);
                        mm::_mm256_storeu_si256(last_chunk.as_mut_ptr() as _, result);
                        write.write_all(&last_chunk[0..remainder.len()])?;
                    }

                    Ok(())
                }
            }

            else {
                unsafe { bytes::write_slice(self, value)?; }
                Ok(())
            }
        }

        fn write_as_little_endian(&mut self, value: &[f32]) -> Result<()> {
            for number in value {
                self.write_as_little_endian(number)?;
            }

            Ok(())
        }
    }*/
}