RingBuffer.h 12 KB

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