jack-compiler/util.c

76 lines
1.5 KiB
C
Raw Normal View History

2020-12-20 13:58:10 -05:00
#include <string.h>
#include <stdlib.h>
#include "util.h"
2020-12-21 19:50:55 -05:00
char* heapstr(const char* str, int len) {
int size = sizeof(char) * (len + 1);
char* outstr = (char*)malloc(size);
2020-12-20 13:58:10 -05:00
strcpy(outstr, str);
return outstr;
}
2020-12-21 19:50:55 -05:00
char* ezheapstr(const char* str) {
2020-12-20 13:58:10 -05:00
return heapstr(str, strlen(str));
}
2020-12-21 19:50:55 -05:00
void* copy(void* v, int size) {
void* copy = malloc(size);
memcpy(copy, v, size);
2020-12-21 14:49:37 -05:00
return copy;
}
2020-12-20 13:58:10 -05:00
int countplaces(int n) {
int places = 1;
int divisor = 1;
if(n < 0) {
n = -n;
places++;
}
while(n / divisor >= 10) {
places++;
divisor *= 10;
}
return places;
}
char* itoa(int i) {
2020-12-21 19:50:55 -05:00
int size = sizeof(char)*(countplaces(i)+1);
char* a = (char*)malloc(size);
snprintf(a, size, "%i", i);
2020-12-20 13:58:10 -05:00
return a;
}
2020-12-21 19:50:55 -05:00
STRINGLIST* initstrlist(const char** strs, int count) {
STRINGLIST* strlist = (STRINGLIST*)malloc(sizeof(STRINGLIST));
STRINGLIST* curr = strlist;
for(int i = 0; i < count-1; i++) {
curr->content = ezheapstr(strs[i]);
curr->next = (STRINGLIST*)malloc(sizeof(STRINGLIST));
curr = curr->next;
}
curr->content = ezheapstr(strs[count-1]);
curr->next = NULL;
return strlist;
}
2020-12-21 13:05:49 -05:00
void printstrlist(STRINGLIST* strlist, FILE* stream) {
while(strlist != NULL) {
fprintf(stream, "%s\n", strlist->content);
strlist = strlist->next;
2020-12-20 13:58:10 -05:00
}
}
2020-12-21 13:05:49 -05:00
void freestrlist(STRINGLIST* strlist) {
STRINGLIST* next = strlist->next;
free(strlist);
2020-12-20 13:58:10 -05:00
if(next != NULL)
2020-12-21 13:05:49 -05:00
freestrlist(next);
2020-12-20 13:58:10 -05:00
}
2020-12-22 11:18:54 -05:00
bool existsinarray(STRINGARRAY* arr, const char* item) {
for(int i = 0; i < arr->size; i++)
if(!strcmp(arr->items[i], item))
return true;
return false;
}