C++ Utilities 5.26.1
Useful C++ classes and routines such as argument parser, IO and conversion utilities
Loading...
Searching...
No Matches
binarywriter.cpp
Go to the documentation of this file.
1#include "./binarywriter.h"
2
4
5#include <cstring>
6#include <memory>
7
8using namespace std;
9
10namespace CppUtilities {
11
30void 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
47void 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
void giveOwnership()
The writer will take ownership over the assigned stream.
void setStream(std::ostream *stream, bool giveOwnership=false)
Assigns the stream the writer will write to when calling one of the write-methods.
const std::ostream * stream() const
Returns a pointer to the stream the writer will write to when calling one of the write-methods.
Contains all utilities provides by the c++utilities library.
STL namespace.