Add a string/string mapper struct

This commit is contained in:
Nils O. Selåsdal
2014-02-04 20:51:47 +01:00
parent 3119016172
commit 0c3fc0f31d
3 changed files with 53 additions and 6 deletions
+18 -3
View File
@@ -8,17 +8,23 @@ struct UCValStr {
const char *str;
};
struct UCStrStr {
const char *val;
const char *str;
};
/** Helper macro to define an entry in a UCValStr array */
#define UC_VS_ENTRY(constant) {constant, #constant}
#define UC_VS_TERMINATOR {-1, NULL}
#define UC_SS_TERMINATOR {NULL, NULL}
/** Find @val in @array.
* The last .str in @array must be a NULL pointer.
/** find @val in @array.
* the last .str in @array must be a null pointer.
* (does a linear search)
*
* @param val value to find
* @param array array to search
* @return the string associated with @val or NULL
* @return the string associated with @val or null
*/
const char *uc_val_2_str(unsigned int val, const struct UCValStr *array);
@@ -34,5 +40,14 @@ const char *uc_val_2_str_bs(unsigned int val,
const struct UCValStr *array,
size_t array_len);
/** find @val in @array.
* the last .val in @array must be a null pointer.
* (does a linear search)
*
* @param val value to find, using strcmp
* @param array array to search
* @return the string associated with @val or null
*/
const char *uc_str_2_str(const char *val, const struct UCStrStr *array);
#endif
+20 -3
View File
@@ -1,4 +1,4 @@
#include <stdio.h>
#include <string.h>
#include <limits.h>
#include "ucore/val_str.h"
#include "ucore/saturating_math.h"
@@ -25,13 +25,15 @@ const char *uc_val_2_str_bs(unsigned int val,
{
size_t i = array_len;
const struct UCValStr *start = array;
const char *found = NULL;
while (i != 0) {
const struct UCValStr *curr;
curr = &start[i / 2]; //middle
if (curr->val == val) {
return curr->str;
found = curr->str;
break;
}
if (curr->val < val) {
@@ -42,6 +44,21 @@ const char *uc_val_2_str_bs(unsigned int val,
i = i / 2;
}
return NULL;
return found;
}
const char *uc_str_2_str(const char *val, const struct UCStrStr *array)
{
const char *found = NULL;
while (array->val) {
if (strcmp(val, array->val) == 0) {
found = array->str;
break;
}
array++;
}
return found;
}
+15
View File
@@ -56,6 +56,19 @@ START_TEST (test_val_str_bsearch_even)
fail_if(uc_val_2_str_bs(999 , vals , len) != NULL);
END_TEST
START_TEST (test_str_str_search)
struct UCStrStr vals[] = {
{"1", "A"},
{"2", "B"},
{"3", "C"},
UC_SS_TERMINATOR
};
ck_assert_str_eq(uc_str_2_str("1" , vals) , "A");
ck_assert_str_eq(uc_str_2_str("2" , vals) , "B");
ck_assert_str_eq(uc_str_2_str("3" , vals) , "C");
fail_if(uc_str_2_str("10", vals) != NULL);
END_TEST
Suite *val_str_suite(void)
{
@@ -65,6 +78,8 @@ Suite *val_str_suite(void)
tcase_add_test(tc, test_val_str_bsearch_odd);
tcase_add_test(tc, test_val_str_bsearch_even);
tcase_add_test(tc, test_str_str_search);
suite_add_tcase(s, tc);
return s;