#include "util.h"

void *memset(void *s, int c, size_t n) {
    unsigned char *p = (unsigned char*)s;
    for(size_t i = 0; i < n; i++) p[i] = (unsigned char)c;
    return s;
}

void *memcpy(void *dest, const void *src, size_t n) {
    unsigned char *d = (unsigned char*)dest;
    const unsigned char *s = (const unsigned char*)src;
    for(size_t i = 0; i < n; i++) d[i] = s[i];
    return dest;
}

void *memmove(void *dest, const void *src, size_t n) {
    unsigned char *d = (unsigned char*)dest;
    const unsigned char *s = (const unsigned char*)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 unsigned char *p1 = (const unsigned char*)s1;
    const unsigned char *p2 = (const unsigned char*)s2;
    for(size_t i = 0; i < n; i++) {
        if(p1[i] != p2[i]) return p1[i] - p2[i];
    }
    return 0;
}

size_t strlen(const char *s) {
    size_t len = 0;
    while(s[len]) len++;
    return len;
}

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) {
    for(size_t i = 0; i < n; i++) {
        if(s1[i] != s2[i]) return (unsigned char)s1[i] - (unsigned char)s2[i];
        if(!s1[i]) return 0;
    }
    return 0;
}

int atoi(const char *s) {
    int n = 0, sign = 1;
    while(*s == ' ') s++;
    if(*s == '-') { sign = -1; s++; }
    else if(*s == '+') s++;
    while(*s >= '0' && *s <= '9') n = n * 10 + (*s++ - '0');
    return sign * n;
}

char *strcpy(char *dest, const char *src) {
    char *d = dest;
    while((*d++ = *src++));
    return dest;
}
