Merge pull request #21 from noverd/klibc-string-1

KLIBC string.h (strcmp, strcpy, strlen and strcat)
This commit is contained in:
Aren Elchinyan 2025-01-13 21:22:56 +03:00 committed by GitHub
commit 19b5ea5ec8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 69 additions and 3 deletions

11
kernel/include/kstring.h Normal file
View File

@ -0,0 +1,11 @@
#ifndef __K_STRING
#define __K_STRING
#include <kstdint.h>
int strcmp(const char *s1, const char *s2);
char *strcpy(char *dst, const char *src);
char *strcat(char *dst, const char *src);
int strlen(const char *s);
#endif

View File

@ -1,5 +1,6 @@
#include <khal.h>
#include <kstdint.h>
#include <kstring.h>
int multiboot2_init(uint64_t *addr, uint32_t magic);
@ -14,6 +15,18 @@ void kernel_main64(uint64_t *multiboot2, uint32_t magic, void *esp, uint64_t bas
} else {
serial_printf("[ERR]\n");
}
char *str1 = "ABCF";
char *str2 = "ABCD";
char buf[7] = "";
auto cmp_value = strcmp(str1, str2);
serial_printf("[LOG] STR1 AND STR2 CMP %d\n", cmp_value);
serial_printf("[LOG] STR1 LEN %d\n", strlen(str1));
strcpy((char*)&buf, str1);
serial_printf("[LOG] STRCPY RESULT: %s\n", buf);
serial_printf("[LOG] STRCPY RESULT LEN %d\n", strlen(buf));
strcat((char*)&buf, "CAT");
serial_printf("[LOG] STRCAT RESULT: %s\n", buf);
serial_printf("[LOG] STRCAT RESULT LEN %d\n", strlen(buf));
for (;;) {}
}
}

42
kernel/klibc/kstring.c Normal file
View File

@ -0,0 +1,42 @@
#include <kstring.h>
#include <kstdint.h>
int strcmp(const char *s1, const char *s2)
{
for (int i = 0;; i++)
{
if (s1[i] > s2[i])
{
return 1;
}
else if (s1[i] < s2[i])
{
return -1; // INT сломан, тут он возращает maxValue.
}
if (s1[i] == '\0' || s2[i] == '\0')
{
return 0;
}
}
}
char *strcpy(char *dst, const char *src)
{
char *buf = dst;
while ((*dst++ = *src++) != '\0'); // Задаем по байту в dst из src, пока результатом этого не станет NUL
return buf;
}
int strlen(const char *s)
{
int i;
for (i = 0; s[i] != '\0'; i++); // Добавляем к i, пока не встретим NUL
return i;
}
char *strcat(char *dst, const char *src)
{
char *buf = dst;
strcpy(dst+strlen(dst), src); // Копируем строку в цель со смешением в длинну dst
return buf;
}

View File

@ -77,4 +77,4 @@ void serial_printf(const char *fmt, ...) {
}
}
va_end(args);
}
}