114 lines
2.4 KiB
C++
114 lines
2.4 KiB
C++
#include "DataReader.h"
|
|
#include <arpa/inet.h>
|
|
|
|
|
|
namespace Network {
|
|
namespace Dns {
|
|
|
|
DataReader::DataReader(const uint8_t* data, unsigned length) :
|
|
m_data(data),
|
|
m_length(length)
|
|
{
|
|
}
|
|
|
|
DataReader::DataReader(const std::vector<uint8_t>& data) :
|
|
DataReader(data.data(), data.size())
|
|
{
|
|
}
|
|
|
|
const uint8_t* DataReader::GetPtr() const
|
|
{
|
|
return m_data;
|
|
}
|
|
|
|
unsigned DataReader::GetLength() const
|
|
{
|
|
return m_length;
|
|
}
|
|
|
|
uint8_t DataReader::operator[](unsigned index) const
|
|
{
|
|
if (index >= m_length)
|
|
throw DataReaderOutOfBounds();
|
|
return m_data[index];
|
|
}
|
|
|
|
DataReader& DataReader::operator+=(unsigned index)
|
|
{
|
|
if (index > m_length)
|
|
throw DataReaderOutOfBounds();
|
|
m_data += index;
|
|
m_length -= index;
|
|
return *this;
|
|
}
|
|
|
|
const DataReader DataReader::operator+(unsigned index) const
|
|
{
|
|
DataReader reader(*this);
|
|
return reader += index;
|
|
}
|
|
|
|
uint8_t DataReader::Read8(unsigned& pos) const
|
|
{
|
|
uint8_t value =
|
|
(static_cast<uint8_t>((*this)[pos + 0]) << 0);
|
|
pos++;
|
|
return value;
|
|
}
|
|
|
|
uint16_t DataReader::Read16(unsigned& pos) const
|
|
{
|
|
uint16_t value =
|
|
(static_cast<uint16_t>((*this)[pos + 0]) << 8) |
|
|
(static_cast<uint16_t>((*this)[pos + 1]) << 0);
|
|
pos += 2;
|
|
return value;
|
|
}
|
|
|
|
uint32_t DataReader::Read32(unsigned& pos) const
|
|
{
|
|
uint32_t value =
|
|
(static_cast<uint32_t>((*this)[pos + 0]) << 24) |
|
|
(static_cast<uint32_t>((*this)[pos + 1]) << 16) |
|
|
(static_cast<uint32_t>((*this)[pos + 2]) << 8) |
|
|
(static_cast<uint32_t>((*this)[pos + 3]) << 0);
|
|
pos += 4;
|
|
return value;
|
|
}
|
|
|
|
uint64_t DataReader::Read64(unsigned& pos) const
|
|
{
|
|
uint64_t value =
|
|
(static_cast<uint64_t>((*this)[pos + 0]) << 56) |
|
|
(static_cast<uint64_t>((*this)[pos + 1]) << 48) |
|
|
(static_cast<uint64_t>((*this)[pos + 2]) << 40) |
|
|
(static_cast<uint64_t>((*this)[pos + 3]) << 32) |
|
|
(static_cast<uint64_t>((*this)[pos + 4]) << 24) |
|
|
(static_cast<uint64_t>((*this)[pos + 5]) << 16) |
|
|
(static_cast<uint64_t>((*this)[pos + 6]) << 8) |
|
|
(static_cast<uint64_t>((*this)[pos + 7]) << 0);
|
|
pos += 8;
|
|
return value;
|
|
}
|
|
|
|
std::ostream& operator<<(std::ostream& stream, const DataReader& reader)
|
|
{
|
|
stream << "DataReader[" << reader.m_length << "] = {";
|
|
for (unsigned i = 0; i < reader.m_length; ++i)
|
|
{
|
|
if (i)
|
|
stream << ", ";
|
|
for(int j = 7; j >= 0; j--)
|
|
if (reader.m_data[i] & (1 << j))
|
|
stream << "1";
|
|
else
|
|
stream << "0";
|
|
stream << " " << static_cast<int>(reader.m_data[i]);
|
|
}
|
|
stream << "}";
|
|
return stream;
|
|
}
|
|
|
|
} // namespace Dns
|
|
} // namespace Network
|