add PagedBuffer; use own main() for tests

This commit is contained in:
Josh Holtrop 2016-07-17 20:43:18 -04:00
parent 3be19dbf81
commit cab874305f
4 changed files with 134 additions and 2 deletions

79
src/core/PagedBuffer.h Normal file
View File

@ -0,0 +1,79 @@
#ifndef PAGEDBUFFER_H
#define PAGEDBUFFER_H
#include "System.h"
#include <vector>
#include <stdint.h>
template <typename T>
class PagedBuffer
{
public:
/**
* Create a PagedBuffer.
*
* Note: sizeof(T) must be a power of 2. A single page can hold
* System::page_size / sizeof(T) entries.
*/
PagedBuffer<T>()
{
static_assert((sizeof(T) & (sizeof(T) - 1)) == 0,
"sizeof(T) must be a power of 2");
m_size = 0u;
}
~PagedBuffer<T>()
{
for (auto it : m_pages)
{
System::free_pages(it, 1);
}
}
const T & operator[](unsigned int index) const
{
while (index >= (m_pages.size() * n_per_page()))
{
grow();
}
return m_pages[page_index(index)][index_in_page(index)];
}
T & operator[](unsigned int index)
{
while (index >= (m_pages.size() * n_per_page()))
{
grow();
}
return m_pages[page_index(index)][index_in_page(index)];
}
size_t size() { return m_size; }
protected:
unsigned int n_per_page()
{
return System::page_size / sizeof(T);
}
unsigned int page_index(unsigned int index)
{
return index / n_per_page();
}
unsigned int index_in_page(unsigned int index)
{
return index % n_per_page();
}
void grow()
{
m_pages.push_back((T *)System::alloc_pages(1));
m_size += n_per_page();
}
std::vector<T *> m_pages;
unsigned long m_size;
};
#endif

9
test/src/main.cc Normal file
View File

@ -0,0 +1,9 @@
#include "gtest/gtest.h"
#include "System.h"
int main(int argc, char * argv[])
{
::testing::InitGoogleTest(&argc, argv);
System::init();
return RUN_ALL_TESTS();
}

View File

@ -0,0 +1,45 @@
#include "gtest/gtest.h"
#include "PagedBuffer.h"
struct X
{
uint64_t a;
uint32_t b;
uint32_t c;
};
struct Y
{
uint32_t a;
uint32_t b;
};
TEST(PagedBufferTest, empty_paged_buffer_has_size_0)
{
PagedBuffer<X> pbx;
ASSERT_EQ(0u, pbx.size());
PagedBuffer<Y> pby;
ASSERT_EQ(0u, pby.size());
}
TEST(PagedBufferTest, allows_adding_elements)
{
PagedBuffer<X> pbx;
for (uint32_t i = 0u; i < 1000u; i++)
{
X x = {i, 2u * i, 4u * i};
pbx[i] = x;
}
ASSERT_GE(pbx.size(), 1000u);
for (uint32_t i = 0u; i < 1000u; i++)
{
const X & x = pbx[i];
ASSERT_EQ(i, x.a);
ASSERT_EQ(2u * i, x.b);
ASSERT_EQ(4u * i, x.c);
}
}

View File

@ -33,8 +33,7 @@ def build(bld):
test_libs += ["pthread"]
test_sources = bld.path.ant_glob("src/core/**/*.cc")
test_sources += bld.path.ant_glob("test/src/**/*.cc")
test_sources += ["libs/googletest/src/gtest-all.cc",
"libs/googletest/src/gtest_main.cc"]
test_sources += ["libs/googletest/src/gtest-all.cc"]
test_includes = ["src/core"]
test_includes += ["libs/googletest/include", "libs/googletest"]
bld(features = "cxx cxxprogram",