C++ Utilities  4.14.1
Useful C++ classes and routines 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 
59 void BinaryWriter::setStream(ostream *stream, bool giveOwnership)
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  const uint64 size = value.size();
81  uint64 boundCheck = 0x80;
82  byte prefixLength = 1;
83  for (; boundCheck != 0x8000000000000000; boundCheck <<= 7, ++prefixLength) {
84  if (size < boundCheck) {
85  BE::getBytes(size | boundCheck, m_buffer);
86  break;
87  }
88  }
89  if (prefixLength == 9) {
90  throw ConversionException("The size of the string exceeds the maximum.");
91  }
92  m_stream->write(m_buffer + 8 - prefixLength, prefixLength);
93  m_stream->write(value.data(), static_cast<streamsize>(size));
94 }
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.
std::uint64_t uint64
unsigned 64-bit integer
Definition: types.h:49
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
std::uint8_t byte
unsigned byte
Definition: types.h:14