1 /*
2 * Copyright 2014, Paweł Dziepak, pdziepak@quarnos.org.
3 * Copyright 2009, Ingo Weinhold, ingo_weinhold@gmx.de.
4 * Distributed under the terms of the MIT License.
5 */
6 #ifndef UTILITY_H
7 #define UTILITY_H
8
9 #include <OS.h>
10
11 #include <string.h>
12
13 #include <algorithm>
14
15
16 #define PAGE_MASK (B_PAGE_SIZE - 1)
17
18 #define PAGE_OFFSET(x) ((x) & (PAGE_MASK))
19 #define PAGE_BASE(x) ((x) & ~(PAGE_MASK))
20 #define TO_PAGE_SIZE(x) ((x + (PAGE_MASK)) & ~(PAGE_MASK))
21
22
23 extern "C" void dprintf(const char *format, ...);
24
25
26 namespace utility {
27
28
29 template<typename T>
30 class vector {
31 public:
32 inline vector();
33
34 void push_back(const T& value);
pop_back()35 void pop_back() { fSize--; }
36
back()37 T& back() { return fData[fSize - 1]; }
38
39 T& operator[](size_t idx) { return fData[idx]; }
40 const T& operator[](size_t idx) const { return fData[idx]; }
41
size()42 size_t size() const { return fSize; }
empty()43 bool empty() const { return size() == 0; }
44
45 private:
46 void _Grow();
47
48 size_t fMaxSize;
49 size_t fSize;
50 T* fData;
51 };
52
53
54 template<typename T>
vector()55 vector<T>::vector()
56 :
57 fMaxSize(0),
58 fSize(0),
59 fData(NULL)
60 {
61 }
62
63
64 template<typename T>
65 void
push_back(const T & value)66 vector<T>::push_back(const T& value)
67 {
68 if (fSize + 1 > fMaxSize)
69 _Grow();
70 fData[fSize++] = value;
71 }
72
73
74 template<typename T>
75 void
_Grow()76 vector<T>::_Grow()
77 {
78 size_t newSize = std::max(fMaxSize * 2, size_t(4));
79 T* newBuffer = new T[newSize];
80 if (fSize > 0) {
81 memcpy(newBuffer, fData, fSize * sizeof(T));
82 delete[] fData;
83 }
84 fData = newBuffer;
85 fMaxSize = newSize;
86 }
87
88
89 } // namespace utility
90
91
92 #endif // UTILITY_H
93