initial commit
[chaz/rasterize] / common.c
1
2 /*
3 * CS5600 University of Utah
4 * Charles McGarvey
5 * mcgarvey@eng.utah.edu
6 */
7
8 #include <ctype.h>
9 #include <errno.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13
14 #include "common.h"
15
16
17 static void* (*_mem_fn)(void*, size_t) = NULL;
18
19 static int _mem_blocks = 0;
20
21
22 /*
23 * Check the result of the allocation function and call the callback function
24 * if it failed.
25 */
26 __fast__
27 void* _mem_check(void* mem, void* old, size_t size)
28 {
29 if (mem == NULL && size != 0) {
30 if (_mem_fn) {
31 mem = _mem_fn(old, size);
32 if (mem != NULL) {
33 goto done;
34 }
35 }
36 fprintf(stderr, "Memory allocation failed: %s\n", strerror(errno));
37 abort();
38 }
39
40 done:
41 if (old == NULL) {
42 ++_mem_blocks;
43 }
44 return mem;
45 }
46
47
48 void* mem_alloc(size_t size)
49 {
50 void* mem = _mem_check(malloc(size), NULL, size);
51 #ifdef MEM_TRACE
52 fprintf(stderr, " ALLOC %6d %18p %10zd\n", _mem_blocks - 1, mem, size);
53 #endif
54 return mem;
55 }
56
57 void* mem_realloc(void* mem, size_t size)
58 {
59 void* old = mem;
60 mem = _mem_check(realloc(mem, size), mem, size);
61 #ifdef MEM_TRACE
62 fprintf(stderr, " REALLOC %6d %18p %10zd (was %p)\n", _mem_blocks - 1, mem, size, old);
63 #endif
64 return mem;
65 }
66
67 void mem_free(void* mem)
68 {
69 --_mem_blocks;
70 #ifdef MEM_TRACE
71 fprintf(stderr, " FREE %6d %18p\n", _mem_blocks, mem);
72 #endif
73 free(mem);
74 }
75
76 void mem_set_fn(void* (*fn)(void*, size_t))
77 {
78 _mem_fn = fn;
79 }
80
81 int mem_blocks()
82 {
83 return _mem_blocks;
84 }
85
86
87 void rtrim(char *str)
88 {
89 char *m;
90 for (m = str + strlen(str) - 1; str <= m && isspace((int)*m); --m);
91 m[1] = '\0';
92 }
93
94 void ltrim(char *str)
95 {
96 char *m;
97 for (m = str; *m && isspace((int)*m); ++m);
98 memmove(str, m, strlen(m) + 1);
99 }
100
This page took 0.044749 seconds and 5 git commands to generate.