5 #include "cgds/BufferTop.h"
7 // NOTE: no _init() method here, since BufferTop has no specific initialization
9 BufferTop
* _buffertop_new(size_t dataSize
, UInt capacity
, OrderType bType
, UInt arity
)
11 BufferTop
* bufferTop
= (BufferTop
*) safe_malloc(sizeof (BufferTop
));
12 bufferTop
->capacity
= capacity
;
13 bufferTop
->bType
= bType
; //redondant, but facilitate understanding
14 // WARNING: heap must have opposite type: "smallest" element first
15 bufferTop
->heap
= _heap_new(dataSize
, (bType
== MAX_T
? MIN_T
: MAX_T
), arity
);
19 BufferTop
* buffertop_copy(BufferTop
* bufferTop
)
21 BufferTop
* bufferTopCopy
= _buffertop_new(
22 bufferTop
->heap
->dataSize
, bufferTop
->capacity
,
23 bufferTop
->heap
->hType
, bufferTop
->heap
->arity
);
24 heap_destroy(bufferTopCopy
->heap
); //TODO: bad style...
25 bufferTopCopy
->heap
= heap_copy(bufferTop
->heap
);
29 List
* buffertop_2list(BufferTop
* bufferTop
)
31 // Copy the buffer, and then use the copy to build the list
32 BufferTop
* bufferTopCopy
= buffertop_copy(bufferTop
);
33 List
* bufferInList
= _list_new(bufferTop
->heap
->array
->dataSize
);
34 while (!buffertop_empty(bufferTopCopy
))
36 void* topItem
= buffertop_first_raw(bufferTopCopy
)->item
;
37 // NOTE: list_insert_front(), to reverse (wrong) items order
38 // ==> in the returned list, top element is at head.
39 _list_insert_front(bufferInList
, topItem
);
40 buffertop_pop(bufferTopCopy
);
42 buffertop_destroy(bufferTopCopy
);
46 Bool
buffertop_empty(BufferTop
* bufferTop
)
48 return (heap_size(bufferTop
->heap
) == 0);
51 UInt
buffertop_size(BufferTop
* bufferTop
)
53 return heap_size(bufferTop
->heap
);
56 void _buffertop_tryadd(BufferTop
* bufferTop
, void* item
, Real value
)
58 if (heap_size(bufferTop
->heap
) >= bufferTop
->capacity
&&
59 ((bufferTop
->bType
== MIN_T
&&
60 value
>= ((ItemValue
*) (bufferTop
->heap
->array
->datas
[0]))->value
)
62 (bufferTop
->bType
== MAX_T
&&
63 value
<= ((ItemValue
*) (bufferTop
->heap
->array
->datas
[0]))->value
)))
65 // shortcut : if value "worse" than top->value and buffer is full, skip
69 // insertion somewhere in the item-values heap
70 _heap_insert(bufferTop
->heap
, item
, value
);
72 if (heap_size(bufferTop
->heap
) > bufferTop
->capacity
)
73 // we must remove current root
74 heap_pop(bufferTop
->heap
);
77 ItemValue
* buffertop_first_raw(BufferTop
* bufferTop
)
79 return heap_top_raw(bufferTop
->heap
);
82 void buffertop_pop(BufferTop
* bufferTop
)
84 heap_pop(bufferTop
->heap
);
87 void buffertop_clear(BufferTop
* bufferTop
)
89 heap_clear(bufferTop
->heap
);
92 void buffertop_destroy(BufferTop
* bufferTop
)
94 heap_destroy(bufferTop
->heap
);