tracy/server/TracyFileWrite.hpp

103 lines
2.2 KiB
C++
Raw Normal View History

2017-09-30 14:19:50 +00:00
#ifndef __TRACYFILEWRITE_HPP__
#define __TRACYFILEWRITE_HPP__
2017-09-30 16:37:32 +00:00
#include <algorithm>
2017-09-30 14:19:50 +00:00
#include <stdio.h>
2017-10-01 00:23:30 +00:00
#include <string.h>
2017-09-30 14:19:50 +00:00
#include "TracyFileHeader.hpp"
2017-09-30 17:25:24 +00:00
#include "../common/tracy_lz4.hpp"
#include "../common/TracyForceInline.hpp"
2017-09-30 17:25:24 +00:00
2017-09-30 14:19:50 +00:00
namespace tracy
{
class FileWrite
{
public:
static FileWrite* Open( const char* fn )
{
auto f = fopen( fn, "wb" );
return f ? new FileWrite( f ) : nullptr;
}
~FileWrite()
{
2017-09-30 16:37:32 +00:00
if( m_offset > 0 )
{
2017-09-30 17:25:24 +00:00
WriteLz4Block();
2017-09-30 16:37:32 +00:00
}
2017-09-30 14:19:50 +00:00
fclose( m_file );
2017-09-30 17:25:24 +00:00
LZ4_freeStream( m_stream );
2017-09-30 14:19:50 +00:00
}
tracy_force_inline void Write( const void* ptr, size_t size )
2017-09-30 14:19:50 +00:00
{
2017-09-30 16:37:32 +00:00
if( m_offset + size <= BufSize )
{
WriteSmall( ptr, size );
2017-09-30 16:37:32 +00:00
}
else
{
WriteBig( ptr, size );
2017-09-30 16:37:32 +00:00
}
2017-09-30 14:19:50 +00:00
}
private:
2017-09-30 16:37:32 +00:00
FileWrite( FILE* f )
2017-09-30 17:25:24 +00:00
: m_stream( LZ4_createStream() )
, m_file( f )
2017-09-30 16:37:32 +00:00
, m_offset( 0 )
2017-09-30 17:25:24 +00:00
, m_active( 0 )
{
fwrite( Lz4Header, 1, sizeof( Lz4Header ), m_file );
}
2017-09-30 16:37:32 +00:00
tracy_force_inline void WriteSmall( const void* ptr, size_t size )
{
memcpy( m_buf[m_active] + m_offset, ptr, size );
m_offset += size;
}
void WriteBig( const void* ptr, size_t size )
{
auto src = (const char*)ptr;
while( size > 0 )
{
const auto sz = std::min( size, BufSize - m_offset );
memcpy( m_buf[m_active] + m_offset, src, sz );
m_offset += sz;
src += sz;
size -= sz;
if( m_offset == BufSize )
{
WriteLz4Block();
}
}
}
2017-09-30 17:25:24 +00:00
void WriteLz4Block()
{
char lz4[LZ4Size];
const uint32_t sz = LZ4_compress_fast_continue( m_stream, m_buf[m_active], lz4, m_offset, LZ4Size, 1 );
fwrite( &sz, 1, sizeof( sz ), m_file );
fwrite( lz4, 1, sz, m_file );
m_offset = 0;
m_active = 1 - m_active;
}
2017-09-30 16:37:32 +00:00
enum { BufSize = 64 * 1024 };
2017-09-30 17:25:24 +00:00
enum { LZ4Size = LZ4_COMPRESSBOUND( BufSize ) };
2017-09-30 14:19:50 +00:00
2017-09-30 17:25:24 +00:00
LZ4_stream_t* m_stream;
2017-09-30 14:19:50 +00:00
FILE* m_file;
2017-09-30 17:25:24 +00:00
char m_buf[2][BufSize];
2017-09-30 16:37:32 +00:00
size_t m_offset;
2017-09-30 17:25:24 +00:00
uint8_t m_active;
2017-09-30 14:19:50 +00:00
};
}
#endif