正确的方式来建立从片阵列? [英] Proper way to build an array from a slice?

查看:110
本文介绍了正确的方式来建立从片阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,这似乎有点傻,但我无法找到一个函数从片的内容返回一个静态大小的数组。

Ok, this seems a bit silly, but I'm having trouble finding a function to return a statically sized array from the contents of a slice.

对数组和切片锈病图书节说一无所知。 (它确实表明了如何从一个数组中分​​得一杯羹,但我想要去的其他方式。)我还检查了的 的std ::片 和的 的std ::阵列 ,但如果它的存在,我没有看到它。

The Rust Book sections on arrays and slices says nothing about it. (It does show how to take a slice from an array, but I want to go the other way.) I also checked the documentation for std::slice and std::array, but if it's there, I'm not seeing it.

有当然写出每个元素一个接一个的选择,但似乎可笑。现在,我最后写一个python单行做到这一点对我来说。

There is of course the option of writing out each element one by one, but that seems ridiculous. For now, I ended up writing a python one-liner to do it for me.

", ".join(["k[{}]".format(i) for i in range(32)])

所以,我结束了与此:

So I ended up with this:

use db_key::Key;

#[derive(Clone)]
pub struct Sha256{
    bits : [u8;32]
}

impl Key for Sha256 {
    fn from_u8(k: &[u8]) -> Self {
        Sha256{bits:
               // FIXME: This is dumb.
               [ k[0], k[1], k[2], k[3], k[4], k[5], k[6], k[7], k[8], k[9], k[10], k[11], k[12], k[13], k[14], k[15], k[16], k[17], k[18], k[19], k[20], k[21], k[22], k[23], k[24], k[25], k[26], k[27], k[28], k[29], k[30], k[31] ]
        }
    }
    fn as_slice<T, F: Fn(&[u8]) -> T>(&self, f: F) -> T {
        f(&self.bits)
    }
}

我想知道,如果有一个合适的方式,如 k.to_array(32)或类似的规定。

和,是的,我知道上面的code可能会失败,超出范围的访问。我不知道是什么 DB_KEY ::键预计,无效的输入。

And, yes, I realize the above code could fail with out-of-bounds access. I'm not sure what db_key::Key expects on invalid input.

编辑:

<一个href=\"http://stackoverflow.com/questions/29570607/is-there-a-good-way-to-convert-a-vect-to-an-array\">Is有一个VEC转换为数组的好办法?是类似的,但不太一般。一个好的答案,这个可能也是一个很好的答案与另外服用一片从 VEC ,它能够高效简洁来完成这个问题。我还没有考虑写入每个你关心大小的单独的转换功能是一个妥善的解决方案。

Is there a good way to convert a Vec to an array? is similar but less general. A good answer to this will probably also be a good answer to that question with the addition of taking a slice from the vec, which can be done efficiently and concisely. I also don't consider "write a separate conversion function for each size you care about" to be a proper solution.

如何获得片称为在锈静态数组?也相似,但接受的答案是黑客我已经想出了独立。

How to get a slice as a static array in rust? is also similar, but the accepted answer is the hack I had already come up with independently.

推荐答案

您可以使用一个循环来解决这个问题的简单(但也许令人失望)的方式:

You can use a loop to solve it the straightforward (but maybe disappointing) way:

let input = b"abcdef";
let mut array = [0u8; 32];
for (x, y) in input.iter().zip(array.iter_mut()) {
    *y = *x;
}

我们可以用一个函数来执行运行时大小检查,把片成固定大小数组的引用。

We can use a function to do a runtime size check and turn a slice into a reference to a fixed size array.

Libstd没有提供足够的性状可靠地检查输入和输出类型这里匹配,但是我们在理论上可以开发自己(为一个有限数目的阵列类型)。无论哪种方式,投看起来像这样, U 是任意数组类型指定。

Libstd doesn't provide enough traits to reliably check that the input and output types match here, but we could in theory develop that ourselves (for a finite number of array types). Either way, the cast looks like this, U is arbitrary array type you specify.

/// Return a reference to a fixed size array from a slice.
///
/// Return **Some(array)** if the dimensions match, **None** otherwise.
///
/// **Note:** Unsafe because we can't check if the **U** type is really an array.
pub unsafe fn as_array<T, U>(xs: &[T]) -> Option<&U> where
    U: AsRef<[T]>,
{
    let sz = std::mem::size_of::<U>();
    let input_sz = xs.len() * std::mem::size_of::<T>();

    // The size check could be relaxed to sz <= input_sz
    if sz == input_sz {
        Some(&*(xs.as_ptr() as *const U))
    } else {
        None
    }
}

这篇关于正确的方式来建立从片阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