summaryrefslogtreecommitdiff
path: root/csv.c
blob: a606c7285b420f4246dfe324256e76b8fbc2cdc6 (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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
#include "csv.h"

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// === Compiletimeoptions ===

#ifndef CSV_DEFAULT_DELIMITER
#	define CSV_DEFAULT_DELIMITER '"'
#endif

#ifndef CSV_DEFAULT_SEPARATOR
#	define CSV_DEFAULT_SEPARATOR ','
#endif

// === some usefull Makros ===

#define UNUSED(x) (void) (sizeof((x), 0)) // mark a parameter as 'unused'
#define STR(s) #s                         // Stringify a Makro
#define XSTR(s) STR(s)

// === Semantic Version Information ===

#define CSV_VER_MAJOR 1
#define CSV_VER_MINOR 0
#define CSV_VER_PATCH 0
#define CSV_VER_APPENDIX "-dev"

const char csv_version[] = XSTR(CSV_VER_MAJOR) "." XSTR(CSV_VER_MINOR) "." XSTR(CSV_VER_PATCH) CSV_VER_APPENDIX "\0" XSTR(__DATE__) "\0" XSTR(__TIME__);

// === CSV-MEMORY Interface ===

#if ( (defined(__GNUC__) && __GNUC__ >= 5) || (defined(__clang__) && (__clang_major__ > 3 || (__clang_major__ == 3 && __clang_minor__ >= 4))) )
#	define mul_overflow __builtin_mul_overflow
#else
static inline int
mul_overflow(size_t a, size_t b, size_t *out)
{
	*out = a * b;
	return (a != 0 && (*out / a) != b);
}
#endif

static void *
csv_mem_allocate(size_t n, size_t sz, void *cb_arg)
{
	UNUSED(cb_arg);

	size_t len;
	if ( n == 0 || sz == 0 || mul_overflow(n, sz, &len) ) {
		return NULL;
	}
	return malloc(len);
}

static void *
csv_mem_reallocate(void *ptr, size_t n, size_t sz, void *cb_arg)
{
	UNUSED(cb_arg);

	size_t len;
	if ( n == 0 || sz == 0 || mul_overflow(n, sz, &len) ) {
		return NULL;
	}
	return realloc(ptr, len);
}

static void
csv_mem_free(void *ptr, size_t n, size_t sz, void *cb_arg)
{
	UNUSED(n);
	UNUSED(sz);
	UNUSED(cb_arg);

	free(ptr);
}

// === CSV-OPTIONS Interface ===

const csv_options_t csv_default_options = {
	.field_delimiter = CSV_DEFAULT_DELIMITER,
	.field_separator = CSV_DEFAULT_SEPARATOR,
	.cb_error        = NULL,
	.cb_allocate     = csv_mem_allocate,
	.cb_reallocate   = csv_mem_reallocate,
	.cb_free         = csv_mem_free
};

// === CSV-ERROR Interface ===

static void
csv_fatal_error(csv_err_t csv_err, const csv_options_t *const csv_options)
{
	if ( csv_options->cb_error != NULL ) {
		(*csv_options->cb_error)(csv_err, csv_options->cb_error_arg);
	}
	fprintf(stderr, "fatal error: %s\n", csv_err_str(csv_err));
	abort();
}

// === CSV-STRING Interface ===

static inline void
csv_string_init(csv_string_t *csv_string)
{
	assert(csv_string != NULL);

	csv_string->str = NULL;
	csv_string->cap = 0;
	csv_string->pos = 0;
}

static inline void
csv_string_reset(csv_string_t *csv_string)
{
	assert(csv_string != NULL);

	csv_string->pos = 0;
}

static inline int
csv_string_empty(csv_string_t *csv_string)
{
	assert(csv_string != NULL);

	return (csv_string->pos == 0) ? 1 : 0;
}

static inline void
csv_string_append(csv_string_t *csv_string, char ch, const csv_options_t *const csv_options)
{
	assert(csv_string != NULL);
	assert(csv_options != NULL);

	static const size_t INITIAL_CAP = 16;

	if ( csv_string->pos == csv_string->cap ) { // grow if needed
		if ( csv_string->str == NULL ) {        // first call?
			if ( (csv_string->str = csv_options->cb_allocate(INITIAL_CAP, 1, csv_options->cb_memory_arg)) == NULL ) {
				csv_fatal_error(CSV_ERR_OUT_OF_MEMORY, csv_options);
				return;
			}
			csv_string->cap = INITIAL_CAP;
		}
		else {                                      // subsequent call
			size_t cap = (csv_string->cap * 3) / 2; // *= 1.5
			char * str = csv_options->cb_reallocate(csv_string->str, cap, 1, csv_options->cb_memory_arg);
			if ( str == NULL ) {
				csv_fatal_error(CSV_ERR_OUT_OF_MEMORY, csv_options);
				return;
			}
			csv_string->str = str;
			csv_string->cap = cap;
		}
	}

	csv_string->str[csv_string->pos++] = ch; // append char
}

static inline void
csv_string_free(csv_string_t *csv_string, const csv_options_t *const csv_options)
{
	assert(csv_string != NULL);
	assert(csv_options != NULL);

	csv_options->cb_free(csv_string->str, csv_string->cap, 1, csv_options->cb_memory_arg);

	// call *_init() for sane default values; prevent possible double-free
	csv_string_init(csv_string);
}

// === CSV-FIELD Interface ===

static inline void
csv_field_init(csv_field_t *csv_field)
{
	assert(csv_field != NULL);

	csv_field->fields = NULL;
	csv_field->cap    = 0;
	csv_field->pos    = 0;
}

static inline void
csv_field_reset(csv_field_t *csv_field)
{
	assert(csv_field != NULL);

	csv_field->pos = 0;
}

static inline void
csv_field_append(csv_field_t *csv_field, size_t idx, const csv_options_t *const csv_options)
{
	assert(csv_field != NULL);
	assert(csv_options != NULL);

	static const size_t INITIAL_CAP = 16;

	if ( csv_field->pos == csv_field->cap ) { // grow if needed
		if ( csv_field->fields == NULL ) {    // first call
			if ( (csv_field->fields = csv_options->cb_allocate(INITIAL_CAP, sizeof(csv_field->fields[0]), csv_options->cb_memory_arg)) == NULL ) {
				csv_fatal_error(CSV_ERR_OUT_OF_MEMORY, csv_options);
				return;
			}
			csv_field->cap = INITIAL_CAP;
		}
		else {                                         // subsequent call
			size_t  cap    = (csv_field->cap * 3) / 2; // *= 1.5
			size_t *fields = csv_options->cb_reallocate(csv_field->fields, cap, sizeof(csv_field->fields[0]), csv_options->cb_memory_arg);
			if ( fields == NULL ) {
				csv_fatal_error(CSV_ERR_OUT_OF_MEMORY, csv_options);
				return;
			}
			csv_field->fields = fields;
			csv_field->cap    = cap;
		}
	}

	csv_field->fields[csv_field->pos++] = idx; // append idx
}

static inline void
csv_field_free(csv_field_t *csv_field, const csv_options_t *const csv_options)
{
	assert(csv_field != NULL);
	assert(csv_options != NULL);

	csv_options->cb_free(csv_field->fields, csv_field->cap, sizeof(csv_field->fields[0]), csv_options->cb_memory_arg);

	csv_field_init(csv_field);
}

// === CSV Interface ===

void
csv_init(csv_t *csv)
{
	assert(csv != NULL);

	csv_init_opt(csv, NULL);
}

void
csv_init_opt(csv_t *csv, const csv_options_t *const csv_options)
{
	assert(csv != NULL);

	if ( csv_options != NULL ) {
		csv->csv_options = csv_options;
	}
	else {
		csv->csv_options = &csv_default_options;
	}

	csv_string_init(&csv->csv_string);
	csv_field_init(&csv->csv_field);
}

void
csv_cleanup(csv_t *csv)
{
	assert(csv != NULL);
	assert(csv->csv_options != NULL);

	csv_string_free(&csv->csv_string, csv->csv_options);
	csv_field_free(&csv->csv_field, csv->csv_options);
	csv->csv_options = NULL;
}

size_t
csv_nfields(const csv_t *const csv)
{
	assert(csv != NULL);

	return csv->csv_field.pos;
}

const char *
csv_field(const csv_t *const csv, size_t idx)
{
	assert(csv != NULL);
	assert(idx >= 0 && idx < csv->csv_field.pos);

	if ( idx < 0 || idx >= csv->csv_field.pos ) {
		csv_fatal_error(CSV_ERR_OUT_OF_RANGE, csv->csv_options);
		return NULL;
	}
	return &csv->csv_string.str[csv->csv_field.fields[idx]];
}

size_t
csv_read(csv_t *csv, FILE *in)
{
	assert(csv != NULL);
	assert(in != NULL);

	// initialize if needed...
	if ( csv->csv_options == NULL ) {
		csv_init(csv);
	}

	if ( ferror(in) ) {
		csv_fatal_error(CSV_ERR_IO_READ, csv->csv_options);
		return 0;
	}

	// do not try to read if EOF has already been seen
	if ( feof(in) ) {
		csv_cleanup(csv);
		return 0;
	}

	enum {
		STATE_START_FIELD,
		STATE_QUOTED_FIELD,
		STATE_SIMPLE_FIELD,
		STATE_END_FIELD,
		STATE_END_LINE,
		STATE_END_FILE,
	};

	register const int DELIM = csv->csv_options->field_delimiter;
	register const int SEP   = csv->csv_options->field_separator;

	csv_string_reset(&csv->csv_string);
	csv_field_reset(&csv->csv_field);

	for ( int state = STATE_START_FIELD;; ) {
		int ch;

		switch ( state ) {
		case STATE_START_FIELD:
			csv_field_append(&csv->csv_field, csv->csv_string.pos, csv->csv_options);

			ch = getc(in);
			if ( ch == EOF ) {
				state = STATE_END_FILE;
			}
			else if ( ch == '\r' ) { // test for CR..
				ch = getc(in);
				if ( ch != '\n' ) { // ..LF
					ungetc(ch, in);
				}
				state = STATE_END_LINE;
			}
			else if ( ch == '\n' ) {
				state = STATE_END_LINE;
			}
			else if ( ch == SEP ) {
				state = STATE_END_FIELD;
			}
			else if ( ch == DELIM ) {
				state = STATE_QUOTED_FIELD;
			}
			else {
				if ( ch != '\0' ) {
					csv_string_append(&csv->csv_string, ch, csv->csv_options);
				}
				state = STATE_SIMPLE_FIELD;
			}
			break;

		case STATE_QUOTED_FIELD:
			do {
				ch = getc(in);
				if ( ch == EOF ) {
					state = STATE_END_FILE;
				}
				else if ( ch == DELIM ) {
					ch = getc(in);
					if ( ch == EOF ) {
						state = STATE_END_FILE;
					}
					else if ( ch == DELIM ) {
						csv_string_append(&csv->csv_string, DELIM, csv->csv_options);
					}
					else if ( ch == SEP ) {
						state = STATE_END_FIELD;
					}
					else if ( ch == '\r' ) {
						ch = getc(in);
						if ( ch != '\n' ) {
							ungetc(ch, in);
						}
						state = STATE_END_LINE;
					}
					else if ( ch == '\n' ) {
						state = STATE_END_LINE;
					}
					else {
						csv_string_append(&csv->csv_string, DELIM, csv->csv_options);
						ungetc(ch, in); // we have read too far... Put the character back!
					}
				}
				else {
					if ( ch != '\0' ) {
						csv_string_append(&csv->csv_string, ch, csv->csv_options);
					}
				}
			} while ( state == STATE_QUOTED_FIELD );
			break;

		case STATE_SIMPLE_FIELD:
			do {
				ch = getc(in);
				if ( ch == EOF ) {
					state = STATE_END_FILE;
				}
				else if ( ch == SEP ) {
					state = STATE_END_FIELD;
				}
				else if ( ch == '\r' ) {
					ch = getc(in);
					if ( ch != '\n' ) {
						ungetc(ch, in);
					}
					state = STATE_END_LINE;
				}
				else if ( ch == '\n' ) {
					state = STATE_END_LINE;
				}
				else {
					if ( ch != '\0' ) {
						csv_string_append(&csv->csv_string, ch, csv->csv_options);
					}
				}
			} while ( state == STATE_SIMPLE_FIELD );
			break;

		case STATE_END_FIELD:
			csv_string_append(&csv->csv_string, '\0', csv->csv_options);
			state = STATE_START_FIELD;
			break;

		case STATE_END_LINE:
			csv_string_append(&csv->csv_string, '\0', csv->csv_options);
			return csv->csv_field.pos;

		case STATE_END_FILE:
			if ( ferror(in) ) {
				csv_fatal_error(CSV_ERR_IO_READ, csv->csv_options);
				return 0;
			}

			if ( csv_string_empty(&csv->csv_string) ) {
				csv_cleanup(csv);
				return 0; // EOF reached
			}

			/*
			 * The last data record was not terminated with a NEWLINE-Symbol.
			 * So we can't signal End-Of-File for now.  Terminate the current
			 * field and return the numbor of fields processed so far.
			 */
			csv_string_append(&csv->csv_string, '\0', csv->csv_options);

			return csv->csv_field.pos;

		default:
			assert(!"this should never be happen...");
			break;
		}
	}
	// NOT REACHED
}

const char *
csv_err_str(csv_err_t csv_err)
{
	switch ( csv_err ) {
	case CSV_ERR_OK:
		return "no error";
	case CSV_ERR_OUT_OF_MEMORY:
		return "out of memory";
	case CSV_ERR_OUT_OF_RANGE:
		return "index out of range";
	case CSV_ERR_IO_READ:
		return "read error";
	case CSV_ERR_IO_WRITE:
		return "write error";
	default:
		return "unknown error";
	}
	// NOT REACHED
}