mips/masm/string.c

82 lines
1.6 KiB
C
Raw Normal View History

2024-10-04 23:41:10 +00:00
#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;
}