the asumptions were of course, incorrect
[convexer.git] / cxr / cxr_mem.h
1 #ifndef CXR_MEM_H
2 #define CXR_MEM_H
3
4 #include <string.h>
5 #include <stdlib.h>
6
7 #include "cxr_types.h"
8 #include "cxr_math.h"
9
10 typedef struct cxr_abuffer cxr_abuffer;
11
12 struct cxr_abuffer
13 {
14 u8 *arr;
15 u32 esize,
16 count,
17 capacity;
18 };
19
20 #ifdef CXR_DEBUG_ALLOCATORS
21 #define CXR_STR_PRE(x) #x
22 #define CXR_STR(x) CXR_STR_PRE(x)
23 #define cxr_ab_ptr(b,i) __cxr_ab_ptr(b,i, __FILE__ ":L" CXR_STR(__LINE__) )
24 #else
25 #define cxr_ab_ptr(b,i) __cxr_ab_ptr(b,i)
26 #endif
27
28 static void *__cxr_ab_ptr( struct cxr_abuffer *buffer, u32 index
29
30 #ifdef CXR_DEBUG_ALLOCATORS
31 ,const char *debug_str
32 #endif
33
34 )
35 {
36
37 #ifdef CXR_DEBUG_ALLOCATORS
38 if( index >= buffer->capacity || index < 0 )
39 {
40 printf( "index out of capactity (%d /: [0->%d (cap)]) (%s)\n", index,
41 buffer->capacity, debug_str );
42 exit(1);
43 }
44 #endif
45
46 return buffer->arr + buffer->esize*index;
47 }
48
49 static void cxr_ab_reserve( struct cxr_abuffer *buffer, u32 count )
50 {
51 if( buffer->count + count > buffer->capacity )
52 {
53 buffer->capacity = cxr_max(buffer->capacity*2, buffer->capacity+count);
54 buffer->arr = realloc( buffer->arr, buffer->capacity*buffer->esize );
55 }
56 }
57
58 static void *cxr_ab_empty( struct cxr_abuffer *buffer )
59 {
60 cxr_ab_reserve( buffer, 1 );
61 return cxr_ab_ptr( buffer, buffer->count ++ );
62 }
63
64 static void *cxr_ab_empty_at( struct cxr_abuffer *buffer, int at )
65 {
66 cxr_ab_reserve( buffer, 1 );
67
68 if( at == buffer->count )
69 {
70 buffer->count ++;
71 return cxr_ab_ptr( buffer, at );
72 }
73
74 /* Shift buffer to make room */
75 memmove
76 (
77 cxr_ab_ptr( buffer, at+1 ),
78 cxr_ab_ptr( buffer, at ),
79 (buffer->count-at)*buffer->esize
80 );
81
82 buffer->count ++;
83 return cxr_ab_ptr( buffer, at );
84 }
85
86 static void cxr_ab_push( struct cxr_abuffer *buffer, void *em )
87 {
88 cxr_ab_reserve( buffer, 1 );
89
90 memcpy( buffer->arr+buffer->count*buffer->esize, em, buffer->esize );
91 buffer->count ++;
92 }
93
94 static void cxr_ab_init( struct cxr_abuffer *buffer, u32 esize, u32 cap )
95 {
96 buffer->esize = esize;
97 buffer->capacity = cap;
98 buffer->count = 0;
99
100 if( cap )
101 buffer->arr = malloc( buffer->esize*buffer->capacity );
102 else
103 buffer->arr = NULL;
104 }
105
106 static void cxr_ab_clear( struct cxr_abuffer *buffer )
107 {
108 buffer->count = 0;
109 }
110
111 static void cxr_ab_free( struct cxr_abuffer *buffer )
112 {
113 free( buffer->arr );
114 }
115
116 #endif /* CXR_TYPES_H */