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
//! Marker types which define a [`ByteOrder`] to use.

/// A macro that picks which `$expr` to evaluate to based on if the current
/// `#[cfg(target_endian = "..")]` matches `$endian` and optionally
/// #[cfg(target_pointer_width = "..")] matches `$pointer_width`.
///
/// A fallback branch is supported with `_ => $expr`.
///
/// # Examples
///
/// ```no_run
/// use musli_zerocopy::{endian, ByteOrder, Endian, Ref, ZeroCopy};
///
/// #[derive(ZeroCopy)]
/// #[repr(C)]
/// struct Header {
///     big: Ref<Data<endian::Big>, endian::Big>,
///     little: Ref<Data<endian::Little>, endian::Little>,
/// }
///
/// #[derive(ZeroCopy)]
/// #[repr(C)]
/// struct Data<E = endian::Native>
/// where
///     E: ByteOrder,
/// {
///     name: Ref<str, E>,
///     age: Endian<u32, E>,
/// }
///
/// let header: Header = todo!();
/// let data: Ref<Data> = endian::pick!("big" => header.big, "little" => header.little);
/// // Example using fallback:
/// let data: Ref<Data> = endian::pick!("big" => header.big, _ => header.little);
/// ```
///
/// Note that this evaluates to a private type in case the current endianness is
/// not covered:
///
/// ```compile_fail
/// #[cfg(target_endian = "little")]
/// let data: u32 = endian::pick!("big" => 1u32);
/// #[cfg(target_endian = "big")]
/// let data: u32 = endian::pick!("little" => 1u32);
/// ```
#[macro_export]
#[doc(hidden)]
macro_rules! __pick {
    ($($endian:literal $(/ $pointer_width:literal)? => $expr:expr),+ $(, _ => $fallback:expr)? $(,)?) => {
        match () {
            $(
                #[cfg(all(target_endian = $endian $(, target_pointer_width = $pointer_width)*))]
                () => $expr,
            )*
            #[cfg(not(any($(all(target_endian = $endian $(, target_pointer_width = $pointer_width)*)),*)))]
            () => $crate::__pick_fallback!($($fallback)*)
        }
    };
}

#[macro_export]
#[doc(hidden)]
macro_rules! __pick_fallback {
    () => {
        struct UnsupportedEndian;
        UnsupportedEndian
    };

    ($expr:expr) => {
        $expr
    };
}

/// A macro that matches `$expr` to its associated `$pat` if the current
/// `#[cfg(target_endian = "..")]` matches `$endian` and optionally
/// #[cfg(target_pointer_width = "..")] matches `$pointer_width`.
///
/// Note that if running on a platform which is not covered, the result will
/// always be `false`:
///
/// ```
/// use musli_zerocopy::endian;
///
/// #[derive(Debug, PartialEq)]
/// enum Endian { Little, Big }
///
/// let e = endian::pick!("little" => Endian::Little, "big" => Endian::Big);
///
/// #[cfg(target_endian = "little")]
/// assert!(!endian::matches!(e, "big" => Big));
/// #[cfg(target_endian = "big")]
/// assert!(!endian::matches!(e, "little" => Little));
/// ```
///
/// # Examples
///
/// ```
/// use musli_zerocopy::endian;
///
/// #[derive(Debug, PartialEq)]
/// enum Endian { Little, Big }
///
/// let e = endian::pick!("little" => Endian::Little, "big" => Endian::Big);
///
/// assert!(endian::matches!(e, "little" => Endian::Little, "big" => Endian::Big));
/// ```
#[macro_export]
#[doc(hidden)]
macro_rules! __matches {
    ($expr:expr, $($endian:literal $(/ $pointer_width:literal)? => $pat:pat),+ $(,)?) => {
        match $expr {
            $(
                #[cfg(all(target_endian = $endian $(, target_pointer_width = $pointer_width)*))]
                value => matches!(value, $pat),
            )*
            #[cfg(not(any($(all(target_endian = $endian $(, target_pointer_width = $pointer_width)*)),*)))]
            _ => false,
        }
    };
}

#[doc(inline)]
pub use __pick as pick;

#[doc(inline)]
pub use __matches as matches;

#[doc(inline)]
pub use self::endian::Endian;
mod endian;

/// Alias for the native endian [`ByteOrder`].
#[cfg(target_endian = "little")]
pub type Native = Little;

/// Alias for the native endian [`ByteOrder`].
#[cfg(target_endian = "big")]
pub type Native = Big;

/// Marker type indicating that the big endian [`ByteOrder`] is in use.
#[non_exhaustive]
pub struct Big;

/// Marker type indicating that the little endian [`ByteOrder`] is in use.
#[non_exhaustive]
pub struct Little;

use crate::ZeroCopy;

