summaryrefslogtreecommitdiff
path: root/src/user/lib/libc/std/string.c
blob: d8e4a48e3411bc80930d49de27b170fdeeef2498 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#include <string.h>
#include <stdlib.h>

int strlen(const char *str) {
	int i = 0;
	while (str[i++]);
	return i-1;
}

char *strchr(const char *str, int c) {
	while (*str) {
		if (*str == c) return (char*)str;
		str++;
	}
	return NULL;
}

char *strcpy(char *dest, const char *src) {
	memcpy(dest, src, strlen(src) + 1);
	return (char*)src;
}

char *strdup(const char *src) {
	char* ret = (char*)malloc(strlen(src) + 1);
	if (ret == NULL) return ret;
	strcpy(ret, src);
	return ret;
}

char *strcat(char *dest, const char *src) {
	char *dest2 = dest;
	dest2 += strlen(dest) - 1;
	while (*src) {
		*dest2 = *src;
		src++;
		dest2++;
	}
	*dest2 = 0;
	return dest;
}

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

void *memcpy(void *vd, const void *vs, int count) {
	uint8_t *dest = (uint8_t*)vd, *src = (uint8_t*)vs;
	int f = count % 4, n = count / 4, i;
	const uint32_t* s = (uint32_t*)src;
	uint32_t* d = (uint32_t*)dest;
	for (i = 0; i < n; i++) {
		d[i] = s[i];
	}
	if (f != 0) {
		for (i = count - f; i < count; i++) {
			dest[i] = src[i];
		}
	}
	return vd;
}

void *memset(void *dest, int val, int count) {
	uint8_t *dest_c = (uint8_t*)dest;
	int i;
	for (i = 0; i < count; i++) {
		dest_c[i] = val;
	}
	return dest;
}

uint16_t *memsetw(uint16_t *dest, uint16_t val, int count) {
	int i;
	for (i = 0; i < count; i++) {
		dest[i] = val;
	}
	return dest;
}


// Formatting

char* format_int(char* buf, int number) {
	if (number == 0) {
		*(buf++) = '0';
		return buf;
	}
	if (number < 0) {
		*(buf++) = '-';
		number = 0 - number;
	}

	int order = 0, temp = number, i;
	char numbers[] = "0123456789";
	while (temp > 0) {
		order++;
		temp /= 10;
	}

	for (i = order; i > 0; i--) {
		buf[i - 1] = numbers[number % 10];
		number /= 10;
	}
	return buf + order;
}

char* format_hex(char *buf, unsigned v) {
	*(buf++) = '0';
	*(buf++) = 'x';

	int i;
	char hexdigits[] = "0123456789ABCDEF";
	for (i = 0; i < 8; i++) {
		*(buf++) = hexdigits[v >> 28];
		v = v << 4;
	}
	return buf;
}