Various small fixes
[cgds.git] / src / BufferTop.c
1 /**
2 * @file BufferTop.c
3 */
4
5 #include "cgds/BufferTop.h"
6
7 // NOTE: no init() method here, since BufferTop has no specific initialization
8
9 BufferTop* _buffertop_new(
10 size_t dataSize, UInt capacity, OrderType bType, UInt arity)
11 {
12 BufferTop* bufferTop = (BufferTop*) safe_malloc(sizeof (BufferTop));
13 bufferTop->capacity = capacity;
14 bufferTop->bType = bType; //redondant, but facilitate understanding
15 // WARNING: heap must have opposite type: "smallest" element first
16 bufferTop->heap =
17 _heap_new(dataSize, (bType == MAX_T ? MIN_T : MAX_T), arity);
18 return bufferTop;
19 }
20
21 BufferTop* buffertop_copy(BufferTop* bufferTop)
22 {
23 BufferTop* bufferTopCopy = _buffertop_new(
24 bufferTop->heap->dataSize, bufferTop->capacity,
25 bufferTop->heap->hType, bufferTop->heap->arity);
26 heap_destroy(bufferTopCopy->heap); //TODO: bad style...
27 bufferTopCopy->heap = heap_copy(bufferTop->heap);
28 return bufferTopCopy;
29 }
30
31 List* buffertop_2list(BufferTop* bufferTop)
32 {
33 // Copy the buffer, and then use the copy to build the list
34 BufferTop* bufferTopCopy = buffertop_copy(bufferTop);
35 List* bufferInList = _list_new(bufferTop->heap->array->dataSize);
36 while (!buffertop_empty(bufferTopCopy))
37 {
38 void* topItem = buffertop_first_raw(bufferTopCopy)->item;
39 // NOTE: list_insert_front(), to reverse (wrong) items order
40 // ==> in the returned list, top element is at head.
41 _list_insert_front(bufferInList, topItem);
42 buffertop_pop(bufferTopCopy);
43 }
44 buffertop_destroy(bufferTopCopy);
45 return bufferInList;
46 }
47
48 bool buffertop_empty(BufferTop* bufferTop)
49 {
50 return (heap_size(bufferTop->heap) == 0);
51 }
52
53 UInt buffertop_size(BufferTop* bufferTop)
54 {
55 return heap_size(bufferTop->heap);
56 }
57
58 void _buffertop_tryadd(BufferTop* bufferTop, void* item, Real value)
59 {
60 if (heap_size(bufferTop->heap) >= bufferTop->capacity &&
61 ((bufferTop->bType == MIN_T &&
62 value >= ((ItemValue*) (bufferTop->heap->array->datas[0]))->value)
63 ||
64 (bufferTop->bType == MAX_T &&
65 value <= ((ItemValue*) (bufferTop->heap->array->datas[0]))->value)))
66 {
67 // Shortcut : if value "worse" than top->value and buffer is full, skip
68 return;
69 }
70
71 // Insertion somewhere in the item-values heap
72 _heap_insert(bufferTop->heap, item, value);
73
74 if (heap_size(bufferTop->heap) > bufferTop->capacity)
75 // We must remove current root
76 heap_pop(bufferTop->heap);
77 }
78
79 ItemValue* buffertop_first_raw(BufferTop* bufferTop)
80 {
81 return heap_top_raw(bufferTop->heap);
82 }
83
84 void buffertop_pop(BufferTop* bufferTop)
85 {
86 heap_pop(bufferTop->heap);
87 }
88
89 void buffertop_clear(BufferTop* bufferTop)
90 {
91 heap_clear(bufferTop->heap);
92 }
93
94 void buffertop_destroy(BufferTop* bufferTop)
95 {
96 heap_destroy(bufferTop->heap);
97 safe_free(bufferTop);
98 }