Skip to content
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

Modify HEAP::clear() to not free allocated blocks #1059

Merged
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
30 changes: 22 additions & 8 deletions src/jdlib/heap.cpp
Expand Up @@ -9,24 +9,28 @@

#include "heap.h"

#include <cstring>


using namespace JDLIB;

HEAP::HEAP( std::size_t blocksize ) noexcept
: m_blocksize{ blocksize }
, m_block_iter{ m_heap_list.end() }
{}


HEAP::~HEAP()
{
clear();
}
HEAP::~HEAP() noexcept = default;


/**
* @brief ブロックを確保したまま利用状況を初期化する
*/
void HEAP::clear()
{
m_heap_list.clear();
m_space_avail = 0;
m_ptr_head = nullptr;
m_block_iter = m_heap_list.begin();
}


Expand All @@ -37,9 +41,19 @@ void* HEAP::heap_alloc( std::size_t size_bytes, std::size_t alignment )

while(1) {
if( !m_ptr_head || m_space_avail < size_bytes || m_space_avail >= m_blocksize ) {
// 確保したメモリブロックはゼロ初期化する
m_heap_list.emplace_back( new unsigned char[m_blocksize]{} );
m_ptr_head = &m_heap_list.back()[0];
if( m_block_iter != m_heap_list.end() ) {
// メモリブロックは使う前にzero-fillする
m_ptr_head = &(*m_block_iter)[0];
std::memset( m_ptr_head, 0, sizeof(unsigned char) * m_blocksize );
++m_block_iter;
}
else {
// std::listは要素追加でイテレーターが無効にならない
// イテレーターがendを指しているときはブロックを追加
// 確保したメモリブロックはゼロ初期化する
m_heap_list.emplace_back( new unsigned char[m_blocksize]{} );
m_ptr_head = &m_heap_list.back()[0];
}
m_space_avail = m_blocksize - 1;
}

Expand Down
9 changes: 6 additions & 3 deletions src/jdlib/heap.h
Expand Up @@ -13,21 +13,24 @@ namespace JDLIB
{
class HEAP
{
std::list< std::unique_ptr<unsigned char[]> > m_heap_list;
using BlockList = std::list< std::unique_ptr<unsigned char[]> >;

BlockList m_heap_list;
std::size_t m_blocksize; // ブロックサイズ
std::size_t m_space_avail{}; // ブロックの未使用サイズ
void* m_ptr_head{}; // 検索開始位置
BlockList::iterator m_block_iter; // ブロックを再利用するためのイテレーター

public:
explicit HEAP( std::size_t blocksize ) noexcept;
~HEAP();
~HEAP() noexcept;

HEAP( const HEAP& ) = delete;
HEAP& operator=( const HEAP& ) = delete;
HEAP( HEAP&& ) noexcept = default;
HEAP& operator=( HEAP&& ) = default;

void clear();
void clear(); // ブロックを確保したまま利用状況を初期化する

// 戻り値はunsigned char*のエイリアス
void* heap_alloc( std::size_t size_bytes, std::size_t alignment );
Expand Down