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
/*
 * SPDX-FileCopyrightText: 2023 Inria
 * SPDX-FileCopyrightText: 2023 Sebastiano Vigna
 *
 * SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later
 */

/*!

Implementations for primitive types, `()`, [`PhantomData`] and [`Option`].

*/

use crate::prelude::*;
use common_traits::NonZero;
use core::hash::Hash;
use core::marker::PhantomData;
use core::mem::size_of;
use core::num::{
    NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize, NonZeroU128,
    NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize,
};
use deser::*;
use ser::*;

macro_rules! impl_prim_type_hash {
    ($($ty:ty),*) => {$(
        impl CopyType for $ty {
            type Copy = Zero;
        }

        impl TypeHash for $ty {
            fn type_hash(
                hasher: &mut impl core::hash::Hasher,
            ) {
                stringify!($ty).hash(hasher);
            }
        }

        impl ReprHash for $ty {
            fn repr_hash(hasher: &mut impl core::hash::Hasher, offset_of: &mut usize) {
                crate::traits::std_repr_hash::<Self>(hasher, offset_of)
            }
        }

        impl MaxSizeOf for $ty {
            fn max_size_of() -> usize {
                size_of::<$ty>()
            }
        }
    )*};
}

macro_rules! impl_prim_ser_des {
    ($($ty:ty),*) => {$(
		impl SerializeInner for $ty {
            // Note that primitive types are declared zero-copy to be able to
            // be part of zero-copy types, but we actually deserialize
            // them in isolation as values.
            const IS_ZERO_COPY: bool = true;
            const ZERO_COPY_MISMATCH: bool = false;

            #[inline(always)]
            fn _serialize_inner(&self, backend: &mut impl WriteWithNames) -> ser::Result<()> {
                backend.write_all(&self.to_ne_bytes())
            }
        }

		impl DeserializeInner for $ty {
            #[inline(always)]
            fn _deserialize_full_inner(backend: &mut impl ReadWithPos) -> deser::Result<$ty> {
                let mut buf = [0; size_of::<$ty>()];
                backend.read_exact(&mut buf)?;
                Ok(<$ty>::from_ne_bytes(buf))
            }
            type DeserType<'a> = Self;
            #[inline(always)]
            fn _deserialize_eps_inner<'a>(
                backend: &mut SliceWithPos<'a>,
            ) -> deser::Result<Self::DeserType<'a>> {
                let res = <$ty>::from_ne_bytes(
                        backend.data[..size_of::<$ty>()]
                            .try_into()
                            .unwrap());

                backend.skip(size_of::<$ty>());
                Ok(res)
            }
        }
    )*};
}

impl_prim_type_hash!(isize, i8, i16, i32, i64, i128, usize, u8, u16, u32, u64, u128, f32, f64);
impl_prim_ser_des!(isize, i8, i16, i32, i64, i128, usize, u8, u16, u32, u64, u128, f32, f64);

macro_rules! impl_nonzero_ser_des {
    ($($ty:ty),*) => {$(
		impl SerializeInner for $ty {
            // Note that primitive types are declared zero-copy to be able to
            // be part of zero-copy types, but we actually deserialize
            // them in isolation as values.
            const IS_ZERO_COPY: bool = true;
            const ZERO_COPY_MISMATCH: bool = false;

            #[inline(always)]
            fn _serialize_inner(&self, backend: &mut impl WriteWithNames) -> ser::Result<()> {
                backend.write_all(&self.get().to_ne_bytes())
            }
        }

		impl DeserializeInner for $ty {
            #[inline(always)]
            fn _deserialize_full_inner(backend: &mut impl ReadWithPos) -> deser::Result<$ty> {
                let mut buf = [0; size_of::<$ty>()];
                backend.read_exact(&mut buf)?;
                Ok(<$ty as NonZero>::BaseType::from_ne_bytes(buf).try_into().unwrap())
            }
            type DeserType<'a> = Self;
            #[inline(always)]
            fn _deserialize_eps_inner<'a>(
                backend: &mut SliceWithPos<'a>,
            ) -> deser::Result<Self::DeserType<'a>> {
                let res = <$ty as NonZero>::BaseType::from_ne_bytes(
                        backend.data[..size_of::<$ty>()]
                            .try_into()
                            .unwrap()).try_into().unwrap();

                backend.skip(size_of::<$ty>());
                Ok(res)
            }
        }
    )*};
}

