#include "compression.hpp" #include #include #include #include #include #include namespace Misc { std::vector compress(const std::vector& data) { const std::size_t originalSize = data.size(); std::vector result( static_cast(LZ4_compressBound(static_cast(originalSize)) + sizeof(originalSize))); const int size = LZ4_compress_default(reinterpret_cast(data.data()), reinterpret_cast(result.data()) + sizeof(originalSize), static_cast(data.size()), static_cast(result.size() - sizeof(originalSize))); if (size == 0) throw std::runtime_error("Failed to compress"); std::memcpy(result.data(), &originalSize, sizeof(originalSize)); result.resize(static_cast(size) + sizeof(originalSize)); return result; } std::vector decompress(const std::vector& data) { std::size_t originalSize; std::memcpy(&originalSize, data.data(), sizeof(originalSize)); std::vector result(originalSize); const int size = LZ4_decompress_safe(reinterpret_cast(data.data()) + sizeof(originalSize), reinterpret_cast(result.data()), static_cast(data.size() - sizeof(originalSize)), static_cast(result.size())); if (size < 0) throw std::runtime_error("Failed to decompress"); if (originalSize != static_cast(size)) throw std::runtime_error("Size of decompressed data (" + std::to_string(size) + ") doesn't match stored (" + std::to_string(originalSize) + ")"); return result; } }