Skip to content

Instantly share code, notes, and snippets.

@chriseth
Last active August 31, 2022 15:11
Show Gist options
  • Select an option

  • Save chriseth/d8bf126817fa236c0406c130433a0a7e to your computer and use it in GitHub Desktop.

Select an option

Save chriseth/d8bf126817fa236c0406c130433a0a7e to your computer and use it in GitHub Desktop.
// Adapted from https://github.com/omgnetwork/plasma-contracts
// Licensed under Apache License 2.0
// SPDX-License-Identifier: Apache-2.0
export { Queue, insert, pop, min, defaultLessThanMemory, defaultLessThanStorage }
struct Queue<T> {
T[] heap;
function(T memory, T storage) internal view returns (bool) lessThanMemory;
function(T storage, T storage) internal view returns (bool) lessThanStorage;
}
function defaultLessThanMemory<T>(T memory _a, T storage _b) view returns (bool)
{
return _a < _b;
}
function defaultLessThanStorage<T>(T storage _a, T storage _b) view returns (bool)
{
return _a < _b;
}
function min<T>(Queue<T> storage self) view returns (T storage)
{
require(self.heap.length > 0, "Queue is empty");
return self.heap[0];
}
function insert<T>(Queue<T> storage self, T memory _element)
{
self.heap.push();
uint i = self.heap.length - 1;
for (; i > 0 && self.lessThanMemory(_element, self.heap[i / 2]); i /= 2)
self.heap[i] = self.heap[i / 2];
self.heap[i] = _element;
}
function pop<T>(Queue<T> storage self)
{
require(self.heap.length > 0, "Queue is empty");
T storage last = self.heap[self.heap.length - 1];
uint i = 0;
while (true)
{
mc = minChild(self, i);
if (mc >= self.heap.length - 1 || self.lessThanStorage(last, self.heap[mc]))
break;
self.heap[i] = self.heap[mc];
i = mc;
}
self.heap[i] = last;
self.heap.pop();
}
function minChild(Queue storage self, uint256 i) view returns (uint256)
{
if (
i * 2 + 1 >= self.heap.length ||
self.lessThanStorage(self.heap[i * 2], self.heap[i * 2 + 1])
)
return i * 2;
else
return i * 2 + 1;
}
@itinance
Copy link
Copy Markdown

would be really cool to get generics one day

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment