All pastes #946961 Raw Edit

Someone

public text v1 · immutable
·published 2008-03-18 01:56 UTC
rendered paste body
// C Source File
// Created 03/15/2008 06:32:43 PM

/*
*  By Lardmaster,
*  Anyone feel free to use it for any purposes.
*
*  Uses unsigned shorts as pointers for the linked list of free block, to save memory.  Thus the max number of blocks is 65,534
*  Simple fixed block sized memory allocator with free and allocate.
*
*/


#include "lardalloc.h"

/*
*  converts the within buffer(LARD_PTR) pointer to a system wide pointer
*/
void * conv_to_ptr(const lardbuffer *b, LARD_PTR ptr) {
    return (char *)b+HEADER_SIZE+ptr*b->size;
}
/*
*  converts a systemwide pointer to somewhere inside the buffer into an LARD_PTR which points locally
*/
LARD_PTR conv_to_short(const lardbuffer *b, const void * ptr) {
    return ((char *)ptr-(char *)b-HEADER_SIZE)/b->size;
}

/*
*  allocates the buffer with a system malloc call
*/
lardbuffer * initialize_buffer(unsigned int size, unsigned int maxelements) {
    int mallocsize=HEADER_SIZE+size*MIN(maxelements,sizeof(unsigned char));
    lardbuffer * b= (lardbuffer*)(malloc(mallocsize));
    b->size=size;
    b->first_free=0;
    for (LARD_PTR i=0; i<maxelements-1; i++) {
        *(LARD_PTR *)conv_to_ptr(b,i)=i+1;
    }
    *(LARD_PTR *)conv_to_ptr(b,maxelements-1)=USHRT_MAX;
    return (lardbuffer *)b;
}
/*
* returns a pointer to an allocated memory block of size b->size
*/
void * allocate(lardbuffer *b) {
    if (b->first_free==USHRT_MAX) {
        return NULL;
    }
    void * ptr=conv_to_ptr(b,b->first_free);
    b->first_free=*(LARD_PTR *)ptr;
    return ptr;
}


/*
* a simple inline method to dereference the LARD_PTR pointers quickly.
*/
LARD_PTR deref(lardbuffer *b, LARD_PTR ptr) {
    return *((LARD_PTR *)conv_to_ptr(b,ptr));
}

/*
* frees the memory block pointer to by ptr, which must be in larbuffer b
*/

void lardfree(lardbuffer *b, void * ptr) {
    LARD_PTR old_first=b->first_free;
    b->first_free=conv_to_short(b,ptr);
    *(LARD_PTR *) ptr=old_first;
}