impl_prim_type_hash!(
    NonZeroIsize,
    NonZeroI8,
    NonZeroI16,
    NonZeroI32,
    NonZeroI64,
    NonZeroI128,
    NonZeroUsize,
    NonZeroU8,
    NonZeroU16,
    NonZeroU32,
    NonZeroU64,
    NonZeroU128
);

impl_nonzero_ser_des!(
    NonZeroIsize,
    NonZeroI8,
    NonZeroI16,
    NonZeroI32,
    NonZeroI64,
    NonZeroI128,
    NonZeroUsize,
    NonZeroU8,
    NonZeroU16,
    NonZeroU32,
    NonZeroU64,
    NonZeroU128
);

impl_prim_type_hash!(bool, char, ());

// Booleans are zero-copy serialized as u8.

impl SerializeInner for bool {
    const IS_ZERO_COPY: bool = true;
    const ZERO_COPY_MISMATCH: bool = false;

    #[inline(always)]
    fn _serialize_inner(&self, backend: &mut impl WriteWithNames) -> ser::Result<()> {
        let val = if *self { 1 } else { 0 };
        backend.write_all(&[val])
    }
}

impl DeserializeInner for bool {
    #[inline(always)]
    fn _deserialize_full_inner(backend: &mut impl ReadWithPos) -> deser::Result<bool> {
        Ok(u8::_deserialize_full_inner(backend)? != 0)
    }
    type DeserType<'a> = Self;
    #[inline(always)]
    fn _deserialize_eps_inner<'a>(
        backend: &mut SliceWithPos<'a>,
    ) -> deser::Result<Self::DeserType<'a>> {
        let res = backend.data[0] != 0;
        backend.skip(1);
        Ok(res)
    }
}

// Chars are zero-copy serialized as u32.

impl SerializeInner for char {
    const IS_ZERO_COPY: bool = true;
    const ZERO_COPY_MISMATCH: bool = false;

    #[inline(always)]
    fn _serialize_inner(&self, backend: &mut impl WriteWithNames) -> ser::Result<()> {
        (*self as u32)._serialize_inner(backend)
    }
}

impl DeserializeInner for char {
    #[inline(always)]
    fn _deserialize_full_inner(backend: &mut impl ReadWithPos) -> deser::Result<Self> {
        Ok(char::from_u32(u32::_deserialize_full_inner(backend)?).unwrap())
    }
    type DeserType<'a> = Self;
    #[inline(always)]
    fn _deserialize_eps_inner<'a>(
        backend: &mut SliceWithPos<'a>,
    ) -> deser::Result<Self::DeserType<'a>> {
        Ok(char::from_u32(u32::_deserialize_eps_inner(backend)?).unwrap())
    }
}

// () is zero-copy. No reading or writing is performed when (de)serializing it.

impl SerializeInner for () {
    const IS_ZERO_COPY: bool = true;
    const ZERO_COPY_MISMATCH: bool = false;

    #[inline(always)]
    fn _serialize_inner(&self, _backend: &mut impl WriteWithNames) -> ser::Result<()> {
        Ok(())
    }
}

impl DeserializeInner for () {
    #[inline(always)]
    fn _deserialize_full_inner(_backend: &mut impl ReadWithPos) -> deser::Result<Self> {
        Ok(())
    }
    type DeserType<'a> = Self;
    #[inline(always)]
    fn _deserialize_eps_inner<'a>(
        _backend: &mut SliceWithPos<'a>,
    ) -> deser::Result<Self::DeserType<'a>> {
        Ok(())
    }
}

