cnorxz/src/include/allocator.h

84 lines
1.6 KiB
C
Raw Normal View History

2019-02-13 21:59:13 +01:00
#ifndef __ma_allocator__
#define __ma_allocator__
#include <cstdlib>
#include <new>
#include <vector>
#include <cstdint>
#include <cassert>
#include <iostream>
namespace MultiArrayHelper
{
template <typename T>
struct Allocator
{
typedef T value_type;
static constexpr size_t type_size = sizeof(value_type);
static constexpr size_t N = 32;
2019-03-18 11:33:33 +01:00
struct VX
{
alignas(N) char x[N];
};
2019-02-13 21:59:13 +01:00
Allocator() = default;
template <typename U>
Allocator(const Allocator<U>& x) {}
T* allocate(size_t n)
{
const size_t nn = n*type_size;
2019-03-18 11:33:33 +01:00
const size_t off = nn%N;
const size_t nnx = (off == 0) ? nn : nn + N - off;
2019-03-18 13:11:07 +01:00
const size_t nnd = nnx/N;
2019-03-18 11:33:33 +01:00
VX* vx = new VX[nnd];
return reinterpret_cast<T*>(vx);
2019-02-13 21:59:13 +01:00
}
void deallocate(T* p, size_t n)
{
2019-03-18 11:33:33 +01:00
VX* vx = reinterpret_cast<VX*>(p);
delete [] vx;
2019-02-13 21:59:13 +01:00
}
};
template <class T, class U>
bool operator==(const Allocator<T>& a, const Allocator<U>& b)
{
return true;
}
template <class T, class U>
bool operator!=(const Allocator<T>& a, const Allocator<U>& b)
{
return false;
}
} // namespace MultiArrayHelper
namespace MultiArrayTools
{
template <typename T>
using vector = std::vector<T,MultiArrayHelper::Allocator<T>>;
template <typename T>
inline std::vector<T> toStdVec(const vector<T>& v)
{
return std::vector<T>(v.begin(), v.end());
}
template <typename T>
inline vector<T> toMatVec(const std::vector<T>& v)
{
return vector<T>(v.begin(), v.end());
}
2019-02-13 21:59:13 +01:00
} // namespace MultiArrayTools
#endif