kern/lib/c/string.c

127 lines
2.3 KiB
C

/* See the end of this file for copyright and license terms. */
#include <gay/types.h>
#include <string.h>
int memcmp(const void *s1, const void *s2, size_t n)
{
int delta = 0;
while (n-- > 0) {
/* POSIX explicitly wants a cast to unsigned char */
delta = *(const unsigned char *)s1++ - *(const unsigned char *)s2++;
if (delta != 0)
break;
}
return delta;
}
void *memcpy(void *dest, const void *src, size_t n)
{
u8 *tmp = (u8 *)dest;
while (n-- > 0)
*tmp++ = *(const u8 *)src++;
return dest;
}
void *memset(void *ptr, int c, size_t n)
{
char *tmp = (char *)ptr;
while (n-- > 0)
*tmp++ = (char)c;
return ptr;
}
void *memmove(void *dest, const void *src, size_t n)
{
char *tmp = (char *)dest;
const char *s = (const char *)src;
if (dest == src)
return dest;
if (dest < src) {
while (n-- != 0)
*tmp++ = *s++;
} else {
tmp += n;
s += n;
while (n-- != 0)
*--tmp = *--s;
}
return dest;
}
int strcmp(const char *s1, const char *s2)
{
while (*s1 == *s2) {
if (*s1++ == '\0' || *s2++ == '\0')
break;
}
/* POSIX explicitly wants a cast to unsigned char */
return *((const unsigned char *)s1) - *((const unsigned char *)s2);
}
char *strcpy(char *dest, const char *src)
{
char *tmp = dest;
while ((*tmp++ = *src++) != '\0');
/* nothing */
return dest;
}
char *strncpy(char *dest, const char *src, size_t n)
{
char *tmp = dest;
while (n-- != 0) {
if ((*tmp++ = *src++) == '\0')
break;
}
return dest;
}
size_t strlen(const char *s)
{
const char *tmp = s;
while (*tmp++ != '\0');
/* nothing */
return (size_t)tmp - (size_t)s - 1;
}
size_t strnlen(const char *s, size_t maxlen)
{
const char *tmp = s;
while (*tmp++ != '\0' && maxlen-- > 0);
/* nothing */
return (size_t)tmp - (size_t)s - 1;
}
/*
* This file is part of GayBSD.
* Copyright (c) 2021 fef <owo@fef.moe>.
*
* GayBSD is nonviolent software: you may only use, redistribute, and/or
* modify it under the terms of the Cooperative Nonviolent Public License
* (CNPL) as found in the LICENSE file in the source code root directory
* or at <https://git.pixie.town/thufie/npl-builder>; either version 7
* of the license, or (at your option) any later version.
*
* GayBSD comes with ABSOLUTELY NO WARRANTY, to the extent
* permitted by applicable law. See the CNPL for details.
*/