Skip to content

Instantly share code, notes, and snippets.

@yuanfeiz
Created April 6, 2017 09:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuanfeiz/b2fea9200d36f28534628799819e4020 to your computer and use it in GitHub Desktop.
Save yuanfeiz/b2fea9200d36f28534628799819e4020 to your computer and use it in GitHub Desktop.
An implementation of the rotated queue
pragma solidity ^0.4.0;
////////////////////////////////////////////////////////////
// This is an example contract hacked together at a meetup.
// It is by far not complete and only used to show some
// features of Solidity.
////////////////////////////////////////////////////////////
contract queue
{
Queue requests;
event ElementPopped(uint256 _element);
event ElementPushed(uint256 _element, uint256 _index);
function queue() {
requests.data.length = 200;
}
struct Queue {
uint256[] data;
uint256 front;
uint256 back;
}
/// @dev the number of elements stored in the queue.
function length(Queue storage q) constant internal returns (uint256) {
return q.back - q.front;
}
/// @dev the number of elements this queue can hold
function capacity(Queue storage q) constant internal returns (uint256) {
return q.data.length - 1;
}
function isOverlapped(Queue storage q) internal returns (bool) {
return (q.back + 1) % q.data.length == q.front;
}
/// @dev push a new element to the back of the queue
function push(Queue storage q, uint256 data) internal {
if (isOverlapped(q)) throw;
q.data[q.back] = data;
ElementPushed(data, q.back);
q.back = (q.back + 1) % q.data.length;
}
/// @dev remove and return the element at the front of the queue
function pop(Queue storage q) internal returns (uint256 r)
{
if (q.back == q.front)
return; // throw;
r = q.data[q.front];
delete q.data[q.front];
q.front = (q.front + 1) % q.data.length;
return r;
}
function addRequest(uint256 d) {
push(requests, d);
}
function popRequest() {
ElementPopped(pop(requests));
}
function queueLength() constant returns (uint256) {
return length(requests);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment