summaryrefslogtreecommitdiff
path: root/src/common.c
blob: 054dae4ae35be63b2e367e1ba8b1180f24788f3c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
/*
 * common.c -- miscellanious helper functions.
 *
 * Copyright (c) 2003, WiseGuys Internet B.V.
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * 
 * - Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the
 * distribution.
 * 
 * - Neither the name of the WiseGuys Internet B.V. nor the names of
 * its contributors may be used to endorse or promote products derived
 * from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <ctype.h>
#include "common.h"

extern void wgmem_error( const char *fmt, ... )
{
        va_list ap;

	fprintf(stderr, "MEMERROR : ");
        va_start(ap, fmt);
        vfprintf(stderr, fmt, ap);
        va_end(ap);

	exit(-1);
}


extern void *wg_malloc( size_t size )
{
	void *result;
	if ( !size ) {
		wgmem_error( "Error mallocing 0 bytes.\n" );
	}

	result = malloc( size );
	if ( !result ) {
		wgmem_error( "Error while mallocing %u bytes.\n", size );
	}

	return result;
}

extern void *wg_calloc( size_t nmemb, size_t size )
{
	void *result;
	if ( !size || !nmemb ) {
		wgmem_error( "Error callocing 0 bytes.\n" );
	}

	result = calloc( nmemb, size );
	if ( !result ) {
		wgmem_error( "Error while callocing %u elements of %u bytes.\n", nmemb, size);
	}

	return result;
}

extern void *wg_zalloc( size_t size )
{
	void *result;

	if (!size) {
		wgmem_error( "Error zallocing 0 bytes.\n" );
	}

	result = calloc(1, size);
	if ( !result ) {
		wgmem_error( "Error while zallocing %u bytes.\n", size );
	}

	return result;
}

extern char* wg_strdup( const char *s )
{
	char *result = strdup( s );

	if ( !result ) {
		wgmem_error( "Error while strduping %u bytes.\n", strlen(s) );
	}

	return( result ); 
}

extern void* wg_realloc( void *ptr, size_t size ) 
{ 
	void *result;

	if (!size) {
		wgmem_error( "Error reallocing 0 bytes.\n" );
	}

	result = realloc( ptr, size );
	if ( !result ) {
		wgmem_error( "Error while reallocing %u bytes.\n", size );
	}

	return( result ); 
}

extern void wg_free( void *mem )
{
        if ( mem ) {
                free(mem);
        }
}

extern char *wg_getline( char *line, int size, FILE *fp )
{
        char *p;

        if ( fgets(line, size, fp) == NULL ) {
		return NULL;
	}
        
        /** kill term null **/
        if ( (p = strpbrk( line, "\n\r" )) ) {
                *p = '\0';
        }           
  
        return line;
}



/*
 * wg_split: split a line into segments, using whitespace-sequences as separators.
 *
 * ARGUMENTS:
 * - result:
 * 
 *  After the split, this array contains pointers to the start of each
 *  detected segment. Must be preallocated and at least as large as
 *  maxsegments. The pointers point into the dest buffer.
 * 
 * - dest: 
 * 
 *  String into which result points as an index. Must be preallocated, and
 *  at least as big as src. You can use src as dest, but in that case src
 *  is overwritten!
 * 
 * - src:  
 * 
 *  The string to split. Sequences of whitespace are treated as separators, unless
 *  escaped. There are two ways to escape: by using single quotes (anything
 *  between single quotes is treated as one segment), or by using a backslash
 *  to escape the next character. The backslash escape works inside quotation
 *  as well.
 * 
 *  Example:
 *  
 *  "It\'s   very\ easy   'to  use WiseGuys\' wg_split()' function" is split into:
 *  
 *  "It's"
 *  "very easy"
 *  "to  use WiseGuys' wg_split()"
 *  "function"
 *  
 * - maxsegments: 
 * 
 *  The maximum number of segments. If the splitter runs out of segments,
 *  the remainder of the string is stored in the last segment.
 *  
 * RETURN VALUE:
 * The number of segments found.
 */
