1 /* 2 * Copyright 2008-2009, Axel Dörfler, axeld@pinc-software.de. 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(0) 20 { 21 SetSize(size); 22 } 23 24 ~CircularBuffer() 25 { 26 free(fBuffer); 27 } 28 29 status_t InitCheck() const 30 { 31 return fBuffer != NULL ? B_OK : B_NO_MEMORY; 32 } 33 34 status_t SetSize(size_t size) 35 { 36 MakeEmpty(); 37 38 if (fSize == size) 39 return B_OK; 40 41 fSize = size; 42 fBuffer = (Type*)malloc(fSize * sizeof(Type)); 43 if (fBuffer == NULL) { 44 fSize = 0; 45 return B_NO_MEMORY; 46 } 47 48 return B_OK; 49 } 50 51 void MakeEmpty() 52 { 53 fIn = 0; 54 fFirst = 0; 55 } 56 57 bool IsEmpty() const 58 { 59 return fIn == 0; 60 } 61 62 int32 CountItems() const 63 { 64 return fIn; 65 } 66 67 Type* ItemAt(int32 index) const 68 { 69 if (index >= (int32)fIn || index < 0 || fBuffer == NULL) 70 return NULL; 71 72 return &fBuffer[(fFirst + index) % fSize]; 73 } 74 75 void AddItem(const Type& item) 76 { 77 uint32 index; 78 if (fIn < fSize) 79 index = fFirst + fIn++; 80 else 81 index = fFirst++; 82 83 if (fBuffer != NULL) 84 fBuffer[index % fSize] = item; 85 } 86 87 size_t Size() const 88 { 89 return fSize; 90 } 91 92 private: 93 uint32 fFirst; 94 uint32 fIn; 95 uint32 fSize; 96 Type* fBuffer; 97 }; 98 99 #endif // CIRCULAR_BUFFER_H 100