hello-dns/tdns/safearray.hh
2018-04-09 20:49:37 +02:00

83 lines
1.6 KiB
C++

#pragma once
#include <string>
#include <cstdint>
#include <array>
#include <arpa/inet.h>
#include <string.h>
template<int N>
struct SafeArray
{
std::array<uint8_t, N> payload;
uint16_t payloadpos{0}, payloadsize{0};
void rewind()
{
payloadpos = 0;
}
uint8_t getUInt8()
{
return payload.at(payloadpos++);
}
uint16_t getUInt16()
{
uint16_t ret;
memcpy(&ret, &payload.at(payloadpos+2)-2, 2);
payloadpos+=2;
return htons(ret);
}
void putUInt8(uint8_t val)
{
payload.at(payloadpos++)=val;
}
uint16_t putUInt16(uint16_t val)
{
val = htons(val);
memcpy(&payload.at(payloadpos+2)-2, &val, 2);
payloadpos+=2;
return payloadpos - 2;
}
void putUInt16At(uint16_t pos, uint16_t val)
{
val = htons(val);
memcpy(&payload.at(pos+2)-2, &val, 2);
}
void putUInt32(uint32_t val)
{
val = htonl(val);
memcpy(&payload.at(payloadpos+sizeof(val)) - sizeof(val), &val, sizeof(val));
payloadpos += sizeof(val);
}
void putBlob(const std::string& blob)
{
memcpy(&payload.at(payloadpos+blob.size()) - blob.size(), blob.c_str(), blob.size());
payloadpos += blob.size();;
}
void putBlob(const unsigned char* blob, int size)
{
memcpy(&payload.at(payloadpos+size) - size, blob, size);
payloadpos += size;
}
std::string getBlob(int size)
{
std::string ret(&payload.at(payloadpos), &payload.at(payloadpos+size));
payloadpos += size;
return ret;
}
std::string serialize() const
{
return std::string((const char*)&payload.at(0), (const char*)&payload.at(payloadpos));
}
};