codebased/include/common/string.h
2023-04-14 02:17:45 +02:00

50 lines
1.0 KiB
C

#ifndef COMMON_STRING_H
#define COMMON_STRING_H
#include "common/generic_array.h"
#include "common/result.h"
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
const char* data;
size_t length;
} StringView;
typedef struct {
char* data;
size_t length;
} HeapString;
static inline HeapString heapstring_from(const char* text, size_t length)
{
char* allocated = malloc(sizeof(char) * length + 1);
strncpy(allocated, text, length);
HeapString string = {
.data = allocated,
.length = length,
};
return string;
}
static inline HeapString heapstring_from_cstring(const char* text)
{
return heapstring_from(text, strlen(text));
}
static inline void heapstring_destroy(HeapString* string)
{
if (string->data)
free(string->data);
}
GENERIC_ARRAY(char, StringBuilder, stringbuilder)
HeapString stringbuilder_build(StringBuilder* builder);
RESULT(HeapString, HeapString, UnescapeStringResult)
UnescapeStringResult common_unescape_string(StringView source);
HeapString common_escape_string(StringView source);
#endif