bytequeue.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // this is a single reader [maybe multiple writer?] byte queue
  2. // Copyright 2008 Alex Norman
  3. // writen by Alex Norman
  4. //
  5. // This file is part of avr-bytequeue.
  6. //
  7. // avr-bytequeue is free software: you can redistribute it and/or modify
  8. // it under the terms of the GNU General Public License as published by
  9. // the Free Software Foundation, either version 3 of the License, or
  10. //(at your option) any later version.
  11. //
  12. // avr-bytequeue is distributed in the hope that it will be useful,
  13. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. // GNU General Public License for more details.
  16. //
  17. // You should have received a copy of the GNU General Public License
  18. // along with avr-bytequeue. If not, see <http://www.gnu.org/licenses/>.
  19. #include "bytequeue.h"
  20. #include "interrupt_setting.h"
  21. void bytequeue_init(byteQueue_t* queue, uint8_t* dataArray, byteQueueIndex_t arrayLen) {
  22. queue->length = arrayLen;
  23. queue->data = dataArray;
  24. queue->start = queue->end = 0;
  25. }
  26. bool bytequeue_enqueue(byteQueue_t* queue, uint8_t item) {
  27. interrupt_setting_t setting = store_and_clear_interrupt();
  28. // full
  29. if (((queue->end + 1) % queue->length) == queue->start) {
  30. restore_interrupt_setting(setting);
  31. return false;
  32. } else {
  33. queue->data[queue->end] = item;
  34. queue->end = (queue->end + 1) % queue->length;
  35. restore_interrupt_setting(setting);
  36. return true;
  37. }
  38. }
  39. byteQueueIndex_t bytequeue_length(byteQueue_t* queue) {
  40. byteQueueIndex_t len;
  41. interrupt_setting_t setting = store_and_clear_interrupt();
  42. if (queue->end >= queue->start)
  43. len = queue->end - queue->start;
  44. else
  45. len = (queue->length - queue->start) + queue->end;
  46. restore_interrupt_setting(setting);
  47. return len;
  48. }
  49. // we don't need to avoid interrupts if there is only one reader
  50. uint8_t bytequeue_get(byteQueue_t* queue, byteQueueIndex_t index) { return queue->data[(queue->start + index) % queue->length]; }
  51. // we just update the start index to remove elements
  52. void bytequeue_remove(byteQueue_t* queue, byteQueueIndex_t numToRemove) {
  53. interrupt_setting_t setting = store_and_clear_interrupt();
  54. queue->start = (queue->start + numToRemove) % queue->length;
  55. restore_interrupt_setting(setting);
  56. }