]> git.lizzy.rs Git - nothing.git/blob - src/ui/history.c
(#354) Introduce history to the consolé
[nothing.git] / src / ui / history.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <assert.h>
4
5 #include "history.h"
6 #include "system/lt.h"
7 #include "system/error.h"
8 #include "str.h"
9
10 struct History
11 {
12     Lt *lt;
13
14     char **buffer;
15     size_t cursor;
16     size_t capacity;
17 };
18
19 History *create_history(size_t capacity)
20 {
21     Lt *lt = create_lt();
22     if (lt == NULL) {
23         return NULL;
24     }
25
26     History *history = PUSH_LT(
27         lt,
28         malloc(sizeof(History)),
29         free);
30     if (history == NULL) {
31         throw_error(ERROR_TYPE_LIBC);
32         RETURN_LT(lt, NULL);
33     }
34     history->lt = lt;
35
36     history->capacity = capacity;
37     history->cursor = 0;
38
39     history->buffer = PUSH_LT(lt, calloc(capacity, sizeof(char*)), free);
40     if (history->buffer == NULL) {
41         throw_error(ERROR_TYPE_LIBC);
42         RETURN_LT(lt, NULL);
43     }
44
45     return history;
46 }
47
48 void destroy_history(History *history)
49 {
50     assert(history);
51
52     for (size_t i = 0; i < history->capacity; ++i) {
53         if (history->buffer[i] != NULL) {
54             free(history->buffer[i]);
55         }
56     }
57
58     RETURN_LT0(history->lt);
59 }
60
61 int history_push(History *history, const char *command)
62 {
63     assert(history);
64     assert(command);
65
66     const size_t next_cursor = (history->cursor + 1) % history->capacity;
67
68     if (history->buffer[history->cursor] != NULL) {
69         free(history->buffer[history->cursor]);
70     }
71
72     history->buffer[history->cursor] = string_duplicate(command, NULL);
73
74     if (history->buffer[history->cursor] == NULL) {
75         return -1;
76     }
77
78     history->cursor = next_cursor;
79
80     return 0;
81 }
82
83 const char *history_get(History *history, size_t i)
84 {
85     assert(history);
86     return history->buffer[(history->cursor + i) % history->capacity];
87 }