Demilade Sonuga's blog

All posts

Vec I

2023-04-08

The final thing on our list before we can get on with event handling is the vector, and we're finally here.

Vec, like Box, is a smart pointer that owns and manages heap-allocated values. Unlike the Box, it stores a sequence of zero or more values of a type.

Aims

Our Vec, like the Box, must be able to hold any type with a non-zero size (we won't be trying to create vectors of zero-sized types in this project). Must be able to allocate properly aligned memory for the data it holds and deallocate that memory when it's no longer needed.

It must be able to increase its capacity when it runs out of space.

It must be indexable, like a regular array.

It must have safe interface functions to push and pop values from one end, like a stack. To retrieve useful information, like the length (number of elements currently held) and the capacity (number of elements that can be held) and a pointer to the first element. To remove an element at any random index. It must also have safe interfaces for creating iterators over its elements.

That covers our requirements for our Vec.

Come up with an implementation yourself. Refer to the implementations in std and alloc and the rustonomicon. Our Vec is not for general use, so ours won't be nearly as complex as those.

In The Next Post

We'll start implementing a Vec

References

  • Vec implementation in std: https://doc.rust-lang.org/std/vec/struct.Vec.html
  • Vec implementation in alloc: https://doc.rust-lang.org/alloc/vec/struct.Vec.html
  • Vec implementation in the rustonomicion: https://doc.rust-lang.org/nomicon/vec/vec.html