cxl/src/String.c

54 lines
1.2 KiB
C

#include "String.h"
#include <string.h>
String * String_new(const char * s)
{
size_t size = strlen(s);
return String_new_size(s, size);
}
String * String_new_size(const char * s, size_t size)
{
String * new_st = (String *)malloc(sizeof(String));
char * smem = (char *)malloc(size + 1u);
memcpy(smem, s, size);
smem[size] = '\0';
new_st->value = smem;
new_st->size = size;
return new_st;
}
String * String_plus(const String * st, const char * s)
{
String * new_st = (String *)malloc(sizeof(String));
size_t size1 = st->size;
size_t size2 = strlen(s);
size_t size = size1 + size2;
char * smem = (char *)malloc(size + 1u);
memcpy(smem, st->value, size1);
memcpy(&smem[size1], s, size2);
smem[size] = '\0';
new_st->value = smem;
new_st->size = size;
return new_st;
}
String * String_concat(String * st, const char * s)
{
size_t size2 = strlen(s);
size_t size = st->size + size2;
char * smem = (char *)malloc(size + 1u);
memcpy(smem, st->value, st->size);
memcpy(&smem[st->size], s, size2);
smem[size] = '\0';
st->value = smem;
st->size = size;
return st;
}
void String_free(String * st)
{
free(st->value);
free(st);
}