tracy/server/TracyFileRead.hpp

82 lines
1.8 KiB
C++
Raw Normal View History

2017-09-30 14:19:50 +00:00
#ifndef __TRACYFILEREAD_HPP__
#define __TRACYFILEREAD_HPP__
2017-09-30 16:43:39 +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
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 FileRead
{
public:
static FileRead* Open( const char* fn )
{
auto f = fopen( fn, "rb" );
return f ? new FileRead( f ) : nullptr;
}
~FileRead()
{
fclose( m_file );
2017-09-30 17:25:24 +00:00
LZ4_freeStreamDecode( m_stream );
2017-09-30 14:19:50 +00:00
}
tracy_force_inline void Read( void* ptr, size_t size )
2017-09-30 14:19:50 +00:00
{
2017-09-30 23:59:07 +00:00
if( size <= BufSize - m_offset )
2017-09-30 16:43:39 +00:00
{
2017-09-30 23:59:07 +00:00
memcpy( ptr, m_buf[m_active] + m_offset, size );
m_offset += size;
}
else
{
auto dst = (char*)ptr;
while( size > 0 )
2017-09-30 16:43:39 +00:00
{
2017-09-30 23:59:07 +00:00
if( m_offset == BufSize )
{
m_active = 1 - m_active;
m_offset = 0;
uint32_t sz;
fread( &sz, 1, sizeof( sz ), m_file );
fread( m_lz4buf, 1, sz, m_file );
LZ4_decompress_safe_continue( m_stream, m_lz4buf, m_buf[m_active], sz, BufSize );
2017-09-30 23:59:07 +00:00
}
2017-09-30 16:43:39 +00:00
2017-09-30 23:59:07 +00:00
const auto sz = std::min( size, BufSize - m_offset );
memcpy( dst, m_buf[m_active] + m_offset, sz );
m_offset += sz;
dst += sz;
size -= sz;
}
2017-09-30 16:43:39 +00:00
}
2017-09-30 14:19:50 +00:00
}
private:
2017-09-30 16:43:39 +00:00
FileRead( FILE* f )
2017-09-30 17:25:24 +00:00
: m_stream( LZ4_createStreamDecode() )
, m_file( f )
2017-09-30 16:43:39 +00:00
, m_offset( BufSize )
2017-09-30 17:25:24 +00:00
, m_active( 1 )
2017-09-30 16:43:39 +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_streamDecode_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];
char m_lz4buf[LZ4Size];
2017-09-30 16:43:39 +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