Skip to content

Feature: Add a scratch allocator #29

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Oct 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ IF( CPPCORE_BUILD_UNITTESTS )
SET( cppcore_memory_test_src
test/memory/TStackAllocatorTest.cpp
test/memory/TPoolAllocatorTest.cpp
test/memory/TScratchAllocatorTest.cpp
)

SET( cppcore_random_test_src
Expand All @@ -163,7 +164,7 @@ IF( CPPCORE_BUILD_UNITTESTS )
SOURCE_GROUP( code\\container FILES ${cppcore_container_test_src} )
SOURCE_GROUP( code\\memory FILES ${cppcore_memory_test_src} )
SOURCE_GROUP( code\\random FILES ${cppcore_random_test_src} )

# Prevent overriding the parent project's compiler/linker
# settings on Windows
SET(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
Expand Down
6 changes: 3 additions & 3 deletions doc/Common.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ You need to manage singe bits and you want to avoid dealing with the OR-, AND- a

void main() {
TBitField<uint32_t> bitfield(0);

// The first bit is set
bitfield.setBit(1);
if (bitfield.getBit(1)) std::cout "First bit is set" << std:endl;
Expand All @@ -53,12 +53,12 @@ void main() {
### Usecases
### Examples

## TSharedPtr
## TSharedPtr
### Introduction
### Usecases
### Examples

## Variant
## Variant
### Introduction
### Usecases
### Examples
32 changes: 32 additions & 0 deletions doc/Memory.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,37 @@ allocation scheme in all containers.
## CPPCore::TPoolAllocator
This allocator can be use to create an initial pool of object at the program startup.

## CPPCore::TScratchAllocator
### Introduction
The scratch allocator preallocates a memory block which can be used in your program. You do not have to deallocate any of the allocations.
This will be done when clearing the allocator. All allocations will be invalidated.

### Usecases
Common use cases include:
- Temporary allocations in algorithms (e.g., path finding, sorting)
- Frame-based memory management in games
- Scratch space for parsing and serialization
- Short-lived computational tasks with multiple dynamic allocations

### Examples
```cpp
#include <Memory/TScratchAllocator.h>

using namespace ::cppcore;

int main() {
// Will work
ScratchAllocator myAllocator(1024);
char *ptr1 = myAllocator.alloc(512);
assert(ptr1 != nullptr);

// Overrange shall get catched
char *ptr2 = myAllocator.alloc(600);
assert(ptr2 == nullptr);

return 0;
}
```

## CPPCore::TStackAllocator
The stack allocator preallocates a memory block which can be used in your program. When deallocating your memory you have to follow the first-in last-out rule.
6 changes: 3 additions & 3 deletions include/cppcore/IO/FileSystem.h
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,13 @@ class FileSystem {
/// @brief The class constructor with the location.
/// @param[in] location The root location.
FileSystem(const char *location);

/// @brief The class destructor.
~FileSystem() = default;

/// @brief Will perform a refresh.
void refresh();

/// @brief Will return the free disk info.
/// @return the File-system space.
FSSpace *getFreeDiskSpace();
Expand Down
2 changes: 1 addition & 1 deletion include/cppcore/Memory/TDefaultAllocator.h
Original file line number Diff line number Diff line change
Expand Up @@ -129,4 +129,4 @@ inline void TDefaultAllocator<T>::dumpAllocations(std::string &allocs) {
// empty
}

} // Namespace cppcore
} // namespace cppcore
4 changes: 2 additions & 2 deletions include/cppcore/Memory/TPoolAllocator.h
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ class TPoolAllocator {

/// @brief Will reset the allocator.
void reset();

/// No copying allowed
CPPCORE_NONE_COPYING(TPoolAllocator)

Expand Down Expand Up @@ -283,4 +283,4 @@ void TPoolAllocator<T>::reset() {
m_current = m_first;
}

} // Namespace cppcore
} // namespace cppcore
161 changes: 161 additions & 0 deletions include/cppcore/Memory/TScratchAllocator.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
/*-----------------------------------------------------------------------------------------------
The MIT License (MIT)

Copyright (c) 2014-2024 Kim Kulling

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-----------------------------------------------------------------------------------------------*/
#pragma once

#include <cppcore/CPPCoreCommon.h>
#include <memory>
#include <limits>

namespace cppcore {

//-------------------------------------------------------------------------------------------------
/// @class TScratchAllocator
/// @ingroup CPPCore
///
/// @brief A simple scratch allocator.
///
/// You can use it to manage all the dynamic allocations without caring about cleaning it up. All
/// Allocations will be a one-shot alloc, which do not need to get released. When calling clear
/// all allocation will be invalidated and cannot be used anymore.
//-------------------------------------------------------------------------------------------------
template<class T>
class TScratchAllocator {
public:
/// @brief The default class constructor.
TScratchAllocator();

/// @brief The class constructor with the pool size.
/// @param[in] numItems The buffer size.
explicit TScratchAllocator(size_t numItems);

/// @brief The class destructor.
~TScratchAllocator();

/// @brief Will allocate the number of items.
/// @param[in] numItems The number of items.
/// @return Pointr showing to the scratch buffer.
T *alloc(size_t numItems);

/// @brief Will reserve the pool.
/// @apram[in] size The pool size to reserve.
void reserve(size_t size);

/// @brief Will clear the pool, memory will be deallocated.
/// @note All instances which are currently is use will get invalid. PLease use with care.
void clear();

/// @brief Returns the capacity of items in the pool allocator.
/// @return The capacity.
size_t capacity() const;

/// @brief Will return the reserved memory in bytes.
/// @return The reserved memory in bytes.
size_t reservedMem() const;

/// @brief Will return the free memory in the pool in bytes.
/// @return The free memory in bytes.
size_t freeMem() const;

/// No copying allowed
CPPCORE_NONE_COPYING(TScratchAllocator)

private:
T *mBlock = nullptr;
size_t mSize;
size_t mIndex;
};

template<class T>
inline TScratchAllocator<T>::TScratchAllocator() :
mSize(0u), mIndex(0u) {
// empty
}

template<class T>
inline TScratchAllocator<T>::TScratchAllocator(size_t numItems) :
mSize(numItems), mIndex(0u) {
reserve(numItems);
}

template<class T>
inline TScratchAllocator<T>::~TScratchAllocator() {
clear();
}

template<class T>
inline T *TScratchAllocator<T>::alloc(size_t numItems) {
if (numItems == 0) {
return nullptr;
}

// Check for overflow
if (numItems > std::numeric_limits<size_t>::max() / sizeof(T)) {
return nullptr;
}

if ((mIndex + numItems) > mSize) {
return nullptr;
}

// Ensure alignment
size_t alignment = alignof(T);
mIndex = (mIndex + alignment - 1) & ~(alignment - 1);

T *ptr = &mBlock[mIndex];
mIndex += numItems;
return ptr;
}

template<class T>
void TScratchAllocator<T>::reserve(size_t size) {
clear();
mBlock = new T[size];
mSize = size;
mIndex = 0u;
}

template<class T>
inline void TScratchAllocator<T>::clear() {
delete [] mBlock;
mBlock = nullptr;
mSize = 0u;
}

template<class T>
inline size_t TScratchAllocator<T>::capacity() const {
return mSize;
}

template<class T>
inline size_t TScratchAllocator<T>::reservedMem() const {
return mIndex;
}

template<class T>
inline size_t TScratchAllocator<T>::freeMem() const {
return (mSize - mIndex);
}

using ScratchAllocator = TScratchAllocator<char>;

} // namespace cppcore
6 changes: 4 additions & 2 deletions include/cppcore/Memory/TStackAllocator.h
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ class TStackAllocator {
/// @brief The class destructor.
~TStackAllocator();

/// Will alloc the number of items from the stack.
/// Will allocate the number of items from the stack.
/// @param size [in] The requested size of items.
T *alloc(size_t size);

Expand Down Expand Up @@ -184,11 +184,13 @@ inline void TStackAllocator<T>::clear() {
m_data = nullptr;
m_capacity = 0;
m_top = 0;
m_numAllocs = 0;
}

template <class T>
inline void TStackAllocator<T>::reset() {
m_top = 0;
m_numAllocs = 0;
}

template <class T>
Expand Down
4 changes: 1 addition & 3 deletions test/Random/RandomGeneratorTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,7 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

using namespace cppcore;

class RandomGeneratorTest : public testing::Test {
// empty
};
class RandomGeneratorTest : public testing::Test {};

TEST_F( RandomGeneratorTest, getTest ) {
RandomGenerator generator;
Expand Down
66 changes: 66 additions & 0 deletions test/memory/TScratchAllocatorTest.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*-----------------------------------------------------------------------------------------------
The MIT License (MIT)

Copyright (c) 2014-2024 Kim Kulling

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-----------------------------------------------------------------------------------------------*/
#include <cppcore/Memory/TScratchAllocator.h>

#include <gtest/gtest.h>

using namespace cppcore;

class TScratchAllocatorTest : public testing::Test {
public:
static constexpr size_t BufferSize = 1024u;
};

TEST_F(TScratchAllocatorTest, CreateTest) {
bool ok( true );
try {
ScratchAllocator myAllocator(BufferSize);
} catch ( ... ) {
ok = false;
}
EXPECT_TRUE( ok );
}

TEST_F(TScratchAllocatorTest, AllocTest) {
ScratchAllocator myAllocator(BufferSize);
char *ptr1 = myAllocator.alloc(512);
EXPECT_NE(ptr1, nullptr);
EXPECT_EQ(myAllocator.capacity(), BufferSize);
EXPECT_EQ(myAllocator.freeMem(), 512);
EXPECT_EQ(myAllocator.reservedMem(), 512);

char *ptr2 = myAllocator.alloc(600);
EXPECT_EQ(ptr2, nullptr);

myAllocator.clear();
}

TEST_F(TScratchAllocatorTest, ClearTest) {
ScratchAllocator myAllocator(BufferSize);
EXPECT_EQ(myAllocator.capacity(), BufferSize);
EXPECT_EQ(myAllocator.freeMem(), BufferSize);

myAllocator.clear();
EXPECT_EQ(myAllocator.capacity(), 0u);
EXPECT_EQ(myAllocator.freeMem(), 0u);
}
4 changes: 1 addition & 3 deletions test/memory/TStackAllocatorTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,7 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

using namespace cppcore;

class TStackAllocatorTest : public testing::Test {
protected:
};
class TStackAllocatorTest : public testing::Test {};

TEST_F( TStackAllocatorTest, CreateTest ) {
bool ok( true );
Expand Down
Loading