Vermilliest

Untitled

Feb 8th, 2018
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. pragma solidity ^0.4.18;
  2.  
  3. contract QueueExample {
  4.  
  5.     bytes32 front;
  6.     bytes32 back;
  7.     bool isEmpty;
  8.  
  9.     struct ElementData {
  10.         // Some Data
  11.         int num;
  12.     }
  13.    
  14.     struct Element {
  15.         ElementData data;
  16.         bytes32 prev;
  17.     }
  18.    
  19.     mapping (bytes32 => Element) queue;
  20.     mapping (bytes32 => bool) used;
  21.  
  22.     function QueueExample() public {
  23.         isEmpty = true;
  24.     }
  25.    
  26.     function enqueue(int someData) public {
  27.         bytes32 key;
  28.         uint increment = 0;
  29.         do {
  30.             // u can use tx's hash instead of block.number
  31.             key = sha256(someData, msg.sender, block.number, increment++);
  32.         } while (used[key]);
  33.         used[key] = true;
  34.         queue[key] = Element(ElementData(someData), back);
  35.         if (isEmpty) {
  36.             front = back = key;
  37.             isEmpty = false;
  38.         } else {
  39.             queue[back].prev = key;
  40.             back = key;
  41.         }
  42.     }
  43.    
  44.     function dequeue() public returns(int returnableData) {
  45.         returnableData = getFront();
  46.         bytes32 toDelete = front;
  47.         front = queue[front].prev;
  48.         if (back == toDelete) {
  49.             isEmpty = true;
  50.         }
  51.         delete used[toDelete];
  52.         delete queue[toDelete];
  53.     }
  54.    
  55.     function getFront() public view returns(int returnableData) {
  56.         require(!isEmpty);
  57.         ElementData storage data = queue[front].data;
  58.         returnableData = data.num;
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment