37e8a1ba5f8f99d65c694731fe50a21eb97b35cf
[pub/USBasp.git] / LUFA / Drivers / Misc / RingBuffer.h
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2011.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.lufa-lib.org
7 */
8
9 /*
10 Copyright 2011 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 disclaim 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 buffer, for fast insertion/deletion.
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 *
46 * \section Sec_Dependencies Module Source Dependencies
47 * The following files must be built with any user project that uses this module:
48 * - None
49 *
50 * \section Sec_ModDescription Module Description
51 * Lightweight ring buffer, for fast insertion/deletion. Multiple buffers can be created of
52 * different sizes to suit different needs.
53 *
54 * Note that for each buffer, insertion and removal operations may occur at the same time (via
55 * a multi-threaded ISR based system) however the same kind of operation (two or more insertions
56 * or deletions) must not overlap. If there is possibility of two or more of the same kind of
57 * operating occurring at the same point in time, atomic (mutex) locking should be used.
58 *
59 * \section Sec_ExampleUsage Example Usage
60 * The following snippet is an example of how this module may be used within a typical
61 * application.
62 *
63 * \code
64 * // Create the buffer structure and its underlying storage array
65 * RingBuffer_t Buffer;
66 * uint8_t BufferData[128];
67 *
68 * // Initialise the buffer with the created storage array
69 * RingBuffer_InitBuffer(&Buffer, BufferData, sizeof(BufferData));
70 *
71 * // Insert some data into the buffer
72 * RingBuffer_Insert(Buffer, 'H');
73 * RingBuffer_Insert(Buffer, 'E');
74 * RingBuffer_Insert(Buffer, 'L');
75 * RingBuffer_Insert(Buffer, 'L');
76 * RingBuffer_Insert(Buffer, 'O');
77 *
78 * // Cache the number of stored bytes in the buffer
79 * uint16_t BufferCount = RingBuffer_GetCount(&Buffer);
80 *
81 * // Printer stored data length
82 * printf("Buffer Length: %d, Buffer Data: \r\n", BufferCount);
83 *
84 * // Print contents of the buffer one character at a time
85 * while (BufferCount--)
86 * putc(RingBuffer_Remove(&Buffer));
87 * \endcode
88 *
89 * @{
90 */
91
92 #ifndef __RING_BUFF_H__
93 #define __RING_BUFF_H__
94
95 /* Includes: */
96 #include <util/atomic.h>
97 #include <stdint.h>
98 #include <stdbool.h>
99
100 #include <LUFA/Common/Common.h>
101
102 /* Type Defines: */
103 /** \brief Ring Buffer Management Structure.
104 *
105 * Type define for a new ring buffer object. Buffers should be initialized via a call to
106 * \ref RingBuffer_InitBuffer() before use.
107 */
108 typedef struct
109 {
110 uint8_t* In; /**< Current storage location in the circular buffer */
111 uint8_t* Out; /**< Current retrieval location in the circular buffer */
112 uint8_t* Start; /**< Pointer to the start of the buffer's underlying storage array */
113 uint8_t* End; /**< Pointer to the end of the buffer's underlying storage array */
114 uint8_t Size; /**< Size of the buffer's underlying storage array */
115 uint16_t Count; /**< Number of bytes currently stored in the buffer */
116 } RingBuffer_t;
117
118 /* Inline Functions: */
119 /** Initializes a ring buffer ready for use. Buffers must be initialized via this function
120 * before any operations are called upon them. Already initialized buffers may be reset
121 * by re-initializing them using this function.
122 *
123 * \param[out] Buffer Pointer to a ring buffer structure to initialize.
124 * \param[out] DataPtr Pointer to a global array that will hold the data stored into the ring buffer.
125 * \param[out] Size Maximum number of bytes that can be stored in the underlying data array.
126 */
127 static inline void RingBuffer_InitBuffer(RingBuffer_t* Buffer, uint8_t* const DataPtr, const uint16_t Size)
128 {
129 GCC_FORCE_POINTER_ACCESS(Buffer);
130
131 ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
132 {
133 Buffer->In = DataPtr;
134 Buffer->Out = DataPtr;
135 Buffer->Start = &DataPtr[0];
136 Buffer->End = &DataPtr[Size];
137 Buffer->Size = Size;
138 Buffer->Count = 0;
139 }
140 }
141
142 /** Retrieves the minimum number of bytes stored in a particular buffer. This value is computed
143 * by entering an atomic lock on the buffer while the IN and OUT locations are fetched, so that
144 * the buffer cannot be modified while the computation takes place. This value should be cached
145 * when reading out the contents of the buffer, so that as small a time as possible is spent
146 * in an atomic lock.
147 *
148 * \note The value returned by this function is guaranteed to only be the minimum number of bytes
149 * stored in the given buffer; this value may change as other threads write new data and so
150 * the returned number should be used only to determine how many successive reads may safely
151 * be performed on the buffer.
152 *
153 * \param[in] Buffer Pointer to a ring buffer structure whose count is to be computed.
154 */
155 static inline uint16_t RingBuffer_GetCount(RingBuffer_t* const Buffer)
156 {
157 uint16_t Count;
158
159 ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
160 {
161 Count = Buffer->Count;
162 }
163
164 return Count;
165 }
166
167 /** Atomically determines if the specified ring buffer contains any free space. This should
168 * be tested before storing data to the buffer, to ensure that no data is lost due to a
169 * buffer overrun.
170 *
171 * \param[in,out] Buffer Pointer to a ring buffer structure to insert into.
172 *
173 * \return Boolean \c true if the buffer contains no free space, false otherwise.
174 */
175 static inline bool RingBuffer_IsFull(RingBuffer_t* const Buffer)
176 {
177 return (RingBuffer_GetCount(Buffer) == Buffer->Size);
178 }
179
180 /** Atomically determines if the specified ring buffer contains any data. This should
181 * be tested before removing data from the buffer, to ensure that the buffer does not
182 * underflow.
183 *
184 * If the data is to be removed in a loop, store the total number of bytes stored in the
185 * buffer (via a call to the \ref RingBuffer_GetCount() function) in a temporary variable
186 * to reduce the time spent in atomicity locks.
187 *
188 * \param[in,out] Buffer Pointer to a ring buffer structure to insert into.
189 *
190 * \return Boolean \c true if the buffer contains no free space, false otherwise.
191 */
192 static inline bool RingBuffer_IsEmpty(RingBuffer_t* const Buffer)
193 {
194 return (RingBuffer_GetCount(Buffer) == 0);
195 }
196
197 /** Inserts an element into the ring buffer.
198 *
199 * \note Only one execution thread (main program thread or an ISR) may insert into a single buffer
200 * otherwise data corruption may occur. Insertion and removal may occur from different execution
201 * threads.
202 *
203 * \param[in,out] Buffer Pointer to a ring buffer structure to insert into.
204 * \param[in] Data Data element to insert into the buffer.
205 */
206 static inline void RingBuffer_Insert(RingBuffer_t* Buffer,
207 const uint8_t Data)
208 {
209 GCC_FORCE_POINTER_ACCESS(Buffer);
210
211 *Buffer->In = Data;
212
213 if (++Buffer->In == Buffer->End)
214 Buffer->In = Buffer->Start;
215
216 ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
217 {
218 Buffer->Count++;
219 }
220 }
221
222 /** Removes an element from the ring buffer.
223 *
224 * \note Only one execution thread (main program thread or an ISR) may remove from a single buffer
225 * otherwise data corruption may occur. Insertion and removal may occur from different execution
226 * threads.
227 *
228 * \param[in,out] Buffer Pointer to a ring buffer structure to retrieve from.
229 *
230 * \return Next data element stored in the buffer.
231 */
232 static inline uint8_t RingBuffer_Remove(RingBuffer_t* Buffer)
233 {
234 GCC_FORCE_POINTER_ACCESS(Buffer);
235
236 uint8_t Data = *Buffer->Out;
237
238 if (++Buffer->Out == Buffer->End)
239 Buffer->Out = Buffer->Start;
240
241 ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
242 {
243 Buffer->Count--;
244 }
245
246 return Data;
247 }
248
249 /** Returns the next element stored in the ring buffer, without removing it.
250 *
251 * \param[in,out] Buffer Pointer to a ring buffer structure to retrieve from.
252 *
253 * \return Next data element stored in the buffer.
254 */
255 static inline uint8_t RingBuffer_Peek(RingBuffer_t* const Buffer)
256 {
257 return *Buffer->Out;
258 }
259
260 #endif
261
262 /** @} */
263