Demilade Sonuga's blog

All posts

Box I

2023-03-27

Now that we're done with the heap allocator, the next thing on our list is the Box.

Box is a smart pointer that is used to hold data of any type on the heap. For a refresher on the Box struct check the references. It's possible to use the alloc::boxed::Box struct in no std programs but we won't be using it because of our promise at the beginning to build the project using only the core library.

Because of this self-imposed limitation, our Box will be a bit limited, but it will be good enough for our purposes. The thing about Box is that it is a special struct with special support from the compiler, and our custom Box is not going to have this special support.

Aims

Firstly, our Box must be able to hold data of any type, just like the original Box. A Box that can hold an i32 should be the same Box that can hold a closure or a regular struct.

Next: Our Box must be able to allocate properly aligned memory for the data it holds and deallocate that memory when the Box is no longer needed.

Remember that the reason we want a Box in the first place is so we can use it to store closures for event handlers. And the reason we need a Box for this is that we cannot predict the size a closure will have. That is solely determined by the compiler.

Another thing we'll need along the way: our Box must have a mechanism for retrieving the underlying pointer and creating a new Box from a pointer to data and the allocator of the memory that data is stored in.

That covers the requirements for our Box.

You should come up with an implementation yourself. Refer to the implementations in std and alloc but because of our much simpler and specific purposes, ours will not be nearly as complex as those ones.

In The Next Post

We'll start implementing a Box

References

  • Box explanation: https://doc.rust-lang.org/book/ch15-01-box.html
  • Box implementation in alloc: https://doc.rust-lang.org/alloc/boxed/struct.Box.html
  • Box implementation in std: https://doc.rust-lang.org/std/boxed/struct.Box.html