huffman.hpp 792 B

12345678910111213141516171819202122232425262728293031323334353637
  1. #pragma once
  2. namespace nall::Decode {
  3. inline auto Huffman(array_view<uint8_t> input) -> vector<uint8_t> {
  4. vector<uint8_t> output;
  5. uint size = 0;
  6. for(uint byte : range(8)) size |= *input++ << byte * 8;
  7. output.reserve(size);
  8. uint byte = 0, bits = 0;
  9. auto read = [&]() -> bool {
  10. if(bits == 0) bits = 8, byte = *input++;
  11. return byte >> --bits & 1;
  12. };
  13. uint nodes[256][2] = {};
  14. for(uint offset : range(256)) {
  15. for(uint index : range(9)) nodes[offset][0] = nodes[offset][0] << 1 | read();
  16. for(uint index : range(9)) nodes[offset][1] = nodes[offset][1] << 1 | read();
  17. }
  18. uint node = 511;
  19. while(output.size() < size) {
  20. node = nodes[node - 256][read()];
  21. if(node < 256) {
  22. output.append(node);
  23. node = 511;
  24. }
  25. }
  26. return output;
  27. }
  28. }