1 /* 2 * Copyright 2008, Axel Dörfler, axeld@pinc-software.de. All rights reserved. 3 * Distributed under the terms of the MIT License. 4 */ 5 #ifndef CIRCULAR_BUFFER_H 6 #define CIRCULAR_BUFFER_H 7 8 9 #include <stdlib.h> 10 11 #include <OS.h> 12 13 14 template<typename Type> 15 class CircularBuffer { 16 public: 17 CircularBuffer(size_t size) 18 : 19 fSize(size) 20 { 21 fBuffer = (Type *)malloc(fSize * sizeof(Type)); 22 MakeEmpty(); 23 } 24 25 ~CircularBuffer() 26 { 27 free(fBuffer); 28 } 29 30 status_t InitCheck() const 31 { 32 return fBuffer != NULL ? B_OK : B_NO_MEMORY; 33 } 34 35 void MakeEmpty() 36 { 37 fIn = 0; 38 fFirst = 0; 39 } 40 41 bool IsEmpty() const 42 { 43 return fIn == 0; 44 } 45 46 int32 CountItems() const 47 { 48 return fIn; 49 } 50 51 Type* ItemAt(int32 index) const 52 { 53 if (index >= (int32)fIn || index < 0) 54 return NULL; 55 56 return &fBuffer[(fFirst + index) % fSize]; 57 } 58 59 void AddItem(const Type& item) 60 { 61 uint32 index; 62 if (fIn < fSize) 63 index = fFirst + fIn++; 64 else 65 index = fFirst++; 66 67 fBuffer[index % fSize] = item; 68 } 69 70 private: 71 uint32 fFirst; 72 uint32 fIn; 73 uint32 fSize; 74 Type* fBuffer; 75 }; 76 77 #endif // CIRCULAR_BUFFER_H 78