Merge pull request #945 from aaron0x/RefactoryBinaryReaderWriter

Refactory BinaryReader and BinaryWriter
This commit is contained in:
Aleksandar Fabijanic
2016-03-13 23:08:44 -07:00
6 changed files with 190 additions and 258 deletions

View File

@@ -23,6 +23,7 @@
#include "Poco/Foundation.h"
#include "Poco/Buffer.h"
#include "Poco/MemoryStream.h"
#include "Poco/ByteOrder.h"
#include <vector>
#include <istream>
@@ -151,6 +152,32 @@ public:
/// Returns the number of available bytes in the stream.
private:
template<typename T>
BinaryReader& read(T& value, bool flipBytes)
{
_istr.read((char*) &value, sizeof(value));
if (flipBytes) value = ByteOrder::flipBytes(value);
return *this;
}
template<typename T>
void read7BitEncoded(T& value)
{
char c;
value = 0;
int s = 0;
do
{
c = 0;
_istr.read(&c, 1);
T x = (c & 0x7F);
x <<= s;
value += x;
s += 7;
}
while (c & 0x80);
}
std::istream& _istr;
bool _flipBytes;
TextConverter* _pTextConverter;

View File

@@ -23,6 +23,7 @@
#include "Poco/Foundation.h"
#include "Poco/Buffer.h"
#include "Poco/MemoryStream.h"
#include "Poco/ByteOrder.h"
#include <vector>
#include <ostream>
@@ -160,6 +161,36 @@ public:
/// either BIG_ENDIAN_BYTE_ORDER or LITTLE_ENDIAN_BYTE_ORDER.
private:
template<typename T>
BinaryWriter& write(T value, bool flipBytes)
{
if (flipBytes)
{
T fValue = ByteOrder::flipBytes(value);
_ostr.write((const char*) &fValue, sizeof(fValue));
}
else
{
_ostr.write((const char*) &value, sizeof(value));
}
return *this;
}
template<typename T>
void write7BitEncoded(T value)
{
do
{
unsigned char c = (unsigned char) (value & 0x7F);
value >>= 7;
if (value) c |= 0x80;
_ostr.write((const char*) &c, 1);
}
while (value);
}
BinaryWriter& write(const char* value, std::size_t length);
std::ostream& _ostr;
bool _flipBytes;
TextConverter* _pTextConverter;

View File

@@ -24,7 +24,6 @@
#include <stdlib.h> // builtins
#endif
namespace Poco {
@@ -38,6 +37,8 @@ public:
static UInt16 flipBytes(UInt16 value);
static Int32 flipBytes(Int32 value);
static UInt32 flipBytes(UInt32 value);
static float flipBytes(float value);
static double flipBytes(double value);
#if defined(POCO_HAVE_INT64)
static Int64 flipBytes(Int64 value);
static UInt64 flipBytes(UInt64 value);
@@ -96,6 +97,21 @@ public:
static Int64 fromNetwork(Int64 value);
static UInt64 fromNetwork (UInt64 value);
#endif
private:
template<typename T>
static T flip(T value)
{
T flip = value;
std::size_t halfSize = sizeof(T) / 2;
char* flipP = reinterpret_cast<char*>(&flip);
for (std::size_t i = 0; i < halfSize; i++)
{
std::swap(flipP[i], flipP[sizeof(T) - i - 1]);
}
return flip;
}
};
@@ -152,6 +168,18 @@ inline Int32 ByteOrder::flipBytes(Int32 value)
}
inline float ByteOrder::flipBytes(float value)
{
return flip(value);
}
inline double ByteOrder::flipBytes(double value)
{
return flip(value);
}
#if defined(POCO_HAVE_INT64)
inline UInt64 ByteOrder::flipBytes(UInt64 value)
{