diff options
author | Freya Murphy <freya@freyacat.org> | 2024-10-04 19:41:10 -0400 |
---|---|---|
committer | Freya Murphy <freya@freyacat.org> | 2024-10-04 19:41:10 -0400 |
commit | 1c11a13ff33873bcc79d4597d31cd252d5c6c1ae (patch) | |
tree | a4321b97f5ad69d1a9b9d06dd629a4dc532758b0 /masm/string.c | |
parent | update msim usage (diff) | |
download | mips-1c11a13ff33873bcc79d4597d31cd252d5c6c1ae.tar.gz mips-1c11a13ff33873bcc79d4597d31cd252d5c6c1ae.tar.bz2 mips-1c11a13ff33873bcc79d4597d31cd252d5c6c1ae.zip |
refactor masm to add codegen step
Diffstat (limited to 'masm/string.c')
-rw-r--r-- | masm/string.c | 81 |
1 files changed, 81 insertions, 0 deletions
diff --git a/masm/string.c b/masm/string.c new file mode 100644 index 0000000..c05e182 --- /dev/null +++ b/masm/string.c @@ -0,0 +1,81 @@ +#include <merror.h> +#include <stdlib.h> + +#include "lex.h" + +/* init a empty string buffer */ +inline void string_init(struct string *string) +{ + string->len = 0; + string->size = 0; + string->allocated = true; + string->str = NULL; +} + +/* free a string buffer */ +inline void string_free(struct string *string) +{ + if (string->allocated && string->str) + free(string->str); +} + +/* clone a string buffer */ +inline int string_clone(struct string *dst, const struct string *const src) +{ + dst->len = src->len; + dst->size = src->len; + dst->allocated = src->allocated; + + /// bss strings do not need to be + /// malloced or copied + if (src->allocated == false) { + dst->str = src->str; + return M_SUCCESS; + } + + dst->str = malloc(sizeof(char) * src->len); + if (dst->str == NULL) { + PERROR("cannot alloc"); + return M_ERROR; + } + memcpy(dst->str, src->str, sizeof(char) * src->len); + return M_SUCCESS; +} + +/* moves a string */ +inline void string_move(struct string *dst, struct string *src) +{ + dst->len = src->len; + dst->size = src->len; + dst->allocated = src->allocated; + dst->str = src->str; + + // delete ptr in src + src->str = NULL; +} + +/* pushes a char onto a string */ +int string_push(struct string *string, char c) +{ + if (string->len >= string->size) { + int len = string->size ? string->size * 2 : 8; + char *new = realloc(string->str, sizeof(char) + len); + if (new == NULL) { + PERROR("cannot realloc"); + return M_ERROR; + } + string->size = len; + string->str = new; + } + string->str[string->len++] = c; + return M_SUCCESS; +} + +void string_bss(struct string *string, char *src) +{ + int len = strlen(src); + string->str = src; + string->len = len; + string->size = len; + string->allocated = false; +} |