我正在尝试创建一个通用函数,将字节切片转换为整数。
fn i_from_slice<T>(slice: &[u8]) -> Option<T>
where
T: Sized,
{
match slice.len() {
std::mem::size_of::<T>() => {
let mut buf = [0; std::mem::size_of::<T>()];
buf.copy_from_slice(slice);
Some(unsafe { std::mem::transmute_copy(&buf) })
}
_ => None,
}
}
Run Code Online (Sandbox Code Playgroud)
Rust 不会让我这样做:
error[E0532]: expected tuple struct/variant, found function `std::mem::size_of`
--> src/lib.rs:6:9
|
6 | std::mem::size_of::<T>() => {
| ^^^^^^^^^^^^^^^^^^^^^^ not a tuple struct/variant
error[E0277]: the size for values of type `T` cannot be known at compilation time
--> src/lib.rs:7:31
|
7 | let mut buf = [0; std::mem::size_of::<T>()];
| ^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `T`
= note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
= help: consider adding a `where T: std::marker::Sized` bound
= note: required by `std::mem::size_of`
Run Code Online (Sandbox Code Playgroud)
有没有一种方法可以静态地知道 的大小T?
如果您T是整数,则不需要任何不安全代码,因为存在from_ne_bytes.
如果你绝对想要一个通用函数,你可以添加一个特征:
use std::convert::TryInto;
trait FromBytes: Sized {
fn from_ne_bytes_(bytes: &[u8]) -> Option<Self>;
}
impl FromBytes for i32 {
fn from_ne_bytes_(bytes: &[u8]) -> Option<Self> {
bytes.try_into().map(i32::from_ne_bytes).ok()
}
}
// Etc. for the other numeric types.
fn main() {
let i1: i32 = i_from_slice(&[1, 2, 3, 4]).unwrap();
let i2 = i32::from_ne_bytes_(&[1, 2, 3, 4]).unwrap();
assert_eq!(i1, i2);
}
// This `unsafe` usage is invalid, but copied from the original post
// to compare the result with my implementation.
fn i_from_slice<T>(slice: &[u8]) -> Option<T> {
if slice.len() == std::mem::size_of::<T>() {
Some(unsafe { std::mem::transmute_copy(&slice[0]) })
} else {
None
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1247 次 |
| 最近记录: |