exercises

Log | Files | Refs | README

main.rs (1000B)


      1 // This project implements Vec from scratch (https://doc.rust-lang.org/nomicon/vec/vec.html)
      2 
      3 use std::{mem, ptr::NonNull};
      4 
      5 /// Layout:
      6 /// A Vec has three parts: a pointer to the allocation, the size of the allocation,
      7 /// and the number of elements that have been initialized.
      8 pub struct Vec<T> {
      9     // NonNull is a wrapper around a raw pointer, which is covariant over T
     10     // and is decalred to never be null.
     11     ptr: NonNull<T>,
     12     cap: usize,
     13     len: usize,
     14 }
     15 
     16 // Vec<T> is Send/Sync if T is Send/Sync
     17 // (this produces the same results as using Unique<T>)
     18 unsafe impl<T: Send> Send for Vec<T> {}
     19 unsafe impl<T: Sync> Sync for Vec<T> {}
     20 
     21 impl<T> Vec<T> {
     22     pub fn new() -> Self {
     23         assert!(mem::size_of::<T>() != 0, "We're not ready to handle ZSTs");
     24         Vec {
     25             // Initialize values that lazily allocate like Vec::new does
     26             ptr: NonNull::dangling(),
     27             len: 0,
     28             cap: 0,
     29         }
     30     }
     31 }
     32 
     33 fn main() {
     34     println!("Hello, world!");
     35 }