Added some string.h functions

This commit is contained in:
2024-04-08 20:19:26 +02:00
parent b6f78ed9c1
commit 54c49f7e7d
5 changed files with 64 additions and 1 deletions
+40
View File
@@ -1,4 +1,5 @@
#include "string.h"
#include "stdint.h"
// Source: http://www.strudel.org.uk/itoa/
char* itoa(uint32_t val, uint8_t base) {
@@ -17,3 +18,42 @@ char* itoa(uint32_t val, uint8_t base) {
return &buf[i + 1];
}
// Some implementations taken from https://en.wikibooks.org/wiki/C_Programming/String_manipulation
char* strcat(char* str1, const char* str2) {
char* s = str1;
while (*s != '\0') { s++; }
strcpy(s, str2);
return str1;
}
char* strchr(const char* str, char c) {
const char* s = str;
while (*s != '\0' && *s != c) { s++; }
return (*s == c) ? (char*)s : NULL;
}
int strcmp(const char* str1, const char* str2) {
while (*str1 != '\0' && *str1 == *str2) {
str1++;
str2++;
}
uint8_t c1 = (*(uint8_t*)str1);
uint8_t c2 = (*(uint8_t*)str2);
return ((c1 < c2) ? -1 : (c1 > c2));
}
char* strcpy(char* str1, const char* str2) {
char* dst = str1;
const char* src = str2;
while ((*dst++ = *src++) != '\0');
return str1;
}
uint32_t strlen(const char* str) {
const char* p = str;
while (*++p != '\0');
return (uint32_t)(p - str);
}
+6
View File
@@ -5,4 +5,10 @@
char* itoa(uint32_t val, uint8_t base);
char* strcat(char* str1, const char* str2);
char* strchr(const char* str, char c);
int strcmp(const char* str1, const char* str2);
char* strcpy(char* str1, const char* str2);
uint32_t strlen(const char* str);
#endif
+14
View File
@@ -11,6 +11,16 @@ void outb(uint16_t port, uint8_t data) {
asm volatile("out %0, %1" :: "a"(data), "Nd"(port));
}
uint16_t inw(uint16_t port) {
uint8_t result;
asm volatile("in %1, %0" : "=a"(result) : "Nd"(port));
return result;
}
void outw(uint16_t port, uint16_t data) {
asm volatile("out %0, %1" :: "a"(data), "Nd"(port));
}
char* memcopy(char* src, char* dst, uint16_t length) {
for (int i = 0; i < length; i++) {
*(dst + i) = *(src + i);
@@ -37,3 +47,7 @@ void hlt() {
asm volatile("hlt");
}
void exit() {
outw(0x0604, 0x2000);
}
+4
View File
@@ -6,6 +6,8 @@
// Port functions
uint8_t inb(uint16_t port);
void outb(uint16_t port, uint8_t data);
uint16_t inw(uint16_t port);
void outw(uint16_t port, uint16_t data);
// Memory functions
char* memcopy(char* src, char* dst, uint16_t length);
@@ -16,4 +18,6 @@ void cli();
void sti();
void hlt();
void exit();
#endif