以最小开销安全地将所有元素从通用数组移出到元组中的方法

Method for safely moving all elements out of a generic array into a tuple with minimal overhead

在 Rust 中,我想将所有元素移出通用固定宽度数组,这样我就可以单独移动它们。这些元素可能但不一定实现 Copy。我提出了以下解决方案:

struct Vec3<T> {
    underlying_array: [T; 3]
}

impl<T> Vec3<T> {
    fn into_tuple(self) -> (T, T, T) {
        let result = (
            unsafe { mem::transmute_copy(&self.underlying_array[0]) },
            unsafe { mem::transmute_copy(&self.underlying_array[1]) },
            unsafe { mem::transmute_copy(&self.underlying_array[2]) },
        );
        mem::forget(self);
        result
    }
}

它似乎有效,但我想知道在一般情况下它是否安全。来自 C++,通过复制对象的位模式和绕过源对象的析构函数来移动对象通常是不安全的,我认为这基本上就是我在这里所做的。但是在 Rust 中,每种类型都是可移动的(我认为)并且没有办法自定义移动语义(我认为),所以我想不出 Rust 在未优化的情况下实现移动对象的任何其他方式,而不是按位复制.

像这样将元素移出数组安全吗?有没有更惯用的方法呢? Rust 编译器是否足够聪明,可以在可能的情况下消除实际的位复制 transmute_copy,如果没有,是否有更快的方法来做到这一点?

我认为这 不是 的副本,因为在那个例子中,数组元素不是通用的,也没有实现 Drop .已接受答案中的库一次将单个值从数组中移出,同时保持数组的其余部分可用。因为我想一次移动所有值而不关心保留数组,所以我认为这种情况不同。

Rust 1.36 及更高版本

这现在可以用完全安全的代码完成:

impl<T> Vec3<T> {
    fn into_tuple(self) -> (T, T, T) {
        let [a, b, c] = self.underlying_array;
        (a, b, c)
    }
}

以前的版本

正如您所提到的以及在 中所讨论的那样,将泛型类型视为一堆比特可能是非常危险的。一旦我们复制了这些位并且它们是 "live",Drop 等特征的实现就可以在我们最不期望的时候访问该值。

也就是说,您当前的代码 看起来 是安全的,但具有不必要的灵活性。使用 transmutetransmute_copy 是大锤,实际上很少需要。您不希望能够更改值的类型。相反,使用 ptr::read.

通常扩展 unsafe 块以覆盖使某些内容安全的代码范围,然后包含解释 为什么 该块实际上是安全的注释。在这种情况下,我会将其扩展以涵盖 mem::forget;返回的表达式也必须随之而来。

您需要确保不可能在您移出第一个值和忘记数组之间发生恐慌。否则你的数组 是 half-initialized 而你 触发未初始化的行为。在这种情况下,我喜欢你编写一个语句来创建结果元组的结构;在那里的额外代码中不小心塞进鞋拔更难。这也值得添加评论。

use std::{mem, ptr};

struct Vec3<T> {
    underlying_array: [T; 3],
}

impl<T> Vec3<T> {
    fn into_tuple(self) -> (T, T, T) {
        // This is not safe because I copied it directly from Stack Overflow
        // without reading the prose associated with it that said I should 
        // write my own rationale for why this is safe.
        unsafe {
            let result = (
                ptr::read(&self.underlying_array[0]),
                ptr::read(&self.underlying_array[1]),
                ptr::read(&self.underlying_array[2]),
            );
            mem::forget(self);
            result
        }
    }
}

fn main() {}

every type is movable

是的,我相信这是正确的。您可以 (搜索 "one specific case".

there's no way to customize move semantics

是的,

Is the Rust compiler smart enough to elide the actual bit copying

一般来说,我相信编译器会这样做,是的。然而,优化是一件棘手的事情。最终,只有在你的真实案例中查看汇编和分析才会告诉你真相。

is there a faster way to do this?

我不知道。


我通常会写这样的代码:

extern crate arrayvec;
extern crate itertools;

use arrayvec::ArrayVec;
use itertools::Itertools;

struct Vec3<T> {
    underlying_array: [T; 3],
}

impl<T> Vec3<T> {
    fn into_tuple(self) -> (T, T, T) {
        ArrayVec::from(self.underlying_array).into_iter().next_tuple().unwrap()
    }
}

调查两个实现的程序集,第一个需要 25 x86_64 条指令,第二个需要 69 条。同样,我依靠分析来知道哪个是实际上 更快,因为更多指令并不一定意味着更慢。

另请参阅: