Add count_characters and a CUnit test series for it.

This commit is contained in:
Jonathan Bennett
2015-12-31 02:12:08 +00:00
parent 56be13b3f6
commit bc55f0f21f
7 changed files with 59 additions and 6 deletions

View File

@@ -50,6 +50,11 @@
#define NULL_STRING "<NULL>" /*!< String which represents a NULL buffer */
#ifdef HAVE_C_UNIT_TESTS
#include "cunit_common.h"
DECLARE_TEST_SUITE(utils_test, "Utility functions test suite");
#endif
/**
* Structure to handle an encryption mode string string and its associated integer value
*/
@@ -1052,5 +1057,43 @@ ipv4_resolve(const char *dns_str, char *ip_str)
return error;
}
int
count_characters(const char *str, const char match, int len)
{
int i, count = 0;
for (i=0; i < len; i++) {
if (str[i] == match)
count++;
if (str[i] == '\0')
return count;
}
return count;
}
#ifdef HAVE_C_UNIT_TESTS
DECLARE_UTEST(test_count_characters, "test the count_characters function")
{
char test_str[32];
strcpy(test_str, "abcd");
CU_ASSERT(count_characters(test_str, 'a', 4) == 1);
strcpy(test_str, "aacd");
CU_ASSERT(count_characters(test_str, 'a', 4) == 2);
strcpy(test_str, "a,b,c,d,");
CU_ASSERT(count_characters(test_str, ',', 4) == 2);
strcpy(test_str, "a,b,c,d,");
CU_ASSERT(count_characters(test_str, ',', 8) == 4);
strcpy(test_str, "aaaa");
CU_ASSERT(count_characters(test_str, 'a', 3) == 3);
}
int register_utils_test(void)
{
ts_init(&TEST_SUITE(utils_test), TEST_SUITE_DESCR(utils_test), NULL, NULL);
ts_add_utest(&TEST_SUITE(utils_test), UTEST_FCT(test_count_characters), UTEST_DESCR(test_count_characters));
return register_ts(&TEST_SUITE(utils_test));
}
#endif
/***EOF***/

View File

@@ -35,6 +35,8 @@
#define MAX_CMDLINE_ARGS 30 /*!< should be way more than enough */
#define MAX_ARGS_LINE_LEN 1024
#define MAX_HOSTNAME_LEN 64
/* Function prototypes
*/
int is_valid_encoded_msg_len(const int len);
@@ -61,11 +63,18 @@ void chop_newline(char *str);
void chop_char(char *str, const char chop);
void chop_spaces(char *str);
/**
*
* \brief counts the occurences of a character
*
* \return returns the number of chars found
*/
int count_characters(const char *str, const char match, int len);
int strtoargv(const char * const args_str, char **argv_new, int *argc_new);
void free_argv(char **argv_new, int *argc_new);
int ipv4_resolve(const char *dns_str, char *ip_str);
int ipv4_resolve(const char *dns_str, char *ip_str);
#if !HAVE_STRLCAT
size_t strlcat(char *dst, const char *src, size_t siz);
#endif