Bitstream Interpretation Library (BIL)  0.1
BitFileWriter.cpp
Go to the documentation of this file.
1 
11 
12 using namespace bil;
13 
14 
15 static void writeStringSection(const std::string& s, std::ostream& outputStream)
16 {
17  // get string length (only up to first zero char) including trailing zero
18  size_t slen = strlen(s.c_str()) + 1;
19  // test if that fits in two bytes and convert it
20  if (0xffff < slen) throw Exception();
21  boost::uint16_t len = swapBigEndian(static_cast<boost::uint16_t>(slen));
22  // write two bytes length
23  if (!outputStream.write(reinterpret_cast<char*>(&len), sizeof(len)))
24  throw IOException();
25  // write string data including trailing zero
26  if (!outputStream.write(s.c_str(), slen)) throw IOException();
27 }
28 
29 
30 static void writeDataSection(const boost::uint32_t* words, size_t wordCount, std::ostream& outputStream)
31 {
32  // convert word count to four byte byte count
33  boost::uint32_t w = swapBigEndian(static_cast<boost::uint32_t>(wordCount << 2));
34  // write it
35  if (!outputStream.write(reinterpret_cast<char*>(&w), sizeof(w)))
36  throw IOException();
37  // write swapped data words
38  for (size_t i = 0; i < wordCount; ++i)
39  {
40  w = swapBigEndian(*words++);
41  if (!outputStream.write(reinterpret_cast<const char*>(&w), sizeof(w)))
42  throw IOException();
43  }
44 }
45 
46 
47 void bil::writeBitfile(const BitFileData& bitFileData, std::ostream& outputStream)
48 {
49  // write file header
50  if (!outputStream.write(reinterpret_cast<const char*>(BITFILE_HEADER), sizeof(BITFILE_HEADER)))
51  throw IOException();
52 
53  // write source filename section
54  if (!outputStream.write(reinterpret_cast<const char*>(&BITFILE_KEY_SOURCEFILENAME), 1))
55  throw IOException();
56  writeStringSection(bitFileData.sourceFileName(), outputStream);
57  // write target device name section
58  if (!outputStream.write(reinterpret_cast<const char*>(&BITFILE_KEY_TARGETDEVICENAME), 1))
59  throw IOException();
60  writeStringSection(bitFileData.targetDeviceName(), outputStream);
61  // write creation date section
62  if (!outputStream.write(reinterpret_cast<const char*>(&BITFILE_KEY_CREATIONDATE), 1))
63  throw IOException();
64  writeStringSection(bitFileData.creationDate(), outputStream);
65  // write creation time section
66  if (!outputStream.write(reinterpret_cast<const char*>(&BITFILE_KEY_CREATIONTIME), 1))
67  throw IOException();
68  writeStringSection(bitFileData.creationTime(), outputStream);
69 
70  // write raw bitstream
71  if (!outputStream.write(reinterpret_cast<const char*>(&BITFILE_KEY_BITSTREAM), 1))
72  throw IOException();
73  writeDataSection(bitFileData.bitstreamWords(), bitFileData.bitstreamWordCount(), outputStream);
74 }