/// Convert the value `T` from [`Big`] to [`Native`] endian.
///
/// This ignores types which has [`ZeroCopy::CAN_SWAP_BYTES`] set to `false`,
/// such as [`char`]. Such values will simply pass through.
///
/// Swapping the bytes of a type which explicitly records its own byte order
/// like [`Ref<T>`] is a no-op.
///
/// [`Ref<T>`]: crate::Ref
///
/// # Examples
///
/// ```
/// use musli_zerocopy::{endian, ZeroCopy};
///
/// #[derive(Debug, PartialEq, ZeroCopy)]
/// #[repr(C)]
/// struct Struct {
///     c: char,
///     bits32: u32,
///     bits64: u64,
/// }
///
/// let st = endian::from_be(Struct {
///     c: 'a',
///     bits32: 0x10203040u32.to_be(),
///     bits64: 0x5060708090a0b0c0u64.to_be(),
/// });
///
/// assert_eq!(st, Struct {
///     c: 'a',
///     bits32: 0x10203040,
///     bits64: 0x5060708090a0b0c0,
/// });
/// ```
pub fn from_be<T: ZeroCopy>(value: T) -> T {
    from_endian::<_, Big>(value)
}

/// Convert the value `T` from [`Little`] to [`Native`] endian.
///
/// This ignores types which has [`ZeroCopy::CAN_SWAP_BYTES`] set to `false`,
/// such as [`char`]. Such values will simply pass through.
///
/// Swapping the bytes of a type which explicitly records its own byte order
/// like [`Ref<T>`] is a no-op.
///
/// [`Ref<T>`]: crate::Ref
///
/// # Examples
///
/// ```
/// use musli_zerocopy::{endian, ZeroCopy};
///
/// #[derive(Debug, PartialEq, ZeroCopy)]
/// #[repr(C)]
/// struct Struct {
///     c: char,
///     bits32: u32,
///     bits64: u64,
/// }
///
/// let st = endian::from_le(Struct {
///     c: 'a',
///     bits32: 0x10203040u32.to_le(),
///     bits64: 0x5060708090a0b0c0u64.to_le(),
/// });
///
/// assert_eq!(st, Struct {
///     c: 'a',
///     bits32: 0x10203040,
///     bits64: 0x5060708090a0b0c0,
/// });
/// ```
#[inline]
pub fn from_le<T: ZeroCopy>(value: T) -> T {
    from_endian::<_, Little>(value)
}

/// Convert the value `T` from the specified [`ByteOrder`] `E` to [`Native`]
/// endian.
///
/// This ignores types which has [`ZeroCopy::CAN_SWAP_BYTES`] set to `false`,
/// such as [`char`]. Such values will simply pass through.
///
/// Swapping the bytes of a type which explicitly records its own byte order
/// like [`Ref<T>`] is a no-op.
///
/// [`Ref<T>`]: crate::Ref
///
/// # Examples
///
/// ```
/// use musli_zerocopy::{endian, ZeroCopy};
///
/// #[derive(Debug, PartialEq, ZeroCopy)]
/// #[repr(C)]
/// struct Struct {
///     c: char,
///     bits32: u32,
///     bits64: u64,
/// }
///
/// let st = endian::from_endian::<_, endian::Big>(Struct {
///     c: 'a',
///     bits32: 0x10203040u32.to_be(),
///     bits64: 0x5060708090a0b0c0u64.to_be(),
/// });
///
/// assert_eq!(st, Struct {
///     c: 'a',
///     bits32: 0x10203040,
///     bits64: 0x5060708090a0b0c0,
/// });
/// ```
#[inline]
pub fn from_endian<T: ZeroCopy, E: ByteOrder>(value: T) -> T {
    value.transpose_bytes::<E, Native>()
}

mod sealed {
    use super::{Big, Little};

    pub trait Sealed {}

    impl Sealed for Big {}
    impl Sealed for Little {}
}

