]> git.lizzy.rs Git - nothing.git/blob - src/game/level/level_editor/undo_history.c
Remove *_from_memory
[nothing.git] / src / game / level / level_editor / undo_history.c
1 #include <stdlib.h>
2 #include <stdio.h>
3
4 #include <SDL.h>
5
6 #include "system/nth_alloc.h"
7 #include "system/stacktrace.h"
8 #include "undo_history.h"
9 #include "config.h"
10
11 typedef struct {
12     RevertAction revert;
13     void *context_data;
14     size_t context_data_size;
15 } HistoryItem;
16
17 UndoHistory *create_undo_history(Memory *memory)
18 {
19     UndoHistory *result = memory_alloc(memory, sizeof(UndoHistory));
20     result->actions = create_ring_buffer_from_buffer(
21         memory,
22         sizeof(HistoryItem),
23         UNDO_HISTORY_CAPACITY);
24     result->memory = memory;
25     return result;
26 }
27
28 void undo_history_push(UndoHistory *undo_history,
29                        RevertAction revert,
30                        void *context_data,
31                        size_t context_data_size)
32 {
33     trace_assert(undo_history);
34
35     // TODO: undo_history_push kinda leaks the memory
36     HistoryItem item = {
37         .revert = revert,
38         .context_data = memory_alloc(undo_history->memory, context_data_size),
39         .context_data_size = context_data_size
40     };
41     memcpy(item.context_data, context_data, context_data_size);
42     ring_buffer_push(&undo_history->actions, &item);
43 }
44
45 void undo_history_pop(UndoHistory *undo_history)
46 {
47     trace_assert(undo_history);
48
49     if (undo_history->actions.count > 0) {
50         HistoryItem *item = ring_buffer_top(&undo_history->actions);
51         item->revert(item->context_data, item->context_data_size);
52         ring_buffer_pop(&undo_history->actions);
53     }
54 }
55
56 void undo_history_clean(UndoHistory *undo_history)
57 {
58     trace_assert(undo_history);
59
60     while (undo_history->actions.count) {
61         ring_buffer_pop(&undo_history->actions);
62     }
63 }