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
//! # rend
//!
//! rend is a library that provides endian-aware primitives for Rust.
//!
//! It's similar in design to [`simple_endian`](https://crates.io/crates/simple_endian), but has
//! support for more builtin types such as atomics and nonzero integers. It also has support for
//! const functions since it does not rely on traits.
//!
//! rend does not provide endian-aware types for types that are inherently endian-agnostic, such as
//! `bool` and `u8`. It does not provide endian-aware types for types that have an
//! architecture-dependent size, such as `isize` and `usize`. It's also not extensible to custom
//! types.
//!
//! rend is intended to be used to build portable types that can be shared between different
//! architectures, especially with zero-copy deserialization.
//!
//! ## Features
//!
//! - `std`: Enables standard library support (enabled by default)
//! - `validation`: Enables validation support through `bytecheck`
//!
//! ## Example:
//! ```
//! use rend::*;
//!
//! let little_int = i32_le::new(0x12345678);
//! // Internal representation is little-endian
//! assert_eq!(
//!     [0x78, 0x56, 0x34, 0x12],
//!     unsafe { ::core::mem::transmute::<_, [u8; 4]>(little_int) }
//! );
//!
//! // Can also be made with `.into()`
//! let little_int: i32_le = 0x12345678.into();
//! // Still formats correctly
//! assert_eq!("305419896", format!("{}", little_int));
//! assert_eq!("0x12345678", format!("0x{:x}", little_int));
//!
//! let big_int = i32_be::new(0x12345678);
//! // Internal representation is big-endian
//! assert_eq!(
//!     [0x12, 0x34, 0x56, 0x78],
//!     unsafe { ::core::mem::transmute::<_, [u8; 4]>(big_int) }
//! );
//!
//! // Can also be made with `.into()`
//! let big_int: i32_be = 0x12345678.into();
//! // Still formats correctly
//! assert_eq!("305419896", format!("{}", big_int));
//! assert_eq!("0x12345678", format!("0x{:x}", big_int));
//! ```

#![cfg_attr(not(feature = "std"), no_std)]
#![deny(missing_docs)]
#![deny(missing_crate_level_docs)]

#[macro_use]
mod impl_struct;
#[macro_use]
mod impl_traits;
#[cfg(feature = "validation")]
#[macro_use]
mod impl_validation;

#[cfg(feature = "validation")]
use bytecheck::{CharCheckError, CheckBytes, NonZeroCheckError, Unreachable};
#[cfg(has_atomics)]
use core::sync::atomic::{AtomicI16, AtomicI32, AtomicU16, AtomicU32, Ordering};
#[cfg(has_atomics_64)]
use core::sync::atomic::{AtomicI64, AtomicU64};
use core::{
    hash::{Hash, Hasher},
    num::{
        NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroU128, NonZeroU16, NonZeroU32,
        NonZeroU64,
    },
};

/// A wrapper for native-endian types.
///
/// This is mostly useful for `const` conversions to big- and little-endian types in contexts where
/// type inference is required. Because it's native-endian, the inner value is publicly exposed.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct NativeEndian<T> {
    /// The value of the type
    pub value: T,
}

/// A wrapper for big-endian types.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct LittleEndian<T> {
    value: T,
}

/// A wrapper for little-endian types.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct BigEndian<T> {
    value: T,
}

macro_rules! swap_endian {
    (@NativeEndian $expr:expr) => {{
        $expr
    }};
    (@LittleEndian $expr:expr) => {{
        #[cfg(target_endian = "little")]
        {
            $expr
        }
        #[cfg(target_endian = "big")]
        {
            $expr.swap_bytes()
        }
    }};
    (@BigEndian $expr:expr) => {{
        #[cfg(target_endian = "little")]
        {
            $expr.swap_bytes()
        }
        #[cfg(target_endian = "big")]
        {
            $expr
        }
    }};
}

macro_rules! swap_bytes {
    (@signed_int $endian:ident<$ne:ty> $value:expr) => {
        swap_endian!(@$endian $value)
    };
    (@unsigned_int $endian:ident<$ne:ty> $value:expr) => {
        swap_endian!(@$endian $value)
    };
    (@float $endian:ident<$ne:ty> $value:expr) => {
        <$ne>::from_bits(swap_endian!(@$endian $value.to_bits()))
    };
    (@char $endian:ident<$ne:ty> $value:expr) => {
        unsafe { ::core::char::from_u32_unchecked(swap_endian!(@$endian $value as u32)) }
    };
    (@nonzero $endian:ident<$ne:ty> $value:expr) => {
        unsafe { <$ne>::new_unchecked(swap_endian!(@$endian $value.get())) }
    };
    (@atomic $endian:ident<$ne:ty> $value:expr) => {
        swap_endian!(@$endian $value)
    };
}

