00001 /* 00002 * DaqFromIStream.cc 00003 * FileReadoutFormat 00004 * 00005 * Created by Simon Patton on 7/18/10. 00006 * Copyright 2010 DayaBay Collaboration. All rights reserved. 00007 * 00008 */ 00009 #include "FileReadoutFormat/DaqFromIStream.h" 00010 00011 #include <istream> 00012 #include <string> 00013 #include <cstring> 00014 00015 #include "DaqReadoutFormat/ByteBuffer.h" 00016 #include "FileReadoutFormat/DaqFormatFromBytes.h" 00017 00018 using DybDaq::ByteBuffer; 00019 using DybDaq::FileBuffer; 00020 using DybDaq::DaqFormatFromBytes; 00021 using DybDaq::DaqFromIStream; 00022 using std::ifstream; 00023 using std::istream; 00024 using std::string; 00025 00026 static const unsigned int DEFAULT_BUFFER_SIZE = 2 * ByteBuffer::BYTES_IN_INT; 00027 00028 DaqFromIStream::DaqFromIStream() : 00029 m_istream(0), 00030 m_daqFromBytes(new DaqFormatFromBytes()) { 00031 } 00032 00033 DaqFromIStream::~DaqFromIStream() { 00034 delete m_daqFromBytes; 00035 if (0 != m_istream) { 00036 delete m_istream; 00037 } 00038 } 00039 00040 bool DaqFromIStream::close() { 00041 if (0 != m_istream) { 00042 closeStream(*m_istream); 00043 delete m_istream; 00044 m_istream = 0; 00045 } 00046 return true; 00047 } 00048 00049 bool DaqFromIStream::hasIStream() const { 00050 return 0 != m_istream; 00051 } 00052 00053 bool DaqFromIStream::open() { 00054 m_istream = openStream(); 00055 return hasIStream(); 00056 } 00057 00058 const FileBuffer* DaqFromIStream::nextRecord() { 00059 ByteBuffer* buffer = new ByteBuffer(new char[DEFAULT_BUFFER_SIZE], 00060 DEFAULT_BUFFER_SIZE); 00061 m_istream->read(buffer->cursor(), 00062 2 * ByteBuffer::BYTES_IN_INT); 00063 if (m_istream->eof()) { 00064 return 0; 00065 } 00066 00067 unsigned int size = buffer->readUnsignedInt(4); 00068 unsigned int lengthInBytes = size * ByteBuffer::BYTES_IN_INT; 00069 const FileBuffer* result = 0; 00070 unsigned int begin = 0; 00071 while (0 == result && buffer->capacity() != lengthInBytes) { 00072 if (lengthInBytes > buffer->capacity()) { 00073 ByteBuffer* previousBuffer = buffer; 00074 buffer = new ByteBuffer(new char[lengthInBytes], 00075 lengthInBytes); 00076 unsigned int bytesRead = previousBuffer->limit(); 00077 previousBuffer->position(begin); 00078 memcpy(buffer->cursor(), 00079 previousBuffer->cursor(), 00080 bytesRead); 00081 buffer->limit(bytesRead); 00082 previousBuffer->release(); 00083 } 00084 unsigned int bytesRead = buffer->limit(); 00085 m_istream->read(buffer->cursor() + bytesRead, 00086 buffer->capacity() - bytesRead); 00087 buffer->limit(buffer->capacity()); 00088 begin = buffer->position(); 00089 result = m_daqFromBytes->createFileBuffer(buffer); 00090 if (0 == result) { 00091 lengthInBytes = m_daqFromBytes->additionalCapacity() + buffer->capacity(); 00092 } 00093 } 00094 return result; 00095 }