summaryrefslogtreecommitdiff
path: root/src/deserialise/deserialise/mod.rs
blob: d24b29037e9ba6ca2ec92fa5666a324d381fb76c (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
// Copyright 2022-2024 Gabriel Bjørnager Jensen.

use crate::deserialise::DStream;
use crate::error::Error;

use std::convert::Infallible;
use std::error::Error as StdError;
use std::mem::size_of;
use std::num::NonZero;

/// Denotes a type capable of being deserialised.
pub trait Deserialise: Sized {
	type Error;

	/// Deserialises the byte stream to an object.
	fn deserialise(stream: &mut DStream) -> Result<Self, Self::Error>;
}

macro_rules! impl_float {
	($type:ty) => {
		impl Deserialise for $type {
			type Error = Error;

			fn deserialise(stream: &mut DStream) -> Result<Self, Self::Error> {
				let data = stream
					.take(size_of::<Self>())?
					.try_into()
					.unwrap();

				Ok(Self::from_be_bytes(data))
			}
		}
	};
}

macro_rules! impl_int {
	($type:ty) => {
		impl Deserialise for $type {
			type Error = Error;

			fn deserialise(stream: &mut DStream) -> Result<Self, Self::Error> {
				let data = stream
					.take(size_of::<Self>())?
					.try_into()
					.unwrap();

				Ok(Self::from_be_bytes(data))
			}
		}

		impl Deserialise for NonZero<$type> {
			type Error = Error;

			fn deserialise(stream: &mut DStream) -> Result<Self, Self::Error> {
				let value = <$type>::deserialise(stream)?;

				NonZero::new(value)
					.ok_or(Error::NullInteger)
			}
		}
	};
}

impl<T: Deserialise<Error: StdError + 'static>, const N: usize> Deserialise for [T; N] {
	type Error = Box<dyn StdError>;

	fn deserialise(stream: &mut DStream) -> Result<Self, Self::Error> {
		let len = usize::try_from(u64::deserialise(stream)?).unwrap();
		if len != N { return Err(Box::new(Error::ArrayLengthMismatch { len, ok_len: N })) };

		let mut buf = Vec::with_capacity(len);
		for _ in 0x0..len { buf.push(Deserialise::deserialise(stream)?); }

		// If we had used the checked unwrap, we would also
		// have to require `T: Debug`.
		Ok(unsafe { buf.try_into().unwrap_unchecked() })
	}
}

impl Deserialise for () {
	type Error = Error;

	fn deserialise(_stream: &mut DStream) -> Result<Self, Self::Error> { Ok(()) }
}

impl Deserialise for bool {
	type Error = Error;

	fn deserialise(stream: &mut DStream) -> Result<Self, Self::Error> {
		let value = u8::deserialise(stream)?;

		match value {
			0x00 => Ok(false),
			0x01 => Ok(true),
			_    => Err(Error::InvalidBoolean { value })
		}
	}
}

impl Deserialise for char {
	type Error = Error;

	fn deserialise(stream: &mut DStream) -> Result<Self, Self::Error> {
		let value = u32::deserialise(stream)?;

		Self::from_u32(value)
			.ok_or(Error::InvalidCodePoint { value })
	}
}

impl Deserialise for Infallible {
	type Error = Error;

	fn deserialise(_stream: &mut DStream) -> Result<Self, Self::Error> { unreachable!() }
}

impl<T: Deserialise<Error: StdError + 'static>> Deserialise for Option<T> {
	type Error = Box<dyn StdError>;

	fn deserialise(stream: &mut DStream) -> Result<Self, Self::Error> {
		let sign = bool::deserialise(stream)?;

		if sign {
			Ok(Some(T::deserialise(stream)?))
		} else {
			Ok(None)
		}
	}
}

impl<T: Deserialise, E: Deserialise> Deserialise for Result<T, E>
where
	<T as Deserialise>::Error: StdError + 'static,
	<E as Deserialise>::Error: StdError + 'static, {
	type Error = Box<dyn StdError>;

	fn deserialise(stream: &mut DStream) -> Result<Self, Self::Error> {
		let sign = bool::deserialise(stream)?;

		let value = if sign {
			Err(E::deserialise(stream)?)
		} else {
			Ok(T::deserialise(stream)?)
		};

		Ok(value)
	}
}

impl_float!(f32);
impl_float!(f64);

impl_int!(i128);
impl_int!(i16);
impl_int!(i32);
impl_int!(i64);
impl_int!(i8);
impl_int!(u128);
impl_int!(u16);
impl_int!(u32);
impl_int!(u64);
impl_int!(u8);