libluna+libc: Add strncmp, strncat and strncpy
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
apio 2023-03-12 15:20:44 +01:00
parent 354ffd033c
commit d2049567c8
Signed by: apio
GPG Key ID: B8A7D06E42258954
3 changed files with 44 additions and 0 deletions

View File

@ -32,12 +32,21 @@ extern "C"
/* Compare two null-terminated strings. */
int strcmp(const char* a, const char* b);
/* Compare two fixed-size null-terminated strings. */
int strncmp(const char* a, const char* b, size_t max);
/* Copy the null-terminated string src into dest. Should be avoided to prevent buffer overflow attacks. */
__deprecated char* strcpy(char* dest, const char* src);
/* Copy the fixed-size null-terminated string src into dest. */
char* strncpy(char* dest, const char* src, size_t max);
/* Concatenate the null-terminated string src onto dest. Should be avoided to prevent buffer overflow attacks. */
__deprecated char* strcat(char* dest, const char* src);
/* Concatenate the fixed-size null-terminated string src onto dest. */
char* strncat(char* dest, const char* src, size_t max);
/* Return a pointer to the first occurrence of the character c in str, or NULL if it could not be found. */
char* strchr(const char* str, int c);

View File

@ -12,6 +12,7 @@ extern "C"
usize strnlen(const char* str, usize max);
int strcmp(const char* a, const char* b);
int strncmp(const char* a, const char* b, usize max);
usize strspn(const char* str, const char* accept);
usize strcspn(const char* str, const char* reject);
@ -28,6 +29,9 @@ extern "C"
[[deprecated]] char* strcpy(char* dst, const char* src);
[[deprecated]] char* strcat(char* dst, const char* src);
char* strncpy(char* dest, const char* src, size_t max);
char* strncat(char* dest, const char* src, size_t max);
char* strchr(const char* str, int c);
char* strrchr(const char* str, int c);
}

View File

@ -64,6 +64,17 @@ extern "C"
return *(const u8*)a - *(const u8*)b;
}
int strncmp(const char* a, const char* b, usize max)
{
const char* s = a;
while (*a && (*a == *b) && (size_t)(a - s) < (max - 1))
{
a++;
b++;
}
return *(const u8*)a - *(const u8*)b;
}
usize wcslen(const wchar_t* str)
{
const wchar_t* i = str;
@ -113,6 +124,26 @@ extern "C"
return s;
}
char* strncpy(char* dest, const char* src, size_t max)
{
size_t i;
for (i = 0; i < max && src[i] != 0; i++) dest[i] = src[i];
for (; i < max; i++) dest[i] = 0;
return dest;
}
char* strncat(char* dest, const char* src, size_t max)
{
size_t len = strlen(dest);
size_t i;
for (i = 0; i < max && *(src + i); i++) *(dest + len + i) = *(src + i);
*(dest + len + i) = '\0';
return dest;
}
char* strchr(const char* str, int c)
{
while (*str && *str != c) str++;