C++ Utilities  4.9.0
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 }
27 
33  : m_stream(other.m_stream)
34  , m_ownership(false)
35 {
36 }
37 
42 {
43  if (m_ownership) {
44  delete m_stream;
45  }
46 }
47 
60 {
61  if (m_ownership) {
62  delete m_stream;
63  }
64  if (stream) {
65  m_stream = stream;
66  m_ownership = giveOwnership;
67  } else {
68  m_stream = nullptr;
69  m_ownership = false;
70  }
71 }
72 
78 void BinaryWriter::writeLengthPrefixedString(const string &value)
79 {
80  size_t length = value.length();
81  if (length < 0x80) {
82  m_buffer[0] = 0x80 | length;
83  m_stream->write(m_buffer, 1);
84  } else if (length < 0x4000) {
85  BE::getBytes(static_cast<uint16>(0x4000 | length), m_buffer);
86  m_stream->write(m_buffer, 2);
87  } else if (length < 0x200000) {
88  BE::getBytes(static_cast<uint32>(0x200000 | length), m_buffer);
89  m_stream->write(m_buffer + 1, 3);
90  } else if (length < 0x10000000) {
91  BE::getBytes(static_cast<uint32>(0x10000000 | length), m_buffer);
92  m_stream->write(m_buffer, 4);
93  } else {
94  throw ConversionException("The size of the string exceeds the maximum.");
95  }
96  m_stream->write(value.c_str(), length);
97 }
BinaryWriter(std::ostream *stream)
Constructs a new BinaryWriter.
Writes primitive data types to a std::ostream.
Definition: binarywriter.h:13
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:116
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:92