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
use core::marker::PhantomData;
use core::ops::{Deref, DerefMut};
use core::{any, fmt};

use crate::endian::{Big, ByteOrder, Little, Native};
use crate::ZeroCopy;

/// Wrapper capable of enforcing a custom [`ByteOrder`].
///
/// This can be used to store values in a zero-copy container in a portable
/// manner, which is especially important to transfer types such as `char` which
/// have a limited supported bit-pattern.
///
/// # Wrapping fields
///
/// Any type which implements [`ZeroCopy`] and has [`ZeroCopy::CAN_SWAP_BYTES`]
/// set to `true` can be portably wrapped with this type.
///
/// [`ZeroCopy::CAN_SWAP_BYTES`] is not `true` it indicates that the type
/// contains data which cannot be safely byte-swapped, such as [`char`]. Byte
/// swapping such a type is a no-op and will return the original type.
///
/// ```
/// use musli_zerocopy::{endian, Endian, OwnedBuf, Ref, ZeroCopy};
///
/// #[derive(Clone, Copy, ZeroCopy)]
/// #[repr(C)]
/// struct Struct {
///     name: Ref<str>,
///     age: Endian<u32, endian::Big>,
/// }
///
/// let mut buf = OwnedBuf::new();
///
/// let name = buf.store_unsized("John");
///
/// let data = buf.store(&Struct {
///     name,
///     age: Endian::new(35),
/// });
///
/// buf.align_in_place();
///
/// let data = buf.load(data)?;
///
/// assert_eq!(buf.load(data.name)?, "John");
/// assert_eq!(data.age.to_ne(), 35);
/// # Ok::<_, musli_zerocopy::Error>(())
/// ```
#[derive(ZeroCopy)]
#[zero_copy(crate, swap_bytes, bounds = {T: ZeroCopy})]
#[repr(transparent)]
pub struct Endian<T, E: ByteOrder> {
    value: T,
    #[zero_copy(ignore)]
    _marker: PhantomData<E>,
}

impl<T: ZeroCopy> Endian<T, Little> {
    /// Construct new value wrapper with [`Little`] [`ByteOrder`].
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_zerocopy::Endian;
    ///
    /// let value = Endian::le(42u32);
    /// assert_eq!(value.to_ne(), 42);
    /// assert_eq!(value.to_raw(), 42u32.to_le());
    /// ```
    #[inline]
    pub fn le(value: T) -> Self {
        Self::new(value)
    }
}

impl<T: ZeroCopy> Endian<T, Big> {
    /// Construct new value wrapper with [`Big`] [`ByteOrder`].
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_zerocopy::Endian;
    ///
    /// let value = Endian::be(42u32);
    /// assert_eq!(value.to_ne(), 42);
    /// assert_eq!(value.to_raw(), 42u32.to_be());
    /// ```
    #[inline]
    pub fn be(value: T) -> Self {
        Self::new(value)
    }
}

impl<T: ZeroCopy, E: ByteOrder> Endian<T, E> {
    /// Construct new value wrapper with the specified [`ByteOrder`].
    ///
    /// # Panics
    ///
    /// Panics if we try to use this with a `ZeroCopy` type that cannot be
    /// byte-ordered.
    ///
    /// ```should_panic
    /// use musli_zerocopy::{endian, Endian};
    ///
    /// let _: Endian<_, endian::Little> = Endian::new('a');
    /// ```
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_zerocopy::{endian, Endian, ZeroCopy};
    ///
    /// let mut a: Endian<_, endian::Big> = Endian::new('a' as u32);
    /// let mut b: Endian<_, endian::Little> = Endian::new('a' as u32);
    ///
    /// assert_eq!(a.to_ne(), 'a' as u32);
    /// assert_eq!(a.to_bytes(), &[0, 0, 0, 97]);
    ///
    /// assert_eq!(b.to_ne(), 'a' as u32);
    /// assert_eq!(b.to_bytes(), &[97, 0, 0, 0]);
    /// ```
    #[inline]
    pub fn new(value: T) -> Self {
        assert!(
            T::CAN_SWAP_BYTES,
            "Type `{}` cannot be byte-ordered since it would not inhabit valid types",
            any::type_name::<T>()
        );

        Self {
            value: T::swap_bytes::<E>(value),
            _marker: PhantomData,
        }
    }

    /// Get interior value in native [`ByteOrder`].
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_zerocopy::Endian;
    ///
    /// let value = Endian::le(42u32);
    /// assert_eq!(value.to_ne(), 42);
    /// assert_eq!(value.to_raw(), 42u32.to_le());
    /// ```
    #[inline]
    pub fn to_ne(self) -> T {
        T::swap_bytes::<E>(self.value)
    }

    /// Get the raw inner value.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_zerocopy::Endian;
    ///
    /// let value = Endian::le(42u32);
    /// assert_eq!(value.to_ne(), 42);
    /// assert_eq!(value.to_raw(), 42u32.to_le());
    /// ```
    #[inline]
    pub fn to_raw(self) -> T {
        self.value
    }
}

impl<T: ZeroCopy, E: ByteOrder> fmt::Debug for Endian<T, E>
where
    T: fmt::Debug,
{
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Endian<{}>({:?})", any::type_name::<E>(), self.value)
    }
}

impl<T: ZeroCopy, E: ByteOrder> Clone for Endian<T, E>
where
    T: Clone,
{
    fn clone(&self) -> Self {
        Self {
            value: self.value.clone(),
            _marker: self._marker,
        }
    }
}

impl<T: ZeroCopy, E: ByteOrder> Copy for Endian<T, E> where T: Copy {}

/// Any `Endian<T>` implements [`Deref<Target = T>`] for natively wrapped types.
///
/// # Examples
///
/// ```
/// use musli_zerocopy::Endian;
///
/// let value = Endian::new(42u32);
/// assert_eq!(*value, 42u32);
/// ```
impl<T> Deref for Endian<T, Native> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

/// Any `Endian<T>` implements [`DerefMut<Target = T>`] for natively wrapped types.
///
/// # Examples
///
/// ```
/// use musli_zerocopy::Endian;
///
/// let mut value = Endian::new(42u32);
/// assert_eq!(*value, 42u32);
/// *value += 1;
/// assert_eq!(*value, 43u32);
/// ```
impl<T> DerefMut for Endian<T, Native> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.value
    }
}