We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
remove
1 parent 3ea67bb commit 09d43aaCopy full SHA for 09d43aa
carbon.h
@@ -587,6 +587,7 @@ CARBON_API void carbon_list_destroy(CBN_List *l);
587
CARBON_API void carbon_list_push(CBN_List *l, void *value);
588
CARBON_API void carbon_list_pop(CBN_List *l, void *out_value);
589
CARBON_API isz carbon_list_find(CBN_List *l, const void *value);
590
+CARBON_API void carbon_list_remove(CBN_List *l, usz idx);
591
592
/*
593
** $$=====================$$
src/carbon_list.c
@@ -84,3 +84,31 @@ isz carbon_list_find(CBN_List *l, const void *value) {
84
}
85
return -1;
86
87
+
88
+void carbon_list_remove(CBN_List *l, usz idx) {
89
+ if (!l) {
90
+ carbon_log_error("`l` must be a valid pointer");
91
+ return;
92
+ }
93
+ if (idx >= l->size) {
94
+ carbon_log_error("idx out of bounds (size: %$, idx: %$)", $(l->size), $(idx));
95
96
97
+ if (idx < l->size - 1) {
98
+ void *dst = (void *) ((u64) l->items + (idx * l->stride));
99
+ void *src = (void *) ((u64) l->items + ((idx + 1) * l->stride));
100
+ memmove(dst, src, (l->size - idx - 1) * l->stride);
101
102
+ --l->size;
103
+ if (l->size > 0 && l->size < l->capacity / 4) {
104
+ l->capacity /= 2;
105
+ void *prev_p = l->items;
106
+ usz size = l->capacity * l->stride;
107
+ l->items = CARBON_REALLOC(l->items, size);
108
+ if (!l->items && l->size > 0) {
109
+ carbon_log_error("failed to reallocate memory (%zuB)", size);
110
+ CARBON_FREE(prev_p);
111
112
113
114
+}
test/carbon_list_test.c
@@ -52,3 +52,24 @@ CARBON_TEST(carbon_list, find_element) {
52
carbon_list_destroy(&l);
53
return CARBON_OK;
54
55
56
+CARBON_TEST(carbon_list, remove_element) {
57
+ CBN_List l = carbon_list_create(sizeof(i32));
58
+ i32 i = 1, j = 7, k = 3;
59
+ carbon_list_push(&l, &i);
60
+ carbon_list_push(&l, &j);
61
+ carbon_list_push(&l, &k);
62
+ carbon_should_be(3, l.size);
63
+ carbon_should_be(i, carbon_list_at(i32, l, 0));
64
+ carbon_should_be(j, carbon_list_at(i32, l, 1));
65
+ carbon_should_be(k, carbon_list_at(i32, l, 2));
66
+ carbon_list_remove(&l, 0);
67
+ carbon_should_be(2, l.size);
68
+ carbon_should_be(j, carbon_list_at(i32, l, 0));
69
+ carbon_should_be(k, carbon_list_at(i32, l, 1));
70
+ carbon_list_remove(&l, 1);
71
+ carbon_should_be(1, l.size);
72
73
+ carbon_list_destroy(&l);
74
+ return CARBON_OK;
75
0 commit comments