and even more GLIBC feature test fun
[rofl0r-microsocks.git] / sblist.c
blob4def63c5d3cfea73f23b24d51c9f357fd4bf8892
1 #undef _POSIX_C_SOURCE
2 #define _POSIX_C_SOURCE 200809L
3 #include "sblist.h"
4 #include <limits.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #ifndef PAGE_SIZE
8 #warning "your C library sucks."
9 #define PAGE_SIZE 4096
10 #endif
12 sblist* sblist_new(size_t itemsize, size_t blockitems) {
13 sblist* ret = (sblist*) malloc(sizeof(sblist));
14 sblist_init(ret, itemsize, blockitems);
15 return ret;
18 static void sblist_clear(sblist* l) {
19 l->items = NULL;
20 l->capa = 0;
21 l->count = 0;
24 void sblist_init(sblist* l, size_t itemsize, size_t blockitems) {
25 if(l) {
26 l->blockitems = blockitems ? blockitems : PAGE_SIZE / itemsize;
27 l->itemsize = itemsize;
28 sblist_clear(l);
32 void sblist_free_items(sblist* l) {
33 if(l) {
34 if(l->items) free(l->items);
35 sblist_clear(l);
39 void sblist_free(sblist* l) {
40 if(l) {
41 sblist_free_items(l);
42 free(l);
46 char* sblist_item_from_index(sblist* l, size_t idx) {
47 return l->items + (idx * l->itemsize);
50 void* sblist_get(sblist* l, size_t item) {
51 if(item < l->count) return (void*) sblist_item_from_index(l, item);
52 return NULL;
55 int sblist_set(sblist* l, void* item, size_t pos) {
56 if(pos >= l->count) return 0;
57 memcpy(sblist_item_from_index(l, pos), item, l->itemsize);
58 return 1;
61 int sblist_grow_if_needed(sblist* l) {
62 char* temp;
63 if(l->count == l->capa) {
64 temp = realloc(l->items, (l->capa + l->blockitems) * l->itemsize);
65 if(!temp) return 0;
66 l->capa += l->blockitems;
67 l->items = temp;
69 return 1;
72 int sblist_add(sblist* l, void* item) {
73 if(!sblist_grow_if_needed(l)) return 0;
74 l->count++;
75 return sblist_set(l, item, l->count - 1);