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(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 return fBuffer != NULL ? B_OK : B_NO_MEMORY; 44 } 45 46 void MakeEmpty() 47 { 48 fIn = 0; 49 fFirst = 0; 50 } 51 52 bool IsEmpty() const 53 { 54 return fIn == 0; 55 } 56 57 int32 CountItems() const 58 { 59 return fIn; 60 } 61 62 Type* ItemAt(int32 index) const 63 { 64 if (index >= (int32)fIn || index < 0) 65 return NULL; 66 67 return &fBuffer[(fFirst + index) % fSize]; 68 } 69 70 void AddItem(const Type& item) 71 { 72 uint32 index; 73 if (fIn < fSize) 74 index = fFirst + fIn++; 75 else 76 index = fFirst++; 77 78 fBuffer[index % fSize] = item; 79 } 80 81 size_t Size() const 82 { 83 return fSize; 84 } 85 86 private: 87 uint32 fFirst; 88 uint32 fIn; 89 uint32 fSize; 90 Type* fBuffer; 91 }; 92 93 #endif // CIRCULAR_BUFFER_H 94