Crate manually_boxed

source ·
Expand description

Manual memory management, with a reasonable API and fewer footguns

Ptr is a halfway house between Box and *mut T. See its documentation for the details of the API.

We aim to reproduce roughly the division of responsibility (between programmer and compiler) found in C.

§Caller responsibilities

  • Knowing which data is still live, freeing it as and when needed, and not freeing it too soon. Not accessing freed data.

  • Not defeating the library’s anti-alias protections. In particular: holding a suitable singleton (NoAliasSingleton) which each Ptr belongs to (even though there is nothing in the API eg, lifetimes, to link them).

§Library responsibilities

  • Following Rust’s aliasing rules, which are (for our purposes) stricter than C’s. This library aims to prevent accidental creation of overlapping &mut, for example.

  • Threadsafety; Send and Sync. (The caller must still make sure not to free an object that another thread may be using, of course.)

  • Soundness in the face of panics, including panics from methods of the contained type T, eg T’s Drop impl.

  • Drop footguns”, and the like, which lurk in Unsafe Rust.

§Soundness

This library aims to be sound in the usual Rust sense. That is, you should not be able to produce UB without calling unsafe functions and writing buggy code.

However, it is impossible to use this library without making calls to unsafe functions. And the invariants and rules for the unsafe entrypoints, are more global, and arguably harder to uphold, than is usual for a Rust API.

In practice this means that in a real program, memory-safety is likely to depend on the correctness of much nominally “safe” code. The rules have been chosen pragmatically, to minimise the proportion of the caller that needs to be actually marked with unsafe. But in practice, much of a caller’s code will be able to violate invariants and cause UB.

You cannot sensibly pass Ptr to naive, safe, code. If you want to provide a conventionally safe and sound API, you must wrap up your entire data structure, hiding all of this library’s types.

Structs§

Traits§

  • Token-like: &mut self implies &mut NoAliasSingleton
  • Token-like: &self implies &NoAliasSingleton
  • Convenience trait for working with Option<Ptr<_>>