kiba-engine
error.c
1 #include <kiba/core/error.h>
2 
3 #include <kiba/core/memory.h>
4 
5 #define KB_MAX_ERRORS 8
6 #define KB_MAX_ERROR_DATA KB_KILOBYTE(KB_MAX_ERRORS)
7 
8 // TODO this would be threadlocal
9 usize next_error_idx = 0;
10 kb_error error_chain[KB_MAX_ERRORS] = {0};
11 usize next_data_idx = 0;
12 u8 error_data[KB_MAX_ERROR_DATA] = {0};
13 
14 void kb_errors_reset(void) {
15  next_error_idx = 0;
16  memory_zero(error_data, next_data_idx);
17  next_data_idx = 0;
18 }
19 
20 void kb_errors_new(enum kb_error_code code, const char *file, const char *function, i32 line) {
21  kb_errors_reset();
22  error_chain[next_error_idx++] = (kb_error){
23  .code = code,
24  .file = file,
25  .function = function,
26  .line = line,
27  };
28 }
29 
30 void kb_errors_append(enum kb_error_code code, const char *file, const char *function, i32 line) {
31  if (next_error_idx == KB_MAX_ERRORS) {
32  KB_WARN("error chain has reached its maximum length, cannot append error");
33  return;
34  }
35  error_chain[next_error_idx] = (kb_error){
36  .code = code,
37  .file = file,
38  .function = function,
39  .line = line,
40  .data_start = next_data_idx,
41  .data_end = next_data_idx,
42  .next = next_error_idx ? error_chain + next_error_idx - 1 : KB_NULL,
43  };
44  ++next_error_idx;
45 }
46 
47 const void *kb_error_add_data(const void *src, usize size) {
48  if (!next_error_idx) {
49  KB_WARN("no error to append data to, ignoring this call");
50  return KB_NULL;
51  }
52  if (next_data_idx + size > KB_MAX_ERROR_DATA) {
53  KB_WARN("data to append to error would exceed buffer, ignoring this call");
54  return KB_NULL;
55  }
56  memory_copy(error_data + next_data_idx, src, size);
57  next_error_idx += size;
58  error_chain[next_error_idx - 1].data_end = next_data_idx;
59  return src;
60 }
61 
62 kb_error *kb_errors_last_error(void) {
63  if (!next_error_idx) {
64  return KB_NULL;
65  }
66  return error_chain + next_error_idx - 1;
67 }
68 
69 // TODO could add assert for valid dst here and src above
70 void *kb_error_get_data(kb_error *error, void *dst, usize size) {
71  if (error->data_start + size > error->data_end) {
72  KB_WARN("attempted to read more data for error than was initially added");
73  return KB_NULL;
74  }
75  memory_copy(dst, error_data + error->data_start, size);
76  error->data_start += size;
77  return dst;
78 }
void * memory_copy(void *dst, const void *src, usize size)
Copy memory.
Definition: memory.c:83
void * memory_zero(void *mem, usize size)
Zero out memory.
Definition: memory.c:79
Lightweight layer between platform and other engine components to enable tracing/monitoring.
#define KB_NULL
Value of an invalid ptr (nullptr).
Definition: defines.h:18
#define KB_WARN(...)
Log entry with warn log level.
Definition: log.h:161
Definition: error.h:20