Skip to content

Commit

Permalink
[util] add: C++ Allocator interface for Memory Arena
Browse files Browse the repository at this point in the history
add: Some utility functions for calculating mb, kb, and gb
  • Loading branch information
jd28 committed Sep 26, 2024
1 parent 35a87d8 commit 0e3acf0
Show file tree
Hide file tree
Showing 3 changed files with 85 additions and 0 deletions.
63 changes: 63 additions & 0 deletions lib/nw/util/memory.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,25 @@

namespace nw {

/// Convert kilobytes to bytes
constexpr std::uint64_t KB(std::uint64_t kb)
{
return kb * 1024ULL;
}

/// Convert megabytes to bytes
constexpr std::uint64_t MB(std::uint64_t mb)
{
return mb * 1024ULL * 1024ULL;
}

/// Convert gigabytes to bytes
constexpr std::uint64_t GB(std::uint64_t gb)
{
return gb * 1024ULL * 1024ULL * 1024ULL;
}

/// A growable Memory Arena
struct MemoryArena {
MemoryArena(size_t blockSize = 1024);
MemoryArena(const MemoryArena&) = delete;
Expand All @@ -37,6 +56,50 @@ struct MemoryArena {
void alloc_block_(size_t size);
};

/// C++ Allocator interface for Memory arena
template <typename T>
class ArenaAllocator {
public:
using value_type = T;
ArenaAllocator(MemoryArena* arena)
: arena_(arena)
{
}

template <typename U>
ArenaAllocator(const ArenaAllocator<U>& other)
: arena_(other.arena_)
{
}

/// Allocate memory for n objects of type T.
T* allocate(size_t n)
{
if (!arena_) { return nullptr; }
size_t size = n * sizeof(T);
void* ptr = arena_->allocate(size, alignof(T));
return static_cast<T*>(ptr);
}

/// Deallocate memory. a no-op.
void deallocate(T*, size_t) { }

template <typename U>
bool operator==(const ArenaAllocator<U>& other) const
{
return arena_ == other.arena_;
}

template <typename U>
bool operator!=(const ArenaAllocator<U>& other) const
{
return !(*this == other);
}

private:
MemoryArena* arena_ = nullptr;
};

// This is very simple and naive.
template <typename T, size_t chunk_size>
struct ObjectPool {
Expand Down
1 change: 1 addition & 0 deletions tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ add_executable(rollnw_test

serial_gff.cpp

util_memory.cpp
util_string.cpp
util_tokenizer.cpp
)
Expand Down
21 changes: 21 additions & 0 deletions tests/util_memory.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#include <gtest/gtest.h>

#include <nw/util/memory.hpp>

using namespace std::literals;

TEST(Memory, Helpers)
{
EXPECT_EQ(nw::KB(1), 1024ULL);
EXPECT_EQ(nw::MB(1), 1024ULL * 1024ULL);
EXPECT_EQ(nw::GB(1), 1024ULL * 1024ULL * 1024ULL);
}

TEST(Memory, Allocator)
{
nw::MemoryArena arena;
nw::ArenaAllocator<char> allocator(&arena);
std::basic_string<char, std::char_traits<char>, nw::ArenaAllocator<char>> arena_string(allocator);
arena_string = "Hello, World";
EXPECT_EQ(arena_string, "Hello, World");
}

0 comments on commit 0e3acf0

Please sign in to comment.