megadrive_test1

diff src/libc/string.c @ 6:862f8a034cae

expanding the megadrive code
author John Tsiombikas <nuclear@member.fsf.org>
date Sat, 11 Feb 2017 08:56:42 +0200
parents
children
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/libc/string.c	Sat Feb 11 08:56:42 2017 +0200
     1.3 @@ -0,0 +1,107 @@
     1.4 +#include <string.h>
     1.5 +
     1.6 +void *memset(void *s, int c, size_t n)
     1.7 +{
     1.8 +	char *ptr = s;
     1.9 +	while(n--) {
    1.10 +		*ptr++ = c;
    1.11 +	}
    1.12 +	return s;
    1.13 +}
    1.14 +
    1.15 +void *memcpy(void *dest, const void *src, size_t n)
    1.16 +{
    1.17 +	char *dptr = dest;
    1.18 +	const char *sptr = src;
    1.19 +
    1.20 +	while(n--) {
    1.21 +		*dptr++ = *sptr++;
    1.22 +	}
    1.23 +	return dest;
    1.24 +}
    1.25 +
    1.26 +void *memmove(void *dest, const void *src, size_t n)
    1.27 +{
    1.28 +	int i;
    1.29 +	char *dptr;
    1.30 +	const char *sptr;
    1.31 +
    1.32 +	if(dest <= src) {
    1.33 +		/* forward copy */
    1.34 +		dptr = dest;
    1.35 +		sptr = src;
    1.36 +		for(i=0; i<n; i++) {
    1.37 +			*dptr++ = *sptr++;
    1.38 +		}
    1.39 +	} else {
    1.40 +		/* backwards copy */
    1.41 +		dptr = (char*)dest + n - 1;
    1.42 +		sptr = (char*)src + n - 1;
    1.43 +		for(i=0; i<n; i++) {
    1.44 +			*dptr-- = *sptr--;
    1.45 +		}
    1.46 +	}
    1.47 +
    1.48 +	return dest;
    1.49 +}
    1.50 +
    1.51 +size_t strlen(const char *s)
    1.52 +{
    1.53 +	size_t len = 0;
    1.54 +	while(*s++) len++;
    1.55 +	return len;
    1.56 +}
    1.57 +
    1.58 +char *strchr(const char *s, int c)
    1.59 +{
    1.60 +	while(*s) {
    1.61 +		if(*s == c) {
    1.62 +			return (char*)s;
    1.63 +		}
    1.64 +		s++;
    1.65 +	}
    1.66 +	return 0;
    1.67 +}
    1.68 +
    1.69 +char *strrchr(const char *s, int c)
    1.70 +{
    1.71 +	const char *ptr = s;
    1.72 +
    1.73 +	/* find the end */
    1.74 +	while(*ptr) ptr++;
    1.75 +
    1.76 +	/* go back checking for c */
    1.77 +	while(--ptr >= s) {
    1.78 +		if(*ptr == c) {
    1.79 +			return (char*)ptr;
    1.80 +		}
    1.81 +	}
    1.82 +	return 0;
    1.83 +}
    1.84 +
    1.85 +char *strstr(const char *str, const char *substr)
    1.86 +{
    1.87 +	while(*str) {
    1.88 +		const char *s1 = str;
    1.89 +		const char *s2 = substr;
    1.90 +
    1.91 +		while(*s1 && *s1 == *s2) {
    1.92 +			s1++;
    1.93 +			s2++;
    1.94 +		}
    1.95 +		if(!*s2) {
    1.96 +			return (char*)str;
    1.97 +		}
    1.98 +		str++;
    1.99 +	}
   1.100 +	return 0;
   1.101 +}
   1.102 +
   1.103 +int strcmp(const char *s1, const char *s2)
   1.104 +{
   1.105 +	while(*s1 && *s1 == *s2) {
   1.106 +		s1++;
   1.107 +		s2++;
   1.108 +	}
   1.109 +	return *s1 - *s2;
   1.110 +}