macro_rules! impl_endian {
    (
        @$class:ident $native:ty $(= $prim:ty)?,
        $ne:ident = $ne_doc:literal,
        $le:ident = $le_doc:literal,
        $be:ident = $be_doc:literal
    ) => {
        impl_endian!(@$class $ne_doc NativeEndian<$native> as $ne $(= $prim)?);
        impl_endian!(@$class $le_doc LittleEndian<$native> as $le $(= $prim)?);
        impl_endian!(@$class $be_doc BigEndian<$native> as $be $(= $prim)?);
    };
    (@$class:ident $doc:literal $endian:ident<$ne:ty> as $alias:ident $(= $prim:ty)?) => {
        impl_struct!(@$class $endian<$ne> $(= $prim)?);
        #[cfg(feature = "validation")]
        impl_validation!(@$class $endian<$ne> $(= $prim)?);
        #[doc = "Alias for `"]
        #[doc = $doc]
        #[doc = "`"]
        #[allow(non_camel_case_types)]
        pub type $alias = $endian<$ne>;
    };
}

impl_endian!(
    @signed_int i16,
    i16_ne = "`NativeEndian<i16>`",
    i16_le = "`LittleEndian<i16>`",
    i16_be = "`BigEndian<i16>`"
);
impl_endian!(
    @signed_int i32,
    i32_ne = "`NativeEndian<i32>`",
    i32_le = "`LittleEndian<i32>`",
    i32_be = "`BigEndian<i32>`"
);
impl_endian!(
    @signed_int i64,
    i64_ne = "`NativeEndian<i64>`",
    i64_le = "`LittleEndian<i64>`",
    i64_be = "`BigEndian<i64>`"
);
impl_endian!(
    @signed_int i128,
    i128_ne = "`NativeEndian<i128>`",
    i128_le = "`LittleEndian<i128>`",
    i128_be = "`BigEndian<i128>`"
);
impl_endian!(
    @unsigned_int u16,
    u16_ne = "`NativeEndian<u16>`",
    u16_le = "`LittleEndian<u16>`",
    u16_be = "`BigEndian<u16>`"
);
impl_endian!(
    @unsigned_int u32,
    u32_ne = "`NativeEndian<u32>`",
    u32_le = "`LittleEndian<u32>`",
    u32_be = "`BigEndian<u32>`"
);
impl_endian!(
    @unsigned_int u64,
    u64_ne = "`NativeEndian<u64>`",
    u64_le = "`LittleEndian<u64>`",
    u64_be = "`BigEndian<u64>`"
);
impl_endian!(
    @unsigned_int u128,
    u128_ne = "`NativeEndian<u128>`",
    u128_le = "`LittleEndian<u128>`",
    u128_be = "`BigEndian<u128>`"
);

impl_endian!(
    @float f32,
    f32_ne = "`NativeEndian<f32>`",
    f32_le = "`LittleEndian<f32>`",
    f32_be = "`BigEndian<f32>`"
);
impl_endian!(
    @float f64,
    f64_ne = "`NativeEndian<f64>`",
    f64_le = "`LittleEndian<f64>`",
    f64_be = "`BigEndian<f64>`"
);

impl_endian!(
    @char char,
    char_ne = "`NativeEndian<char>`",
    char_le = "`LittleEndian<char>`",
    char_be = "`BigEndian<char>`"
);

