Bitstream Interpretation Library (BIL)  0.1
BitFileReader.cpp
Go to the documentation of this file.
1 
6 #include <boost/scoped_array.hpp>
12 
13 using namespace bil;
14 
15 
16 static void readStringSection(std::string& s, std::istream& inputStream)
17 {
18  // read two byte string length
19  boost::uint16_t len;
20  if (!inputStream.read(reinterpret_cast<char*>(&len), sizeof(len)))
21  throw IOException();
22  // swap bytes
23  size_t length = swapBigEndian(len);
24  // set up temporary char buffer and read into it
25  boost::scoped_array<char> buffer(new char[length]);
26  char* bufPtr = buffer.get();
27  if (!inputStream.read(bufPtr, length)) throw IOException();
28  // test if string has got content
29  if (1 < length)
30  {
31  // null terminate buffer and copy it to string
32  bufPtr[length-1] = 0;
33  s.assign(bufPtr);
34  }
35  else s.clear();
36 }
37 
38 
39 static void readDataSection(BitFileData& bitFileData, std::istream& inputStream)
40 {
41  // read four byte byte count
42  boost::uint32_t len;
43  if (!inputStream.read(reinterpret_cast<char*>(&len), sizeof(len)))
44  throw IOException();
45  // swap bytes
46  size_t length = swapBigEndian(len);
47  // convert byte count to word count
48  if ((length & 0x3) != 0) throw Exception();
49  size_t wordCount = length >> 2;
50  // read data
51  bitFileData.bitstreamWordCount(wordCount);
52  boost::uint32_t* dataPtr = bitFileData.bitstreamWords();
53  if (!inputStream.read(reinterpret_cast<char*>(dataPtr), length))
54  throw IOException();
55  // correct endianess
56  for (size_t i = 0; i < wordCount; ++i)
57  {
58  *dataPtr = swapBigEndian(*dataPtr);
59  dataPtr++;
60  }
61 }
62 
63 
64 void bil::readBitfile(BitFileData& bitFileData, std::istream& inputStream)
65 {
66  // read and check header
67  boost::uint8_t header[sizeof(BITFILE_HEADER)];
68  if (!inputStream.read(reinterpret_cast<char*>(header), sizeof(BITFILE_HEADER)))
69  throw IOException();
70  // check contents
71  if (0 != memcmp(header, BITFILE_HEADER, sizeof(BITFILE_HEADER)))
72  throw Exception();
73 
74  // read sections
75  boost::uint8_t sectionKey;
76  while (inputStream.read(reinterpret_cast<char*>(&sectionKey), 1))
77  {
78  // read section designated by section key
79  switch(sectionKey)
80  {
82  readStringSection(bitFileData.sourceFileName(), inputStream);
83  break;
84 
86  readStringSection(bitFileData.targetDeviceName(), inputStream);
87  break;
88 
90  readStringSection(bitFileData.creationDate(), inputStream);
91  break;
92 
94  readStringSection(bitFileData.creationTime(), inputStream);
95  break;
96 
98  readDataSection(bitFileData, inputStream);
99  break;
100 
101  default: throw Exception();
102  }
103  }
104 
105  // check if eof reached
106  if (!inputStream.eof()) throw IOException();
107 }