root/op/1.32/util.c

Revision 258, 2.0 kB (checked in by athomas, 3 years ago)
  • Added rpl_malloc/rpl_realloc so that systems with dodgy implementations will link.
  • Property svn:eol-style set to native
Line 
1 #include <stdio.h>
2 #include <ctype.h>
3 #include <stdarg.h>
4 #include <stdlib.h>
5 #include "defs.h"
6
7 #if !defined(HAVE_VSNPRINTF)
8 #warning Your system does not support vsnprintf.
9 #warning This leaves op open to potential buffer overflows.
10 #endif
11
12 void vstrnprintf(char *out, int len, const char *format, va_list args) {
13 #ifdef HAVE_VSNPRINTF
14         vsnprintf(out, len, format, args);
15 #else
16         vsprintf(out, format, args);
17 #endif
18 }
19
20 void strnprintf(char *out, int len, const char *format, ...) {
21 va_list args;
22
23         va_start(args, format);
24 #ifdef HAVE_VSNPRINTF
25         vsnprintf(out, len, format, args);
26 #else
27         vsprintf(out, format, args);
28 #endif
29         va_end(args);
30 }
31
32 char *strtolower(char *in) {
33 char *i;
34
35         for (i = in; *i; ++i) *i = tolower(*i);
36         return in;
37 }
38
39 array_t *array_alloc() {
40 array_t *array = malloc(sizeof(array_t));
41
42         if (!array || !(array->data = malloc(sizeof(void**) * ARRAY_CHUNK)))
43                 fatal(1, "failed to allocate array");
44         array->capacity = ARRAY_CHUNK;
45         array->size = 0;
46         return array;
47 }
48
49 void array_free(array_t *array) {
50         free(array->data);
51         free(array);
52 }
53
54 array_t *array_free_contents(array_t *array) {
55 int i;
56
57         for (i = 0; i < array->size; ++i)
58                 free(array->data[i]);
59         array->size = 0;
60         return array;
61 }
62
63 void *array_push(array_t *array, void *object) {
64         if (array->size + 1 >= array->capacity) {
65                 array->capacity += ARRAY_CHUNK;
66                 if (!(array->data = realloc(array->data, sizeof(void**) * array->capacity)))
67                         fatal(1, "failed to extend array");
68         }
69         return (array->data[array->size++] = object);
70 }
71
72 void *array_pop(array_t *array) {
73         if (array->size <= 0) return NULL;
74         return array->data[--array->size];
75 }
76
77 int array_extend(array_t *array, int capacity) {
78         if (capacity < array->capacity) return 0;
79         array->capacity = capacity;
80         array->data = realloc(array->data, sizeof(void**) * array->capacity);
81         return 1;
82 }
83
84 #undef malloc
85 void * rpl_malloc (size_t n) { if (n == 0) n = 1; return malloc (n); }
86 #undef realloc
87 void * rpl_realloc (void *ptr, size_t n) { if (n == 0) n = 1; return realloc (ptr, n); }
Note: See TracBrowser for help on using the browser.