Bitstream Interpretation Library (BIL)  0.1
BinarySerialization.cpp
Go to the documentation of this file.
1 
6 #include <climits>
7 #include <boost/scoped_array.hpp>
10 
11 
12 void bil::writeBinary(const std::string& data, std::ostream& outputStream)
13 {
14  // string length is 255 chars max
15  size_t l = data.size();
16  if (l > UCHAR_MAX) l = UCHAR_MAX;
17  // write string length
18  unsigned char length = static_cast<unsigned char>(l);
19  outputStream.write(reinterpret_cast<const char*>(&length), sizeof(length));
20  if (!outputStream) throw IOException();
21  // write string data as one block
22  if (0 < length)
23  {
24  outputStream.write(data.c_str(), length);
25  if (!outputStream) throw IOException();
26  }
27 }
28 
29 
30 void bil::readBinary(std::string& data, std::istream& inputStream)
31 {
32  // read string length
33  unsigned char length;
34  inputStream.read(reinterpret_cast<char*>(&length), sizeof(length));
35  if (!inputStream) throw IOException();
36  if (0 < length)
37  {
38  // create buffer
39  boost::scoped_array<char> buffer(new char[length]);
40  char* bufferPtr = buffer.get();
41  // read data into buffer
42  inputStream.read(bufferPtr, length);
43  if (!inputStream) throw IOException();
44  // copy buffer into string
45  data.assign(bufferPtr, length);
46  }
47  else data.clear();
48 }