// PhantomData is zero-copy. No reading or writing is performed when
// (de)serializing it.

impl<T: ?Sized> CopyType for PhantomData<T> {
    type Copy = Zero;
}

impl<T: ?Sized> MaxSizeOf for PhantomData<T> {
    fn max_size_of() -> usize {
        0
    }
}

impl<T: ?Sized + TypeHash> TypeHash for PhantomData<T> {
    #[inline(always)]
    fn type_hash(hasher: &mut impl core::hash::Hasher) {
        "PhantomData".hash(hasher);
        T::type_hash(hasher);
    }
}

impl<T: ?Sized> ReprHash for PhantomData<T> {
    #[inline(always)]
    fn repr_hash(_hasher: &mut impl core::hash::Hasher, _offset_of: &mut usize) {}
}

impl<T: ?Sized + TypeHash> SerializeInner for PhantomData<T> {
    const IS_ZERO_COPY: bool = true;
    const ZERO_COPY_MISMATCH: bool = false;

    #[inline(always)]
    fn _serialize_inner(&self, _backend: &mut impl WriteWithNames) -> ser::Result<()> {
        Ok(())
    }
}

impl<T: ?Sized + TypeHash> DeserializeInner for PhantomData<T> {
    #[inline(always)]
    fn _deserialize_full_inner(_backend: &mut impl ReadWithPos) -> deser::Result<Self> {
        Ok(PhantomData::<T>)
    }
    type DeserType<'a> = Self;
    #[inline(always)]
    fn _deserialize_eps_inner<'a>(
        _backend: &mut SliceWithPos<'a>,
    ) -> deser::Result<Self::DeserType<'a>> {
        Ok(PhantomData)
    }
}

// Options are deep-copy types serialized as a one-byte tag (0 for None, 1 for Some) followed, in case, by the value.

impl<T> CopyType for Option<T> {
    type Copy = Deep;
}

impl<T: TypeHash> TypeHash for Option<T> {
    #[inline(always)]
    fn type_hash(hasher: &mut impl core::hash::Hasher) {
        "Option".hash(hasher);
        T::type_hash(hasher);
    }
}

impl<T: ReprHash> ReprHash for Option<T> {
    fn repr_hash(hasher: &mut impl core::hash::Hasher, offset_of: &mut usize) {
        *offset_of = 0;
        T::repr_hash(hasher, offset_of);
    }
}

impl<T: SerializeInner> SerializeInner for Option<T> {
    const IS_ZERO_COPY: bool = false;
    const ZERO_COPY_MISMATCH: bool = false;

    #[inline(always)]
    fn _serialize_inner(&self, backend: &mut impl WriteWithNames) -> ser::Result<()> {
        match self {
            None => backend.write("Tag", &0_u8),
            Some(val) => {
                backend.write("Tag", &1_u8)?;
                backend.write("Some", val)
            }
        }
    }
}

impl<T: DeserializeInner> DeserializeInner for Option<T> {
    #[inline(always)]
    fn _deserialize_full_inner(backend: &mut impl ReadWithPos) -> deser::Result<Self> {
        let tag = u8::_deserialize_full_inner(backend)?;
        match tag {
            0 => Ok(None),
            1 => Ok(Some(T::_deserialize_full_inner(backend)?)),
            _ => Err(deser::Error::InvalidTag(tag as usize)),
        }
    }
    type DeserType<'a> = Option<<T as DeserializeInner>::DeserType<'a>>;
    #[inline(always)]
    fn _deserialize_eps_inner<'a>(
        backend: &mut SliceWithPos<'a>,
    ) -> deser::Result<Self::DeserType<'a>> {
        let tag = u8::_deserialize_full_inner(backend)?;
        match tag {
            0 => Ok(None),
            1 => Ok(Some(T::_deserialize_eps_inner(backend)?)),
            _ => Err(deser::Error::InvalidTag(backend.data[0] as usize)),
        }
    }
}