Remove GPL code from prio_heap
[lttng-modules.git] / lib / prio_heap / prio_heap.c
CommitLineData
f3bc08c5 1/*
162769ef
MD
2 * prio_heap.c
3 *
4 * Static-sized priority heap containing pointers. Based on CLRS,
5 * chapter 6.
6 *
7 * Copyright 2011 - Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
8 *
9 * Permission is hereby granted, free of charge, to any person obtaining a copy
10 * of this software and associated documentation files (the "Software"), to deal
11 * in the Software without restriction, including without limitation the rights
12 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 * copies of the Software, and to permit persons to whom the Software is
14 * furnished to do so, subject to the following conditions:
15 *
16 * The above copyright notice and this permission notice shall be included in
17 * all copies or substantial portions of the Software.
f3bc08c5
MD
18 */
19
20#include <linux/slab.h>
21#include <linux/prio_heap.h>
22
162769ef
MD
23/*
24 * TODO implement heap_init, heap_free, heap_insert.
25 */
f3bc08c5
MD
26
27static void heapify(struct ptr_heap *heap, int pos)
28{
29 void **ptrs = heap->ptrs;
30 void *p = ptrs[pos];
31
32 while (1) {
33 int left = 2 * pos + 1;
34 int right = 2 * pos + 2;
35 int largest = pos;
36 if (left < heap->size && heap->gt(ptrs[left], p))
37 largest = left;
38 if (right < heap->size && heap->gt(ptrs[right], ptrs[largest]))
39 largest = right;
40 if (largest == pos)
41 break;
42 /* Push p down the heap one level and bump one up */
43 ptrs[pos] = ptrs[largest];
44 ptrs[largest] = p;
45 pos = largest;
46 }
47}
48
49void *heap_replace_max(struct ptr_heap *heap, void *p)
50{
51 void *res;
52 void **ptrs = heap->ptrs;
53
54 if (!heap->size) {
55 ptrs[0] = p;
56 heap->size = 1;
57 return NULL;
58 }
59
60 /* Replace the current max and heapify */
61 res = ptrs[0];
62 ptrs[0] = p;
63 heapify(heap, 0);
64 return res;
65}
66
f3bc08c5
MD
67void *heap_remove(struct ptr_heap *heap)
68{
69 void **ptrs = heap->ptrs;
70
71 switch (heap->size) {
72 case 0:
73 return NULL;
74 case 1:
75 heap->size = 0;
76 return ptrs[0];
77 }
78
79 /* Shrink, replace the current max by previous last entry and heapify */
80 return heap_replace_max(heap, ptrs[--heap->size]);
81}
82
83void *heap_cherrypick(struct ptr_heap *heap, void *p)
84{
85 void **ptrs = heap->ptrs;
86 size_t pos, size = heap->size;
87
88 for (pos = 0; pos < size; pos++)
89 if (ptrs[pos] == p)
90 goto found;
91 return NULL;
92found:
93 if (heap->size == 1) {
94 heap->size = 0;
95 return ptrs[0];
96 }
97 /*
98 * Replace p with previous last entry and heapify.
99 */
100 ptrs[pos] = ptrs[--heap->size];
101 heapify(heap, pos);
102 return p;
103}
This page took 0.026079 seconds and 4 git commands to generate.