Skip to content

Commit 09d43aa

Browse files
committed
Added remove func for list object
1 parent 3ea67bb commit 09d43aa

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

carbon.h

+1
Original file line numberDiff line numberDiff line change
@@ -587,6 +587,7 @@ CARBON_API void carbon_list_destroy(CBN_List *l);
587587
CARBON_API void carbon_list_push(CBN_List *l, void *value);
588588
CARBON_API void carbon_list_pop(CBN_List *l, void *out_value);
589589
CARBON_API isz carbon_list_find(CBN_List *l, const void *value);
590+
CARBON_API void carbon_list_remove(CBN_List *l, usz idx);
590591

591592
/*
592593
** $$=====================$$

src/carbon_list.c

+28
Original file line numberDiff line numberDiff line change
@@ -84,3 +84,31 @@ isz carbon_list_find(CBN_List *l, const void *value) {
8484
}
8585
return -1;
8686
}
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+
return;
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+
return;
112+
}
113+
}
114+
}

test/carbon_list_test.c

+21
Original file line numberDiff line numberDiff line change
@@ -52,3 +52,24 @@ CARBON_TEST(carbon_list, find_element) {
5252
carbon_list_destroy(&l);
5353
return CARBON_OK;
5454
}
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+
carbon_should_be(j, carbon_list_at(i32, l, 0));
73+
carbon_list_destroy(&l);
74+
return CARBON_OK;
75+
}

0 commit comments

Comments
 (0)