Add String module

This commit is contained in:
Josh Holtrop 2018-04-07 09:14:26 -04:00
parent 7107699bc5
commit 961b3297f5
2 changed files with 82 additions and 0 deletions

63
src/String.c Normal file
View File

@ -0,0 +1,63 @@
#include "String.h"
#include <string.h>
String * String_new(const char * s)
{
String * new_st = (String *)malloc(sizeof(String));
size_t size = strlen(s);
if (size != 0u)
{
char * smem = (char *)malloc(size);
memcpy(smem, s, size);
new_st->value = smem;
}
else
{
new_st->value = NULL;
}
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);
memcpy(smem, st->value, size1);
memcpy(&smem[size1], s, size2);
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 = NULL;
if (size != 0u)
{
smem = (char *)malloc(size);
memcpy(smem, st->value, st->size);
memcpy(&smem[st->size], s, size2);
}
if (st->value != NULL)
{
free(st->value);
}
st->value = smem;
st->size = size;
return st;
}
void String_free(String * st)
{
if (st->value != NULL)
{
free(st->value);
}
free(st);
}

19
src/String.h Normal file
View File

@ -0,0 +1,19 @@
#ifndef STRING_H
#define STRING_H
#include <stdlib.h>
typedef struct
{
char * value;
size_t size;
} String;
String * String_new(const char * s);
String * String_plus(const String * st, const char * s);
String * String_concat(String * st, const char * s);
static inline char * String_cstr(const String * st) { return st->value; }
static inline size_t String_size(const String * st) { return st->size; }
void String_free(String * st);
#endif