hello-dns/tdns/safearray.hh

83 lines
1.6 KiB
C++
Raw Normal View History

2018-04-02 18:25:19 +07:00
#pragma once
#include <string>
#include <cstdint>
2018-04-09 21:43:24 +07:00
#include <array>
#include <arpa/inet.h>
#include <string.h>
2018-04-02 18:25:19 +07:00
template<int N>
struct SafeArray
{
std::array<uint8_t, N> payload;
uint16_t payloadpos{0}, payloadsize{0};
2018-04-03 23:03:59 +07:00
void rewind()
{
payloadpos = 0;
}
2018-04-02 18:25:19 +07:00
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;
}
2018-04-10 01:49:37 +07:00
uint16_t putUInt16(uint16_t val)
2018-04-02 18:25:19 +07:00
{
val = htons(val);
memcpy(&payload.at(payloadpos+2)-2, &val, 2);
payloadpos+=2;
2018-04-10 01:49:37 +07:00
return payloadpos - 2;
}
void putUInt16At(uint16_t pos, uint16_t val)
{
val = htons(val);
memcpy(&payload.at(pos+2)-2, &val, 2);
2018-04-02 18:25:19 +07:00
}
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();;
}
2018-04-09 22:46:31 +07:00
void putBlob(const unsigned char* blob, int size)
{
memcpy(&payload.at(payloadpos+size) - size, blob, size);
payloadpos += size;
}
2018-04-02 18:25:19 +07:00
std::string getBlob(int size)
{
std::string ret(&payload.at(payloadpos), &payload.at(payloadpos+size));
payloadpos += size;
return ret;
}
2018-04-03 18:18:37 +07:00
std::string serialize() const
{
return std::string((const char*)&payload.at(0), (const char*)&payload.at(payloadpos));
}
2018-04-02 18:25:19 +07:00
};