impl_endian!(
    @nonzero NonZeroI16 = i16,
    NonZeroI16_ne = "`NativeEndian<NonZeroI16>`",
    NonZeroI16_le = "`LittleEndian<NonZeroI16>`",
    NonZeroI16_be = "`BigEndian<NonZeroI16>`"
);
impl_endian!(
    @nonzero NonZeroI32 = i32,
    NonZeroI32_ne = "`NativeEndian<NonZeroI32>`",
    NonZeroI32_le = "`LittleEndian<NonZeroI32>`",
    NonZeroI32_be = "`BigEndian<NonZeroI32>`"
);
impl_endian!(
    @nonzero NonZeroI64 = i64,
    NonZeroI64_ne = "`NativeEndian<NonZeroI64>`",
    NonZeroI64_le = "`LittleEndian<NonZeroI64>`",
    NonZeroI64_be = "`BigEndian<NonZeroI64>`"
);
impl_endian!(
    @nonzero NonZeroI128 = i128,
    NonZeroI128_ne = "`NativeEndian<NonZeroI128>`",
    NonZeroI128_le = "`LittleEndian<NonZeroI128>`",
    NonZeroI128_be = "`BigEndian<NonZeroI128>`"
);
impl_endian!(
    @nonzero NonZeroU16 = u16,
    NonZeroU16_ne = "`NativeEndian<NonZeroU16>`",
    NonZeroU16_le = "`LittleEndian<NonZeroU16>`",
    NonZeroU16_be = "`BigEndian<NonZeroU16>`"
);
impl_endian!(
    @nonzero NonZeroU32 = u32,
    NonZeroU32_ne = "`NativeEndian<NonZeroU32>`",
    NonZeroU32_le = "`LittleEndian<NonZeroU32>`",
    NonZeroU32_be = "`BigEndian<NonZeroU32>`"
);
impl_endian!(
    @nonzero NonZeroU64 = u64,
    NonZeroU64_ne = "`NativeEndian<NonZeroU64>`",
    NonZeroU64_le = "`LittleEndian<NonZeroU64>`",
    NonZeroU64_be = "`BigEndian<NonZeroU64>`"
);
impl_endian!(
    @nonzero NonZeroU128 = u128,
    NonZeroU128_ne = "`NativeEndian<NonZeroU128>`",
    NonZeroU128_le = "`LittleEndian<NonZeroU128>`",
    NonZeroU128_be = "`BigEndian<NonZeroU128>`"
);

#[cfg(has_atomics)]
impl_endian!(
    @atomic AtomicI16 = i16,
    AtomicI16_ne = "`NativeEndian<AtomicI16>`",
    AtomicI16_le = "`LittleEndian<AtomicI16>`",
    AtomicI16_be = "`BigEndian<AtomicI16>`"
);
#[cfg(has_atomics)]
impl_endian!(
    @atomic AtomicI32 = i32,
    AtomicI32_ne = "`NativeEndian<AtomicI32>`",
    AtomicI32_le = "`LittleEndian<AtomicI32>`",
    AtomicI32_be = "`BigEndian<AtomicI32>`"
);
#[cfg(has_atomics_64)]
impl_endian!(
    @atomic AtomicI64 = i64,
    AtomicI64_ne = "`NativeEndian<AtomicI64>`",
    AtomicI64_le = "`LittleEndian<AtomicI64>`",
    AtomicI64_be = "`BigEndian<AtomicI64>`"
);
#[cfg(has_atomics)]
impl_endian!(
    @atomic AtomicU16 = u16,
    AtomicU16_ne = "`NativeEndian<AtomicU16>`",
    AtomicU16_le = "`LittleEndian<AtomicU16>`",
    AtomicU16_be = "`BigEndian<AtomicU16>`"
);
#[cfg(has_atomics)]
impl_endian!(
    @atomic AtomicU32 = u32,
    AtomicU32_ne = "`NativeEndian<AtomicU32>`",
    AtomicU32_le = "`LittleEndian<AtomicU32>`",
    AtomicU32_be = "`BigEndian<AtomicU32>`"
);
#[cfg(has_atomics_64)]
impl_endian!(
    @atomic AtomicU64 = u64,
    AtomicU64_ne = "`NativeEndian<AtomicU64>`",
    AtomicU64_le = "`LittleEndian<AtomicU64>`",
    AtomicU64_be = "`BigEndian<AtomicU64>`"
);

#[cfg(test)]
mod tests {
    use crate::*;
    use core::mem;

