C++ Utilities  4.6.1
Common C++ classes and routines used by my applications such as argument parser, IO and conversion utilities
binarywriter.cpp
Go to the documentation of this file.
1 #include "./binarywriter.h"
2 
3 #include "../conversion/conversionexception.h"
4 
5 #include <cstring>
6 #include <memory>
7 
8 using namespace std;
9 using namespace IoUtilities;
10 using namespace ConversionUtilities;
11 
22 BinaryWriter::BinaryWriter(ostream *stream) :
23  m_stream(stream),
24  m_ownership(false)
25 {}
26 
32  m_stream(other.m_stream),
33  m_ownership(false)
34 {}
35 
40 {
41  if(m_ownership) {
42  delete m_stream;
43  }
44 }
45 
58 {
59  if(m_ownership) {
60  delete m_stream;
61  }
62  if(stream) {
63  m_stream = stream;
64  m_ownership = giveOwnership;
65  } else {
66  m_stream = nullptr;
67  m_ownership = false;
68  }
69 }
70 
76 void BinaryWriter::writeLengthPrefixedString(const string &value)
77 {
78  size_t length = value.length();
79  if(length < 0x80) {
80  m_buffer[0] = 0x80 | length;
81  m_stream->write(m_buffer, 1);
82  } else if(length < 0x4000) {
83  BE::getBytes(static_cast<uint16>(0x4000 | length), m_buffer);
84  m_stream->write(m_buffer, 2);
85  } else if(length < 0x200000) {
86  BE::getBytes(static_cast<uint32>(0x200000 | length), m_buffer);
87  m_stream->write(m_buffer + 1, 3);
88  } else if(length < 0x10000000) {
89  BE::getBytes(static_cast<uint32>(0x10000000 | length), m_buffer);
90  m_stream->write(m_buffer, 4);
91  } else {
92  throw ConversionException("The size of the string exceeds the maximum.");
93  }
94  m_stream->write(value.c_str(), length);
95 }
BinaryWriter(std::ostream *stream)
Constructs a new BinaryWriter.
Writes primitive data types to a std::ostream.
Definition: binarywriter.h:14
The ConversionException class is thrown by the various conversion functions of this library when a co...
STL namespace.
void giveOwnership()
The writer will take ownership over the assigned stream.
Definition: binarywriter.h:118
void writeLengthPrefixedString(const std::string &value)
Writes the length of a string and the string itself to the current stream.
Contains utility classes helping to read and write streams.
Definition: binaryreader.h:10
void setStream(std::ostream *stream, bool giveOwnership=false)
Assigns the stream the writer will write to when calling one of the write-methods.
Contains several functions providing conversions between different data types.
~BinaryWriter()
Destroys the BinaryWriter.
const std::ostream * stream() const
Returns a pointer to the stream the writer will write to when calling one of the write-methods.
Definition: binarywriter.h:94