lokinet/include/llarp/aligned.hpp

143 lines
2.2 KiB
C++
Raw Normal View History

2018-06-01 14:08:54 +00:00
#ifndef LLARP_ALIGNED_HPP
#define LLARP_ALIGNED_HPP
#include <llarp/bencode.h>
2018-06-01 14:08:54 +00:00
#include <llarp/crypto.h>
#include <sodium.h>
2018-06-01 14:24:58 +00:00
#include <iomanip>
2018-06-01 14:08:54 +00:00
#include <iostream>
#include <llarp/logger.hpp>
2018-06-01 14:08:54 +00:00
namespace llarp
{
/// aligned buffer, sz must be multiple of 8 bytes
template < size_t sz >
struct AlignedBuffer
{
2018-06-04 17:22:24 +00:00
AlignedBuffer() = default;
2018-06-01 14:08:54 +00:00
AlignedBuffer(const byte_t* data)
2018-06-01 14:08:54 +00:00
{
for(size_t idx = 0; idx < sz; ++idx)
2018-06-06 12:46:26 +00:00
b[idx] = data[idx];
2018-06-01 14:08:54 +00:00
}
AlignedBuffer&
operator=(const byte_t* data)
2018-06-01 14:08:54 +00:00
{
for(size_t idx = 0; idx < sz; ++idx)
2018-06-06 12:46:26 +00:00
b[idx] = data[idx];
2018-06-01 14:08:54 +00:00
return *this;
}
friend std::ostream&
operator<<(std::ostream& out, const AlignedBuffer& self)
2018-06-01 14:08:54 +00:00
{
2018-06-01 14:24:58 +00:00
size_t idx = 0;
out << std::hex << std::setw(2) << std::setfill('0');
2018-06-01 14:08:54 +00:00
while(idx < sz)
{
2018-06-06 12:46:26 +00:00
out << (int)self.b[idx++];
2018-06-01 14:08:54 +00:00
}
return out << std::dec << std::setw(0) << std::setfill(' ');
2018-06-01 14:08:54 +00:00
}
bool
operator==(const AlignedBuffer& other) const
{
return memcmp(data(), other.data(), sz) == 0;
}
bool
operator!=(const AlignedBuffer& other) const
{
return !(*this == other);
}
size_t
size() const
{
return sz;
}
size_t
size()
{
return sz;
}
2018-06-01 14:08:54 +00:00
void
Zero()
{
for(size_t idx = 0; sz < idx / 8; ++idx)
2018-06-06 12:46:26 +00:00
l[idx] = 0;
2018-06-01 14:08:54 +00:00
}
void
Randomize()
{
2018-06-12 16:45:12 +00:00
randombytes(b, sz);
2018-06-01 14:08:54 +00:00
}
byte_t*
data()
{
2018-06-06 12:46:26 +00:00
return &b[0];
2018-06-01 14:08:54 +00:00
}
const byte_t*
data() const
{
2018-06-06 12:46:26 +00:00
return &b[0];
}
uint64_t*
data_l()
{
2018-06-06 12:46:26 +00:00
return &l[0];
2018-06-01 14:08:54 +00:00
}
const uint64_t*
data_l() const
{
2018-06-06 12:46:26 +00:00
return &l[0];
2018-06-01 14:08:54 +00:00
}
operator const byte_t*() const
2018-06-01 14:08:54 +00:00
{
2018-06-06 12:46:26 +00:00
return &b[0];
2018-06-01 14:08:54 +00:00
}
operator byte_t*()
2018-06-01 14:08:54 +00:00
{
2018-06-06 12:46:26 +00:00
return &b[0];
2018-06-01 14:08:54 +00:00
}
bool
BEncode(llarp_buffer_t* buf) const
{
return bencode_write_bytestring(buf, b, sz);
}
bool
BDecode(llarp_buffer_t* buf)
{
llarp_buffer_t strbuf;
if(!bencode_read_string(buf, &strbuf))
return false;
if(strbuf.sz != sz)
return false;
memcpy(b, strbuf.base, sz);
return true;
}
2018-06-01 14:08:54 +00:00
private:
union {
byte_t b[sz];
uint64_t l[sz / 8];
2018-06-06 12:46:26 +00:00
};
2018-06-01 14:08:54 +00:00
};
}
#endif