#include "pq.h" #include "log.h" // Just sets the head to NULL. PQ pq_init() { return (PQ){.head = NULL}; } // Goes node by node freeing all the memory. void pq_deinit(PQ* pq) { exists(pq); struct Node* curr = pq->head; while (curr != NULL) { struct Node* kod = curr; curr = curr->next; free(kod->proc.program.buf); free(kod); } } // I spent way too long trying to implement this in C. . . So I tried it in // Haskell. The Haskell implementation looks like this: // n_insert :: a -> [a] -> [a] // n_insert p_time [] = [p_time] // n_insert p_time (n_time:n_next) = if n_time > p_time then p_time:n_time:n_next else n_time:n_insert p_time n_next // The C implementation looks like this: Node* n_insert(Proc p, Node* n) { // n_insert p_time [] if (n == NULL) { Node* list = malloc(sizeof(Node)); exists(list); // [p_time] list->proc = p; list->next = NULL; return list; } // n_insert p_time (n_time:n_next) else { // if n_time > p_time then if (n->proc.time > p.time) { Node* list = malloc(sizeof(Node)); exists(list); // p_time:n_time:n_next list->proc = p; list->next = n; // in this case n_time:n_next == n return list; } else { // n_time:n_insert p_time n_next n->next = n_insert(p, n->next); return n; } } } // This function just calls n_insert. void pq_insert(PQ* pq, Proc proc) { exists(pq); pq->head = n_insert(proc, pq->head); } // Free node and buffer. void pq_delete(PQ* pq) { exists(pq); if (pq->head != NULL) { struct Node* kod = pq->head; pq->head = pq->head->next; free(kod->proc.program.buf); free(kod); } } // This function creates a copy of the Proc. Proc pq_access(PQ pq) { exists(pq.head); Proc proc = pq.head->proc; exists(proc.program.buf); Byte* buf = (Byte*)malloc(sizeof(Byte) * proc.program.len); exists(buf); memcpy(buf, proc.program.buf, proc.program.len); return (Proc){ .time = pq.head->proc.time, .program = (Buffer){ .buf = buf, .len = proc.program.len, }, }; } // This function. void pq_print(PQ pq) { struct Node* curr = pq.head; printf("\n"); log(INFO, "This is the queue:\n"); if (curr != NULL) { printf("[INFO]:"); while (curr) { printf("\t(%d, %s)\n", curr->proc.time, curr->proc.program.buf); curr = curr->next; } printf("\n"); } else { log(INFO, "Priority Queue is empty.\n"); } } // When the head is NULL the list is empty. bool pq_empty(PQ pq) { return pq.head == NULL; }