lokinet/include/llarp/aligned.hpp

123 lines
1.9 KiB
C++
Raw Normal View History

2018-06-01 14:08:54 +00:00
#ifndef LLARP_ALIGNED_HPP
#define LLARP_ALIGNED_HPP
#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)
buf.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)
buf.b[idx] = data[idx];
2018-06-01 14:08:54 +00:00
return *this;
}
byte_t& operator[](size_t idx)
{
return buf.b[idx];
}
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)
{
out << (int)self.buf.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;
}
void
Zero()
{
for(size_t idx = 0; sz < idx / 8; ++idx)
buf.l[idx] = 0;
}
void
Randomize()
{
randombytes(buf.b, sz);
}
byte_t*
data()
{
return &buf.b[0];
2018-06-01 14:08:54 +00:00
}
const byte_t*
data() const
{
return &buf.b[0];
}
uint64_t*
data_l()
{
return &buf.l[0];
2018-06-01 14:08:54 +00:00
}
const uint64_t*
data_l() const
{
return &buf.l[0];
2018-06-01 14:08:54 +00:00
}
operator const byte_t*() const
2018-06-01 14:08:54 +00:00
{
return &buf.b[0];
2018-06-01 14:08:54 +00:00
}
operator byte_t*()
2018-06-01 14:08:54 +00:00
{
return &buf.b[0];
2018-06-01 14:08:54 +00:00
}
private:
union {
byte_t b[sz];
uint64_t l[sz / 8];
} buf;
2018-06-01 14:08:54 +00:00
};
}
#endif