unsigned int wg_split( char **result, char *dest, char *src, int maxsegments )
{
	char *p = src;
	char *w = dest;
	int cnt = 0;
	int state=0;

	if ( maxsegments == 0 ) {
		return 0;
	}

	maxsegments--;

	while (cnt < maxsegments && *p) {

		switch (state) {
		case 0:
			/*** Skip spaces ***/
			while ( isspace((int) *p) ) {
				p++;
			}
			state = 1;

		case 1: 
			/*** Start segment ***/
			result[cnt] = w;
			cnt++;
			state = 2;

		case 2:
			/*** Unquoted segment ***/
			while (*p) {
				if ( isspace((int) *p) ) {
					*w++ = '\0';
					p++;
					state = 0;
					break;
				}				
				else if ( *p == '\'' ) {
					/*** Start quotation ***/
					p++;
					state = 3;
					break;
				}
				else if ( *p == '\\' && p[1] ) {
					/*** Escape ***/
					p++;
					*w++ = *p++;
				}
				else {
					*w++ = *p++;
				}
			}
			break;

		case 3:
			/*** Inside quotes ***/
			while (*p) {
				if (*p == '\'') {
					p++;
					break;
				}
				else if ( *p == '\\' && p[1] ) {
					/*** Escape ***/
					p++;
					*w++ = *p++;
				}
				else {
					*w++ = *p++;
				}
			}
			state = 2;
			break;

		}
	}

	if ( !*p ) {
		*w = '\0';
		return cnt;
	}

	/*** We ran out of segments; copy the remainder of the string into last segment ***/
	result[cnt++] = w;
	while (*p) {
		*w++ = *p++;
	}
	*w = '\0';
	return cnt;
}


extern void wg_timerstart(wgtimer_t *t)
{
        gettimeofday( &(t->start), NULL );
}
        


extern uint4 wg_timerstop(wgtimer_t *t)
{
	uint4 result;
        gettimeofday( &(t->stop), NULL );
        result = (t->stop.tv_sec - t->start.tv_sec) * 1000000 +
                 (t->stop.tv_usec - t->start.tv_usec);

	t->start.tv_sec = t->stop.tv_sec;
	t->start.tv_usec = t->stop.tv_usec;

	return result;
}


/**
 * wg_strgmov -- a guarded strcpy() variation
 * 
 * copies src to dest (including terminating zero), and returns
 * pointer to position of terminating zero in dest. The function is
 * guaranteed not to write past destlimit. If the copy couldn't be
 * finished, the function returns NULL after restoring the first 
 * character in dest for your convenience (since this is usually a zero).  
 */
char *wg_strgmov( char *dest, const char *src, const char *destlimit )
{
	char tmp, *w;
	
	if ( !dest || dest >= destlimit ) {
		return NULL;
	}

	tmp = *dest;
	w = dest;

	while ( *src ) {

		*w++ = *src++;

		if ( w == destlimit ) {
			/*** restore old situation ***/
			*dest = tmp;
			return NULL;
		}
	}

	*w = '\0';
	return w;

}

/*
 * wg_trim() -- remove whitespace surrounding a string. 
 *
 * Example: "   bla   bla   bla   " becomes "bla   bla   bla" after trimming.
 *
 * ARGUMENTS
 * - dest : After the trim, this will point to the trimmed string.
 *          Must be preallocated and at least as big as src. You can
 *          use src as dest.
 * - src : Points to the string to be trimmed.
 *
 * RETURNS:
 * dest
 */
char *wg_trim( char *dest, const char *src )
{
	char *lastnonspace = &dest[-1];
	const char *p = src;
	char *w = dest;
	
	while ( isspace((int)*p) ) {
		p++;
	}
	while (*p) {
		if ( !isspace((int)*p) ) {
			lastnonspace = w;
		}
		*w++ = *p++;
	}
	lastnonspace[1] = '\0';

	return dest;
}