Change wapp_str8_lit implementation to support mutable string literals

This commit is contained in:
Abdelrahman Said 2024-10-17 00:07:30 +01:00
parent 894ae028b7
commit 6d09059911
2 changed files with 10 additions and 14 deletions

View File

@ -1,14 +1,4 @@
#include "str8.h" #include "str8.h"
#include <string.h>
Str8 wapp_str8_lit(char *str) {
if (!str) {
return (Str8){.capacity = 0, .size = 0, .buf = (u8 *)""};
}
u64 size = strlen(str);
return (Str8){.capacity = size, .size = size, .buf = (u8 *)str};
}
char wapp_str8_get(const Str8 *str, u64 index) { char wapp_str8_get(const Str8 *str, u64 index) {
if (index >= str->size) { if (index >= str->size) {
@ -23,5 +13,5 @@ void wapp_str8_set(Str8 *str, u64 index, char c) {
return; return;
} }
str->buf[index] = (u8)c; str->buf[index] = (c8)c;
} }

View File

@ -2,6 +2,7 @@
#define STR8_H #define STR8_H
#include "aliases.h" #include "aliases.h"
#include <string.h>
#ifdef __cplusplus #ifdef __cplusplus
BEGIN_C_LINKAGE BEGIN_C_LINKAGE
@ -11,12 +12,17 @@ typedef struct str8 Str8;
struct str8 { struct str8 {
u64 capacity; u64 capacity;
u64 size; u64 size;
u8 *buf; c8 *buf;
}; };
#define wapp_str8_buf(CAPACITY) ((Str8){.capacity = CAPACITY, .size = 0, .buf = (u8[CAPACITY]){0}}) #define wapp_str8_buf(CAPACITY) ((Str8){.capacity = CAPACITY, .size = 0, .buf = (c8[CAPACITY]){0}})
// Utilises the fact that memcpy returns pointer to dest buffer and that getting
// address of compound literals is valid in C to create a string on the stack
#define wapp_str8_lit(STRING) ((Str8){.capacity = sizeof(STRING) - 1, \
.size = sizeof(STRING) - 1, \
.buf = memcpy(&((c8 [sizeof(STRING)]){0}), STRING, sizeof(STRING))})
Str8 wapp_str8_lit(char *str);
char wapp_str8_get(const Str8 *str, u64 index); char wapp_str8_get(const Str8 *str, u64 index);
void wapp_str8_set(Str8 *str, u64 index, char c); void wapp_str8_set(Str8 *str, u64 index, char c);