Skip to content

Commit fe9037a

Browse files
committed
Merge pull request #18 from taiyu-len/master
list_insert now works as it should
2 parents 3838a95 + 4c87498 commit fe9037a

File tree

1 file changed

+13
-11
lines changed

1 file changed

+13
-11
lines changed

sway/list.c

+13-11
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,13 @@ list_t *create_list(void) {
1111
return list;
1212
}
1313

14+
static void list_resize(list_t *list) {
15+
if (list->length == list->capacity) {
16+
list->capacity += 10;
17+
list->items = realloc(list->items, sizeof(void*) * list->capacity);
18+
}
19+
}
20+
1421
void list_free(list_t *list) {
1522
if (list == NULL) {
1623
return;
@@ -20,25 +27,20 @@ void list_free(list_t *list) {
2027
}
2128

2229
void list_add(list_t *list, void *item) {
23-
if (list->length == list->capacity) {
24-
list->capacity += 10;
25-
list->items = realloc(list->items, sizeof(void*) * list->capacity);
26-
}
30+
list_resize(list);
2731
list->items[list->length++] = item;
2832
}
2933

3034
void list_insert(list_t *list, int index, void *item) {
31-
// TODO: Implement this properly
32-
if (list->length == list->capacity) {
33-
list->capacity += 10;
34-
list->items = realloc(list->items, sizeof(void*) * list->capacity);
35-
}
36-
list->items[list->length++] = item;
35+
list_resize(list);
36+
memmove(&list->items[index + 1], &list->items[index], sizeof(void*) * (list->length - index));
37+
list->length++;
38+
list->items[index] = item;
3739
}
3840

3941
void list_del(list_t *list, int index) {
4042
list->length--;
41-
memmove(&list->items[index], &list->items[index + 1], sizeof(void*) * (list->capacity - index - 1));
43+
memmove(&list->items[index], &list->items[index + 1], sizeof(void*) * (list->length - index));
4244
}
4345

4446
void list_cat(list_t *list, list_t *source) {

0 commit comments

Comments
 (0)