fix: (cstr) null checks

This commit is contained in:
thetek 2023-02-12 17:04:36 +01:00
parent 712baafd59
commit 5585cc2d87
2 changed files with 32 additions and 16 deletions

View File

@ -1,5 +1,6 @@
#include "cstr.h"
#include <ctype.h>
#include <errno.h>
#include <string.h>
/**
@ -16,6 +17,8 @@
char *
strtrim (char *str)
{
if (str == NULL) return errno = EINVAL, NULL;
strtrimr (str);
return strtriml (str);
}
@ -33,6 +36,8 @@ strtrim (char *str)
char *
strtriml (char *str)
{
if (str == NULL) return errno = EINVAL, NULL;
while (*str && isspace (*str))
str++;
@ -48,11 +53,13 @@ strtriml (char *str)
*
* @return the new string length
*/
size_t
ssize_t
strtrimr (char *str)
{
size_t len, i;
if (str == NULL) return errno = EINVAL, -1;
i = len = strlen (str);
while (i <= len && isspace (str[i - 1]))
i--;
@ -61,11 +68,13 @@ strtrimr (char *str)
return i;
}
size_t
ssize_t
strcount (const char *str, char c)
{
size_t count;
if (str == NULL) return errno = EINVAL, -1;
count = 0;
while (*str)
if (*str++ == c)
@ -77,21 +86,27 @@ strcount (const char *str, char c)
void
strdowncase (char *str)
{
while (*str)
{
if (isupper (*str))
*str += 0x20;
str++;
}
if (str == NULL)
errno = EINVAL;
else
while (*str)
{
if (isupper (*str))
*str += 0x20;
str++;
}
}
void
strupcase (char *str)
{
while (*str)
{
if (islower (*str))
*str -= 0x20;
str++;
}
if (str == NULL)
errno = EINVAL;
else
while (*str)
{
if (islower (*str))
*str -= 0x20;
str++;
}
}

View File

@ -2,11 +2,12 @@
#define CUTILS_CSTR_H_
#include <stddef.h>
#include <sys/types.h>
char *strtrim (char *str); /* trim whitespace of a cstring (both beginning and end) */
char *strtriml (char *str); /* trim whitespace of a cstring on the left (beginning of string). */
size_t strtrimr (char *str); /* trim whitespace of a cstring on the right (end of string) */
size_t strcount (const char *str, char c);
ssize_t strtrimr (char *str); /* trim whitespace of a cstring on the right (end of string) */
ssize_t strcount (const char *str, char c);
void strdowncase (char *str);
void strupcase (char *str);