From 6d779d8606daf97f44dc13a89a78d1389d03f96b Mon Sep 17 00:00:00 2001 From: Phuntsok Drak-pa Date: Sat, 9 Jun 2018 03:18:28 +0200 Subject: [PATCH] Changed file writing method to dynamic bit-packing --- src/bitpack.cc | 2 +- src/bitpack.hh | 3 +++ src/io.cc | 22 ++++++---------------- 3 files changed, 10 insertions(+), 17 deletions(-) diff --git a/src/bitpack.cc b/src/bitpack.cc index e8934f6..cad6111 100644 --- a/src/bitpack.cc +++ b/src/bitpack.cc @@ -40,7 +40,7 @@ vuchar pack_n(const vuint16::const_iterator t_input_begin, vuchar ret{}; // max value with current number of bits + 1 - const int max_value = ipow(2, t_n); + const int max_value = ipow(2, t_n) - 1; uchar current_char = 0; int step = t_n / 8; diff --git a/src/bitpack.hh b/src/bitpack.hh index f47bf7d..c061bc7 100644 --- a/src/bitpack.hh +++ b/src/bitpack.hh @@ -19,4 +19,7 @@ std::vector pack_16(const std::vector::const_iterator, const std::vector::const_iterator); +/// \brief Bat-packs the input dynamically +std::vector pack(const std::vector); + #endif /* LZW_SRC_BITPACK_H_ */ diff --git a/src/io.cc b/src/io.cc index dce2531..0b3ec0e 100644 --- a/src/io.cc +++ b/src/io.cc @@ -4,7 +4,9 @@ */ #include "io.hh" +#include "bitpack.hh" #include +#include #ifdef Debug constexpr bool debug_mode = true; @@ -71,21 +73,9 @@ void write_file(FILE *const t_out, const vvuint16 &t_text) { * \param t_chunk Chunk to be written to \p t_out */ void write_chunk(FILE *const t_out, const vuint16 &t_chunk) { - const auto chunk_size = static_cast(t_chunk.size()); + const auto output = pack(t_chunk); + const auto chunk_size = static_cast(output.size()); fwrite(&chunk_size, sizeof(chunk_size), 1, t_out); - std::array data = {0, 0, 0}; - for (size_t i = 0; i < t_chunk.size(); ++i) { - if (i % 2 == 0) { - data[0] = static_cast(t_chunk[i] >> 4); - data[1] = static_cast(t_chunk[i] << 4); - } else { - data[1] |= static_cast(t_chunk[i] >> 8) & 0xC; - data[2] = static_cast(t_chunk[i]); - fwrite(data.data(), sizeof(data[0]), 3, t_out); - data.fill(0); - } - } - if (t_chunk.size() % 2 != 0) { - fwrite(data.data(), sizeof(data[0]), 3, t_out); - } + fwrite((const char *)(output.data()), sizeof(output[0]), output.size(), + t_out); }