Allocator API for String and Others

I wanted to use a custom allocator with the allocator api for String, PathBuf (which uses OsString internally) and functions such as std::env::var.

However, none of these have the _in functions that take an allocator that I’d expect.

How can I use a custom allocator with these types?

You can’t use a custom Allocator with those. For instance, String is hardcoded to always use Vec<u8, Global> and you can’t change that without editing the library somehow.

You could set the #[global_allocator] to change how those types allocate, but using a specific, non-global allocator for String, OsString, PathBuf, etc. is not possible.

This is an annoying limitation of the current allocator_api design, because it needs everything that could allocate to take an Allocator for maximum flexibility.

Thanks for the links. Some interesting reading in there, some of which is over my head!

Shame that the allocator api has such a long way to go. Hopefully it’ll get there.

I’m already using the global allocator, just would have been nice to use a scratch stack allocator as opposed to the tlsf heap. Oh well!

If you need a string on the stack, you can use arrayvec::ArrayString. It has a const generic for a cap on its size, and the crate also has an ArrayVec type that uses a statically allocated buffer for storing any T.

You can’t inject this into external functions that allocate like std::env::var though. This is just an optimization though, since you have an allocator that you could use.