repository_infos: Enable automatic updates on the main Haiku repostiory.
[haiku.git] / src / apps / activitymonitor / CircularBuffer.h
blob6bce954f94c99631dfa7c17d2aba83b80be8b8c5
1 /*
2 * Copyright 2008-2013, 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
9 #include <stdlib.h>
11 #include <OS.h>
14 template<typename Type>
15 class CircularBuffer {
16 public:
17 CircularBuffer(size_t size)
19 fSize(0),
20 fBuffer(NULL)
22 SetSize(size);
25 ~CircularBuffer()
27 free(fBuffer);
30 status_t InitCheck() const
32 return fBuffer != NULL ? B_OK : B_NO_MEMORY;
35 status_t SetSize(size_t size)
37 MakeEmpty();
39 if (fSize == size)
40 return B_OK;
42 fSize = size;
43 fBuffer = (Type*)malloc(fSize * sizeof(Type));
44 if (fBuffer == NULL) {
45 fSize = 0;
46 return B_NO_MEMORY;
49 return B_OK;
52 void MakeEmpty()
54 fIn = 0;
55 fFirst = 0;
58 bool IsEmpty() const
60 return fIn == 0;
63 int32 CountItems() const
65 return fIn;
68 Type* ItemAt(int32 index) const
70 if (index >= (int32)fIn || index < 0 || fBuffer == NULL)
71 return NULL;
73 return &fBuffer[(fFirst + index) % fSize];
76 void AddItem(const Type& item)
78 uint32 index;
79 if (fIn < fSize)
80 index = fFirst + fIn++;
81 else
82 index = fFirst++;
84 if (fBuffer != NULL)
85 fBuffer[index % fSize] = item;
88 size_t Size() const
90 return fSize;
93 private:
94 uint32 fFirst;
95 uint32 fIn;
96 uint32 fSize;
97 Type* fBuffer;
101 #endif // CIRCULAR_BUFFER_H