From 4c4994435d83053a5b4536dabab8a755af97d59c Mon Sep 17 00:00:00 2001 From: Pawel Dziepak Date: Tue, 22 Oct 2013 23:56:31 +0200 Subject: [PATCH] kernel/util: Fixes in [MinMax]Heap implementation --- headers/private/kernel/util/Heap.h | 4 +++- headers/private/kernel/util/MinMaxHeap.h | 14 +++++++++++--- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/headers/private/kernel/util/Heap.h b/headers/private/kernel/util/Heap.h index 5d0f896ab3..ed7294c2b2 100644 --- a/headers/private/kernel/util/Heap.h +++ b/headers/private/kernel/util/Heap.h @@ -230,6 +230,7 @@ HEAP_CLASS_NAME::RemoveRoot() #if KDEBUG Element* element = PeekRoot(); HeapLink* link = sGetLink(element); + ASSERT(link->fIndex != -1); link->fIndex = -1; #endif @@ -257,6 +258,8 @@ HEAP_CLASS_NAME::Insert(Element* element, Key key) HeapLink* link = sGetLink(element); + ASSERT(link->fIndex == -1); + fElements[fLastElement] = element; link->fIndex = fLastElement++; link->fKey = key; @@ -270,7 +273,6 @@ HEAP_TEMPLATE_LIST status_t HEAP_CLASS_NAME::_GrowHeap(int minimalSize) { - minimalSize = minimalSize % 2 ? minimalSize : minimalSize + 1; int newSize = max_c(max_c(fSize * 2, 4), minimalSize); size_t arraySize = newSize * sizeof(Element*); diff --git a/headers/private/kernel/util/MinMaxHeap.h b/headers/private/kernel/util/MinMaxHeap.h index 0e9f40bb2d..4dc8b0c9f0 100644 --- a/headers/private/kernel/util/MinMaxHeap.h +++ b/headers/private/kernel/util/MinMaxHeap.h @@ -258,6 +258,7 @@ MIN_MAX_HEAP_CLASS_NAME::RemoveMinimum() #if KDEBUG Element* element = PeekMinimum(); MinMaxHeapLink* link = sGetLink(element); + ASSERT(link->fIndex != -1); link->fIndex = -1; #endif @@ -278,6 +279,7 @@ MIN_MAX_HEAP_CLASS_NAME::RemoveMaximum() #if KDEBUG Element* element = PeekMaximum(); MinMaxHeapLink* link = sGetLink(element); + ASSERT(link->fIndex != -1); link->fIndex = -1; #endif @@ -296,10 +298,12 @@ MIN_MAX_HEAP_CLASS_NAME::Insert(Element* element, Key key) return result; } - ASSERT(fMinLastElement != fSize || fMaxLastElement != fSize); + ASSERT(fMinLastElement < fSize || fMaxLastElement < fSize); MinMaxHeapLink* link = sGetLink(element); + ASSERT(link->fIndex == -1); + link->fMinTree = fMinLastElement < fMaxLastElement; int& lastElement = link->fMinTree ? fMinLastElement : fMaxLastElement; @@ -320,7 +324,7 @@ MIN_MAX_HEAP_TEMPLATE_LIST status_t MIN_MAX_HEAP_CLASS_NAME::_GrowHeap(int minimalSize) { - minimalSize = minimalSize % 2 ? minimalSize : minimalSize + 1; + minimalSize = minimalSize % 2 == 0 ? minimalSize : minimalSize + 1; int newSize = max_c(max_c(fSize * 4, 4), minimalSize); size_t arraySize = newSize * sizeof(Element*); @@ -329,7 +333,11 @@ MIN_MAX_HEAP_CLASS_NAME::_GrowHeap(int minimalSize) if (newBuffer == NULL) return B_NO_MEMORY; fMinElements = newBuffer; - fMaxElements = newBuffer + (newSize / 2); + + newBuffer += newSize / 2; + if (fMaxElements != NULL) + memcpy(newBuffer, fMaxElements, fSize * sizeof(Element*)); + fMaxElements = newBuffer; fSize = newSize / 2; return B_OK;