    #[test]
    fn endian_representation() {
        unsafe {
            // i16
            assert_eq!(
                [0x01, 0x02],
                mem::transmute::<_, [u8; 2]>(i16_be::new(0x0102))
            );
            assert_eq!(
                [0x02, 0x01],
                mem::transmute::<_, [u8; 2]>(i16_le::new(0x0102))
            );

            // i32
            assert_eq!(
                [0x01, 0x02, 0x03, 0x04],
                mem::transmute::<_, [u8; 4]>(i32_be::new(0x01020304))
            );
            assert_eq!(
                [0x04, 0x03, 0x02, 0x01],
                mem::transmute::<_, [u8; 4]>(i32_le::new(0x01020304))
            );

            // i64
            assert_eq!(
                [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08],
                mem::transmute::<_, [u8; 8]>(i64_be::new(0x0102030405060708))
            );
            assert_eq!(
                [0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01],
                mem::transmute::<_, [u8; 8]>(i64_le::new(0x0102030405060708))
            );

            // i128
            assert_eq!(
                [
                    0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
                    0x0e, 0x0f, 0x10
                ],
                mem::transmute::<_, [u8; 16]>(i128_be::new(0x0102030405060708090a0b0c0d0e0f10))
            );
            assert_eq!(
                [
                    0x10, 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04,
                    0x03, 0x02, 0x01
                ],
                mem::transmute::<_, [u8; 16]>(i128_le::new(0x0102030405060708090a0b0c0d0e0f10))
            );

            // u16
            assert_eq!(
                [0x01, 0x02],
                mem::transmute::<_, [u8; 2]>(u16_be::new(0x0102))
            );
            assert_eq!(
                [0x02, 0x01],
                mem::transmute::<_, [u8; 2]>(u16_le::new(0x0102))
            );

            // u32
            assert_eq!(
                [0x01, 0x02, 0x03, 0x04],
                mem::transmute::<_, [u8; 4]>(u32_be::new(0x01020304))
            );
            assert_eq!(
                [0x04, 0x03, 0x02, 0x01],
                mem::transmute::<_, [u8; 4]>(u32_le::new(0x01020304))
            );

            // u64
            assert_eq!(
                [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08],
                mem::transmute::<_, [u8; 8]>(u64_be::new(0x0102030405060708))
            );
            assert_eq!(
                [0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01],
                mem::transmute::<_, [u8; 8]>(u64_le::new(0x0102030405060708))
            );

            // u128
            assert_eq!(
                [
                    0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
                    0x0e, 0x0f, 0x10
                ],
                mem::transmute::<_, [u8; 16]>(u128_be::new(0x0102030405060708090a0b0c0d0e0f10))
            );
            assert_eq!(
                [
                    0x10, 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04,
                    0x03, 0x02, 0x01
                ],
                mem::transmute::<_, [u8; 16]>(u128_le::new(0x0102030405060708090a0b0c0d0e0f10))
            );

            // f32
            assert_eq!(
                [0x40, 0x49, 0x0f, 0xd0],
                mem::transmute::<_, [u8; 4]>(f32_be::new(3.141590118408203125f32))
            );
            assert_eq!(
                [0xd0, 0x0f, 0x49, 0x40],
                mem::transmute::<_, [u8; 4]>(f32_le::new(3.141590118408203125f32))
            );

            // f64
            assert_eq!(
                [0x40, 0x09, 0x21, 0xfb, 0x4d, 0x12, 0xd8, 0x4a],
                mem::transmute::<_, [u8; 8]>(f64_be::new(3.1415926000000000684053702571f64))
            );
            assert_eq!(
                [0x4a, 0xd8, 0x12, 0x4d, 0xfb, 0x21, 0x09, 0x40],
                mem::transmute::<_, [u8; 8]>(f64_le::new(3.1415926000000000684053702571f64))
            );

            // char
            assert_eq!(
                [0x00, 0x01, 0xf3, 0x89],
                mem::transmute::<_, [u8; 4]>(char_be::new('🎉'))
            );
            assert_eq!(
                [0x89, 0xf3, 0x01, 0x00],
                mem::transmute::<_, [u8; 4]>(char_le::new('🎉'))
            );

            // AtomicU16
            assert_eq!(
                [0x01, 0x02],
                mem::transmute::<_, [u8; 2]>(AtomicU16_be::new(0x0102))
            );
            assert_eq!(
                [0x02, 0x01],
                mem::transmute::<_, [u8; 2]>(AtomicU16_le::new(0x0102))
            );

            // AtomicU32
            assert_eq!(
                [0x01, 0x02, 0x03, 0x04],
                mem::transmute::<_, [u8; 4]>(AtomicU32_be::new(0x01020304))
            );
            assert_eq!(
                [0x04, 0x03, 0x02, 0x01],
                mem::transmute::<_, [u8; 4]>(AtomicU32_le::new(0x01020304))
            );

            // AtomicU64
            assert_eq!(
                [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08],
                mem::transmute::<_, [u8; 8]>(AtomicU64_be::new(0x0102030405060708))
            );
            assert_eq!(
                [0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01],
                mem::transmute::<_, [u8; 8]>(AtomicU64_le::new(0x0102030405060708))
            );
        }
    }
}