Debian Codegraph @

io/binarywriter.cpp

raw symbols SCIP
1 #include "./binarywriter.h"
2
3 #include "../conversion/conversionexception.h"
4
5 using namespace std;
6
7 namespace CppUtilities {
8
9 /*!
10 * \class BinaryWriter
11 * \brief Writes primitive data types to a std::ostream.
12 * \remarks Supports both, little endian and big endian.
13 * \sa For automatic deserialization of structs, see https://github.com/Martchus/reflective-rapidjson.
14 */
15
16 /*!
17 * \brief Assigns the stream the writer will write to when calling one of the write-methods.
18 *
19 * You can assign a null pointer when ensuring that none of the write-methods is called
20 * until a stream is assigned.
21 *
22 * \param stream Specifies the stream to be assigned.
23 * \param giveOwnership Specifies whether the writer should take ownership.
24 *
25 * \sa setStream()
26 */
27 void BinaryWriter::setStream(ostream *stream, bool giveOwnership)
28 {
29 if (m_ownership) {
30 delete m_stream;
31 }
32 if (stream) {
33 m_stream = stream;
34 m_ownership = giveOwnership;
35 } else {
36 m_stream = nullptr;
37 m_ownership = false;
38 }
39 }
40
41 /*!
42 * \brief Writes the specified integer \a value. Conversion to bytes is done using the specified function.
43 */
44 void BinaryWriter::writeVariableLengthInteger(std::uint64_t value, void (*getBytes)(std::uint64_t, char *))
45 {
46 std::uint64_t boundCheck = 0x80;
47 std::uint8_t prefixLength = 1;
48 for (; boundCheck != 0x8000000000000000; boundCheck <<= 7, ++prefixLength) {
49 if (value < boundCheck) {
50 getBytes(value | boundCheck, m_buffer);
51 break;
52 }
53 }
54 if (prefixLength == 9) {
55 throw ConversionException("The variable-length integer to be written exceeds the maximum.");
56 }
57 m_stream->write(m_buffer + 8 - prefixLength, prefixLength);
58 }
59
60 } // namespace CppUtilities