sla.h File Reference

Detailed Description

Author
hacatu
Version
0.3.0 Simple slab allocator. Allows for efficient allocation of objects of a fixed size

Definition in file sla.h.

Go to the source code of this file.

Data Structures

struct  cr8r_sla
 Slab allocator. More...
 

Functions

bool cr8r_sla_init (cr8r_sla *self, uint64_t elem_size, uint64_t cap)
 Initialize a slab allocator. More...
 
void cr8r_sla_delete (cr8r_sla *self)
 Delete a slab allocator. More...
 
void * cr8r_sla_alloc (cr8r_sla *self)
 Allocate an object. More...
 
void cr8r_sla_free (cr8r_sla *self, void *p)
 Frees and object which was previously allocated by cr8r_sla_alloc. More...
 

Function Documentation

◆ cr8r_sla_init()

bool cr8r_sla_init ( cr8r_sla self,
uint64_t  elem_size,
uint64_t  cap 
)

Initialize a slab allocator.

Parameters
[out]selfslab allocator to initialize
[in]elem_sizesize of a single element in bytes. allocations returned will be this big. must be at least sizeof(void*)
[in]capthe number of elements to reserve space for initially, which is all reserved in a single "slab". must be at least 1
Returns
1 on success, 0 on failure (allocation failure)

◆ cr8r_sla_delete()

void cr8r_sla_delete ( cr8r_sla self)

Delete a slab allocator.

Frees all slabs and zeros out capacity/len. The allocator should not be used again after this, unless it is reinitialized.

Parameters
[in,out]selfslab allocator to delete

◆ cr8r_sla_alloc()

void* cr8r_sla_alloc ( cr8r_sla self)

Allocate an object.

If successful, the returned pointer will point to uninitialized memory with the element size of the slab allocator.

Parameters
[in]selfslab allocator to allocate from
Returns
pointer to useable uninitialized memory of the slab allocator's element size, or NULL if no unallocated elements are available and allocation of more backing storage fails.

◆ cr8r_sla_free()

void cr8r_sla_free ( cr8r_sla self,
void *  p 
)

Frees and object which was previously allocated by cr8r_sla_alloc.

The slab allocator does not check if this is indeed an allocated block, because doing so would make deallocation an O(log(n)) operation and require a larger minimum element size be enforced. It is technically possible to "abuse" this function to "free" pointers to elements from some other backing store, and then the allocator will hand these out together with elements actually from the underlying slabs. However, this should typically not be done because it ties the slab allocator to an external backing store that is not managed by it.

Parameters
[in]selfslab allocator to work with
[in]ppointer to free