C++ Utilities  5.10.5
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 
10 namespace CppUtilities {
11 
30 void BinaryWriter::setStream(ostream *stream, bool giveOwnership)
31 {
32  if (m_ownership) {
33  delete m_stream;
34  }
35  if (stream) {
36  m_stream = stream;
37  m_ownership = giveOwnership;
38  } else {
39  m_stream = nullptr;
40  m_ownership = false;
41  }
42 }
43 
47 void BinaryWriter::writeVariableLengthInteger(std::uint64_t value, void (*getBytes)(std::uint64_t, char *))
48 {
49  std::uint64_t boundCheck = 0x80;
50  std::uint8_t prefixLength = 1;
51  for (; boundCheck != 0x8000000000000000; boundCheck <<= 7, ++prefixLength) {
52  if (value < boundCheck) {
53  getBytes(value | boundCheck, m_buffer);
54  break;
55  }
56  }
57  if (prefixLength == 9) {
58  throw ConversionException("The variable-length integer to be written exceeds the maximum.");
59  }
60  m_stream->write(m_buffer + 8 - prefixLength, prefixLength);
61 }
62 
63 } // namespace CppUtilities
Contains all utilities provides by the c++utilities library.