Last active
December 11, 2015 10:18
-
-
Save diegostamigni/4585299 to your computer and use it in GitHub Desktop.
history.c || implement a queue --> designed to be used as a command history.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <sys/conf.h> | |
#include <env/history.h> | |
#define HISTORY_SIZE 10 | |
#define FIRST_ELEMENT 0 | |
#define LAST_ELEMENT (HISTORY_SIZE - 1) | |
// private function -- dealloc element in history at position x | |
#define __RELEASE_AT(x) { \ | |
if(*(history+x)) { \ | |
free(*(history+x)); \ | |
*(history+x) = NULL; \ | |
} \ | |
} | |
// private function -- call public hpop | |
#define __POP() { hstpop(); } | |
// define an array of element (char *). | |
// The last element is the most recent. | |
static char *history[HISTORY_SIZE] = {}; | |
// private function -- copy (char *) into history at position (int) | |
static inline void __copy(const char *str, int where) { | |
*(history+where) = (char *) malloc(sizeof(char) * strlen(str+1)); | |
memset(*(history+where), 0, strlen(str)); | |
strncpy(*(history+where), str, strlen(str)); | |
} | |
void hstget_history(char **tmp) { | |
for (register int i = 0; i < HISTORY_SIZE; i++) { | |
if (*(history+i)) { | |
size_t size = strlen(*(history+i)); | |
*(tmp+i) = (char *) malloc(sizeof(char) * (size+1)); | |
strncpy(*(tmp+i), *(history+i), size); | |
} else break; | |
} | |
} | |
void hstpush(const char *element) { | |
if (*(history+0) == NULL) | |
__copy(element, 0); | |
else | |
for (register int i = 0; i < HISTORY_SIZE; i++) { | |
if (!(*(history+i))) { | |
__copy(element, i); | |
break; | |
} else { | |
if (i == LAST_ELEMENT) { | |
__POP() | |
__copy(element, LAST_ELEMENT); | |
break; | |
} | |
} | |
} | |
} | |
void hstpop(void) { | |
// removing the old element -- out of the queue | |
// and moving all other elements | |
for (register int j = 0; j < HISTORY_SIZE; j++) { | |
if (j == LAST_ELEMENT) { | |
__RELEASE_AT(LAST_ELEMENT) | |
break; | |
} else | |
__copy(*(history + (j+1)), j); | |
} | |
} | |
const char *hstget_element(int index) { | |
return *(history+index); | |
} | |
void hstclean(void) { | |
register int i = 0; | |
for (i = 0; i < HISTORY_SIZE; i++) | |
__RELEASE_AT(i) | |
} | |
void hstrelease(void) { | |
hstclean(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment