diff options
Diffstat (limited to 'src/util')
| -rw-r--r-- | src/util/util.c | 23 | ||||
| -rw-r--r-- | src/util/util.h | 5 | ||||
| -rw-r--r-- | src/util/util.test.c | 37 | 
3 files changed, 62 insertions, 3 deletions
diff --git a/src/util/util.c b/src/util/util.c index d3e8742..05701c6 100644 --- a/src/util/util.c +++ b/src/util/util.c @@ -23,12 +23,12 @@ void *kai_expand_array(void **array, size_t *count, size_t element_size)  } -int kai_text_to_reals(ka_real_t *dest, const char *str, size_t count) +size_t kai_text_to_reals(ka_real_t *dest, const char *str, size_t count)  {  	char *nptr = (char*) str;  	char *end; -	int result = count; +	size_t result = count;  	for (int i=0; i<count; i++) {  		dest[i] = KA_STR_TO_REAL(nptr, &end); @@ -40,3 +40,22 @@ int kai_text_to_reals(ka_real_t *dest, const char *str, size_t count)  	return result;  } + + +size_t kai_text_to_longs(long *dest, const char *str, size_t count) +{ +	char *nptr = (char*) str; +	char *end; + +	size_t result = count; + +	for (int i=0; i<count; i++) { +		dest[i] = strtol(nptr, &end, 10); +		if (nptr == end) { +			result -= 1; +		} +		nptr = end; +	} + +	return result; +} diff --git a/src/util/util.h b/src/util/util.h index d6cdd20..0b6bc15 100644 --- a/src/util/util.h +++ b/src/util/util.h @@ -29,6 +29,9 @@ void * kai_expand_array(void **array, size_t *len, size_t element_size);   * in the string to convert, this is the same as `count`. If not, it is the number of   * actual elements present in the string.   */ -int kai_text_to_reals(ka_real_t *dest, const char *str, size_t count); +size_t kai_text_to_reals(ka_real_t *dest, const char *str, size_t count); + + +size_t kai_text_to_longs(long *dest, const char *str, size_t count);  #endif diff --git a/src/util/util.test.c b/src/util/util.test.c index 26aa3d1..6288039 100644 --- a/src/util/util.test.c +++ b/src/util/util.test.c @@ -91,5 +91,42 @@ LILY_TEST("convert string to real array with fewer conversions than expected")  #include LILY_PUSH_TEST() +LILY_TEST("convert string to int array") +{ +	/* the lucas numbers 4 u math fans out there */ +	const char *str = "2 1 3 4 7"; +	long array[5]; +	int conv = kai_text_to_longs(array, str, 5); + +	CHECK_EQ(conv, 5, "%d"); + +	CHECK_EQ(array[0], 2, "%d"); +	CHECK_EQ(array[1], 1, "%d"); +	CHECK_EQ(array[2], 3, "%d"); +	CHECK_EQ(array[3], 4, "%d"); +	CHECK_EQ(array[4], 7, "%d"); +} +#include LILY_PUSH_TEST() + + +LILY_TEST("convert string to int array with fewer conversions than expected") +{ +	const char *str = "2 1"; +	long array[5]; +	int conv = kai_text_to_longs(array, str, 5); + +	CHECK_EQ(conv, 2, "%d"); + +	CHECK_EQ(array[0], 2, "%d"); +	CHECK_EQ(array[1], 1, "%d"); +	CHECK_EQ(array[2], 0, "%d"); +	CHECK_EQ(array[3], 0, "%d"); +	CHECK_EQ(array[4], 0, "%d"); +} +#include LILY_PUSH_TEST() + + + +  #define LILY_FILE_END  #include LILY_REGISTER_TESTS()  | 
