On usage of Custom Allocators

Currently, on unstable, Vec (and other types such as Rc, Box etc) is being enhanced with a generic allocator parameter, wiht a default of Global.

struct Vec<T, A:Allocator=Global>;

I have been experimenting with custom allocators, and have found it much more convenient to instead have a new struct which doesn't have a default and then define Vec with a type alias, like this:

struct VecA<T, A: Allocator>;
type Vec<T> = VecA<T, Global>;

( See here for details )

The advantage is that when used with any allocator that implements Default (and not just Global), methods such as new, with_capacity and traits such as Default, From are still available. This reduces source edits to change to an allocator other than Global considerably. A type defined as Vec<T> = VecA<T,Local> is now almost identical to a normal Vec except it is allocated differently. The only exception is a different vec! macro is needed, veca! rather than vec!.

As far as I know this does not cause compatibility issues with stable Vec, Box etc, so I think it could be considered for the standard library as a better way to enhance Vec, Box, Rc, String etc. to support custom allocators.

4 Likes

It would break any existing links to https://doc.rust-lang.org/std/vec/struct.Vec.html, but that feels acceptable.

3 Likes