//#define FSE 1
#include <iostream>
#include <fstream>
#include <vector>
#include <numeric>
#include <algorithm>
#ifdef FSE
#include "fse.h"
#endif
using namespace std;
enum {
kUncomprSize = 250000,
kUncomprBytes = kUncomprSize * sizeof(uint32_t),
};
using Buffer = vector<uint32_t>;
unsigned int_log(uint32_t x)
{
return 32 - __builtin_clz(x);
}
template<unsigned L>
unsigned elias(const Buffer& deltas)
{
unsigned compr_size = 0;
unsigned top = int_log(*max_element(begin(deltas), end(deltas)));
unsigned bottom = top + 1 - (1 << L);
for (auto x: deltas)
{
auto il = max(int_log(x), bottom);
compr_size += L;
compr_size += il - 1;
}
return compr_size / 8;
}
template<unsigned LSB>
unsigned golomb(const Buffer& deltas)
{
unsigned compr_size = 0;
for (auto x: deltas)
{
auto il = int_log(x);
compr_size += LSB;
compr_size += (il > LSB)? 2 * (il - LSB) - 1: 1;
}
return compr_size / 8;
}
#ifdef FSE
template<unsigned MSB>
unsigned fse(const Buffer& deltas)
{
vector<char> compressible(deltas.size());
transform(begin(deltas), end(deltas), begin(compressible), [](uint32_t x)
{
auto il = int_log(x);
auto res = x << (32 - il);
res >>= 32 - MSB;
res += il << MSB;
return static_cast<char>(res);
});
vector<char> compressed(2 * deltas.size());
auto compr_res = FSE_compress(
compressed.data(), compressed.size(),
compressible.data(), compressible.size()
);
if (FSE_isError(compr_res))
{
std::cout << "FSE error: " << FSE_getErrorName(compr_res) << "\n";
}
unsigned compr_size = 8 * static_cast<unsigned>(compr_res);
for (auto x: deltas)
{
auto il = int_log(x);
compr_size += (il > MSB)? il - MSB - 1: 0;
}
return compr_size / 8;
}
#endif
int main() {
Buffer uncompr(kUncomprSize);
Buffer deltas(kUncomprSize);
ifstream in("/dev/random", ios_base::in | ios_base::binary);
in.read(reinterpret_cast<char*>(uncompr.data()), kUncomprBytes);
sort(begin(uncompr), end(uncompr));
adjacent_difference(begin(uncompr), end(uncompr), begin(deltas));
std::cout << "Elias4: " << elias<4>(deltas) << '\n';
std::cout << "Elias3: " << elias<3>(deltas) << '\n';
std::cout << "Elias2: " << elias<2>(deltas) << '\n';
std::cout << "Golomb12: " << golomb<12>(deltas) << '\n';
std::cout << "Golomb13: " << golomb<13>(deltas) << '\n';
std::cout << "Golomb14: " << golomb<14>(deltas) << '\n';
std::cout << "Golomb15: " << golomb<15>(deltas) << '\n';
#ifdef FSE
std::cout << "FSE1: " << fse<1>(deltas) << '\n';
std::cout << "FSE2: " << fse<2>(deltas) << '\n';
std::cout << "FSE3: " << fse<3>(deltas) << '\n';
#endif
}