nibblecode 0.1.0

A serialization format based on rkyv
Documentation
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
#![feature(
	allocator_api,
	maybe_uninit_slice,
	offset_of_enum,
	ptr_alignment_type,
	ptr_metadata
)]

use core::fmt::{self, Debug, Formatter};
use core::mem::MaybeUninit;
use core::ops::Range;
use core::ptr::{Alignment, read};
use core::str::Utf8Error;

use aligned_alloc::{AlignedAlloc, new_uninit_boxed_slice};

#[macro_use]
mod _macros;
pub mod aligned_alloc;
pub mod boxed;
mod impls;
pub mod list;
pub mod option;
pub mod primitive;
pub mod result;
pub mod string;
pub mod tuple;
pub mod util;

#[cfg(test)]
pub mod test;

pub use nibblecode_derive::Serialize;
use util::check_alignment;

pub enum SerializeError {
	SizedOutOfRange,
	OverflowedPointer,
	ListTooLong,
	StringTooLong,
	BufferTooSmall { serialized_size: usize, len: usize },
}

impl Debug for SerializeError {
	fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
		match self {
			SerializeError::SizedOutOfRange => f.write_str("pointer sized magnitude too big"),
			SerializeError::OverflowedPointer => f.write_str("overflowed pointer size"),
			SerializeError::ListTooLong => f.write_str("list was too long for the pointer size"),
			SerializeError::StringTooLong => {
				f.write_str("string was too long for the archived representation")
			}
			SerializeError::BufferTooSmall {
				serialized_size,
				len,
			} => write!(
				f,
				"buffer too small: trying to write {serialized_size} bytes into buffer of length \
				 {len}",
			),
		}
	}
}

pub enum VerifyError {
	InvalidPointer {
		address: *const u8,
		size: usize,
		range: Range<*const u8>,
	},
	ListTooLong,
	StringTooLong,
	Utf8Error(Utf8Error),
	NonZeroCheckError,
	InvalidEnumDiscriminantError {
		enum_name: &'static str,
		invalid_discriminant: u8,
	},
	UnalignedPointer {
		address: usize,
		align: Alignment,
	},
	InvalidChar,
	InvalidBool {
		byte: u8,
	},
}

impl Debug for VerifyError {
	fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
		match self {
			VerifyError::InvalidPointer {
				address,
				size,
				range,
			} => write!(
				f,
				"pointer overran buffer: ptr {address:p} size {size} in range {range:p}",
			),
			VerifyError::ListTooLong => f.write_str("list size was > `isize::MAX`"),
			VerifyError::StringTooLong => f.write_str("string size was > `isize::MAX`"),
			VerifyError::Utf8Error(utf8_error) => utf8_error.fmt(f),
			VerifyError::NonZeroCheckError => f.write_str("nonzero integer is zero"),
			VerifyError::InvalidEnumDiscriminantError {
				enum_name,
				invalid_discriminant,
			} => write!(
				f,
				"invalid discriminant '{invalid_discriminant}' for enum '{enum_name}'"
			),
			VerifyError::UnalignedPointer { address, align } => write!(
				f,
				"unaligned pointer: ptr {address:p} unaligned for alignment {align:?}"
			),
			VerifyError::InvalidChar => f.write_str("char out of range"),
			VerifyError::InvalidBool { byte } => {
				write!(f, "bool set to invalid byte {byte}, expected either 0 or 1")
			}
		}
	}
}

/// A type that can be serialized and accessed in it's serialized form (as `Self::Archived`)
pub trait Serialize {
	/// The serialized type
	type Archived;

	/// The minimum alignment required by this type
	const ALIGN: Alignment;

	/// An optimization flag that allows the bytes of this type to be copied
	/// directly to a buffer instead of calling `serialize`
	const COPY_OPTIMIZATION: bool = false;

