/**
* @file actstdlib.c
*/

#include "actstdlib.h"


char* act_strcpy(char *dst, const char *src)
{
	char *start = dst;
	char c;
	do {
		c = *src;
		*dst = c;
		src++;
		dst++;
	} while (c);
	return start;
}

char* act_strncpy(char *dst, const char *src,unsigned int size)
{
	char *ret = dst;
	for (; size; size--){
		if (*src) {
			*dst++ = *src++;
			ret = dst;
		} else {
			*dst++ = '\0';
		}
	}
	return ret;
}

char* act_strcat(char *dst, const char *src)
{
	char *start = dst;
	char c;
	do {
		c = *dst;
		dst++;
	} while (c);
	dst--;
	do {
		c = *src;
		*dst = c;
		src++;
		dst++;
	} while (c);
	return start;
}

char* act_strncat(char *dst, const char *src,unsigned int count)
{
	char *start = dst;
	char c;
	do {
		c = *dst;
		dst++;
	} while (c);
	dst--;
	if (count) {
		do {
			c = *src;
			*dst = c;
			src++;
			dst++;
			count--;
		} while (c && count);
		*dst = '\0';
	}
	return start;
}

int act_strlen(const char *str)
{
    const char *estr = str;
	char c;
	do {
		c = *estr;
		estr++;
	} while (c);
    return ((int)(estr - str - 1));
}

int act_strcmp(const char *s1, const char *s2)
{
	char c1,c2;
	do {
		c1 = *s1++;
		c2 = *s2++;
	} while ((c1) && (c2) && (c1==c2));
	return c1 - c2;
}

static char* _xtoa(unsigned long v,char *string, int r, int is_neg)
{
	char *start = string;
	char buf[33],*p;
	
	p=buf;
	
	do {
		*p++ = "0123456789abcdef"[(v % r) & 0xf];
	} while (v /= r);
	
	if (is_neg) {
		*p++ = '-';
	}
	
	do {
		*string++ = *--p;
	} while (buf != p);
	
	*string = '\0';
	
	return start;
}

char* act_itoa(int v,char *string,int r)
{
    if ((r == 10) && (v < 0)) {
		return _xtoa((unsigned long)(-v), string, r, 1);
	}
	return _xtoa((unsigned long)(v), string, r, 0);
}

int act_memcmp(const void *s1, const void *s2,unsigned int count)
{
	int v1,v2;
	if (!count)
		return 0;
	do {
		v1 = *(unsigned char*)s1;
		v2 = *(unsigned char*)s2;
		s1 = (unsigned char*)s1 + 1;
		s2 = (unsigned char*)s2 + 1;
		count--;
	} while (count && (v1==v2));
	return v1 - v2;
}
