All pastes #945724 Raw Edit

Someone

public c v1 · immutable
·published 2008-03-17 04:03 UTC
rendered paste body
// C Source File// Created 03/15/2008 06:32:43 PM/**  By Lardmaster,*  Feel free to use it for any purposes... I doubt it works at this point.**  Uses unsigned shorts as pointers for the linked list of free block, to save memory.  Thus the max number of blocks is 65,535*  Simple fixed block sized memory allocator with free and allocate.*  I hope it works :P.*/#include <tigcclib.h>/**  The size of the header at the top of the allocated memory, an int for size, a short for first_free*/#define HEADER_SIZE sizeof(unsigned int)+sizeof(unsigned short)/**  block size, and the short pointer to the first free block*/typedef struct lardbuffer {	unsigned int size;	unsigned short first_free;} lardbuffer;/**  converts the within buffer(unsigned short) pointer to a system wide pointer*/void * conv_to_ptr(const lardbuffer *b, unsigned short ptr) {	return (void*)(b+HEADER_SIZE+ptr*b->size);}/**  converts a systemwide pointer to somewhere inside the buffer into an unsigned short which points locally*/unsigned short conv_to_short(const lardbuffer *b, const void * ptr) {	return ((unsigned int)(ptr-(void *)b)-HEADER_SIZE)/b->size;}/**  allocates the buffer with a system malloc call*/lardbuffer * initailize_buffer(unsigned int size, unsigned int maxelements) {	int mallocsize=HEADER_SIZE+size*maxelements;	lardbuffer * b= (lardbuffer*)(malloc(mallocsize));	b->size=size;	b->first_free=0;	for(unsigned short i=0; i<maxelements-1; i++) {		*(unsigned short*)conv_to_ptr(b,i)=i+i;	}	*(unsigned shortinvalid operands to binary - *)conv_to_ptr(b,maxelements-1)=0;	return b;}/** returns a pointer to an allocated memory block of size b->size*/void * allocate(lardbuffer *b) {	void * ptr=conv_to_ptr(b,b->first_free);	b->first_free=*((unsigned short*)ptr);	return ptr;}/** a simple inline method to dereference the unsigned short pointers quickly.*/inline unsigned short deref(lardbuffer *b, unsigned short ptr) {	return *((unsigned short *)conv_to_ptr(b,ptr));}/** frees the memory block pointer to by ptr, which must be in larbuffer b*/void free(lardbuffer *b, void * ptr) {	unsigned short next=b->first_free;	unsigned short after=deref(b,next);	while(after!=0) {		if(conv_to_ptr(after)>ptr) {			*((unsigned  short *)conv_to_ptr(next))=conv_to_short(ptr);			*((unsigned short *)ptr)=after;			break;		}	}}