]> git.donarmstrong.com Git - qmk_firmware.git/blob - tmk_core/protocol/lufa/LUFA-git/LUFA/Drivers/Misc/RingBuffer.h
Merge commit '60b30c036397cb5627fa374bb930794b225daa29' as 'lib/lufa'
[qmk_firmware.git] / tmk_core / protocol / lufa / LUFA-git / LUFA / Drivers / Misc / RingBuffer.h
1 /*
2              LUFA Library
3      Copyright (C) Dean Camera, 2014.
4
5   dean [at] fourwalledcubicle [dot] com
6            www.lufa-lib.org
7 */
8
9 /*
10   Copyright 2014  Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
12   Permission to use, copy, modify, distribute, and sell this
13   software and its documentation for any purpose is hereby granted
14   without fee, provided that the above copyright notice appear in
15   all copies and that both that the copyright notice and this
16   permission notice and warranty disclaimer appear in supporting
17   documentation, and that the name of the author not be used in
18   advertising or publicity pertaining to distribution of the
19   software without specific, written prior permission.
20
21   The author disclaims all warranties with regard to this
22   software, including all implied warranties of merchantability
23   and fitness.  In no event shall the author be liable for any
24   special, indirect or consequential damages or any damages
25   whatsoever resulting from loss of use, data or profits, whether
26   in an action of contract, negligence or other tortious action,
27   arising out of or in connection with the use or performance of
28   this software.
29 */
30
31 /** \file
32  *  \brief Lightweight ring (circular) buffer, for fast insertion/deletion of bytes.
33  *
34  *  Lightweight ring buffer, for fast insertion/deletion. Multiple buffers can be created of
35  *  different sizes to suit different needs.
36  *
37  *  Note that for each buffer, insertion and removal operations may occur at the same time (via
38  *  a multi-threaded ISR based system) however the same kind of operation (two or more insertions
39  *  or deletions) must not overlap. If there is possibility of two or more of the same kind of
40  *  operating occurring at the same point in time, atomic (mutex) locking should be used.
41  */
42
43 /** \ingroup Group_MiscDrivers
44  *  \defgroup Group_RingBuff Generic Byte Ring Buffer - LUFA/Drivers/Misc/RingBuffer.h
45  *  \brief Lightweight ring buffer, for fast insertion/deletion of bytes.
46  *
47  *  \section Sec_RingBuff_Dependencies Module Source Dependencies
48  *  The following files must be built with any user project that uses this module:
49  *    - None
50  *
51  *  \section Sec_RingBuff_ModDescription Module Description
52  *  Lightweight ring buffer, for fast insertion/deletion. Multiple buffers can be created of
53  *  different sizes to suit different needs.
54  *
55  *  Note that for each buffer, insertion and removal operations may occur at the same time (via
56  *  a multi-threaded ISR based system) however the same kind of operation (two or more insertions
57  *  or deletions) must not overlap. If there is possibility of two or more of the same kind of
58  *  operating occurring at the same point in time, atomic (mutex) locking should be used.
59  *
60  *  \section Sec_RingBuff_ExampleUsage Example Usage
61  *  The following snippet is an example of how this module may be used within a typical
62  *  application.
63  *
64  *  \code
65  *      // Create the buffer structure and its underlying storage array
66  *      RingBuffer_t Buffer;
67  *      uint8_t      BufferData[128];
68  *
69  *      // Initialize the buffer with the created storage array
70  *      RingBuffer_InitBuffer(&Buffer, BufferData, sizeof(BufferData));
71  *
72  *      // Insert some data into the buffer
73  *      RingBuffer_Insert(&Buffer, 'H');
74  *      RingBuffer_Insert(&Buffer, 'E');
75  *      RingBuffer_Insert(&Buffer, 'L');
76  *      RingBuffer_Insert(&Buffer, 'L');
77  *      RingBuffer_Insert(&Buffer, 'O');
78  *
79  *      // Cache the number of stored bytes in the buffer
80  *      uint16_t BufferCount = RingBuffer_GetCount(&Buffer);
81  *
82  *      // Printer stored data length
83  *      printf("Buffer Length: %d, Buffer Data: \r\n", BufferCount);
84  *
85  *      // Print contents of the buffer one character at a time
86  *      while (BufferCount--)
87  *        putc(RingBuffer_Remove(&Buffer));
88  *  \endcode
89  *
90  *  @{
91  */
92
93 #ifndef __RING_BUFFER_H__
94 #define __RING_BUFFER_H__
95
96         /* Includes: */
97                 #include "../../Common/Common.h"
98
99         /* Enable C linkage for C++ Compilers: */
100                 #if defined(__cplusplus)
101                         extern "C" {
102                 #endif
103
104         /* Type Defines: */
105                 /** \brief Ring Buffer Management Structure.
106                  *
107                  *  Type define for a new ring buffer object. Buffers should be initialized via a call to
108                  *  \ref RingBuffer_InitBuffer() before use.
109                  */
110                 typedef struct
111                 {
112                         uint8_t* In; /**< Current storage location in the circular buffer. */
113                         uint8_t* Out; /**< Current retrieval location in the circular buffer. */
114                         uint8_t* Start; /**< Pointer to the start of the buffer's underlying storage array. */
115                         uint8_t* End; /**< Pointer to the end of the buffer's underlying storage array. */
116                         uint16_t Size; /**< Size of the buffer's underlying storage array. */
117                         uint16_t Count; /**< Number of bytes currently stored in the buffer. */
118                 } RingBuffer_t;
119
120         /* Inline Functions: */
121                 /** Initializes a ring buffer ready for use. Buffers must be initialized via this function
122                  *  before any operations are called upon them. Already initialized buffers may be reset
123                  *  by re-initializing them using this function.
124                  *
125                  *  \param[out] Buffer   Pointer to a ring buffer structure to initialize.
126                  *  \param[out] DataPtr  Pointer to a global array that will hold the data stored into the ring buffer.
127                  *  \param[out] Size     Maximum number of bytes that can be stored in the underlying data array.
128                  */
129                 static inline void RingBuffer_InitBuffer(RingBuffer_t* Buffer,
130                                                          uint8_t* const DataPtr,
131                                                          const uint16_t Size) ATTR_NON_NULL_PTR_ARG(1) ATTR_NON_NULL_PTR_ARG(2);
132                 static inline void RingBuffer_InitBuffer(RingBuffer_t* Buffer,
133                                                          uint8_t* const DataPtr,
134                                                          const uint16_t Size)
135                 {
136                         GCC_FORCE_POINTER_ACCESS(Buffer);
137
138                         uint_reg_t CurrentGlobalInt = GetGlobalInterruptMask();
139                         GlobalInterruptDisable();
140
141                         Buffer->In     = DataPtr;
142                         Buffer->Out    = DataPtr;
143                         Buffer->Start  = &DataPtr[0];
144                         Buffer->End    = &DataPtr[Size];
145                         Buffer->Size   = Size;
146                         Buffer->Count  = 0;
147
148                         SetGlobalInterruptMask(CurrentGlobalInt);
149                 }
150
151                 /** Retrieves the current number of bytes stored in a particular buffer. This value is computed
152                  *  by entering an atomic lock on the buffer, so that the buffer cannot be modified while the
153                  *  computation takes place. This value should be cached when reading out the contents of the buffer,
154                  *  so that as small a time as possible is spent in an atomic lock.
155                  *
156                  *  \note The value returned by this function is guaranteed to only be the minimum number of bytes
157                  *        stored in the given buffer; this value may change as other threads write new data, thus
158                  *        the returned number should be used only to determine how many successive reads may safely
159                  *        be performed on the buffer.
160                  *
161                  *  \param[in] Buffer  Pointer to a ring buffer structure whose count is to be computed.
162                  *
163                  *  \return Number of bytes currently stored in the buffer.
164                  */
165                 static inline uint16_t RingBuffer_GetCount(RingBuffer_t* const Buffer) ATTR_WARN_UNUSED_RESULT ATTR_NON_NULL_PTR_ARG(1);
166                 static inline uint16_t RingBuffer_GetCount(RingBuffer_t* const Buffer)
167                 {
168                         uint16_t Count;
169
170                         uint_reg_t CurrentGlobalInt = GetGlobalInterruptMask();
171                         GlobalInterruptDisable();
172
173                         Count = Buffer->Count;
174
175                         SetGlobalInterruptMask(CurrentGlobalInt);
176                         return Count;
177                 }
178
179                 /** Retrieves the free space in a particular buffer. This value is computed by entering an atomic lock
180                  *  on the buffer, so that the buffer cannot be modified while the computation takes place.
181                  *
182                  *  \note The value returned by this function is guaranteed to only be the maximum number of bytes
183                  *        free in the given buffer; this value may change as other threads write new data, thus
184                  *        the returned number should be used only to determine how many successive writes may safely
185                  *        be performed on the buffer when there is a single writer thread.
186                  *
187                  *  \param[in] Buffer  Pointer to a ring buffer structure whose free count is to be computed.
188                  *
189                  *  \return Number of free bytes in the buffer.
190                  */
191                 static inline uint16_t RingBuffer_GetFreeCount(RingBuffer_t* const Buffer) ATTR_WARN_UNUSED_RESULT ATTR_NON_NULL_PTR_ARG(1);
192                 static inline uint16_t RingBuffer_GetFreeCount(RingBuffer_t* const Buffer)
193                 {
194                         return (Buffer->Size - RingBuffer_GetCount(Buffer));
195                 }
196
197                 /** Atomically determines if the specified ring buffer contains any data. This should
198                  *  be tested before removing data from the buffer, to ensure that the buffer does not
199                  *  underflow.
200                  *
201                  *  If the data is to be removed in a loop, store the total number of bytes stored in the
202                  *  buffer (via a call to the \ref RingBuffer_GetCount() function) in a temporary variable
203                  *  to reduce the time spent in atomicity locks.
204                  *
205                  *  \param[in,out] Buffer  Pointer to a ring buffer structure to insert into.
206                  *
207                  *  \return Boolean \c true if the buffer contains no free space, \c false otherwise.
208                  */
209                 static inline bool RingBuffer_IsEmpty(RingBuffer_t* const Buffer) ATTR_WARN_UNUSED_RESULT ATTR_NON_NULL_PTR_ARG(1);
210                 static inline bool RingBuffer_IsEmpty(RingBuffer_t* const Buffer)
211                 {
212                         return (RingBuffer_GetCount(Buffer) == 0);
213                 }
214
215                 /** Atomically determines if the specified ring buffer contains any free space. This should
216                  *  be tested before storing data to the buffer, to ensure that no data is lost due to a
217                  *  buffer overrun.
218                  *
219                  *  \param[in,out] Buffer  Pointer to a ring buffer structure to insert into.
220                  *
221                  *  \return Boolean \c true if the buffer contains no free space, \c false otherwise.
222                  */
223                 static inline bool RingBuffer_IsFull(RingBuffer_t* const Buffer) ATTR_WARN_UNUSED_RESULT ATTR_NON_NULL_PTR_ARG(1);
224                 static inline bool RingBuffer_IsFull(RingBuffer_t* const Buffer)
225                 {
226                         return (RingBuffer_GetCount(Buffer) == Buffer->Size);
227                 }
228
229                 /** Inserts an element into the ring buffer.
230                  *
231                  *  \warning Only one execution thread (main program thread or an ISR) may insert into a single buffer
232                  *           otherwise data corruption may occur. Insertion and removal may occur from different execution
233                  *           threads.
234                  *
235                  *  \param[in,out] Buffer  Pointer to a ring buffer structure to insert into.
236                  *  \param[in]     Data    Data element to insert into the buffer.
237                  */
238                 static inline void RingBuffer_Insert(RingBuffer_t* Buffer,
239                                                      const uint8_t Data) ATTR_NON_NULL_PTR_ARG(1);
240                 static inline void RingBuffer_Insert(RingBuffer_t* Buffer,
241                                                      const uint8_t Data)
242                 {
243                         GCC_FORCE_POINTER_ACCESS(Buffer);
244
245                         *Buffer->In = Data;
246
247                         if (++Buffer->In == Buffer->End)
248                           Buffer->In = Buffer->Start;
249
250                         uint_reg_t CurrentGlobalInt = GetGlobalInterruptMask();
251                         GlobalInterruptDisable();
252
253                         Buffer->Count++;
254
255                         SetGlobalInterruptMask(CurrentGlobalInt);
256                 }
257
258                 /** Removes an element from the ring buffer.
259                  *
260                  *  \warning Only one execution thread (main program thread or an ISR) may remove from a single buffer
261                  *           otherwise data corruption may occur. Insertion and removal may occur from different execution
262                  *           threads.
263                  *
264                  *  \param[in,out] Buffer  Pointer to a ring buffer structure to retrieve from.
265                  *
266                  *  \return Next data element stored in the buffer.
267                  */
268                 static inline uint8_t RingBuffer_Remove(RingBuffer_t* Buffer) ATTR_NON_NULL_PTR_ARG(1);
269                 static inline uint8_t RingBuffer_Remove(RingBuffer_t* Buffer)
270                 {
271                         GCC_FORCE_POINTER_ACCESS(Buffer);
272
273                         uint8_t Data = *Buffer->Out;
274
275                         if (++Buffer->Out == Buffer->End)
276                           Buffer->Out = Buffer->Start;
277
278                         uint_reg_t CurrentGlobalInt = GetGlobalInterruptMask();
279                         GlobalInterruptDisable();
280
281                         Buffer->Count--;
282
283                         SetGlobalInterruptMask(CurrentGlobalInt);
284
285                         return Data;
286                 }
287
288                 /** Returns the next element stored in the ring buffer, without removing it.
289                  *
290                  *  \param[in,out] Buffer  Pointer to a ring buffer structure to retrieve from.
291                  *
292                  *  \return Next data element stored in the buffer.
293                  */
294                 static inline uint8_t RingBuffer_Peek(RingBuffer_t* const Buffer) ATTR_WARN_UNUSED_RESULT ATTR_NON_NULL_PTR_ARG(1);
295                 static inline uint8_t RingBuffer_Peek(RingBuffer_t* const Buffer)
296                 {
297                         return *Buffer->Out;
298                 }
299
300         /* Disable C linkage for C++ Compilers: */
301                 #if defined(__cplusplus)
302                         }
303                 #endif
304
305 #endif
306
307 /** @} */
308