~donmcc/astr

f7ba3f5976c8ed26fbd3a10cfc84af347fe16787 — Don McCaughey 1 year, 7 months ago baa5210
Added the `astr_empty()` inline function.

The `astr_empty()` function tests a given string to see if it is `NULL`
or points to an empty string.
5 files changed, 40 insertions(+), 1 deletions(-)

M README.md
M astr.3
M astr.c
M astr.h
M astr_tests.c
M README.md => README.md +5 -0
@@ 36,6 36,11 @@ Allocate an empty string.
Allocate a formatted string.

    bool
    astr_empty(char const *s);

Check if a string is `NULL` or zero-length.

    bool
    astr_eq(char const *s1, char const *s2);

Compare the bytes of two strings for equality; `s1` and `s2` may be `NULL`.

M astr.3 => astr.3 +15 -0
@@ 5,6 5,7 @@
.Nm astr_alloc_empty ,
.Nm astr_alloc_formatted ,
.Nm astr_alloc_formatted_from_va_list ,
.Nm astr_empty ,
.Nm astr_eq ,
.Nm astr_formatted_length ,
.Nm astr_formatted_length_from_va_list ,


@@ 20,6 21,8 @@
.Ft char *
.Fn astr_alloc_formatted_from_va_list "char const *format" "va_list arguments"
.Ft bool
.Fn astr_empty "char const *s"
.Ft bool
.Fn astr_eq "char const s1" "char const s2"
.Ft size_t
.Fn astr_formatted_length "char const *format" "..."


@@ 81,6 84,11 @@ and
.Fn astr_alloc_formatted_from_va_list
allocate formatted strings.
.Pp
.Fn astr_empty
tests if a given string pointer is
.Dv NULL
or zero-length.
.Pp
.Fn astr_eq
compares two string pointers for equality in an encoding agnostic way.
The arguments


@@ 116,6 124,13 @@ pointer and set
to
.Er EINVAL .
.Pp
.Fn astr_empty
returns
.Dv true
if the string pointer is
.Dv NULL
or points to an empty string.
.Pp
.Fn astr_eq
returns
.Dv true

M astr.c => astr.c +3 -0
@@ 101,5 101,8 @@ extern char *
astr_alloc_empty(void);

extern bool
astr_empty(char const *s);

extern bool
astr_eq(char const *s1, char const *s2);


M astr.h => astr.h +7 -1
@@ 36,10 36,16 @@ astr_alloc_empty(void)
}

inline bool
astr_empty(char const *s)
{
    return !s || !s[0];
}

inline bool
astr_eq(char const *s1, char const *s2)
{
    if (s1 == s2) return true;
    if (NULL == s1 || NULL == s2) return false;
    if (!s1 || !s2) return false;
    return 0 == strcmp(s1, s2);
}


M astr_tests.c => astr_tests.c +10 -0
@@ 37,6 37,15 @@ test_astr_alloc_formatted_for_NULL_format(void)


static void
test_astr_empty(void)
{
    assert(astr_empty(NULL));
    assert(astr_empty(""));
    assert(!astr_empty("foo"));
}


static void
test_astr_eq(void)
{
    char *s = astr_alloc_formatted("foo");


@@ 154,6 163,7 @@ main(int argc, char *argv[])
    test_astr_alloc_empty();
    test_astr_alloc_formatted();
    test_astr_alloc_formatted_for_NULL_format();
    test_astr_empty();
    test_astr_eq();
    test_astr_eq_for_NULL_string();
    test_astr_eq_for_empty_strings();