summaryrefslogtreecommitdiff
path: root/bzipper/src/serialise/mod.rs
blob: 9c89e091247f2b95b91519a1e8fc96213914fb3c (plain) (blame)
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
// Copyright 2024 Gabriel Bjørnager Jensen.
//
// This file is part of bzipper.
//
// bzipper is free software: you can redistribute
// it and/or modify it under the terms of the GNU
// Lesser General Public License as published by
// the Free Software Foundation, either version 3
// of the License, or (at your option) any later
// version.
//
// bzipper is distributed in the hope that it will
// be useful, but WITHOUT ANY WARRANTY; without
// even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Less-
// er General Public License along with bzipper. If
// not, see <https://www.gnu.org/licenses/>.

#[cfg(test)]
mod test;

use crate::{Error, Result, Sstream};

use core::{convert::Infallible, marker::PhantomData};

mod tuple;

/// Denotes a type capable of being serialised.
///
/// It is recommended to simply derive this trait for custom types.
/// It can, however, be manually implemented:
///
/// ```
/// use bzipper::{Result, Serialise, Sstream};
///
/// struct Foo {
///     bar: u16,
///     baz: f32,
/// }
///
/// impl Serialise for Foo {
///     const SERIALISED_SIZE: usize = u16::SERIALISED_SIZE + f32::SERIALISED_SIZE;
///
///     fn serialise(&self, buf: &mut [u8]) -> Result<()> {
///         debug_assert_eq!(buf.len(), Self::SERIALISED_SIZE);
///
///         // Serialise fields using chaining.
///
///         let mut stream = Sstream::new(buf);
///
///         stream.append(&self.bar)?;
///         stream.append(&self.baz)?;
///
///         Ok(())
///     }
/// }
/// ```
///
/// Implementors of this trait should make sure that [`SERIALISED_SIZE`](Serialise::SERIALISED_SIZE) is properly defined.
/// This value indicates the definitive size of any serialisation of the `Self` type.
pub trait Serialise: Sized {
	/// The amount of bytes that result from a serialisation.
	///
	/// Implementors of this trait should make sure that no serialisation (or deserialisation) uses more than the amount specified by this constant.
	/// When using these traits, always assume that exactly this amount has or will be used.
	const SERIALISED_SIZE: usize;

	/// Serialises `self` into a slice.
	///
	/// In most cases it is wiser to chain serialisations using [`Sstream`] instead of using this method directly.
	///
	/// # Errors
	///
	/// If serialisation failed, e.g. by an unencodable value being provided, an error is returned.
	///
	/// # Panics
	///
	/// This method will usually panic if the provided slice has a length *less* than the value of `SERIALISED_SIZE`.
	/// Official implementations of this trait (including those that are derived) always panic in debug mode if the provided slice has a length that is different at all.
	fn serialise(&self, buf: &mut [u8]) -> Result<()>;
}

macro_rules! impl_numeric {
	($ty:ty) => {
		impl ::bzipper::Serialise for $ty {
			const SERIALISED_SIZE: usize = size_of::<$ty>();

			#[inline]
			fn serialise(&self, buf: &mut [u8]) -> Result<()> {
				debug_assert_eq!(buf.len(), Self::SERIALISED_SIZE);

				::core::debug_assert_eq!(buf.len(), Self::SERIALISED_SIZE);

				let data = self.to_be_bytes();
				buf.copy_from_slice(&data);

				Ok(())
			}
		}
	};
}

macro_rules! impl_non_zero {
	($ty:ty) => {
		impl ::bzipper::Serialise for ::core::num::NonZero<$ty> {
			const SERIALISED_SIZE: usize = ::core::mem::size_of::<$ty>();

			#[inline(always)]
			fn serialise(&self, buf: &mut [u8]) -> Result<()> {
				debug_assert_eq!(buf.len(), Self::SERIALISED_SIZE);

				self.get().serialise(buf)
			}
		}
	};
}

impl<T: Serialise, const N: usize> Serialise for [T; N] {
	const SERIALISED_SIZE: usize = T::SERIALISED_SIZE * N;

	fn serialise(&self, buf: &mut [u8]) -> Result<()> {
		debug_assert_eq!(buf.len(), Self::SERIALISED_SIZE);

		let mut stream = Sstream::new(buf);

		for v in self { stream.append(v)? }

		Ok(())
	}
}

impl Serialise for bool {
	const SERIALISED_SIZE: usize = u8::SERIALISED_SIZE;

	#[inline(always)]
	fn serialise(&self, buf: &mut [u8]) -> Result<()> {
		debug_assert_eq!(buf.len(), Self::SERIALISED_SIZE);

		u8::from(*self).serialise(buf)
	}
}

