BufferRef loadStreamBuffer( IStreamRef is ) { // prevent crash if stream is not valid if( ! is ) throw StreamExc(); off_t fileSize = is->size(); if( fileSize > std::numeric_limits<off_t>::max() ) throw StreamExcOutOfMemory(); if( fileSize ) { // sometimes fileSize will be zero for a stream that doesn't know how big it is auto result = std::make_shared<Buffer>( fileSize ); is->readDataAvailable( result->getData(), fileSize ); return result; } else { const size_t bufferSize = 4096; size_t offset = 0; auto result = std::make_shared<Buffer>( bufferSize ); while( ! is->isEof() ) { if( offset + bufferSize > result->getAllocatedSize() ) result->resize( std::max( (size_t)( result->getAllocatedSize() * 1.5f ), offset + bufferSize ) ); size_t bytesRead = is->readDataAvailable( reinterpret_cast<uint8_t*>( result->getData() ) + offset, bufferSize ); offset += bytesRead; result->setSize( offset ); } return result; } }
void loadStreamMemory( IStreamRef is, std::shared_ptr<uint8_t> *resultData, size_t *resultDataSize ) { // prevent crash if stream is not valid if( ! is ) throw StreamExc(); off_t fileSize = is->size(); if( fileSize > std::numeric_limits<off_t>::max() ) throw StreamExcOutOfMemory(); *resultData = std::shared_ptr<uint8_t>( (uint8_t*)malloc( fileSize ), free ); if( ! (*resultData ) ) throw StreamExcOutOfMemory(); *resultDataSize = static_cast<size_t>( fileSize ); is->readDataAvailable( resultData->get(), fileSize ); }