5 #include "cgds/BufferTop.h"
7 // NOTE: no init() method here, since BufferTop has no specific initialization
9 BufferTop
* _buffertop_new(
10 size_t dataSize
, UInt capacity
, OrderType bType
, UInt arity
)
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
17 _heap_new(dataSize
, (bType
== MAX_T
? MIN_T
: MAX_T
), arity
);
21 BufferTop
* buffertop_copy(BufferTop
* bufferTop
)
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
);
31 List
* buffertop_2list(BufferTop
* bufferTop
)
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
))
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
);
44 buffertop_destroy(bufferTopCopy
);
48 bool buffertop_empty(BufferTop
* bufferTop
)
50 return (heap_size(bufferTop
->heap
) == 0);
53 UInt
buffertop_size(BufferTop
* bufferTop
)
55 return heap_size(bufferTop
->heap
);
58 void _buffertop_tryadd(BufferTop
* bufferTop
, void* item
, Real value
)
60 if (heap_size(bufferTop
->heap
) >= bufferTop
->capacity
&&
61 ((bufferTop
->bType
== MIN_T
&&
62 value
>= ((ItemValue
*) (bufferTop
->heap
->array
->datas
[0]))->value
)
64 (bufferTop
->bType
== MAX_T
&&
65 value
<= ((ItemValue
*) (bufferTop
->heap
->array
->datas
[0]))->value
)))
67 // Shortcut : if value "worse" than top->value and buffer is full, skip
71 // Insertion somewhere in the item-values heap
72 _heap_insert(bufferTop
->heap
, item
, value
);
74 if (heap_size(bufferTop
->heap
) > bufferTop
->capacity
)
75 // We must remove current root
76 heap_pop(bufferTop
->heap
);
79 ItemValue
* buffertop_first_raw(BufferTop
* bufferTop
)
81 return heap_top_raw(bufferTop
->heap
);
84 void buffertop_pop(BufferTop
* bufferTop
)
86 heap_pop(bufferTop
->heap
);
89 void buffertop_clear(BufferTop
* bufferTop
)
91 heap_clear(bufferTop
->heap
);
94 void buffertop_destroy(BufferTop
* bufferTop
)
96 heap_destroy(bufferTop
->heap
);