a7d5f95a7411eba8e149a951c55db45eff895fd6
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
*) safe_malloc(sizeof (BufferTop
));
24 bufferTopCopy
->capacity
= bufferTop
->capacity
;
25 bufferTopCopy
->bType
= bufferTop
->bType
;
26 bufferTopCopy
->heap
= heap_copy(bufferTop
->heap
);
30 List
* buffertop_2list(BufferTop
* bufferTop
)
32 // Copy the buffer, and then use the copy to build the list
33 BufferTop
* bufferTopCopy
= buffertop_copy(bufferTop
);
34 List
* bufferInList
= _list_new(bufferTop
->heap
->items
->dataSize
);
35 while (!buffertop_empty(bufferTopCopy
))
37 void* topItem
= _heap_top(bufferTopCopy
->heap
).item
;
38 // NOTE: list_insert_front(), to reverse (wrong) items order
39 // ==> in the returned list, top element is at head.
40 _list_insert_front(bufferInList
, topItem
);
41 buffertop_pop(bufferTopCopy
);
43 buffertop_destroy(bufferTopCopy
);
47 bool buffertop_empty(BufferTop
* bufferTop
)
49 return (heap_size(bufferTop
->heap
) == 0);
52 UInt
buffertop_size(BufferTop
* bufferTop
)
54 return heap_size(bufferTop
->heap
);
57 void _buffertop_tryadd(BufferTop
* bufferTop
, void* item
, Real value
)
59 if (heap_size(bufferTop
->heap
) >= bufferTop
->capacity
) {
60 Real topValue
= *((Real
*) (bufferTop
->heap
->values
->datas
));
62 (bufferTop
->bType
== MIN_T
&& value
>= topValue
) ||
63 (bufferTop
->bType
== MAX_T
&& value
<= topValue
)
65 // Shortcut : if value "worse" than top->value and buffer is full, skip
70 // Insertion somewhere in the item-values heap
71 _heap_insert(bufferTop
->heap
, item
, value
);
73 if (heap_size(bufferTop
->heap
) > bufferTop
->capacity
)
74 // We must remove current root
75 heap_pop(bufferTop
->heap
);
78 ItemValue
_buffertop_first(BufferTop
* bufferTop
)
80 return _heap_top(bufferTop
->heap
);
83 void buffertop_pop(BufferTop
* bufferTop
)
85 heap_pop(bufferTop
->heap
);
88 void buffertop_clear(BufferTop
* bufferTop
)
90 heap_clear(bufferTop
->heap
);
93 void buffertop_destroy(BufferTop
* bufferTop
)
95 heap_destroy(bufferTop
->heap
);