huffman.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // #include "simple/support/debug.hpp"
  2. #include "simple/compress/huffman.hpp"
  3. #include "simple/compress/iterator.hpp" // out_bits
  4. #include "simple/support/iterator.hpp" // offset_expander
  5. #include <cassert>
  6. #include <vector>
  7. #include <string>
  8. #include <cstdio>
  9. using namespace simple::compress;
  10. void Endecode(std::string text)
  11. {
  12. std::vector<std::byte> encoded;
  13. encoded.reserve(text.size());
  14. auto code = huffman_code(text.begin(), text.end());
  15. #if defined SIMPLE_SUPPORT_DEBUG_HPP
  16. simple::support::print('\n');
  17. simple::support::println("CODE: ");
  18. code.for_each([](auto && kv) { using std::to_string; if(bit_count(kv.second) != 0) simple::support::println(to_string((int)kv.first) + " - " + to_string(kv.second)); });
  19. simple::support::print('\n');
  20. #endif
  21. huffman_encode(code, text.begin(), text.end(), out_bits(simple::support::offset_expander(encoded)));
  22. #if defined SIMPLE_SUPPORT_DEBUG_HPP
  23. simple::support::print("INPUT SIZE: ", text.size(), '\n');
  24. simple::support::print("COMPRESSED SIZE: ", encoded.size(), '\n');
  25. #endif
  26. std::string decoded;
  27. decoded.resize(text.size());
  28. huffman_decode(code, encoded.begin(), decoded.begin(), decoded.end());
  29. assert(text == decoded);
  30. }
  31. int main(int argc, char const* argv[])
  32. {
  33. std::string text = "abcd aaaa bbbb cccc aaaa abcd aaaa aaaa aaaa aaaaa aaaa aaaaaaaaaaa aaaaaaaaaaaaa aaaaaaaaaaaaaa aaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa";
  34. if(argc > 1)
  35. {
  36. auto f = std::fopen(argv[1], "rb");
  37. std::fseek(f,0,SEEK_END);
  38. text.resize(std::ftell(f));
  39. std::fseek(f,0,SEEK_SET);
  40. auto unused [[maybe_unused]] = std::fread(text.data(), text.size(), 1 ,f);
  41. #if defined SIMPLE_SUPPORT_DEBUG_HPP
  42. simple::support::print("s: ", text.size(), '\n');
  43. #endif
  44. }
  45. Endecode(std::move(text));
  46. return 0;
  47. }