impl Serialise for char {
	const SERIALISED_SIZE: usize = u32::SERIALISED_SIZE;

	#[inline(always)]
	fn serialise(&self, buf: &mut [u8]) -> Result<()> {
		debug_assert_eq!(buf.len(), Self::SERIALISED_SIZE);

		u32::from(*self).serialise(buf)
	}

}

// Especially useful for `Result<T, Infallible>`.
// *If* that is needed, of course.
impl Serialise for Infallible {
	const SERIALISED_SIZE: usize = 0x0;

	#[inline(always)]
	fn serialise(&self, _buf: &mut [u8]) -> Result<()> { unreachable!() }

}

impl Serialise for isize {
	const SERIALISED_SIZE: usize = i32::SERIALISED_SIZE;

	#[inline]
	fn serialise(&self, buf: &mut [u8]) -> Result<()> {
		debug_assert_eq!(buf.len(), Self::SERIALISED_SIZE);

		let value = i32::try_from(*self)
			.map_err(|_| Error::IsizeOutOfRange { value: *self })?;

		value.serialise(buf)
	}
}

impl<T: Serialise> Serialise for Option<T> {
	const SERIALISED_SIZE: usize = bool::SERIALISED_SIZE + T::SERIALISED_SIZE;

	fn serialise(&self, buf: &mut [u8]) -> Result<()> {
		debug_assert_eq!(buf.len(), Self::SERIALISED_SIZE);

		// The first element is of type `bool` and is
		// called the "sign." It signifies whether there is
		// a following element or not. The remaining bytes
		// are preserved if `self` is `None`.

		let mut stream = Sstream::new(buf);

		match *self {
			None => {
				stream.append(&false)?;
				// No need to zero-fill.
			},

			Some(ref v) => {
				stream.append(&true)?;
				stream.append(v)?;
			},
		};

		Ok(())
	}
}

impl<T> Serialise for PhantomData<T> {
	const SERIALISED_SIZE: usize = size_of::<Self>();

	#[inline(always)]
	fn serialise(&self, buf: &mut [u8]) -> Result<()> {
		debug_assert_eq!(buf.len(), Self::SERIALISED_SIZE);

		Ok(())
	}
}

impl<T, E> Serialise for core::result::Result<T, E>
where
	T: Serialise,
	E: Serialise, {
	const SERIALISED_SIZE: usize = bool::SERIALISED_SIZE + if size_of::<T>() > size_of::<E>() { size_of::<T>() } else { size_of::<E>() };

	fn serialise(&self, buf: &mut [u8]) -> Result<()> {
		debug_assert_eq!(buf.len(), Self::SERIALISED_SIZE);

		let mut stream = Sstream::new(buf);

		// Remember the descriminant.
		match *self {
			Ok(ref v) => {
				stream.append(&false)?;
				stream.append(v)?;
			},

			Err(ref e) => {
				stream.append(&true)?;
				stream.append(e)?;
			},
		};

		Ok(())
	}
}

impl Serialise for () {
	const SERIALISED_SIZE: usize = size_of::<Self>();

	#[inline(always)]
	fn serialise(&self, buf: &mut [u8]) -> Result<()> {
		debug_assert_eq!(buf.len(), Self::SERIALISED_SIZE);

		Ok(())
	}
}

impl Serialise for usize {
	const SERIALISED_SIZE: Self = u32::SERIALISED_SIZE;

	fn serialise(&self, buf: &mut [u8]) -> Result<()> {
		debug_assert_eq!(buf.len(), Self::SERIALISED_SIZE);

		let value = u32::try_from(*self)
			.map_err(|_| Error::UsizeOutOfRange { value: *self })?;

		value.serialise(buf)
	}
}

//impl_numeric!(f128);
//impl_numeric!(f16);
impl_numeric!(f32);
impl_numeric!(f64);
impl_numeric!(i128);
impl_numeric!(i16);
impl_numeric!(i32);
impl_numeric!(i64);
impl_numeric!(i8);
impl_numeric!(u128);
impl_numeric!(u16);
impl_numeric!(u32);
impl_numeric!(u64);
impl_numeric!(u8);

impl_non_zero!(i128);
impl_non_zero!(i16);
impl_non_zero!(i32);
impl_non_zero!(i64);
impl_non_zero!(i8);
impl_non_zero!(isize);
impl_non_zero!(u128);
impl_non_zero!(u16);
impl_non_zero!(u32);
impl_non_zero!(u64);
impl_non_zero!(u8);
impl_non_zero!(usize);