Code:
typedef struct space {
size_t given;
void *block;
} space_t;
/** @brief Memory allocater, usually via malloc, realloc & free
* @param err Thread safe passback of encountered errors, in the event
* malloc or realloc fail then this will be filled with whatever errno
* holds at that time
* @param space Desitination of allocated memory, initialise with {0}
* @param want Amount of memory you want
* @param dir Direction to restraint allocation to, see below defines
* @return allocated memory or NULL, nothing in space parameter will be
* overwritten if memory failes to be retrieved, if freed will be
* cleared
* @example if ( !(txt = change_space(
* &ret, &text, BUFSIZ, 0 )) ) {...}
**/
void* change_space( int *err, space_t *space, size_t want, int dir );
#define need_space( err, space, want )\
change_space( err, space, want, 0 )
#define more_space( err, space, want )\
change_space( err, space, want, 1 )
#define less_space( err, space, want )\
change_space( err, space, want, -1 )
#define free_space( err, space )\
change_space( err, space, 0, 0 )
typedef size_t node_t;
typedef struct nodes {
node_t count;
node_t total;
space_t space;
} nodes_t;
/** @brief Node allocater, passes over to change_space() after doing
* calculations
* @param err Thread safe passback of encountered errors, in the event
* malloc or realloc fail then this will be filled with whatever errno
* holds at that time
* @param nodes Desitination of allocated memory, initialise with {0}
* @param Nsize size of each node, sizeof(T) is best practice here
* @param want Number of nodes you want
* @param dir Direction to restraint allocation to, see below defines
* @return allocated memory or NULL, nothing in nodes parameter will be
* overwritten if memory failes to be retrieved, if freed will be
* cleared
* @example if ( !(txt = change_space(
* &ret, &text, sizeof(wchar_t), BUFSIZ, 0 )) ) {...}
**/
void* change_nodes(
int *err, nodes_t *nodes, size_t Nsize, size_t want, int dir );
#define need_nodes( T, err, nodes, want )\
(T*)change_nodes( err, nodes, sizeof(T), want, 0 )
#define more_nodes( T, err, nodes, want )\
(T*)change_nodes( err, nodes, sizeof(T), want, 1 )
#define less_nodes( T, err, nodes, want )\
(T*)change_nodes( err, nodes, sizeof(T), want, -1 )
#define free_nodes( T, err, nodes )\
(T*)change_nodes( err, nodes, sizeof(T), 0, 0 )