code_junkie

Most elegant way to implement a circular list (FIFO)

Nov 11th, 2011
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. /* Very simple queue
  2. * These are FIFO queues which discard the new data when full.
  3. *
  4. * Queue is empty when in == out.
  5. * If in != out, then
  6. * - items are placed into in before incrementing in
  7. * - items are removed from out before incrementing out
  8. * Queue is full when in == (out-1 + QUEUE_SIZE) % QUEUE_SIZE;
  9. *
  10. * The queue will hold QUEUE_ELEMENTS number of items before the
  11. * calls to QueuePut fail.
  12. */
  13.  
  14. /* Queue structure */
  15. #define QUEUE_ELEMENTS 100
  16. #define QUEUE_SIZE (QUEUE_ELEMENTS + 1)
  17. int Queue[QUEUE_SIZE];
  18. int QueueIn, QueueOut;
  19.  
  20. void QueueInit(void)
  21. {
  22. QueueIn = QueueOut = 0;
  23. }
  24.  
  25. int QueuePut(int new)
  26. {
  27. if(QueueIn == (( QueueOut - 1 + QUEUE_SIZE) % QUEUE_SIZE))
  28. {
  29. return -1; /* Queue Full*/
  30. }
  31.  
  32. Queue[QueueIn] = new;
  33.  
  34. QueueIn = (QueueIn + 1) % QUEUE_SIZE;
  35.  
  36. return 0; // No errors
  37. }
  38.  
  39. int QueueGet(int *old)
  40. {
  41. if(QueueIn == QueueOut)
  42. {
  43. return -1; /* Queue Empty - nothing to get*/
  44. }
  45.  
  46. *old = Queue[QueueOut];
  47.  
  48. QueueOut = (QueueOut + 1) % QUEUE_SIZE;
  49.  
  50. return 0; // No errors
  51. }
Add Comment
Please, Sign In to add comment