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
use core::fmt;
#[cfg(feature = "alloc")]
use core::ptr;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
use core::marker::PhantomData;
#[cfg(feature = "std")]
use std::error::Error as StdError;
#[cfg(feature = "alloc")]
use core::mem::{align_of, size_of};
#[cfg(feature = "alloc")]
use self::super::trivial::TriviallyTransmutable;
#[derive(Clone, PartialEq, Eq, Hash)]
pub enum Error<'a, S, T> {
Guard(GuardError),
Unaligned(UnalignedError<'a, S, T>),
#[cfg(feature = "alloc")]
IncompatibleVecTarget(IncompatibleVecTargetError<S, T>),
InvalidValue,
}
impl<'a, S, T> Error<'a, S, T> {
#[cfg(feature = "alloc")]
pub fn copy(self) -> Result<Vec<T>, Error<'a, S, T>>
where T: TriviallyTransmutable
{
match self {
Error::Unaligned(e) => Ok(e.copy()),
Error::IncompatibleVecTarget(e) => Ok(e.copy()),
e => Err(e),
}
}
#[cfg(feature = "alloc")]
pub unsafe fn copy_unchecked(self) -> Result<Vec<T>, Error<'a, S, T>> {
match self {
Error::Unaligned(e) => Ok(e.copy_unchecked()),
Error::IncompatibleVecTarget(e) => Ok(e.copy_unchecked()),
e => Err(e),
}
}
pub fn without_src<'z>(self) -> Error<'z, S, T> {
match self {
Error::Unaligned(UnalignedError { source: _, offset, phantom }) => {
Error::Unaligned(UnalignedError {
source: &[],
offset: offset,
phantom: phantom,
})
}
Error::Guard(e) => Error::Guard(e),
Error::InvalidValue => Error::InvalidValue,
#[cfg(feature = "alloc")]
Error::IncompatibleVecTarget(e) => Error::IncompatibleVecTarget(e),
}
}
}
impl<'a, S, T> fmt::Debug for Error<'a, S, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::Guard(e) => write!(f, "Guard({:?})", e),
Error::Unaligned(e) => write!(f, "Unaligned({:?})", e),
Error::InvalidValue => f.write_str("InvalidValue"),
#[cfg(feature = "alloc")]
Error::IncompatibleVecTarget(_) => f.write_str("IncompatibleVecTarget"),
}
}
}
#[cfg(feature = "std")]
#[allow(deprecated)]
impl<'a, S, T> StdError for Error<'a, S, T> {
fn description(&self) -> &str {
match self {
Error::Guard(e) => e.description(),
Error::Unaligned(e) => e.description(),
Error::InvalidValue => "invalid target value",
Error::IncompatibleVecTarget(e) => e.description(),
}
}
}
impl<'a, S, T> fmt::Display for Error<'a, S, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::Guard(e) => e.fmt(f),
Error::Unaligned(e) => e.fmt(f),
Error::InvalidValue => f.write_str("Invalid target value"),
#[cfg(feature = "alloc")]
Error::IncompatibleVecTarget(e) => e.fmt(f),
}
}
}
impl<'a, S, T> From<GuardError> for Error<'a, S, T> {
fn from(o: GuardError) -> Self {
Error::Guard(o)
}
}
impl<'a, S, T> From<UnalignedError<'a, S, T>> for Error<'a, S, T> {
fn from(o: UnalignedError<'a, S, T>) -> Self {
Error::Unaligned(o)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct GuardError {
pub required: usize,
pub actual: usize,
pub reason: ErrorReason,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ErrorReason {
NotEnoughBytes,
TooManyBytes,
InexactByteCount,
}
#[cfg(feature = "std")]
impl StdError for GuardError {
fn description(&self) -> &str {
self.reason.description()
}
}
impl fmt::Display for GuardError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} (required: {}, actual: {})", self.reason.description(), self.required, self.actual)
}
}
impl ErrorReason {
pub fn description(self) -> &'static str {
match self {
ErrorReason::NotEnoughBytes => "Not enough bytes to fill type",
ErrorReason::TooManyBytes => "Too many bytes for type",
ErrorReason::InexactByteCount => "Not exactly the amount of bytes for type",
}
}
}
#[cfg(feature = "alloc")]
unsafe fn copy_to_vec_unchecked<S, T>(data: &[S]) -> Vec<T> {
let len = data.len() * size_of::<S>() / size_of::<T>();
let mut out = Vec::with_capacity(len);
ptr::copy_nonoverlapping(data.as_ptr() as *const u8, out.as_mut_ptr() as *mut u8, len * size_of::<T>());
out.set_len(len);
out
}
#[derive(Clone, Eq, Hash, PartialEq)]
pub struct UnalignedError<'a, S, T> {
pub offset: usize,
pub source: &'a [S],
phantom: PhantomData<T>,
}
impl<'a, S, T> UnalignedError<'a, S, T> {
pub fn new(offset: usize, source: &'a [S]) -> Self {
UnalignedError {
offset: offset,
source: source,
phantom: PhantomData,
}
}
#[cfg(feature = "alloc")]
pub unsafe fn copy_unchecked(&self) -> Vec<T> {
copy_to_vec_unchecked::<S, T>(self.source)
}
#[cfg(feature = "alloc")]
pub fn copy(&self) -> Vec<T>
where T: TriviallyTransmutable
{
unsafe {
self.copy_unchecked()
}
}
}
impl<'a, S, T> fmt::Debug for UnalignedError<'a, S, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
struct Source {
len: usize,
}
impl fmt::Debug for Source {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("&[S]")
.field("len", &self.len)
.finish()
}
}
f.debug_struct("UnalignedError")
.field("offset", &self.offset)
.field("source", &Source { len: self.source.len() })
.finish()
}
}
#[cfg(feature = "std")]
impl<'a, S, T> StdError for UnalignedError<'a, S, T> {
fn description(&self) -> &str {
"data is unaligned"
}
}
impl<'a, S, T> fmt::Display for UnalignedError<'a, S, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "data is unaligned (off by {} bytes)", self.offset)
}
}
#[cfg(feature = "alloc")]
#[derive(Clone, Eq, Hash, PartialEq)]
pub struct IncompatibleVecTargetError<S, T> {
pub vec: Vec<S>,
target: PhantomData<T>,
}
#[cfg(feature = "alloc")]
impl<S, T> IncompatibleVecTargetError<S, T> {
pub fn new(vec: Vec<S>) -> Self {
IncompatibleVecTargetError {
vec: vec,
target: PhantomData,
}
}
pub unsafe fn copy_unchecked(&self) -> Vec<T> {
copy_to_vec_unchecked::<S, T>(&self.vec)
}
pub fn copy(&self) -> Vec<T>
where T: TriviallyTransmutable
{
unsafe {
self.copy_unchecked()
}
}
}
#[cfg(feature = "alloc")]
impl<'a, S, T> From<IncompatibleVecTargetError<S, T>> for Error<'a, S, T> {
fn from(e: IncompatibleVecTargetError<S, T>) -> Self {
Error::IncompatibleVecTarget(e)
}
}
#[cfg(feature = "alloc")]
impl<S, T> fmt::Debug for IncompatibleVecTargetError<S, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("IncompatibleVecTargetError")
.field("size_of<S>", &size_of::<S>())
.field("align_of<S>", &align_of::<S>())
.field("size_of<T>", &size_of::<T>())
.field("align_of<T>", &align_of::<T>())
.finish()
}
}
#[cfg(feature = "std")]
impl<S, T> StdError for IncompatibleVecTargetError<S, T> {
fn description(&self) -> &str {
"incompatible target type"
}
}
#[cfg(feature = "alloc")]
impl<S, T> fmt::Display for IncompatibleVecTargetError<S, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
"incompatible target type (size: {}, align: {}) for transmutation from source (size: {}, align: {})",
size_of::<T>(),
align_of::<T>(),
size_of::<S>(),
align_of::<S>())
}
}