#include "common.h" #if __APPLE__ char * strndup (const char *s, size_t n) { char *result; size_t len = strlen (s); if (n < len) len = n; result = (char *) malloc (len + 1); if (!result) return 0; result[len] = '\0'; return (char *) memcpy (result, s, len); } #endif int generateHash(const char* string, int table_size) { int i, sum; size_t string_length = strlen(string); for (sum=0, i=0; i < string_length; i++) { sum += string[i]; } return sum % table_size; } char **getCommand(const char* string) { char** command_array = NULL; int i = 0; int j = 1; char last_pos = 0; char current_char = string[i]; short done = 0; while (!done) { if (current_char == ' ') { command_array = realloc(command_array, sizeof(char*)*j+1); if (command_array == NULL) { printf("ERROR, couldn't allocate memory for command_array\n"); } command_array[j] = strndup(string+last_pos+1, i-last_pos-1); last_pos = i; j++; } else if (current_char == '\n') { command_array = realloc(command_array, sizeof(char*)*j+1); if (command_array == NULL) { printf("ERROR, couldn't allocate memory for command_array\n"); } command_array[j] = strndup(string+last_pos+1, i-last_pos-1); last_pos = i; done = 1; j++; } i++; current_char = string[i]; } command_array[0] = (void*)(intptr_t)(j-1); return command_array; } void addCommand(const char *command_string, void(*function)) { int hash = generateHash(command_string, COMMAND_HASH_SIZE); if (is_running) printf("command '%s' added with hash %d\n", command_string, hash); commands_table[hash] = function; } void freeCommand(char **command_array) { int j; for (j = 1; j < (intptr_t)command_array[0]+1; j++) { free(command_array[j]); } free(command_array); } void setConfig(const char* variable, const char* value) { if (variable && value) { int hash = generateHash(variable, CONFIG_HASH_SIZE); //printf("\n%s's hash is %d\n", variable, hash); config[hash] = realloc(config[hash], strlen(value)); strcpy(config[hash], value); config_name[hash] = realloc(config_name[hash], strlen(variable)); strcpy(config_name[hash], variable); if (is_running) printf("%s(%d) set to %s", config_name[hash], hash, config[hash]); //printf("%s's value: %s\n", variable, config[hash]); } else { printf("usage: %s", SET_SYNTAX); } } void freeConfig() { int i = 0; for (i = 0;i < CONFIG_HASH_SIZE;i++) { if (config[i]) { free(config[i]); free(config_name[i]); } } } void addHelp(const char* variable, const char* value) { int hash = generateHash(variable, COMMAND_HASH_SIZE); help[hash] = realloc(help[hash], strlen(value)); strcpy(help[hash], value); } void freeHelp() { int i; for (i = 0;i < COMMAND_HASH_SIZE;i++) { if (help[i]) { free(help[i]); } } } void addSyntax(const char* variable, const char* value) { int hash = generateHash(variable, COMMAND_HASH_SIZE); syntax[hash] = realloc(syntax[hash], strlen(value)); strcpy(syntax[hash], value); } void freeSyntax() { int i; for (i = 0;i < COMMAND_HASH_SIZE;i++) { if (syntax[i]) { free(syntax[i]); } } } void quitProgram() { is_running = 0; is_quitting = 1; }