All pastes #1850260 Raw Edit

Stuff

public c v1 · immutable
#1850260 ·published 2010-03-23 13:52 UTC
rendered paste body
#include <stdlib.h>#include <string.h>#define SIZE 10typedef struct {  size_t size;  void *ptr;  size_t alloc_size;  size_t use_size;  int extra_info;} ARRAY;void init_array(ARRAY *ap, size_t size);void alloc_array(ARRAY *ap);void expand_array(ARRAY *ap, size_t expand_size);void copy_array(ARRAY *dest, ARRAY *src);void arrcpy(ARRAY *dest, ARRAY *src);void foreach_array(ARRAY *ap, void (*func)(const ARRAY *, void *));void qsort_array(ARRAY *ap, int (*compar)(const void *, const void *));void *bsearch_array(void *key, ARRAY *ap, int (*compar)(const void *, const void *));void free_array(ARRAY *ap);void init_array(ARRAY *ap, size_t size){  memset(ap, 0, sizeof(ARRAY));  ap->size = size;} void alloc_array(ARRAY *ap){  void *temp;    temp = ap->ptr;    if (ap->ptr) {    if (ap->use_size) {      if (ap->use_size % (ap->size * SIZE) == 0) {	ap->alloc_size += ap->size * SIZE;	temp = realloc(temp, ap->alloc_size);	memset(&((char *)temp)[ap->alloc_size - (ap->size * SIZE)], 0, ap->size * SIZE);      }    }  }else{    ap->alloc_size = ap->size * SIZE;    temp = malloc(ap->alloc_size);    memset(temp, 0, ap->alloc_size);  }    ap->ptr = temp;} void expand_array(ARRAY *ap, size_t expand_size){  size_t old_size;  size_t new_size;  size_t init_size;    if (ap->alloc_size >= expand_size) {    return;  }    if (expand_size % (ap->size * SIZE) == 0) {    new_size = expand_size;  }else{    new_size = ((int)(expand_size / (ap->size * SIZE)) + 1) * (ap->size * SIZE);  }    old_size = ap->alloc_size;  init_size = new_size - old_size;  ap->alloc_size = new_size;  ap->ptr = realloc(ap->ptr, ap->alloc_size);  memset(&((char *)ap->ptr)[old_size], 0, init_size);}void copy_array(ARRAY *dest, ARRAY *src){  dest->size = src->size;  dest->ptr = src->ptr;  dest->alloc_size = src->alloc_size;  dest->use_size = src->use_size;}void arrcpy(ARRAY *dest, ARRAY *src){  strncpy(dest->ptr, src->ptr, dest->alloc_size);}void foreach_array(ARRAY *ap, void (*func)(const ARRAY *, void *)){  int i;  int elems;    elems = ap->use_size / ap->size;  for (i = 0; i < elems; i++) {    func(ap, &(((char *)(ap->ptr))[i * ap->size]));  }}void qsort_array(ARRAY *ap, int (*compar)(const void *, const void *)){  qsort(ap->ptr, ap->use_size / ap->size, ap->size, compar);}void *bsearch_array(void *key, ARRAY *ap, int (*compar)(const void *, const void *)){  return bsearch(key, ap->ptr, ap->use_size / ap->size, ap->size, compar);}void free_array(ARRAY *ap){  free(ap->ptr);  init_array(ap, ap->size);}