Keyboard firmwares for Atmel AVR and Cortex-M
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MtxCircBuffer.h 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /* mbed USBHost Library
  2. * Copyright (c) 2006-2013 ARM Limited
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #ifndef MTXCIRCBUFFER_H
  17. #define MTXCIRCBUFFER_H
  18. #include "stdint.h"
  19. #include "rtos.h"
  20. //Mutex protected circular buffer
  21. template<typename T, int size>
  22. class MtxCircBuffer {
  23. public:
  24. MtxCircBuffer() {
  25. write = 0;
  26. read = 0;
  27. }
  28. bool isFull() {
  29. mtx.lock();
  30. bool r = (((write + 1) % size) == read);
  31. mtx.unlock();
  32. return r;
  33. }
  34. bool isEmpty() {
  35. mtx.lock();
  36. bool r = (read == write);
  37. mtx.unlock();
  38. return r;
  39. }
  40. void flush() {
  41. write = 0;
  42. read = 0;
  43. }
  44. void queue(T k) {
  45. mtx.lock();
  46. while (((write + 1) % size) == read) {
  47. mtx.unlock();
  48. Thread::wait(10);
  49. mtx.lock();
  50. }
  51. buf[write++] = k;
  52. write %= size;
  53. mtx.unlock();
  54. }
  55. uint16_t available() {
  56. mtx.lock();
  57. uint16_t a = (write >= read) ? (write - read) : (size - read + write);
  58. mtx.unlock();
  59. return a;
  60. }
  61. bool dequeue(T * c) {
  62. mtx.lock();
  63. bool empty = (read == write);
  64. if (!empty) {
  65. *c = buf[read++];
  66. read %= size;
  67. }
  68. mtx.unlock();
  69. return (!empty);
  70. }
  71. private:
  72. volatile uint16_t write;
  73. volatile uint16_t read;
  74. volatile T buf[size];
  75. Mutex mtx;
  76. };
  77. #endif