/// Defines a byte order to use.
///
/// This trait is implemented by two marker types [`Big`] and
/// [`Little`], and its internals are intentionally hidden. Do not attempt
/// to use them yourself.
pub trait ByteOrder: 'static + Sized + self::sealed::Sealed {
    /// Maps the `value` through `map`, unless the current byte order is
    /// [`Native`].
    #[doc(hidden)]
    fn try_map<T, F>(value: T, map: F) -> T
    where
        F: FnOnce(T) -> T;

    /// Swap the bytes for a `usize` with the current byte order.
    #[doc(hidden)]
    fn swap_usize(value: usize) -> usize;

    /// Swap the bytes for a `isize` with the current byte order.
    #[doc(hidden)]
    fn swap_isize(value: isize) -> isize;

    /// Swap the bytes of a `u16` with the current byte order.
    #[doc(hidden)]
    fn swap_u16(value: u16) -> u16;

    /// Swap the bytes of a `i16` with the current byte order.
    #[doc(hidden)]
    fn swap_i16(value: i16) -> i16;

    /// Swap the bytes for a `u32` with the current byte order.
    #[doc(hidden)]
    fn swap_u32(value: u32) -> u32;

    /// Swap the bytes for a `i32` with the current byte order.
    #[doc(hidden)]
    fn swap_i32(value: i32) -> i32;

    /// Swap the bytes for a `u64` with the current byte order.
    #[doc(hidden)]
    fn swap_u64(value: u64) -> u64;

    /// Swap the bytes for a `i64` with the current byte order.
    #[doc(hidden)]
    fn swap_i64(value: i64) -> i64;

    /// Swap the bytes for a `u128` with the current byte order.
    #[doc(hidden)]
    fn swap_u128(value: u128) -> u128;

    /// Swap the bytes for a `i128` with the current byte order.
    #[doc(hidden)]
    fn swap_i128(value: i128) -> i128;

    /// Swap the bytes for a `f32` with the current byte order.
    #[doc(hidden)]
    fn swap_f32(value: f32) -> f32;

    /// Swap the bytes for a `f64` with the current byte order.
    #[doc(hidden)]
    fn swap_f64(value: f64) -> f64;
}

impl ByteOrder for Little {
    #[cfg(target_endian = "little")]
    #[inline(always)]
    fn try_map<T, F>(value: T, _: F) -> T
    where
        F: FnOnce(T) -> T,
    {
        value
    }

    #[cfg(not(target_endian = "little"))]
    #[inline(always)]
    fn try_map<T, F>(value: T, map: F) -> T
    where
        F: FnOnce(T) -> T,
    {
        map(value)
    }

    #[inline]
    fn swap_usize(value: usize) -> usize {
        usize::from_le(value)
    }

    #[inline]
    fn swap_isize(value: isize) -> isize {
        isize::from_le(value)
    }

    #[inline]
    fn swap_u16(value: u16) -> u16 {
        u16::to_le(value)
    }

    #[inline]
    fn swap_i16(value: i16) -> i16 {
        i16::to_le(value)
    }

    #[inline]
    fn swap_u32(value: u32) -> u32 {
        u32::from_le(value)
    }

    #[inline]
    fn swap_i32(value: i32) -> i32 {
        i32::from_le(value)
    }

    #[inline]
    fn swap_u64(value: u64) -> u64 {
        u64::from_le(value)
    }

    #[inline]
    fn swap_i64(value: i64) -> i64 {
        i64::from_le(value)
    }

    #[inline]
    fn swap_u128(value: u128) -> u128 {
        u128::from_le(value)
    }

    #[inline]
    fn swap_i128(value: i128) -> i128 {
        i128::from_le(value)
    }

    #[inline]
    fn swap_f32(value: f32) -> f32 {
        f32::from_bits(u32::from_le(value.to_bits()))
    }

    #[inline]
    fn swap_f64(value: f64) -> f64 {
        f64::from_bits(u64::from_le(value.to_bits()))
    }
}

impl ByteOrder for Big {
    #[cfg(target_endian = "big")]
    #[inline(always)]
    fn try_map<T, F>(value: T, _: F) -> T
    where
        F: FnOnce(T) -> T,
    {
        value
    }

    #[cfg(not(target_endian = "big"))]
    #[inline(always)]
    fn try_map<T, F>(value: T, map: F) -> T
    where
        F: FnOnce(T) -> T,
    {
        map(value)
    }

    #[inline]
    fn swap_usize(value: usize) -> usize {
        usize::from_be(value)
    }

    #[inline]
    fn swap_isize(value: isize) -> isize {
        isize::from_be(value)
    }

    #[inline]
    fn swap_u16(value: u16) -> u16 {
        u16::to_be(value)
    }

    #[inline]
    fn swap_i16(value: i16) -> i16 {
        i16::to_be(value)
    }

    #[inline]
    fn swap_u32(value: u32) -> u32 {
        u32::from_be(value)
    }

    #[inline]
    fn swap_i32(value: i32) -> i32 {
        i32::from_be(value)
    }

    #[inline]
    fn swap_u64(value: u64) -> u64 {
        u64::from_be(value)
    }

    #[inline]
    fn swap_i64(value: i64) -> i64 {
        i64::from_be(value)
    }

    #[inline]
    fn swap_u128(value: u128) -> u128 {
        u128::from_be(value)
    }

    #[inline]
    fn swap_i128(value: i128) -> i128 {
        i128::from_be(value)
    }

    #[inline]
    fn swap_f32(value: f32) -> f32 {
        f32::from_bits(u32::from_be(value.to_bits()))
    }

    #[inline]
    fn swap_f64(value: f64) -> f64 {
        f64::from_bits(u64::from_be(value.to_bits()))
    }
}