[176] | 1 | #ifndef _CARTESIANHEAP_H_ |
---|
| 2 | #define _CARTESIANHEAP_H_ |
---|
| 3 | |
---|
| 4 | //#include "heaplayers.h" |
---|
| 5 | //#include "treap.h" |
---|
| 6 | |
---|
| 7 | // NB: All objects are rounded up to at least the size of a treap node |
---|
| 8 | // (around 24 bytes on a 32-bit architecture). |
---|
| 9 | |
---|
| 10 | template <class SuperHeap> |
---|
| 11 | class CartesianHeap : public SuperHeap { |
---|
| 12 | |
---|
| 13 | // Provide a freelist wrapper for treap nodes. |
---|
| 14 | class MyTreap : public Treap<size_t, void *> { |
---|
| 15 | public: |
---|
| 16 | // class Node : public PerClassHeap<Treap<size_t, void *>::Node, FreelistHeap<SuperHeap> > {}; |
---|
| 17 | }; |
---|
| 18 | |
---|
| 19 | public: |
---|
| 20 | |
---|
| 21 | ~CartesianHeap (void) { |
---|
| 22 | // FIX ME |
---|
| 23 | // free everything from the treap. |
---|
| 24 | } |
---|
| 25 | |
---|
| 26 | void * malloc (size_t sz) { |
---|
| 27 | // Round sz up. |
---|
| 28 | sz = (sz < sizeof(MyTreap::Node)) ? sizeof(MyTreap::Node) : sz; |
---|
| 29 | MyTreap::Node * n = (MyTreap::Node *) treap.lookupGreater (sz); |
---|
| 30 | if (n != NULL) { |
---|
| 31 | assert (n->getValue() == (void *) n); |
---|
| 32 | void * ptr = n->getValue(); |
---|
| 33 | treap.remove (n); |
---|
| 34 | // delete n; // onto a freelist |
---|
| 35 | return ptr; |
---|
| 36 | } else { |
---|
| 37 | return SuperHeap::malloc (sz); |
---|
| 38 | } |
---|
| 39 | } |
---|
| 40 | |
---|
| 41 | void free (void * ptr) { |
---|
| 42 | // MyTreap::Node * n = new MyTreap::Node; // from a freelist |
---|
| 43 | // cout << "n = " << (void *) n << endl; |
---|
| 44 | MyTreap::Node * n = (MyTreap::Node *) ptr; |
---|
| 45 | treap.insert (n, getSize(ptr), ptr, (unsigned int) ptr); |
---|
| 46 | } |
---|
| 47 | |
---|
| 48 | // Removes a pointer from the treap. |
---|
| 49 | void remove (void * ptr) { |
---|
| 50 | treap.remove ((MyTreap::Node *) ptr); |
---|
| 51 | } |
---|
| 52 | |
---|
| 53 | private: |
---|
| 54 | |
---|
| 55 | MyTreap treap; |
---|
| 56 | |
---|
| 57 | }; |
---|
| 58 | |
---|
| 59 | #endif // _CARTESIANHEAP_H_ |
---|