codebased/include/common/string.h
2023-04-25 02:13:20 +02:00

57 lines
1.2 KiB
C

#ifndef COMMON_STRING_H
#define COMMON_STRING_H
#include "common/array.h"
#include "common/maybe_unused.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;
MAYBE_UNUSED 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;
}
MAYBE_UNUSED static inline HeapString heapstring_from_cstring(const char* text)
{
return heapstring_from(text, strlen(text));
}
MAYBE_UNUSED static inline void heapstring_destroy(HeapString* string)
{
if (string->data)
free(string->data);
}
MAYBE_UNUSED static inline HeapString heapstring_clone(const HeapString* source)
{
return heapstring_from(source->data, source->length);
}
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