r3/src/token.c

71 lines
1.4 KiB
C
Raw Normal View History

2014-05-14 23:52:45 -04:00
/*
* token.c
2014-06-27 01:24:40 -04:00
* Copyright (C) 2014 c9s <yoanlin93@gmail.com>
2014-05-14 23:52:45 -04:00
*
* Distributed under terms of the MIT license.
*/
#include <stdlib.h>
2014-05-15 00:47:14 -04:00
#include <stdio.h>
#include <string.h>
#include <assert.h>
2014-05-26 09:39:36 -04:00
#include "r3.h"
#include "r3_str.h"
2014-05-28 09:08:06 -04:00
#include "str_array.h"
#include "zmalloc.h"
2014-05-14 23:52:45 -04:00
2014-05-16 06:03:52 -04:00
str_array * str_array_create(int cap) {
str_array * list = (str_array*) zmalloc( sizeof(str_array) );
2014-05-31 13:25:34 -04:00
if (!list)
return NULL;
2014-05-14 23:52:45 -04:00
list->len = 0;
list->cap = cap;
list->tokens = (char**) zmalloc( sizeof(char*) * cap);
2014-05-14 23:52:45 -04:00
return list;
}
2014-05-16 06:03:52 -04:00
void str_array_free(str_array *l) {
2014-05-31 13:26:36 -04:00
assert(l);
2014-05-21 06:22:11 -04:00
for ( int i = 0; i < l->len ; i++ ) {
2014-05-26 13:07:33 -04:00
if (l->tokens[ i ]) {
zfree(l->tokens[i]);
}
2014-05-15 01:39:50 -04:00
}
2014-05-21 06:22:11 -04:00
zfree(l);
2014-05-15 01:39:50 -04:00
}
2014-05-26 13:07:33 -04:00
bool str_array_is_full(const str_array * l) {
2014-05-14 23:52:45 -04:00
return l->len >= l->cap;
}
2014-05-26 13:07:33 -04:00
bool str_array_resize(str_array * l, int new_cap) {
l->tokens = zrealloc(l->tokens, sizeof(char**) * new_cap);
2014-05-14 23:52:45 -04:00
l->cap = new_cap;
return l->tokens != NULL;
}
2014-05-16 06:03:52 -04:00
bool str_array_append(str_array * l, char * token) {
if ( str_array_is_full(l) ) {
bool ret = str_array_resize(l, l->cap + 20);
2014-05-14 23:52:45 -04:00
if (ret == FALSE ) {
return FALSE;
}
}
2014-05-15 00:47:14 -04:00
l->tokens[ l->len++ ] = token;
2014-05-14 23:52:45 -04:00
return TRUE;
}
2014-05-26 13:07:33 -04:00
void str_array_dump(const str_array *l) {
2014-05-15 00:47:14 -04:00
printf("[");
for ( int i = 0; i < l->len ; i++ ) {
printf("\"%s\"", l->tokens[i] );
if ( i + 1 != l->len ) {
printf(", ");
}
}
printf("]\n");
}
2014-05-14 23:52:45 -04:00
2014-05-15 00:47:14 -04:00