使用旧的Rust 2015
0.1.2 |
|
---|---|
0.1.1 |
|
0.1.0 |
|
#354 in #decoding
8KB
98 行
as_with_bytes
简单值的简单序列化。
使用这些特质,值可以作为字节序列化,而无需任何数据复制。
实现
AsBytes
,WithBytes
和 TryWithBytes
都在类型 T
和 [T]
上实现,其中 T: Copy
。当在动态大小的切片上使用 try_with_bytes
时,它总是返回 Some(&[T])
,尽管引用的切片可以是空的。这个特质的实现只是为了泛型。
示例
let n: u32 = 0;
assert_eq!(n.as_bytes(), &[0, 0, 0, 0]);
都是同一块内存
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));
如何获取
此库可在crates.io上找到 此处。更多文档也可以在该位置找到。
lib.rs
:
使用这些特质,值可以作为字节序列化,而无需任何数据复制。
这里使用的泛化只适用于不包含其他数据指针的数据。因此,这些特质仅针对实现 Copy
的类型以及内容实现 Copy
的切片实现。
此库不对跨系统可移植性作出保证;它只是编码值的原始字节。
都是同一块内存
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));