026 implementation of rust Necromancer’s book VEC



The videos recorded in this series are mainly put on station BRust dead book learning video

The source code information related to rust dead book is ingithub.com/anonymousGiga/Rustonomi…

Starting with this section, we implement a VEC with the knowledge we learned in rust’s book of the dead.

Initial definition of myvec

Our definition of VEC is as follows:

pub Struct MyVec<T> {
    ptr: *mut T,
    cap: usize,
    len: usize,

Questions so defined: the bare pointer PTR we use here is actually intended to achieve the effect of variable reference. From the perspective of security, there should be no alias, or more generally, we should lock its content and owner here.

Therefore, we define a unique type so that the raw pointer has data.

Optimized VEC definition

Unique type definition

Unique type should meet the following conditions:

  • Variable for t;
  • Have a value of type T (for drop check);
  • If t is send / sync, unique is also send / sync;
  • The pointer is never null.

Possible unique definitions are as follows:

use std::marker::PhantomData;

//1. The definition of structure meets the first two points
struct Unique<T> {
    PTR: * const T, // the pointer is immutable, and the content pointed to by the pointer is variable
    _ Marker: phantomdata < T >, // used for drop check. If it is not added, the compiler will think that the structure does not have type T, and it doesn't matter whether the destructor is called or not

//2. Meet the third point
unsafe impl<T: Send> Send for Unique<T> {}
unsafe impl<T: Sync> Sync for Unique<T> {}

impl<T> Unique<T> {
    const unsafe fn new_unchecked(ptr: *mut T) -> Self {
        unsafe { Unique { ptr: ptr, _marker: PhantomData} }

    //3. Meet the fourth point
    fn new(ptr: *mut T) -> Option<Self> {
        if !ptr.is_null() {
            Some(unsafe { Unique { ptr: ptr, _marker: PhantomData} })
        } else {

    fn as_ptr(&self) -> *mut T {
        self.ptr as *mut T

New VEC definition

pub struct MyVec<T> {
    //ptr: *mut T,
    ptr: Unique<T>,
    cap: usize,
    len: usize,

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Linghu rushed