as_with_bytes 0.1.0

A way to encode and decode certain values as bytes without performing any duplication of memory. This has probably been done before, but whatever.
Documentation

as_with_bytes

Simple serialization for simple values.

Using these traits, values can be serialized as bytes without any copying of data whatsoever.

Implementations

AsBytes, WithBytes, and TryWithBytes are all implemented for types T and [T] where T: Copy. try_with_bytes always returns Some(&[T]) when used on a dynamically sized slice, although the slice referenced can be empty. The trait is only implemented there for genericity.

Examples

let n: u32 = 0;

assert_eq!(n.as_bytes(), &[0, 0, 0, 0]);

It's all the same block of memory

use core::ptr;

let arr = [10, -11];

// They reference the same memory address
assert!(ptr::eq(unsafe { <[i32; 2]>::with_bytes(arr.as_bytes()) }, &arr));