#include <libk/std.h>
#include <libk/string.h>

size_t memset (void* dst, uint8_t b, size_t n) {
  uint8_t* dst1 = dst;
  size_t i;
  for (i = 0; i < n; i++)
    dst1[i] = b;
  return i;
}

void* memcpy (void* dst, const void* src, size_t n) {
  uint8_t* dst1 = dst;
  const uint8_t* src1 = src;
  size_t i;
  for (i = 0; i < n; i++)
    dst1[i] = src1[i];
  return dst;
}

// SOURCE: https://stackoverflow.com/a/48967408
void strncpy (char* dst, const char* src, size_t n) {
  size_t i = 0;
  while (i++ != n && (*dst++ = *src++))
    ;
}

size_t strlen (const char* str) {
  const char* s;
  for (s = str; *s; ++s)
    ;
  return (s - str);
}

int memcmp (const void* s1, const void* s2, size_t n) {
  unsigned char* p = (unsigned char*)s1;
  unsigned char* q = (unsigned char*)s2;

  while (n--) {
    if (*p != *q) {
      return (int)*p - (int)*q;
    }
    p++, q++;
  }
  return 0;
}

int strncmp (const char* s1, const char* s2, size_t n) {
  while (n && *s1 && (*s1 == *s2)) {
    ++s1;
    ++s2;
    --n;
  }
  if (n == 0) {
    return 0;
  } else {
    return (*(unsigned char*)s1 - *(unsigned char*)s2);
  }
}

int strcmp (const char* s1, const char* s2) {
  while (*s1 && (*s1 == *s2)) {
    s1++;
    s2++;
  }
  return *(const unsigned char*)s1 - *(const unsigned char*)s2;
}

/* https://stackoverflow.com/a/2490637 */
char* strcat (char* dest, const char* src) {
  char* rdest = dest;

  while (*dest)
    dest++;

  while ((*dest++ = *src++))
    ;

  return rdest;
}

char* strncat (char* dest, const char* src, size_t n) {
  char* ptr = dest;
  while (*ptr != '\0')
    ptr++;

  while (n > 0 && *src != '\0') {
    *ptr++ = *src++;
    n--;
  }

  *ptr = '\0';
  return dest;
}

void* memmove (void* dest, const void* src, unsigned int n) {
  char* pcSource = (char*)src;
  char* pcDstn = (char*)dest;
  // return if pcDstn and pcSource is NULL
  if ((pcSource == NULL) || (pcDstn == NULL)) {
    return NULL;
  }
  // overlap buffer
  if ((pcSource < pcDstn) && (pcDstn < pcSource + n)) {
    for (pcDstn += n, pcSource += n; n--;) {
      *--pcDstn = *--pcSource;
    }
  } else {
    while (n--) {
      *pcDstn++ = *pcSource++;
    }
  }
  return dest;
}