	/// Serialize this type.
	///
	/// Implementations must fully initialize `out` and initialize into the start of `heap`.
	///
	/// # Safety
	/// `out` and `heap` must be valid pointers (unless `T` is a ZST), and `heap` must have
	/// at least the number of bytes returned by `Serialized::serialized_size`
	unsafe fn serialize(
		&self,
		out: *mut MaybeUninit<Self::Archived>,
		heap: *mut MaybeUninit<u8>,
	) -> usize;

	/// How many bytes will type type take up in the 'heap', including padding, if it was
	/// serialized starting at this offset in the buffer. Assume the entire buffer is properly
	/// aligned.
	///
	/// Types that are entirely self-contained should always return 0.
	fn serialized_size(&self, offset: usize) -> Result<usize, SerializeError>;

	/// Check that the data in the buffer is valid. `buffer_end` is a pointer to just after the
	/// buffer, you should not attempt to read past it.
	///
	/// # Safety
	/// `this` must be a valid pointer, and `buffer_end` must be after it, and part of the
	/// same allocation.
	unsafe fn verify(this: *const Self::Archived, buffer_end: *const u8)
	-> Result<(), VerifyError>;
}

/// Serialize a value and write the bytes to the given buffer without checking the length or
/// validity.
///
/// # Safety
/// `buffer` must be large enough to store the given value
///
/// # Example
///
/// ```
/// #![feature(ptr_alignment_type)]
///
/// use core::fmt::Debug;
///
/// use nibblecode::aligned_alloc::new_uninit_boxed_slice;
/// use nibblecode::{Serialize, access, to_bytes_in_unchecked};
///
/// #[derive(Serialize, Debug)]
/// #[nibblecode(compare(PartialEq), derive(Debug))]
/// struct Example {
/// 	name: String,
/// 	value: i32,
/// }
///
/// let value = Example {
/// 	name: "pi".to_string(),
/// 	value: 31415926,
/// };
///
/// let mut bytes = new_uninit_boxed_slice::<Example>(2);
/// let bytes = unsafe {
/// 	to_bytes_in_unchecked(&value, &mut bytes);
/// 	bytes.assume_init()
/// };
///
/// let archived = access::<Example>(&bytes).unwrap();
///
/// assert_eq!(*archived, value);
/// ```
#[inline]
pub unsafe fn to_bytes_in_unchecked<'a, T: Serialize + ?Sized>(
	value: &T,
	buffer: &'a mut [MaybeUninit<u8>],
) -> usize {
	unsafe {
		if T::COPY_OPTIMIZATION {
			*(buffer as *mut [MaybeUninit<u8>]).cast() =
				MaybeUninit::new(read((value as *const T).cast::<T::Archived>()));

			size_of::<T::Archived>()
		} else {
			// SAFETY: the caller is responsible for making sure the buffer is large enough
			size_of::<T::Archived>()
				+ value.serialize(
					(&raw mut *buffer).cast(),
					(&raw mut *buffer)
						.cast::<MaybeUninit<u8>>()
						.add(size_of::<T::Archived>()),
				)
		}
	}
}

/// Serialize a value and write the bytes to the given buffer, returning th number of bytes
/// written.
///
/// # Safety
/// `buffer` must be large enough to store the given value
///
/// # Example
///
/// ```
/// #![feature(ptr_alignment_type)]
///
/// use core::fmt::Debug;
///
/// use nibblecode::aligned_alloc::new_uninit_boxed_slice;
/// use nibblecode::{Serialize, access, to_bytes_in};
///
/// #[derive(Serialize, Debug)]
/// #[nibblecode(compare(PartialEq), derive(Debug))]
/// struct Example {
/// 	name: String,
/// 	value: i32,
/// }
///
/// let value = Example {
/// 	name: "pi".to_string(),
/// 	value: 31415926,
/// };
///
/// let mut bytes = new_uninit_boxed_slice::<Example>(2);
/// to_bytes_in(&value, &mut bytes).unwrap();
/// let bytes = unsafe { bytes.assume_init() };
///
/// let archived = access::<Example>(&bytes).unwrap();
///
/// assert_eq!(*archived, value);
/// ```
#[inline]
pub fn to_bytes_in<'a, T: Serialize + ?Sized>(
	value: &T,
	buffer: &'a mut [MaybeUninit<u8>],
) -> Result<usize, SerializeError> {
	value
		.serialized_size(size_of::<T::Archived>())
		.and_then(|heap_size| {
			let serialized_size = size_of::<T::Archived>() + heap_size;
			if serialized_size <= buffer.len() {
				unsafe {
					to_bytes_in_unchecked(value, &mut *buffer);
				}
				// We choose to return the pre-calculated size, rather than the one calculated
				// while serializing, because it allows the compiler to remove some of the extra
				// size calculations
				Ok(serialized_size)
			} else {
				Err(SerializeError::BufferTooSmall {
					serialized_size,
					len: buffer.len(),
				})
			}
		})
}

