tracy/server/TracySlab.hpp

91 lines
1.8 KiB
C++
Raw Normal View History

2017-09-15 17:41:09 +00:00
#ifndef __TRACYSLAB_HPP__
#define __TRACYSLAB_HPP__
#include <assert.h>
#include <vector>
2017-09-16 23:22:46 +00:00
#include "TracyMemory.hpp"
2017-09-15 17:41:09 +00:00
namespace tracy
{
template<size_t BlockSize>
class Slab
{
public:
Slab()
: m_ptr( new char[BlockSize] )
, m_offset( 0 )
2017-09-22 20:25:18 +00:00
, m_buffer( { m_ptr } )
2017-09-16 23:22:46 +00:00
{
memUsage.fetch_add( BlockSize, std::memory_order_relaxed );
}
2017-09-15 17:41:09 +00:00
~Slab()
{
2017-09-16 23:22:46 +00:00
memUsage.fetch_sub( BlockSize * m_buffer.size(), std::memory_order_relaxed );
2017-09-15 17:41:09 +00:00
for( auto& v : m_buffer )
{
delete[] v;
}
}
void* Alloc( size_t size )
{
assert( size <= BlockSize );
if( m_offset + size > BlockSize )
{
m_ptr = new char[BlockSize];
m_offset = 0;
m_buffer.emplace_back( m_ptr );
2017-09-16 23:22:46 +00:00
memUsage.fetch_add( BlockSize, std::memory_order_relaxed );
2017-09-15 17:41:09 +00:00
}
void* ret = m_ptr + m_offset;
m_offset += size;
return ret;
}
2017-09-15 17:54:43 +00:00
template<typename T>
T* Alloc()
{
2017-09-15 18:24:15 +00:00
return new( Alloc( sizeof( T ) ) ) T;
2017-09-15 17:54:43 +00:00
}
2017-09-15 17:41:09 +00:00
void Unalloc( size_t size )
{
assert( size <= m_offset );
m_offset -= size;
}
void Reset()
{
if( m_buffer.size() > 1 )
{
2017-09-16 23:22:46 +00:00
memUsage.fetch_sub( BlockSize * ( m_buffer.size() - 1 ), std::memory_order_relaxed );
2017-09-15 17:41:09 +00:00
for( int i=1; i<m_buffer.size(); i++ )
{
delete[] m_buffer[i];
}
m_ptr = m_buffer[0];
m_buffer.clear();
m_buffer.emplace_back( m_ptr );
}
m_offset = 0;
}
Slab( const Slab& ) = delete;
Slab( Slab&& ) = delete;
Slab& operator=( const Slab& ) = delete;
Slab& operator=( Slab&& ) = delete;
private:
char* m_ptr;
size_t m_offset;
std::vector<char*> m_buffer;
};
}
#endif