thread
,我有以下设置:
#[repr(packed)]
struct MyStruct {
bytes: [u8; 4]
}
unsafe fn any_as_u8_slice<T: Sized>(p: &T) -> &[u8] {
::std::slice::from_raw_parts(
(p as *const T) as *const u8,
::std::mem::size_of::<T>(),
)
}
fn main() {
let s = MyStruct { bytes: [0u8, 1u8, 2u8, 3u8].to_owned() };
let bytes: &[u8] = unsafe { any_as_u8_slice(&s) };
println!("{:?}", bytes);
}
playground
)
输出:
[0, 1, 2, 3]
这非常有效,但是它不考虑动态调整大小的结构成员,如
Vec<u8>
它们的大小需要在运行时确定。理想情况下,我希望对
Vec<u8>
目前,我有以下几点:
#[repr(packed)]
struct MyStruct {
bytes: Vec<u8>
}
unsafe fn any_as_u8_slice<T: Sized>(p: &T) -> &[u8] {
::std::slice::from_raw_parts(
(p as *const T) as *const u8,
::std::mem::size_of::<T>(),
)
}
fn main() {
let s = MyStruct { bytes: [0u8, 1u8, 2u8, 3u8].to_vec() };
let bytes: &[u8] = unsafe { any_as_u8_slice(&s) };
println!("{:?}", bytes);
}
(
playground
输出:
[208, 25, 156, 239, 136, 85, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0]
我假设上面的输出引用了某种指针,但我不确定。
目前,
bincode
serde
板条箱,但它将向量的长度序列化为
usize
. 我更愿意指定这个,并将长度编码为
u8
this thread
. 不幸的是,这里最好的解决方案是重写
Bincode
图书馆,这使我寻找任何替代解决方案。
编辑
塞德
二进制码
use serde::{Serialize};
#[derive(Clone, Debug, Serialize)]
struct MyStruct {
bytes: Vec<u8>
}
fn main() {
let s = MyStruct { bytes: [0u8, 1u8, 2u8, 3u8].to_vec() };
let bytes = bincode::serialize(&s).unwrap();
println!("{:?}", bytes);
}
输出:
[4, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3]
想要的输出:
[4, 0, 1, 2, 3]