Changeset

6151:a34a14054532

util.indexedbheap: Fix a possible traceback when removing the last item.
author Waqas Hussain <waqas20@gmail.com>
date Wed, 23 Apr 2014 11:38:34 -0400
parents 6150:5b59798c979a
children 6157:44de98f516f5
files util/indexedbheap.lua
diffstat 1 files changed, 11 insertions(+), 7 deletions(-) [+]
line wrap: on
line diff
--- a/util/indexedbheap.lua	Wed Apr 23 00:23:46 2014 +0200
+++ b/util/indexedbheap.lua	Wed Apr 23 11:38:34 2014 -0400
@@ -113,23 +113,27 @@
 	k = _percolate_down(self.priorities, k, self.ids, self.index);
 end
 function indexed_heap:remove_index(k)
-	local size = #self.priorities;
+	local result = self.priorities[k];
+	if result == nil then return; end
 
-	local result = self.priorities[k];
 	local result_sync = self.ids[k];
 	local item = self.items[result_sync];
-	if result == nil then return; end
-	self.index[result_sync] = nil;
-	self.items[result_sync] = nil;
+	local size = #self.priorities;
 
 	self.priorities[k] = self.priorities[size];
 	self.ids[k] = self.ids[size];
 	self.index[self.ids[k]] = k;
+
 	t_remove(self.priorities);
 	t_remove(self.ids);
 
-	k = _percolate_up(self.priorities, k, self.ids, self.index);
-	k = _percolate_down(self.priorities, k, self.ids, self.index);
+	self.index[result_sync] = nil;
+	self.items[result_sync] = nil;
+
+	if size > k then
+		k = _percolate_up(self.priorities, k, self.ids, self.index);
+		k = _percolate_down(self.priorities, k, self.ids, self.index);
+	end
 
 	return result, item, result_sync;
 end