93 lines
2.8 KiB
C
93 lines
2.8 KiB
C
#include "doubly-linked-list.h"
|
|
#include <stdatomic.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
dll_list *list = NULL;
|
|
dll_node *head = NULL;
|
|
char *list_string = NULL;
|
|
|
|
#define ASSERT_STR_EQ(expected, actual) \
|
|
{ \
|
|
if (strcmp(expected, actual) != 0) { \
|
|
fprintf(stderr, \
|
|
"strings don't match. expected: \"%s\", actual: \"%s\"\n", \
|
|
expected, actual); \
|
|
cleanup(); \
|
|
return 1; \
|
|
} \
|
|
}
|
|
|
|
char *list_to_string(dll_list *list) {
|
|
char *list_string = malloc(sizeof(char));
|
|
list_string[0] = '\0';
|
|
dll_node *current_node = list->head;
|
|
while (current_node != NULL) {
|
|
// TODO: There's probably a better way to do this. Find it
|
|
int list_string_length = strlen(list_string);
|
|
int new_length = list_string_length + strlen(current_node->value) + 1;
|
|
if (current_node->previous != NULL) {
|
|
new_length += 2; // Add space for another ", "
|
|
}
|
|
char *new_list_string = realloc(list_string, new_length);
|
|
if (new_list_string == NULL) {
|
|
fprintf(stderr, "error: failed to reallocate memory for list string\n");
|
|
return NULL;
|
|
} else {
|
|
list_string = new_list_string;
|
|
}
|
|
if (list_string_length > 0 && current_node->previous != NULL) {
|
|
strcpy(&list_string[list_string_length], ", ");
|
|
list_string_length += 2;
|
|
}
|
|
strcpy(&list_string[list_string_length], current_node->value);
|
|
list_string[new_length - 1] = '\0';
|
|
current_node = current_node->next;
|
|
}
|
|
return list_string;
|
|
}
|
|
|
|
void cleanup() {
|
|
if (list != NULL) {
|
|
dll_list_free(list);
|
|
list = NULL;
|
|
}
|
|
|
|
if (head != NULL) {
|
|
dll_node_free(head);
|
|
head = NULL;
|
|
}
|
|
|
|
if (list_string != NULL) {
|
|
free(list_string);
|
|
list_string = NULL;
|
|
}
|
|
}
|
|
|
|
int main(int argc, char **argv) {
|
|
list = dll_list_new();
|
|
dll_node *head = dll_node_new("0");
|
|
dll_list_append(list, head);
|
|
head = NULL;
|
|
// TODO: Extract test utilities to shared file
|
|
list_string = list_to_string(list);
|
|
ASSERT_STR_EQ("0", list_string);
|
|
|
|
dll_node *third = dll_node_new("2");
|
|
dll_list_insert(list, third, 2);
|
|
|
|
free(list_string);
|
|
list_string = list_to_string(list);
|
|
ASSERT_STR_EQ("0, 2", list_string);
|
|
|
|
dll_node *second = dll_node_new("1");
|
|
dll_list_insert(list, second, 1);
|
|
|
|
free(list_string);
|
|
list_string = list_to_string(list);
|
|
ASSERT_STR_EQ("0, 1, 2", list_string);
|
|
|
|
cleanup();
|
|
return 0;
|
|
}
|