stuff-from-scratch/src/compression/huffman/HuffmanEncoder.h

56 lines
1.6 KiB
C
Raw Normal View History

2022-11-28 10:16:04 +00:00
#pragma once
#include "RawTree.h"
#include "HuffmanCodeLengthTable.h"
#include "HuffmanFixedCodes.h"
#include <vector>
#include <unordered_map>
class PrefixCodeGenerator
{
public:
virtual ~PrefixCodeGenerator() = default;
virtual std::optional<PrefixCode> getLiteralValue(unsigned char symbol) const = 0;
virtual std::optional<PrefixCode> getLengthValue(unsigned length) const = 0;
virtual std::optional<PrefixCode> getDistanceValue(unsigned distance) const = 0;
2022-11-28 10:16:04 +00:00
virtual std::optional<PrefixCode> getEndOfStreamValue() const = 0;
2022-11-28 10:16:04 +00:00
};
class HuffmanEncoder : public PrefixCodeGenerator
{
using DataStream = std::vector<unsigned char>;
using CountPair = std::pair<unsigned char, unsigned>;
public:
void encode(const DataStream& stream);
void encode(const std::unordered_map<unsigned char, unsigned>& counts);
uint32_t getLengthValue(unsigned length);
std::optional<PrefixCode> getLiteralValue(unsigned char symbol) const override;
std::optional<PrefixCode> getLengthValue(unsigned length) const override;
std::optional<PrefixCode> getDistanceValue(unsigned distance) const override;
std::optional<PrefixCode> getEndOfStreamValue() const override;
void initializeTrees();
void setUseFixedCode(bool useFixed);
2022-11-28 10:16:04 +00:00
private:
void initializeLiteralLengthTable();
2022-11-28 10:16:04 +00:00
void dumpTree(const RawTree<CountPair>& tree) const;
void dumpNode(RawNode<CountPair>* node, unsigned depth) const;
bool mUseFixedCode{false};
bool mTableIsInitialized{false};
HuffmanCodeLengthTable mLiteralLengthTable;
HuffmanCodeLengthTable mDistanceTable;
};