/// Serialize a value to bytes.
///
/// Returns the serialized bytes in a [`Box<[u8]>`].
///
/// # Example
///
/// ```
/// #![feature(ptr_alignment_type)]
///
/// use core::fmt::Debug;
///
/// use nibblecode::{Serialize, access, to_bytes};
///
/// #[derive(Serialize, Debug)]
/// #[nibblecode(compare(PartialEq), derive(Debug))]
/// struct Example {
/// 	name: String,
/// 	value: i32,
/// }
///
/// let value = Example {
/// 	name: "pi".to_string(),
/// 	value: 31415926,
/// };
///
/// let bytes = to_bytes(&value).unwrap();
/// let deserialized = access::<Example>(&bytes).unwrap();
///
/// assert_eq!(*deserialized, value);
/// ```
#[inline]
pub fn to_bytes<T: Serialize + ?Sized>(
	value: &T,
) -> Result<Box<[u8], AlignedAlloc<T>>, SerializeError> {
	value
		.serialized_size(size_of::<T::Archived>())
		.map(|heap_size| {
			let mut buffer = new_uninit_boxed_slice::<T>(heap_size);

			unsafe {
				to_bytes_in_unchecked(value, &mut *buffer);

				// SAFETY: `to_bytes_in_unchecked` should've initialized everything
				buffer.assume_init()
			}
		})
}

/// Return a pointer to the archived data without verifying it.
#[inline]
#[must_use]
pub unsafe fn access_ptr_unchecked<T: Serialize + ?Sized>(bytes: &[u8]) -> *const T::Archived {
	<*const [u8]>::cast(bytes)
}

/// Verify this buffer and return a pointer to the archived data.
#[inline]
pub fn access_ptr<T: Serialize + ?Sized>(bytes: &[u8]) -> Result<*const T::Archived, VerifyError> {
	let bytes = bytes as *const [u8];

	let address = bytes.cast::<u8>();

	check_alignment(address, T::ALIGN)?;

	let archived = bytes.cast::<T::Archived>();

	unsafe {
		// SAFETY: this should never overflow, see the comment in `[T]::as_ptr_range`
		let buffer_end = address.add(bytes.len());

		if bytes.len() < size_of::<T::Archived>() {
			return Err(VerifyError::InvalidPointer {
				address,
				size: size_of::<T::Archived>(),
				range: address..buffer_end,
			});
		}

		// SAFETY: `archived` is valid, since we just made sure `bytes` had enough bytes for it.
		// `buffer_end` is also correct.
		T::verify(archived, buffer_end)?;

		Ok(archived)
	}
}

/// Access a byte slice.
///
/// This function does not check that the bytes are valid to access. Use
/// [`access`] to safely access the buffer using validation.
///
/// # Safety
///
/// The byte slice must represent a valid archived type when accessed at the
/// default root position.
///
/// # Example
///
/// ```
/// #![feature(ptr_alignment_type)]
///
/// use core::fmt::Debug;
///
/// use nibblecode::{Serialize, access_unchecked, to_bytes};
///
/// #[derive(Serialize)]
/// struct Example {
/// 	name: String,
/// 	value: i32,
/// }
///
/// let value = Example {
/// 	name: "pi".to_string(),
/// 	value: 31415926,
/// };
///
/// let bytes = to_bytes(&value).unwrap();
///
/// let archived = unsafe { access_unchecked::<Example>(&*bytes) };
/// assert_eq!(archived.name, "pi");
/// assert_eq!(archived.value, 31415926);
/// ```
#[inline]
#[must_use]
pub unsafe fn access_unchecked<T: Serialize + ?Sized>(bytes: &[u8]) -> &T::Archived {
	unsafe { &*access_ptr_unchecked::<T>(bytes) }
}

