如何创建堆栈分配的矢量类容器?

kmk*_*mky 7 stack vector rust

您将如何创建一个堆栈分配的类似矢量的容器,它可以包含的元素数量有一些固定的上限?您可以在下面看到我的尝试,但它无法编译:

// The following is at crate level
#![feature(unsafe_destructor)]

use std::mem;
use std::ptr;
use std::slice::Iter;

pub struct StackVec<T> {
    buf: [T; 10],
    len: usize,
}

impl<T> StackVec<T> {
    pub fn new() -> StackVec<T> {
        StackVec {
            buf: unsafe { mem::uninitialized() },
            len: 0,
        }
    }

    pub fn iter(&self) -> Iter<T> {
        (&self.buf[..self.len]).iter()
    }

    pub fn push(&mut self, value: T) {
        unsafe { ptr::write(self.buf.get_mut(self.len).unwrap(), value); }
        self.len += 1;
    }

    pub fn pop(&mut self) -> Option<T> {
        if self.len == 0 {
            None
        } else {
            unsafe {
                self.len -= 1;
                Some(ptr::read(self.buf.get(self.len).unwrap()))
            }
        }
    }
}

#[unsafe_destructor]
impl<T> Drop for StackVec<T>
    where T: Drop
{
    fn drop(&mut self) {
        for elem in self.iter() {
            unsafe { ptr::read(elem); }
        }
        unsafe { mem::forget(self.buf); } // ERROR: [1]
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的编译时错误:
[1]错误:无法移出类型stackvec::StackVec<T>,这定义了Drop特征

blu*_*uss 6

我写了一个实现,我将重点介绍.

  • 完整的代码可以在crates.io/arrayvec(API文档)

  • 使用特征(称为Array)来抽象不同的数组大小.它需要提供原始指针,以便我们可以将该数组用作后备存储.

/// Trait for fixed size arrays.
pub unsafe trait Array {
    /// The array's element type
    type Item;
    unsafe fn new() -> Self;
    fn as_ptr(&self) -> *const Self::Item;
    fn as_mut_ptr(&mut self) -> *mut Self::Item;
    fn capacity() -> usize;
}
Run Code Online (Sandbox Code Playgroud)
  • 在当代生锈风格中,我们只能针对特定的阵列尺寸实现此特性.我用宏来覆盖一些小尺寸:
macro_rules! fix_array_impl {
    ($len:expr ) => (
        unsafe impl<T> Array for [T; $len] {
            type Item = T;
            /// Note: Returning an uninitialized value here only works
            /// if we can be sure the data is never used. The nullable pointer
            /// inside enum optimization conflicts with this this for example,
            /// so we need to be extra careful. See `Flag` enum.
            unsafe fn new() -> [T; $len] { mem::uninitialized() }
            fn as_ptr(&self) -> *const T { self as *const _ as *const _ }
            fn as_mut_ptr(&mut self) -> *mut T { self as *mut _ as *mut _}
            fn capacity() -> usize { $len }
        }
    )
}

macro_rules! fix_array_impl_recursive {
    () => ();
    ($len:expr, $($more:expr,)*) => (
        fix_array_impl!($len);
        fix_array_impl_recursive!($($more,)*);
    );
}

fix_array_impl_recursive!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
                          16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
                          32, 40, 48, 56, 64, 72, 96, 128, 160, 192, 224,);
Run Code Online (Sandbox Code Playgroud)
  • 我们需要抑制嵌入式数组的默认丢弃.你可以在理论上使用Option<Array>和使用在最后一刻ptr::write覆盖它.NoneDrop

  • 然而,我们必须使用我们自己的枚举,类似于Option一个原因:我们需要避免应用于具有相同表示的枚举的非可空指针优化Option.然后在Drop中我们对内部数组的默认析构函数进行了至关重要的抑制:我们强行覆盖了我们的枚举.当然,只有在破坏了所有元素之后.

/// Make sure the non-nullable pointer optimization does not occur!
#[repr(u8)]
enum Flag<T> {
    Dropped,
    Alive(T),
}

/// A vector with a fixed capacity.
pub struct ArrayVec<A: Array> {
    len: u8,
    xs: Flag<A>,
}

impl<A: Array> Drop for ArrayVec<A> {
    fn drop(&mut self) {
        // clear all elements, then inhibit drop of inner array
        while let Some(_) = self.pop() { }
        unsafe {
            ptr::write(&mut self.xs, Flag::Dropped);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)
  • 我们实现Deref<Target=[T]>DerefMut免费获得大量的切片方法.这是Rust的一大特色!
impl<A: Array> Deref for ArrayVec<A> {
    type Target = [A::Item];
    fn deref(&self) -> &[A::Item] {
        unsafe {
            slice::from_raw_parts(self.inner_ref().as_ptr(), self.len())
        }
    }
}
Run Code Online (Sandbox Code Playgroud)
  • ArrayVec类型具有一个不变量,它Flag<A>始终Flag::Alive(A)在值为活动时.我们应该能够优化这一点.(那里标有FIXME.)
fn inner_mut(&mut self) -> &mut A {
    // FIXME: Optimize this, we know it's always present.
    match self.xs {
        Flag::Alive(ref mut xs) => xs,
        _ => unreachable!(),
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的问题!探索这个答案导致了arrayvec上面链接的创建,并揭示了一些非常重要的要点,使它成为一个安全的生锈数据结构.