Dynamically allocated objects take their memory from a heap.

The memory for an object is provided by an allocator which maintains the storage pool used for the heap.

Often a call to allocator is denoted as

P := new T
where   T   is the type of an allocated object,   and   P   is a reference to the object.

The storage pool chosen by the allocator can be determined by either:

 the object type   T
 the type of pointer   P


In the former case objects can be allocated only in one storage pool.

In the latter case objects of the type can be allocated in any storage pool or on the stack.



Task

The task is to show how allocators and user-defined storage pools are supported by the language.

In particular:

 define an arena storage pool.   An arena is a pool in which objects are allocated individually, but freed by groups.
 allocate some objects (e.g., integers) in the pool.


Explain what controls the storage pool choice in the language.




#![feature(rustc_private)]
 
extern crate arena;
 
use arena::TypedArena;
 
fn main() {
    // Memory is allocated using the default allocator (currently jemalloc).  The memory is
    // allocated in chunks, and when one chunk is full another is allocated.  This ensures that
    // references to an arena don't become invalid when the original chunk runs out of space.  The
    // chunk size is configurable as an argument to TypedArena::with_capacity if necessary.
    let arena = TypedArena::new();
 
    // The arena crate contains two types of arenas: TypedArena and Arena.  Arena is
    // reflection-basd and slower, but can allocate objects of any type.  TypedArena is faster, and
    // can allocate only objects of one type.  The type is determined by type inference--if you try
    // to allocate an integer, then Rust's compiler knows it is an integer arena.
    let v1 = arena.alloc(1i32);
 
    // TypedArena returns a mutable reference
    let v2 = arena.alloc(3);
    *v2 += 38;
    println!("{}", *v1 + *v2);
 
    // The arena's destructor is called as it goes out of scope, at which point it deallocates
    // everything stored within it at once.
}