Files
nt-lite/code/libc.c
T

122 lines
2.7 KiB
C

// everyone needs a little libc
#include <stdint.h>
#include <stddef.h>
char* strcpy(char* dest, const char* src) {
char* d = dest;
while (*src) *d++ = *src++;
*d = 0;
return dest;
}
char* strncpy(char* dest, const char* src, size_t n) {
size_t i;
for (i = 0; i < n && src[i]; i++) dest[i] = src[i];
for (; i < n; i++) dest[i] = 0;
return dest;
}
char* strcat(char* dest, const char* src) {
char* ptr = dest;
while (*ptr != '\0') {
ptr++;
}
while (*src != '\0') {
*ptr = *src;
ptr++;
src++;
}
*ptr = '\0';
return dest;
}
char* strncat(char* dest, const char* src, size_t n) {
char* ptr = dest;
while (*ptr != '\0') {
ptr++;
}
while (n > 0 && *src != '\0') {
*ptr = *src;
ptr++;
src++;
n--;
}
*ptr = '\0';
return dest;
}
int strcmp(const char* s1, const char* s2) {
while (*s1 && *s1 == *s2) s1++, s2++;
return (unsigned char)*s1 - (unsigned char)*s2;
}
int strncmp(const char *s1, const char *s2, size_t n) {
while (n && *s1 && (*s1 == *s2)) {
s1++;
s2++;
n--;
}
return n == 0 ? 0 : *(unsigned char *)s1 - *(unsigned char *)s2;
}
int _stricmp(const char* s1, const char* s2) {
// 0x20 (32) is the bit that differs between 'A' and 'a'
while (*s1 && ((*s1 | 0x20) == (*s2 | 0x20))) {
s1++, s2++;
}
return (unsigned char)(*s1 | 0x20) - (unsigned char)(*s2 | 0x20);
}
size_t strlen(const char* s) {
size_t n = 0;
while (*s++) n++;
return n;
}
size_t strnlen(const char *s, size_t maxlen) {
size_t len;
for (len = 0; len < maxlen; len++) {
if (s[len] == '\0') {
break;
}
}
return len;
}
char* strchr(const char* s, int c) {
while (*s) {
if (*s == (char)c) return (char *)s;
s++;
}
return NULL;
}
char* strrchr(const char* s, int c) {
char ch = (char)c;
const char* last = NULL;
do {
if (*s == ch) last = s;
} while (*s++);
return (char*)last;
}
void* memmove(void* dest, const void* src, size_t n) {
uint8_t* d = (uint8_t *)dest;
const uint8_t* s = (const uint8_t *)src;
if (d < s) {
for (size_t i = 0; i < n; i++) d[i] = s[i];
} else if (d > s) {
for (size_t i = n; i > 0; i--) d[i - 1] = s[i - 1];
}
return dest;
}
int memcmp(const void* s1, const void* s2, size_t n) {
const uint8_t* a = (const uint8_t *)s1;
const uint8_t* b = (const uint8_t *)s2;
for (size_t i = 0; i < n; i++) {
if (a[i] != b[i]) return a[i] - b[i];
}
return 0;
}