]> git.donarmstrong.com Git - qmk_firmware.git/blob - tool/mbed/mbed-sdk/libraries/USBHost/USBHostSerial/MtxCircBuffer.h
Squashed 'tmk_core/' changes from 7967731..b9e0ea0
[qmk_firmware.git] / tool / mbed / mbed-sdk / libraries / USBHost / USBHostSerial / MtxCircBuffer.h
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
17 #ifndef MTXCIRCBUFFER_H
18 #define MTXCIRCBUFFER_H
19
20 #include "stdint.h"
21 #include "rtos.h"
22
23 //Mutex protected circular buffer
24 template<typename T, int size>
25 class MtxCircBuffer {
26 public:
27
28     MtxCircBuffer() {
29         write = 0;
30         read = 0;
31     }
32
33     bool isFull() {
34         mtx.lock();
35         bool r = (((write + 1) % size) == read);
36         mtx.unlock();
37         return r;
38     }
39
40     bool isEmpty() {
41         mtx.lock();
42         bool r = (read == write);
43         mtx.unlock();
44         return r;
45     }
46
47     void flush() {
48         write = 0;
49         read = 0;
50     }
51
52     void queue(T k) {
53         mtx.lock();
54         while (((write + 1) % size) == read) {
55             mtx.unlock();
56             Thread::wait(10);
57             mtx.lock();
58         }
59         buf[write++] = k;
60         write %= size;
61         mtx.unlock();
62     }
63
64     uint16_t available() {
65         mtx.lock();
66         uint16_t a = (write >= read) ? (write - read) : (size - read + write);
67         mtx.unlock();
68         return a;
69     }
70
71     bool dequeue(T * c) {
72         mtx.lock();
73         bool empty = (read == write);
74         if (!empty) {
75             *c = buf[read++];
76             read %= size;
77         }
78         mtx.unlock();
79         return (!empty);
80     }
81
82 private:
83     volatile uint16_t write;
84     volatile uint16_t read;
85     volatile T buf[size];
86     Mutex mtx;
87 };
88
89 #endif