Files
Espresso/lib/espresso/kstring.c
2026-03-20 16:57:08 -05:00

59 lines
1.1 KiB
C

#include <stdlib.h>
#include <types.h>
#include <string.h>
/*
A custom standard for strings for use in the Espresso kernel.
*/
struct kstring {
size_t s_len;
char* data; /* NOT null-terminated */
};
/*
if the length of initial_data is more than initial_len, only initial_len bytes will be copied.
if the length of initial_data is less then initial_len, the rest of the bytes are zeroed.
if initial_data is null, no data is copied and the string in set to zero.
*/
struct kstring* make_kstring(size_t initial_len, const char* initial_data)
{
struct kstring* str = malloc(sizeof(struct kstring));
if (!str)
{
return NULL;
}
str->s_len = initial_len;
str->data = malloc(initial_len);
if (!str->data)
{
return NULL;
}
memset(str->data, 0, initial_len);
if (initial_data)
{
size_t slen = strlen(initial_data);
if (slen < initial_len)
{
strncpy(str->data, initial_data, slen);
}
else if (slen > initial_len)
{
strncpy(str->data, initial_data, initial_len);
}
else
{
strcpy(str->data, initial_data);
}
}
return str;
}