#ifndef LIBUALLOC_MCACHE_API_H
#define LIBUALLOC_MCACHE_API_H

#include <libualloc/libualloc.h>

/*
	Allocator: mcache - memory allocation cache

	Remember all allocations per context in two doubly linked lists: one
	for currently in use, one for currently free (cache). Serve new allocations
	from the cache. Same as acache, but is more expensive and has clean().

	Allocation size:      fixed
	Standard calls:       alloc, free, clean
	Per allocation cost:  2 pointers
	Per page cost:        n/a (not paged)
*/

typedef struct uall_mcache_elem_s uall_mcache_elem_t;
typedef struct uall_mcache_page_s uall_mcache_page_t;

typedef struct {
	/* configuration */
	uall_sysalloc_t *sys;
	long elem_size;

	void *user_data;

	/* internal states - init all bytes to 0 */
	uall_mcache_elem_t *free_elems; /* singly linked list cache */
	uall_mcache_elem_t *used_elems; /* singly linked list cache */
} uall_mcache_t;


/* Return a new allocation of ctx->elem_size */
UALL_INLINE void *uall_mcache_alloc(uall_mcache_t *ctx);

/* Free a previous allocation (really just cache it for later reuse) */
UALL_INLINE void uall_mcache_free(uall_mcache_t *ctx, void *ptr);

/* Free all allocated and cached blocks; after the call ctx is ready to
   accept new allocations; cheaper than calling uall_mcache_free()
   multiple times */
UALL_INLINE void uall_mcache_clean(uall_mcache_t *ctx);

/* Free all unused (cached free) elements (but keep elements that are in use) */
UALL_INLINE void uall_mcache_flush(uall_mcache_t *ctx);

#endif
