libc: Add strings.h

This commit is contained in:
apio 2022-10-22 21:13:22 +02:00
parent 433b307cb2
commit 7600bc5582
4 changed files with 70 additions and 8 deletions

View File

@ -80,9 +80,6 @@ extern "C"
/* Returns the error string associated with the error number err. */ /* Returns the error string associated with the error number err. */
char* strerror(int err); char* strerror(int err);
/* Clears n bytes of buf. */
void* bzero(void* buf, size_t n);
/* Copies the string src into dest. This function is unsafe, use strlcpy instead. */ /* Copies the string src into dest. This function is unsafe, use strlcpy instead. */
__lc_deprecated("strcpy is unsafe and should not be used; use strlcpy instead") char* strcpy(char* dest, __lc_deprecated("strcpy is unsafe and should not be used; use strlcpy instead") char* strcpy(char* dest,
const char* src); const char* src);

View File

@ -0,0 +1,27 @@
#ifndef _STRINGS_H
#define _STRINGS_H
#include <stddef.h>
#ifdef __cplusplus
extern "C"
{
#endif
/* Clears n bytes of buf. */
void bzero(void* buf, size_t n);
/* Copies n bytes of src into dest. */
void bcopy(void* dest, const void* src, size_t n);
/* Compares strings a and b while treating uppercase and lowercase characters as the same. */
int strcasecmp(const char* a, const char* b);
/* Compares at most max bytes of strings a and b while treating uppercase and lowercase characters as the same. */
int strncasecmp(const char* a, const char* b, size_t max);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -230,11 +230,6 @@ extern "C"
return NULL; return NULL;
} }
void* bzero(void* buf, size_t n)
{
return memset(buf, 0, n);
}
char* strstr(const char* haystack, const char* needle) char* strstr(const char* haystack, const char* needle)
{ {
size_t needle_size = strlen(needle); size_t needle_size = strlen(needle);

43
libs/libc/src/strings.cpp Normal file
View File

@ -0,0 +1,43 @@
#include <ctype.h>
#include <string.h>
#include <strings.h>
static char fold(char c)
{
if (isalpha(c)) return tolower(c);
return c;
}
extern "C"
{
void bzero(void* buf, size_t n)
{
memset(buf, 0, n);
}
void bcopy(void* dest, const void* src, size_t n)
{
memcpy(dest, src, n);
}
int strcasecmp(const char* a, const char* b)
{
while (*a && (fold(*a) == fold(*b)))
{
a++;
b++;
}
return (unsigned char)fold(*a) - (unsigned char)fold(*b);
}
int strncasecmp(const char* a, const char* b, size_t max)
{
const char* base = a;
while (*a && (fold(*a) == fold(*b)) && (size_t)(a - base) < (max - 1))
{
a++;
b++;
}
return (unsigned char)fold(*a) - (unsigned char)fold(*b);
}
}