feat: (str) str_cmp, str_eq

This commit is contained in:
thetek 2023-02-15 09:20:57 +01:00
parent b39ba90bc9
commit 197f826067
3 changed files with 40 additions and 0 deletions

View File

@ -1,6 +1,7 @@
#ifndef CUTILS_STR_H_
#define CUTILS_STR_H_
#include <stdbool.h>
#include <stddef.h>
/* represents a string, where length and capacity are stored alongside the string data. */
@ -18,5 +19,7 @@ void str_new_from_len (str_t *str, const char *src, size_t len); /* initialize a
void str_free (str_t *str); /* free the contents of a str_t string. */
void str_append (str_t *str, const char *src); /* append a string to the end of a str_t string. */
void str_append_len (str_t *str, const char *src, size_t len); /* append a string to the end of a str_t string with a given length. */
int str_cmp (const str_t *str, const char *s2); /* compare a str_t string with a cstring. */
bool str_eq (const str_t *str, const char *s2); /* check if a str_t string equals a cstring. */
#endif // CUTILS_STR_H_

View File

@ -121,3 +121,32 @@ str_append_len (str_t *str, const char *src, size_t len)
str->len += len;
str->str[str->len] = '\0';
}
/**
* compare a str_t string with a cstring.
*
* @param str: the str_t string to compare
* @param s2: the cstring to compare
*
* @return integer less than, equal to, or greater than zero if str is found
* to be less than, to match, or to be greater than s2
*/
int
str_cmp (const str_t *str, const char *s2)
{
return strcmp (str->str, s2);
}
/**
* check if a str_t string equals a cstring.
*
* @param str: the str_t string to compare
* @param s2: the cstring to compare
*
* @return true if str equals s2, else false
*/
inline bool
str_eq (const str_t *str, const char *s2)
{
return str_cmp (str, s2) == 0;
}

View File

@ -84,6 +84,14 @@ test_str (void)
test_add (&group, test_assert (str.cap = next_pow_of_two (2 * strlen (s))), "str_append .cap");
str_free (&str);
str_new_from (&str, s);
test_add (&group, test_assert (str_eq (&str, s)), "str_eq true");
test_add (&group, test_assert (!str_eq (&str, "foo")), "str_eq false");
test_add (&group, test_assert (str_cmp (&str, "A") > 0), "str_eq greater");
test_add (&group, test_assert (str_cmp (&str, s) == 0), "str_eq equal");
test_add (&group, test_assert (str_cmp (&str, "Z") < 0), "str_eq less");
str_free (&str);
return test_group_get_results (&group);
}