#serialization #codec #decoding #encoding

yanked as_with_bytes

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

Uses old Rust 2015

0.1.2 Sep 16, 2017
0.1.1 Sep 10, 2017
0.1.0 Sep 10, 2017

#354 in #decoding

MIT license

8KB
98 lines

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));

How to obtain

This is available on crates.io here. More documentation can also be found at that location.


lib.rs:

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

The generalization that is used here only works for data which contains no pointers to other data. As such, the traits are only implemented for types which implement Copy and for slices whose contents implement Copy.

This crate makes no guarantees about portability across systems; it simply encodes the raw bytes of values.

It's all the same block of memory

use as_with_bytes::{AsBytes, WithBytes};

use std::ptr;

let arr = [10, -11];

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

No runtime deps