/// Access a byte slice.
///
/// This is a safe alternative to [`access_unchecked`].
///
/// # Example
///
/// ```
/// #![feature(ptr_alignment_type)]
///
/// use core::fmt::Debug;
///
/// use nibblecode::{Serialize, access, to_bytes};
///
/// #[derive(Serialize)]
/// struct Example {
/// 	name: String,
/// 	value: i32,
/// }
///
/// let value = Example {
/// 	name: "pi".to_string(),
/// 	value: 31415926,
/// };
///
/// let bytes = to_bytes(&value).unwrap();
/// let archived = access::<Example>(&bytes).unwrap();
///
/// assert_eq!(archived.name, "pi");
/// assert_eq!(archived.value, 31415926);
/// ```
#[inline]
pub fn access<T: Serialize + ?Sized>(bytes: &[u8]) -> Result<&T::Archived, VerifyError> {
	access_ptr::<T>(bytes).map(|archived| unsafe { &*archived })
}

/// Mutably access a byte slice.
///
/// This function does not check that the bytes are valid to access. Use
/// [`access_mut`] to safely access the buffer using
/// validation.
///
/// # Safety
///
/// The byte slice must represent a valid archived type when accessed at the
/// default root position.
///
/// # Example
///
/// ```
/// #![feature(ptr_alignment_type)]
///
/// use core::fmt::Debug;
///
/// use nibblecode::{Serialize, access_unchecked_mut, to_bytes};
///
/// #[derive(Serialize)]
/// struct Example {
/// 	name: String,
/// 	value: i32,
/// }
///
/// let value = Example {
/// 	name: "pi".to_string(),
/// 	value: 31415926,
/// };
///
/// let mut bytes = to_bytes(&value).unwrap();
///
/// let mut archived = unsafe { access_unchecked_mut::<Example>(&mut *bytes) };
/// assert_eq!(archived.name, "pi");
/// assert_eq!(archived.value, 31415926);
///
/// // Because the access is mutable, we can mutate the archived data
/// let value = &mut archived.value;
/// assert_eq!(*value, 31415926);
/// *value = 12345.into();
/// assert_eq!(*value, 12345);
/// ```
#[inline]
#[must_use]
pub unsafe fn access_unchecked_mut<T: Serialize + ?Sized>(bytes: &mut [u8]) -> &mut T::Archived {
	unsafe { &mut *<*mut [u8]>::cast(bytes) }
}

/// Mutably access a byte slice.
///
/// This is a safe alternative to [`access_unchecked_mut`].
///
/// # Example
///
/// ```
/// #![feature(ptr_alignment_type)]
///
/// use core::fmt::Debug;
///
/// use nibblecode::{Serialize, access_mut, to_bytes};
///
/// #[derive(Serialize)]
/// struct Example {
/// 	name: String,
/// 	value: i32,
/// }
///
/// let value = Example {
/// 	name: "pi".to_string(),
/// 	value: 31415926,
/// };
///
/// let mut bytes = to_bytes(&value).unwrap();
///
/// let mut archived = access_mut::<Example>(&mut bytes).unwrap();
///
/// // Because the access is mutable, we can mutate the archived data
/// let value = &mut archived.value;
/// assert_eq!(*value, 31415926);
/// *value = 12345.into();
/// assert_eq!(*value, 12345);
/// ```
#[inline]
pub fn access_mut<T: Serialize + ?Sized>(
	bytes: &mut [u8],
) -> Result<&mut T::Archived, VerifyError> {
	access_ptr::<T>(bytes).map(|archived| unsafe { &mut *archived.cast_mut() })
}