addition: init and destroy ByteString

This commit is contained in:
2026-05-31 20:48:45 -06:00
parent af8bf3a747
commit f5c5e4cdd7
3 changed files with 69 additions and 16 deletions

View File

@@ -1,6 +1,19 @@
#ifndef LAE_STRINGS_H
#define LAE_STRINGS_H
#include "lae_allocator.h"
typedef struct ByteStr ByteStr;
typedef enum {
STR_OK,
STR_BAD_ALLOC,
STR_OUT_OF_BOUNDS,
STR_NULL_ARG,
STR_NULL_STRING,
STR_INVALID_CAPACITY,
} StringErr;
StringErr bstr_init(ByteStr **bstr, Allocator alloc, size_t capacity);
StringErr bstr_destroy(ByteStr **bstr);
#endif

View File

@@ -1,12 +1,63 @@
#include "lae_strings.h"
#include "lae_allocator.h"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct ByteStr {
uint8_t* buf;
size_t len;
size_t cap;
uint8_t *buf;
size_t len;
size_t cap;
Allocator allocator;
};
StringErr bstr_init(ByteStr **bstr, Allocator alloc, size_t capacity) {
if (bstr == NULL) {
return STR_NULL_ARG;
}
if (capacity < 1) {
return STR_INVALID_CAPACITY;
}
ByteStr *new_bstr = alloc.alloc(alloc.ctx, sizeof(ByteStr));
if (new_bstr == NULL) {
return STR_BAD_ALLOC;
}
uint8_t *new_buf = alloc.alloc(alloc.ctx, capacity);
if (new_buf == NULL) {
alloc.free(alloc.ctx, new_bstr, sizeof(ByteStr));
return STR_BAD_ALLOC;
}
*new_bstr = (ByteStr){
.buf = new_buf,
.len = 0,
.cap = capacity,
.allocator = alloc,
};
*bstr = new_bstr;
return STR_OK;
}
StringErr bstr_destroy(ByteStr **bstr) {
if (bstr == NULL || *bstr == NULL) {
return STR_NULL_ARG;
}
ByteStr *tmp = *bstr;
tmp->allocator.free(tmp->allocator.ctx, tmp->buf, tmp->cap);
tmp->buf = NULL;
tmp->cap = 0;
tmp->len = 0;
tmp->allocator.free(tmp->allocator.ctx, *bstr, sizeof(ByteStr));
*bstr = NULL;
return STR_OK;
}

View File

@@ -1,18 +1,7 @@
#include "mylib.h"
#include "lae_strings.h"
#include <stdio.h>
#include <stdlib.h>
int main(void) {
MyLib *lib = mylib_create();
if (!lib) {
fprintf(stderr, "Error: could not create MyLib\n");
return EXIT_FAILURE;
}
int result = mylib_do_something(lib, 42);
printf("Result: %d\n", result);
mylib_destroy(lib);
return EXIT_SUCCESS;
return EXIT_SUCCESS;
}