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

时间:2015-03-24 17:51:20

标签: vector stack 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]
    }
}

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

2 个答案:

答案 0 :(得分:5)

我已经写了一个实现,我将重点介绍。

  • 完整代码位于crates.io/arrayvecAPI doc

  • 使用特征(称为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;
}
  • 在当代生锈风格中,我们只能针对特定的数组大小实现此特性。我用一个宏来覆盖一些小尺寸:
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,);
  • 我们需要抑制嵌入式数组的默认丢弃。您可以在理论上使用Option<Array>并使用ptr::writeNone的最后一刻用Drop覆盖它。

  • 我们必须必须使用我们自己的枚举,类似于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);
        }
    }
}
  • 我们实施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())
        }
    }
}
  • 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!(),
    }
}

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

答案 1 :(得分:1)

我的猜测是,编译器不知道数组的哪些元素是“空闲的”,并且在删除数组时需要运行析构函数。

尝试存储Option<T>,其中.take()方法允许您将元素移出数组。