introduce the active_list for searching.
[oweals/opkg-lede.git] / libopkg / active_list.c
index 08e1bd7ad72e2bb87fcab6e328d40f6bfc56b24a..1d38d8d6bc7c09e37c64dbbd02af2452f5ea2a42 100644 (file)
@@ -18,6 +18,8 @@
 
 #include "active_list.h"
 #include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
 
 
 void active_list_init(struct active_list *ptr) {
@@ -71,6 +73,18 @@ struct active_list * active_list_prev(struct active_list *head, struct active_li
     return prev;
 }
 
+
+struct active_list *active_list_move_node(struct active_list *old_head, struct active_list *new_head, struct active_list *node) {
+    struct active_list *prev;
+    if (!old_head || !new_head || !node)
+        return NULL;
+    if (old_head == new_head)
+        return node;
+    prev = active_list_prev(old_head, node);
+    active_list_add(new_head, node);
+    return prev;
+}
+
 static void list_head_clear (struct list_head *head) {
     struct active_list *next;
     struct list_head *n, *ptr;
@@ -103,3 +117,48 @@ void active_list_add(struct active_list *head, struct active_list *node) {
     list_add_tail(&node->node, &head->node);
     node->depended  = head;
 }
+
+struct active_list * active_list_head_new() {
+    struct active_list * head = calloc(1, sizeof(struct active_list));
+    active_list_init(head);
+    return head;
+}
+
+void active_list_head_delete(struct active_list *head) {
+    active_list_clear(head);
+    free(head);
+}
+
+/*
+ *  Using insert sort. 
+ *  Note. the list should not be large, or it will be very inefficient. 
+ *
+ */
+struct active_list * active_list_sort(struct active_list *head, int (*compare)(const void *, const void *)) {
+    struct active_list tmphead;
+    struct active_list *node, *ptr;
+    if ( !head )
+        return NULL;
+    active_list_init(&tmphead);
+    for (node = active_list_next(head, NULL); node; node = active_list_next(head, NULL)) {
+        if (tmphead.node.next == &tmphead.node) {
+            active_list_move_node(head, &tmphead, node);
+        } else {
+            for (ptr = active_list_next(&tmphead, NULL); ptr; ptr=active_list_next(&tmphead, ptr)) {
+                if (compare(ptr, node) <= 0) {
+                    break;
+                }
+            }
+            if (!ptr) {
+                active_list_move_node(head, &tmphead, node);
+            } else {
+                active_list_move_node(head, ptr, node);
+            }
+        }
+        node->depended = &tmphead;
+    }
+    for (ptr = active_list_prev(&tmphead, NULL); ptr; ptr=active_list_prev(&tmphead, NULL)) {
+        active_list_move_node(&tmphead, head, ptr);
+    }
+    return head;
+}