2016-08-29 15:35:48 +02:00
|
|
|
#include "./binarywriter.h"
|
|
|
|
|
|
|
|
#include "../conversion/conversionexception.h"
|
|
|
|
|
|
|
|
#include <cstring>
|
|
|
|
#include <memory>
|
|
|
|
|
|
|
|
using namespace std;
|
2019-06-10 21:56:46 +02:00
|
|
|
|
|
|
|
namespace CppUtilities {
|
2016-08-29 15:35:48 +02:00
|
|
|
|
|
|
|
/*!
|
2019-06-10 21:56:46 +02:00
|
|
|
* \class BinaryWriter
|
2016-08-29 15:35:48 +02:00
|
|
|
* \brief Writes primitive data types to a std::ostream.
|
|
|
|
* \remarks Supports both, little endian and big endian.
|
2018-05-31 23:26:38 +02:00
|
|
|
* \sa For automatic deserialization of structs, see https://github.com/Martchus/reflective-rapidjson.
|
2016-08-29 15:35:48 +02:00
|
|
|
*/
|
|
|
|
|
|
|
|
/*!
|
|
|
|
* \brief Assigns the stream the writer will write to when calling one of the write-methods.
|
|
|
|
*
|
|
|
|
* You can assign a null pointer when ensuring that none of the write-methods is called
|
|
|
|
* until a stream is assigned.
|
|
|
|
*
|
|
|
|
* \param stream Specifies the stream to be assigned.
|
2019-06-04 19:27:49 +02:00
|
|
|
* \param giveOwnership Specifies whether the writer should take ownership.
|
2016-08-29 15:35:48 +02:00
|
|
|
*
|
|
|
|
* \sa setStream()
|
|
|
|
*/
|
|
|
|
void BinaryWriter::setStream(ostream *stream, bool giveOwnership)
|
|
|
|
{
|
2017-05-01 03:13:11 +02:00
|
|
|
if (m_ownership) {
|
2016-08-29 15:35:48 +02:00
|
|
|
delete m_stream;
|
|
|
|
}
|
2017-05-01 03:13:11 +02:00
|
|
|
if (stream) {
|
2016-08-29 15:35:48 +02:00
|
|
|
m_stream = stream;
|
|
|
|
m_ownership = giveOwnership;
|
|
|
|
} else {
|
|
|
|
m_stream = nullptr;
|
|
|
|
m_ownership = false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/*!
|
2018-05-31 23:26:38 +02:00
|
|
|
* \brief Writes the specified integer \a value. Conversion to bytes is done using the specified function.
|
2016-08-29 15:35:48 +02:00
|
|
|
*/
|
2019-03-13 19:00:37 +01:00
|
|
|
void BinaryWriter::writeVariableLengthInteger(std::uint64_t value, void (*getBytes)(std::uint64_t, char *))
|
2016-08-29 15:35:48 +02:00
|
|
|
{
|
2019-03-13 19:00:37 +01:00
|
|
|
std::uint64_t boundCheck = 0x80;
|
|
|
|
std::uint8_t prefixLength = 1;
|
2017-07-28 20:34:50 +02:00
|
|
|
for (; boundCheck != 0x8000000000000000; boundCheck <<= 7, ++prefixLength) {
|
2018-05-31 23:26:38 +02:00
|
|
|
if (value < boundCheck) {
|
|
|
|
getBytes(value | boundCheck, m_buffer);
|
2017-07-28 20:34:50 +02:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (prefixLength == 9) {
|
2018-05-31 23:26:38 +02:00
|
|
|
throw ConversionException("The variable-length integer to be written exceeds the maximum.");
|
2016-08-29 15:35:48 +02:00
|
|
|
}
|
2017-07-28 20:34:50 +02:00
|
|
|
m_stream->write(m_buffer + 8 - prefixLength, prefixLength);
|
2018-05-31 23:26:38 +02:00
|
|
|
}
|
2019-06-10 21:56:46 +02:00
|
|
|
|
|
|
|
} // namespace CppUtilities
|