diff --git a/include/Void/Text/Gzip.hpp b/include/Void/Text/Gzip.hpp new file mode 100644 index 0000000..1843a60 --- /dev/null +++ b/include/Void/Text/Gzip.hpp @@ -0,0 +1,1086 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Compression +{ + enum class GzipErrorCode : std::int32_t { + none = 0, + invalid_state = 1, + bad_header = 2, + truncated_input = 3, + bad_block = 4, + bad_huffman = 5, + checksum_mismatch = 6, + output_limit_exceeded = 7, + input_limit_exceeded = 8, + invalid_argument = 9 + }; + + [[nodiscard]] inline Void::Result::Error + make_gzip_error(GzipErrorCode code, std::string message) + { + using Void::Result::ErrorKind; + ErrorKind kind = ErrorKind::internal; + switch (code) { + case GzipErrorCode::none: + kind = ErrorKind::internal; + break; + case GzipErrorCode::invalid_state: + case GzipErrorCode::invalid_argument: + kind = ErrorKind::invalid_argument; + break; + case GzipErrorCode::bad_header: + case GzipErrorCode::bad_block: + case GzipErrorCode::bad_huffman: + case GzipErrorCode::truncated_input: + case GzipErrorCode::checksum_mismatch: + kind = ErrorKind::corrupt; + break; + case GzipErrorCode::output_limit_exceeded: + case GzipErrorCode::input_limit_exceeded: + kind = ErrorKind::exhausted; + break; + } + return Void::Result::Error{kind, std::move(message)}; + } + + /// Bounds for one codec instance. Memory stays bounded: retained input is + /// compacted as it is consumed and decoded output is capped. + struct GzipLimits { + std::size_t max_output_bytes{256ULL * 1024ULL * 1024ULL}; + /// Maximum unconsumed input retained between feeds. + std::size_t max_input_buffer_bytes{1024ULL * 1024ULL}; + }; + + namespace Detail + { + inline constexpr std::array make_crc_table() noexcept + { + std::array table{}; + for (std::uint32_t i = 0; i < 256; ++i) { + std::uint32_t crc = i; + for (int bit = 0; bit < 8; ++bit) { + crc = (crc & 1U) != 0 ? (0xEDB88320U ^ (crc >> 1)) : (crc >> 1); + } + table[i] = crc; + } + return table; + } + + inline constexpr auto kCrcTable = make_crc_table(); + + [[nodiscard]] inline std::uint32_t + crc32_update(std::uint32_t crc, + std::span data) noexcept + { + crc = ~crc; + for (const std::byte value : data) { + crc = kCrcTable[(crc ^ std::to_integer(value)) & + 0xFFU] ^ + (crc >> 8); + } + return ~crc; + } + } // namespace Detail +} // namespace Void::Compression + +namespace Void::Compression +{ + /// Streaming DEFLATE (RFC 1951) decoder with optional gzip (RFC 1952) + /// framing. Input is fed in chunks; decoded bytes are appended to the + /// caller's output string, which also serves as the 32 KiB history window + /// (keep using the same string for the whole stream). + class Inflater + { + public: + + [[nodiscard]] static Void::Result::Result + create_gzip(GzipLimits limits = {}); + [[nodiscard]] static Void::Result::Result + create_deflate(GzipLimits limits = {}); + + /// Decode as much of `input` as possible, appending to `output`. + /// Returns success when the input was consumed or more input is + /// needed; malformed input fails immediately. + [[nodiscard]] Void::Result::Result + feed(std::span input, std::string& output); + + /// Assert the stream ended cleanly and (for gzip) the CRC and size + /// match. No more feeds are accepted afterwards. + [[nodiscard]] Void::Result::Result finish(std::string& output); + + [[nodiscard]] bool finished() const noexcept + { + return m_stage == Stage::Done; + } + [[nodiscard]] std::uint64_t total_output() const noexcept + { + return m_total_out; + } + + private: + + enum class Stage : std::uint8_t { + GzipHeader, + BlockHeader, + StoredHeader, + StoredData, + HuffmanBlock, + Trailer, + Done, + Failed + }; + + struct Huffman { + std::array count{}; + // One entry per possible symbol (literal/distance/code-length). + std::array symbol{}; + }; + + Inflater() = default; + + [[nodiscard]] bool fill_bits(int need) noexcept; + [[nodiscard]] std::optional bits(int need) noexcept; + void align_byte() noexcept; + [[nodiscard]] int decode(const Huffman& tree) noexcept; + + [[nodiscard]] bool build(Huffman& tree, + const std::array& lengths, + std::size_t count) noexcept; + + /// One resumable step. Returns 1 on progress, 0 when more input is + /// needed, -1 on error. + int step(std::string& output); + + int run_stored(std::string& output); + int run_huffman(std::string& output); + [[nodiscard]] int fail(GzipErrorCode code, std::string message); + + GzipLimits m_limits{}; + bool m_gzip{false}; + Stage m_stage{Stage::BlockHeader}; + + std::vector m_in{}; + std::size_t m_pos{0}; + std::uint32_t m_bitbuf{0}; + int m_bitcount{0}; + + std::uint64_t m_total_out{0}; + std::uint32_t m_crc{0}; + std::uint32_t m_isize{0}; + /// Output offset already included in m_crc. + std::size_t m_crc_upto{0}; + void sync_crc(const std::string& output) noexcept; + void emit(std::string& output, std::uint8_t value); + + // Gzip header parsing. + std::vector m_gzip_header{}; + std::uint8_t m_flags{0}; + std::size_t m_skip_remaining{0}; + int m_hdr_state{0}; + unsigned m_extra_len{0}; + + // Block state. + bool m_final_block{false}; + std::size_t m_stored_remaining{0}; + std::size_t m_stored_check{0}; + bool m_stored_need_header{true}; + + // Huffman block state. + bool m_huffman_started{false}; + /// Set by finish(): the remaining input is all that will arrive, so a + /// truncated dynamic header fails instead of waiting. + bool m_final_input{false}; + /// A retry will rewind to an earlier position, so input compaction + /// is deferred until the parse completes. + bool m_rewind_pending{false}; + Huffman m_litlen{}; + Huffman m_dist{}; + std::optional m_pending_length{}; + + Void::Result::Error m_error{}; + }; + + /// Streaming deflate/gzip encoder using stored (uncompressed) DEFLATE + /// blocks. Output is valid RFC 1951/1952 and bounded: at most one block of + /// pending input is retained between feeds. + class Deflater + { + public: + + [[nodiscard]] static Void::Result::Result + create_deflate(GzipLimits limits = {}); + [[nodiscard]] static Void::Result::Result + create_gzip(GzipLimits limits = {}); + + /// Encode `input`, appending framed bytes to `output`. + [[nodiscard]] Void::Result::Result + feed(std::span input, std::string& output); + + /// Emit the final block and (for gzip) the CRC/size trailer. + [[nodiscard]] Void::Result::Result finish(std::string& output); + + [[nodiscard]] std::uint64_t total_input() const noexcept + { + return m_total_in; + } + [[nodiscard]] bool finished() const noexcept { return m_finished; } + + private: + + Deflater() = default; + void emit_block(std::string& output, bool final_block); + + bool m_gzip{false}; + bool m_header_written{false}; + bool m_finished{false}; + std::vector m_pending{}; + std::uint32_t m_crc{0}; + std::uint64_t m_total_in{0}; + }; +} // namespace Void::Compression + +namespace Void::Compression +{ + namespace Detail + { + // RFC 1951 ยง3.2.5 length and distance code tables (index 0 = symbol 257). + inline constexpr std::array kLengthBase{ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, + 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258}; + inline constexpr std::array kLengthExtra{ + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, + 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0}; + inline constexpr std::array kDistBase{ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, + 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, + 6145, 8193, 12289, 16385, 24577}; + inline constexpr std::array kDistExtra{ + 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, + 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; + } // namespace Detail + + inline void Inflater::sync_crc(const std::string& output) noexcept + { + if (output.size() <= m_crc_upto) { + return; + } + const auto* data = + reinterpret_cast(output.data()) + m_crc_upto; + m_crc = Detail::crc32_update( + m_crc, std::span{data, output.size() - m_crc_upto}); + m_crc_upto = output.size(); + } + + inline void Inflater::emit(std::string& output, std::uint8_t value) + { + output.push_back(static_cast(value)); + ++m_total_out; + m_isize = static_cast(m_total_out); + } + + inline bool Inflater::fill_bits(int need) noexcept + { + while (m_bitcount < need && m_pos < m_in.size()) { + m_bitbuf |= static_cast(m_in[m_pos]) << m_bitcount; + ++m_pos; + m_bitcount += 8; + } + return m_bitcount >= need; + } + + inline std::optional Inflater::bits(int need) noexcept + { + if (need <= 0 || need > 24) { + return std::nullopt; + } + if (!fill_bits(need)) { + return std::nullopt; + } + const std::uint32_t mask = (1U << need) - 1U; + const std::uint32_t value = m_bitbuf & mask; + m_bitbuf >>= need; + m_bitcount -= need; + return value; + } + + inline void Inflater::align_byte() noexcept + { + const int drop = m_bitcount % 8; + m_bitbuf >>= drop; + m_bitcount -= drop; + } + + // Peek-style Huffman decode: bits are consumed only when a complete code + // matches, so a "need more input" result leaves the stream position + // unchanged and any decode can be retried safely after more input. + // Returns a symbol, kNeedInput (-2) or kInvalidCode (-1): symbol 0 is a + // valid code-length/literal value and must not be the need-input sentinel. + inline constexpr int kNeedInput = -2; + inline constexpr int kInvalidCode = -1; + + inline int Inflater::decode(const Huffman& tree) noexcept + { + int code = 0; + int first = 0; + int index = 0; + for (int len = 1; len <= 15; ++len) { + if (!fill_bits(len)) { + return kNeedInput; + } + code |= static_cast((m_bitbuf >> (len - 1)) & 1U); + const int count = tree.count[static_cast(len)]; + if (code - first < count) { + const int symbol = + tree.symbol[static_cast(index + code - first)]; + m_bitbuf >>= len; + m_bitcount -= len; + return symbol; + } + index += count; + first = (first + count) << 1; + code <<= 1; + } + return kInvalidCode; + } + + inline bool Inflater::build(Huffman& tree, + const std::array& lengths, + std::size_t count) noexcept + { + tree.count.fill(0); + tree.symbol.fill(0); + for (std::size_t i = 0; i < count; ++i) { + if (lengths[i] > 15) { + return false; + } + ++tree.count[lengths[i]]; + } + if (tree.count[0] == count) { + return true; // empty tree (no codes) + } + int left = 1; + for (int len = 1; len <= 15; ++len) { + left <<= 1; + left -= tree.count[static_cast(len)]; + if (left < 0) { + return false; // over-subscribed + } + } + std::array offsets{}; + for (int len = 1; len < 15; ++len) { + offsets[static_cast(len + 1)] = + offsets[static_cast(len)] + + tree.count[static_cast(len)]; + } + for (std::size_t i = 0; i < count; ++i) { + if (lengths[i] != 0) { + tree.symbol[static_cast( + offsets[lengths[i]]++)] = static_cast(i); + } + } + return true; + } + + inline int Inflater::fail(GzipErrorCode code, std::string message) + { + m_stage = Stage::Failed; + m_error = make_gzip_error(code, std::move(message)); + return -1; + } + + inline Void::Result::Result Inflater::create_deflate(GzipLimits limits) + { + Inflater inflater; + inflater.m_limits = limits; + inflater.m_gzip = false; + inflater.m_stage = Stage::BlockHeader; + return inflater; + } + + inline Void::Result::Result Inflater::create_gzip(GzipLimits limits) + { + Inflater inflater; + inflater.m_limits = limits; + inflater.m_gzip = true; + inflater.m_stage = Stage::GzipHeader; + return inflater; + } + + inline Void::Result::Result + Inflater::feed(std::span input, std::string& output) + { + if (m_stage == Stage::Failed) { + return std::unexpected{m_error}; + } + if (m_stage == Stage::Done && !input.empty()) { + return std::unexpected{make_gzip_error( + GzipErrorCode::bad_header, + "Gzip: trailing data after the end of the stream")}; + } + if (output.size() != static_cast(m_total_out)) { + return std::unexpected{make_gzip_error( + GzipErrorCode::invalid_argument, + "Gzip: output must be the same string across feeds")}; + } + const std::size_t retained = m_in.size() - m_pos; + if (input.size() > m_limits.max_input_buffer_bytes || + retained > m_limits.max_input_buffer_bytes - input.size()) { + return std::unexpected{make_gzip_error( + GzipErrorCode::input_limit_exceeded, + "Gzip: input buffer limit exceeded")}; + } + m_in.insert(m_in.end(), input.begin(), input.end()); + + for (;;) { + const int result = step(output); + if (result < 0) { + return std::unexpected{m_error}; + } + if (result == 0 || m_stage == Stage::Done) { + break; + } + } + // Compact consumed input; bits already pulled into m_bitbuf stay + // there. A suspended block header still needs to rewind, so keep the + // buffer intact until its parse completes. + if (m_pos > 0 && !m_rewind_pending) { + m_in.erase(m_in.begin(), + m_in.begin() + static_cast(m_pos)); + m_pos = 0; + } + return {}; + } + + inline Void::Result::Result + Inflater::finish(std::string& output) + { + if (m_stage == Stage::Failed) { + return std::unexpected{m_error}; + } + m_final_input = true; + for (;;) { + const int result = step(output); + if (result < 0) { + return std::unexpected{m_error}; + } + if (result == 0) { + return std::unexpected{make_gzip_error( + GzipErrorCode::truncated_input, + "Gzip: stream ended before the final block")}; + } + if (m_stage == Stage::Done) { + break; + } + } + if (m_pos < m_in.size()) { + return std::unexpected{make_gzip_error( + GzipErrorCode::bad_header, + "Gzip: trailing data after the end of the stream")}; + } + return {}; + } + + inline int Inflater::run_huffman(std::string& output) + { + for (;;) { + const auto saved_bitbuf = m_bitbuf; + const auto saved_bitcount = m_bitcount; + const auto saved_pos = m_pos; + const auto restore = [&] { + m_bitbuf = saved_bitbuf; + m_bitcount = saved_bitcount; + m_pos = saved_pos; + m_rewind_pending = true; + }; + + if (!m_pending_length.has_value()) { + const int symbol = decode(m_litlen); + if (symbol == kNeedInput) { + restore(); + return 0; + } + if (symbol == kInvalidCode) { + return fail(GzipErrorCode::bad_huffman, + "Gzip: invalid literal/length code"); + } + if (symbol < 256) { + if (m_total_out >= m_limits.max_output_bytes) { + return fail(GzipErrorCode::output_limit_exceeded, + "Gzip: output limit exceeded"); + } + emit(output, static_cast(symbol)); + continue; + } + if (symbol == 256) { + m_rewind_pending = false; + if (m_final_block) { + align_byte(); + m_stage = m_gzip ? Stage::Trailer : Stage::Done; + } else { + m_stage = Stage::BlockHeader; + } + return 1; + } + const auto index = static_cast(symbol - 257); + if (index >= Detail::kLengthBase.size()) { + return fail(GzipErrorCode::bad_huffman, + "Gzip: invalid length symbol"); + } + const int extra = Detail::kLengthExtra[index]; + std::optional extra_bits = 0U; + if (extra > 0) { + extra_bits = bits(extra); + } + if (!extra_bits.has_value()) { + restore(); + return 0; + } + m_pending_length = Detail::kLengthBase[index] + *extra_bits; + } + + const int distance_symbol = decode(m_dist); + if (distance_symbol == kNeedInput) { + restore(); + return 0; + } + if (distance_symbol == kInvalidCode || distance_symbol >= 30) { + return fail(GzipErrorCode::bad_huffman, + "Gzip: invalid distance code"); + } + const auto distance_index = static_cast(distance_symbol); + const int distance_extra = Detail::kDistExtra[distance_index]; + std::optional distance_bits = 0U; + if (distance_extra > 0) { + distance_bits = bits(distance_extra); + } + if (!distance_bits.has_value()) { + restore(); + return 0; + } + const std::size_t distance = + Detail::kDistBase[distance_index] + *distance_bits; + const std::size_t length = *m_pending_length; + m_pending_length.reset(); + if (distance > output.size()) { + return fail(GzipErrorCode::bad_block, + "Gzip: distance exceeds decoded history"); + } + for (std::size_t i = 0; i < length; ++i) { + if (m_total_out >= m_limits.max_output_bytes) { + return fail(GzipErrorCode::output_limit_exceeded, + "Gzip: output limit exceeded"); + } + emit(output, static_cast( + output[output.size() - distance])); + } + } + } +} // namespace Void::Compression + +namespace Void::Compression +{ + inline int Inflater::step(std::string& output) + { + switch (m_stage) { + case Stage::Done: + return 1; + case Stage::Failed: + return -1; + + case Stage::GzipHeader: { + while (m_hdr_state < 6) { + if (m_hdr_state == 0) { + while (m_gzip_header.size() < 10) { + if (!fill_bits(8)) { + return 0; + } + m_gzip_header.push_back(static_cast(*bits(8))); + } + if (m_gzip_header[0] != 0x1f || m_gzip_header[1] != 0x8b || + m_gzip_header[2] != 0x08) { + return fail(GzipErrorCode::bad_header, + "Gzip: not a gzip stream"); + } + if ((m_gzip_header[3] & 0xE0U) != 0) { + return fail(GzipErrorCode::bad_header, + "Gzip: reserved header flags set"); + } + m_flags = m_gzip_header[3]; + m_hdr_state = 1; + } else if (m_hdr_state == 1) { + if ((m_flags & 0x04U) == 0) { + m_hdr_state = 3; + continue; + } + auto length = bits(16); + if (!length) { + return 0; + } + m_extra_len = *length; + m_hdr_state = 2; + } else if (m_hdr_state == 2) { + while (m_extra_len > 0) { + if (!fill_bits(8)) { + return 0; + } + (void)bits(8); + --m_extra_len; + } + m_hdr_state = 3; + } else if (m_hdr_state == 3) { + if ((m_flags & 0x08U) == 0) { + m_hdr_state = 4; + continue; + } + for (;;) { + if (!fill_bits(8)) { + return 0; + } + if (*bits(8) == 0) { + break; + } + } + m_hdr_state = 4; + } else if (m_hdr_state == 4) { + if ((m_flags & 0x10U) == 0) { + m_hdr_state = 5; + continue; + } + for (;;) { + if (!fill_bits(8)) { + return 0; + } + if (*bits(8) == 0) { + break; + } + } + m_hdr_state = 5; + } else { + if ((m_flags & 0x02U) != 0) { + if (!fill_bits(16)) { + return 0; + } + (void)bits(16); + } + m_hdr_state = 6; + } + } + m_stage = Stage::BlockHeader; + return 1; + } + + case Stage::BlockHeader: { + if (m_total_out > m_limits.max_output_bytes) { + return fail(GzipErrorCode::output_limit_exceeded, + "Gzip: output limit exceeded"); + } + // A suspended parse resumes by re-reading the whole block + // header, so the snapshot is taken before its 3 bits. + const auto block_bitbuf = m_bitbuf; + const auto block_bitcount = m_bitcount; + const auto block_pos = m_pos; + if (!fill_bits(3)) { + return 0; + } + m_final_block = *bits(1) != 0; + const auto type = *bits(2); + if (type == 0) { + align_byte(); + m_stage = Stage::StoredHeader; + return 1; + } + if (type == 1) { + std::array lengths{}; + for (std::size_t i = 0; i < 144; ++i) { + lengths[i] = 8; + } + for (std::size_t i = 144; i < 256; ++i) { + lengths[i] = 9; + } + for (std::size_t i = 256; i < 280; ++i) { + lengths[i] = 7; + } + for (std::size_t i = 280; i < 288; ++i) { + lengths[i] = 8; + } + if (!build(m_litlen, lengths, 288)) { + return fail(GzipErrorCode::bad_huffman, + "Gzip: invalid fixed literal tree"); + } + lengths.fill(0); + for (std::size_t i = 0; i < 32; ++i) { + lengths[i] = 5; + } + if (!build(m_dist, lengths, 32)) { + return fail(GzipErrorCode::bad_huffman, + "Gzip: invalid fixed distance tree"); + } + m_pending_length.reset(); + m_rewind_pending = false; + m_stage = Stage::HuffmanBlock; + return 1; + } + if (type != 2) { + return fail(GzipErrorCode::bad_block, + "Gzip: reserved block type"); + } + // Worst-case dynamic header: 5+5+4 bits, 19 code lengths of 3 + // bits, then up to 316 code lengths of 7 bits. Parsing only + // starts once all of it can be read, so the header never + // suspends half-way (small streams are parsed in finish()). + constexpr std::size_t kMaxDynamicHeaderBits = + 14 + 19 * 3 + (286 + 30) * 7; + const std::size_t available = + static_cast(m_bitcount) + + 8 * (m_in.size() - m_pos); + if (!m_final_input && available < kMaxDynamicHeaderBits) { + m_bitbuf = block_bitbuf; + m_bitcount = block_bitcount; + m_pos = block_pos; + m_rewind_pending = true; + return 0; + } + // Dynamic Huffman header. A partial parse is discarded by + // restoring the bit position, so the work is redone on more + // input instead of keeping half-updated state. + const auto restore = [&] { + m_bitbuf = block_bitbuf; + m_bitcount = block_bitcount; + m_pos = block_pos; + m_rewind_pending = true; + }; + + auto hlit = bits(5); + if (!hlit) { + restore(); + return 0; + } + auto hdist = bits(5); + if (!hdist) { + restore(); + return 0; + } + auto hclen = bits(4); + if (!hclen) { + restore(); + return 0; + } + const std::size_t nlit = *hlit + 257; + const std::size_t ndist = *hdist + 1; + const std::size_t nclen = *hclen + 4; + if (nlit > 286 || ndist > 30) { + return fail(GzipErrorCode::bad_huffman, + "Gzip: too many literal or distance codes"); + } + static constexpr std::array kOrder{ + 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, + 4, 12, 3, 13, 2, 14, 1, 15}; + std::array code_lengths{}; + for (std::size_t i = 0; i < nclen; ++i) { + auto value = bits(3); + if (!value) { + restore(); + return 0; + } + code_lengths[static_cast(kOrder[i])] = + static_cast(*value); + } + Huffman code_tree; + if (!build(code_tree, code_lengths, 19)) { + return fail(GzipErrorCode::bad_huffman, + "Gzip: invalid code-length tree"); + } + + std::array lengths{}; + std::size_t index = 0; + const std::size_t total = nlit + ndist; + while (index < total) { + const int symbol = decode(code_tree); + if (symbol == kNeedInput) { + restore(); + return 0; + } + if (symbol == kInvalidCode) { + return fail(GzipErrorCode::bad_huffman, + "Gzip: invalid code-length symbol"); + } + if (symbol < 16) { + lengths[index++] = static_cast(symbol); + continue; + } + std::size_t repeat = 0; + std::uint8_t value = 0; + if (symbol == 16) { + if (index == 0) { + return fail(GzipErrorCode::bad_huffman, + "Gzip: repeat without previous length"); + } + value = lengths[index - 1]; + auto extra = bits(2); + if (!extra) { + restore(); + return 0; + } + repeat = 3 + *extra; + } else if (symbol == 17) { + auto extra = bits(3); + if (!extra) { + restore(); + return 0; + } + repeat = 3 + *extra; + } else { + auto extra = bits(7); + if (!extra) { + restore(); + return 0; + } + repeat = 11 + *extra; + } + if (index + repeat > total) { + return fail(GzipErrorCode::bad_huffman, + "Gzip: code lengths exceed the tree size"); + } + for (std::size_t i = 0; i < repeat; ++i) { + lengths[index++] = value; + } + } + if (lengths[256] == 0) { + return fail(GzipErrorCode::bad_huffman, + "Gzip: missing end-of-block code"); + } + if (!build(m_litlen, lengths, nlit)) { + return fail(GzipErrorCode::bad_huffman, + "Gzip: invalid literal tree"); + } + std::array distance_lengths{}; + for (std::size_t i = 0; i < ndist; ++i) { + distance_lengths[i] = lengths[nlit + i]; + } + if (!build(m_dist, distance_lengths, ndist)) { + return fail(GzipErrorCode::bad_huffman, + "Gzip: invalid distance tree"); + } + m_pending_length.reset(); + m_rewind_pending = false; + m_stage = Stage::HuffmanBlock; + return 1; + } + + case Stage::StoredHeader: { + const auto saved_bitbuf = m_bitbuf; + const auto saved_bitcount = m_bitcount; + const auto saved_pos = m_pos; + auto length = bits(16); + if (!length) { + m_bitbuf = saved_bitbuf; + m_bitcount = saved_bitcount; + m_pos = saved_pos; + m_rewind_pending = true; + return 0; + } + auto complement = bits(16); + if (!complement) { + m_bitbuf = saved_bitbuf; + m_bitcount = saved_bitcount; + m_pos = saved_pos; + m_rewind_pending = true; + return 0; + } + if ((*length ^ 0xFFFFU) != *complement) { + return fail(GzipErrorCode::bad_block, + "Gzip: stored block length mismatch"); + } + m_stored_remaining = *length; + m_rewind_pending = false; + m_stage = Stage::StoredData; + return 1; + } + + case Stage::StoredData: { + while (m_stored_remaining > 0) { + std::uint8_t value = 0; + if (m_bitcount >= 8) { + value = static_cast(m_bitbuf & 0xFFU); + m_bitbuf >>= 8; + m_bitcount -= 8; + } else if (m_pos < m_in.size()) { + value = std::to_integer(m_in[m_pos]); + ++m_pos; + } else { + return 0; + } + if (m_total_out >= m_limits.max_output_bytes) { + return fail(GzipErrorCode::output_limit_exceeded, + "Gzip: output limit exceeded"); + } + emit(output, value); + --m_stored_remaining; + } + m_rewind_pending = false; + if (m_final_block) { + align_byte(); + m_stage = m_gzip ? Stage::Trailer : Stage::Done; + } else { + m_stage = Stage::BlockHeader; + } + return 1; + } + + case Stage::HuffmanBlock: + return run_huffman(output); + + case Stage::Trailer: { + align_byte(); + const auto saved_bitbuf = m_bitbuf; + const auto saved_bitcount = m_bitcount; + const auto saved_pos = m_pos; + std::uint32_t expected_crc = 0; + std::uint32_t expected_size = 0; + for (int i = 0; i < 4; ++i) { + auto value = bits(8); + if (!value) { + m_bitbuf = saved_bitbuf; + m_bitcount = saved_bitcount; + m_pos = saved_pos; + return 0; + } + expected_crc |= *value << (8 * i); + } + for (int i = 0; i < 4; ++i) { + auto value = bits(8); + if (!value) { + m_bitbuf = saved_bitbuf; + m_bitcount = saved_bitcount; + m_pos = saved_pos; + return 0; + } + expected_size |= *value << (8 * i); + } + sync_crc(output); + if (expected_crc != m_crc) { + return fail(GzipErrorCode::checksum_mismatch, + "Gzip: CRC32 mismatch"); + } + if (expected_size != m_isize) { + return fail(GzipErrorCode::checksum_mismatch, + "Gzip: ISIZE mismatch"); + } + m_stage = Stage::Done; + return 1; + } + } + return -1; + } +} // namespace Void::Compression + +namespace Void::Compression +{ + inline Void::Result::Result + Deflater::create_deflate(GzipLimits) + { + Deflater deflater; + deflater.m_gzip = false; + return deflater; + } + + inline Void::Result::Result + Deflater::create_gzip(GzipLimits) + { + Deflater deflater; + deflater.m_gzip = true; + return deflater; + } + + inline void Deflater::emit_block(std::string& output, bool final_block) + { + if (m_gzip && !m_header_written) { + m_header_written = true; + // Fixed gzip member header: deflate, no flags, mtime 0, OS unix. + constexpr std::array kHeader{ + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03}; + for (const unsigned char value : kHeader) { + output.push_back(static_cast(value)); + } + } + const auto length = static_cast(m_pending.size()); + const auto complement = static_cast(~length); + output.push_back(static_cast(final_block ? 0x01 : 0x00)); + output.push_back(static_cast(length & 0xFFU)); + output.push_back(static_cast((length >> 8U) & 0xFFU)); + output.push_back(static_cast(complement & 0xFFU)); + output.push_back(static_cast((complement >> 8U) & 0xFFU)); + if (!m_pending.empty()) { + output.append(reinterpret_cast(m_pending.data()), + m_pending.size()); + } + m_pending.clear(); + } + + inline Void::Result::Result + Deflater::feed(std::span input, std::string& output) + { + if (m_finished) { + return std::unexpected{make_gzip_error( + GzipErrorCode::invalid_state, + "Gzip: feed after the stream was finished")}; + } + m_total_in += input.size(); + if (m_gzip) { + m_crc = Detail::crc32_update(m_crc, input); + } + + // Keep at most one block buffered so memory stays bounded even for a + // very large single input span. + std::size_t pos = 0; + while (pos < input.size()) { + const std::size_t space = 65535 - m_pending.size(); + const std::size_t take = std::min(space, input.size() - pos); + m_pending.insert(m_pending.end(), input.begin() + + static_cast(pos), + input.begin() + static_cast(pos + take)); + pos += take; + if (m_pending.size() == 65535) { + emit_block(output, false); + } + } + return {}; + } + + inline Void::Result::Result Deflater::finish(std::string& output) + { + if (m_finished) { + return std::unexpected{make_gzip_error( + GzipErrorCode::invalid_state, + "Gzip: stream already finished")}; + } + emit_block(output, true); + if (m_gzip) { + const auto size = static_cast(m_total_in); + std::uint32_t crc = m_crc; + for (int i = 0; i < 4; ++i) { + output.push_back(static_cast((crc >> (8 * i)) & 0xFFU)); + } + for (int i = 0; i < 4; ++i) { + output.push_back(static_cast((size >> (8 * i)) & 0xFFU)); + } + } + m_finished = true; + return {}; + } +} // namespace Void::Compression diff --git a/tests/standalone/Text/Gzip.cpp b/tests/standalone/Text/Gzip.cpp new file mode 100644 index 0000000..04c800d --- /dev/null +++ b/tests/standalone/Text/Gzip.cpp @@ -0,0 +1,232 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace +{ + using namespace Void::Compression; + + std::vector from_hex(std::string_view hex) + { + const auto digit = [](char c) -> int { + if (c >= '0' && c <= '9') { + return c - '0'; + } + if (c >= 'a' && c <= 'f') { + return c - 'a' + 10; + } + if (c >= 'A' && c <= 'F') { + return c - 'A' + 10; + } + return 0; + }; + std::vector out; + out.reserve(hex.size() / 2); + for (std::size_t i = 0; i + 1 < hex.size(); i += 2) { + out.push_back(static_cast((digit(hex[i]) << 4) | + digit(hex[i + 1]))); + } + return out; + } + + Void::Result::Result + inflate_all(bool gzip, std::span input, + std::size_t chunk = 0, GzipLimits limits = {}) + { + auto inflater = gzip ? Inflater::create_gzip(limits) + : Inflater::create_deflate(limits); + if (!inflater) { + return std::unexpected{inflater.error()}; + } + std::string output; + const std::size_t step = chunk == 0 ? input.size() : chunk; + for (std::size_t pos = 0; pos < input.size(); pos += step) { + const std::size_t count = + step == 0 ? 0 : std::min(step, input.size() - pos); + if (auto fed = inflater->feed(input.subspan(pos, count), output); + !fed) { + return std::unexpected{fed.error()}; + } + } + if (auto done = inflater->finish(output); !done) { + return std::unexpected{done.error()}; + } + return output; + } + + std::string binary_pattern() + { + std::string out; + for (int repeat = 0; repeat < 4; ++repeat) { + for (int value = 0; value < 256; ++value) { + out.push_back(static_cast(value)); + } + } + return out; + } + + std::string text_pattern() + { + std::string out; + for (int i = 0; i < 20; ++i) { + out += "one two three four five six seven eight nine ten "; + } + return out; + } + + constexpr std::string_view kHelloGz = + "1f8b0800000000000003cb48cdc9c9070086a6103605000000"; + constexpr std::string_view kHelloRaw = "cb48cdc9c90700"; + constexpr std::string_view kEmptyGz = + "1f8b080000000000000303000000000000000000"; + constexpr std::string_view kEmptyRaw = "0300"; + constexpr std::string_view kTextGz = + "1f8b0800000000000003edcbcb0d00200804d156b6b955b94082f8295fedc203c7" + "49e69912b10cd19c44b1e12832892e1b9d930a4a6d019537deb4040912fc0c0e88" + "ddb3a9d4030000"; + constexpr std::string_view kBinaryGz = + "1f8b08000000000000036360646266616563e7e0e4e2e6e1e5e31710141216111513" + "97909492969195935750545256515553d7d0d4d2d6d1d5d33730343236313533b7b0" + "b4b2b6b1b5b37770747276717573f7f0f4f2f6f1f5f30f080c0a0e090d0b8f888c8a" + "8e898d8b4f484c4a4e494d4bcfc8cccacec9cdcb2f282c2a2e292d2bafa8acaaaea9" + "adab6f686c6a6e696d6befe8eceaeee9edeb9f3071d2e42953a74d9f3173d6ec3973" + "e7cd5fb070d1e2254b972d5fb172d5ea356bd7addfb071d3e62d5bb76ddfb173d7ee" + "3d7bf7ed3f70f0d0e123478f1d3f71f2d4e93367cf9dbf70f1d2e52b57af5dbf71f3" + "d6ed3b77efdd7ff0f0d1e3274f9f3d7ff1f2d5eb376fdfbdfff0f1d3e72f5fbf7dff" + "f1f3d7ef3f7ffffd6718f5ffa8ff47b0ff01264c0bb700040000"; +} // namespace + +Void::Testing::Test gzip_inflates_rfc1952_vectors() +{ + struct Vector { + std::string_view gz; + std::string expected; + }; + const Vector vectors[] = { + {kHelloGz, "hello"}, + {kEmptyGz, ""}, + {kTextGz, text_pattern()}, + {kBinaryGz, binary_pattern()}, + }; + for (const auto& vector : vectors) { + const auto bytes = from_hex(vector.gz); + auto inflated = inflate_all(true, bytes); + Void::Testing::require(inflated.has_value()); + Void::Testing::expect_eq(*inflated, vector.expected); + } +} + +Void::Testing::Test deflate_inflates_rfc1951_vectors() +{ + const auto hello = from_hex(kHelloRaw); + auto inflated = inflate_all(false, hello); + Void::Testing::require(inflated.has_value()); + Void::Testing::expect_eq(*inflated, std::string{"hello"}); + + const auto empty = from_hex(kEmptyRaw); + auto empty_out = inflate_all(false, empty); + Void::Testing::require(empty_out.has_value()); + Void::Testing::expect(empty_out->empty()); +} + +Void::Testing::Test gzip_inflates_across_chunk_boundaries() +{ + const auto bytes = from_hex(kTextGz); + for (const std::size_t chunk : {1U, 2U, 3U, 7U, 64U}) { + auto inflated = inflate_all(true, bytes, chunk); + Void::Testing::require(inflated.has_value()); + Void::Testing::expect_eq(*inflated, text_pattern()); + } +} + +Void::Testing::Test gzip_rejects_malformed_and_truncated_input() +{ + const auto good = from_hex(kHelloGz); + + // Truncated: the trailer is missing. + { + const std::span truncated{good.data(), + good.size() - 4}; + Void::Testing::expect(!inflate_all(true, truncated).has_value()); + } + // Corrupt CRC in the trailer. + { + auto corrupt = good; + corrupt[corrupt.size() - 5] ^= std::byte{0xff}; + Void::Testing::expect(!inflate_all(true, corrupt).has_value()); + } + // Bad magic. + { + auto bad = good; + bad[0] = std::byte{0x00}; + Void::Testing::expect(!inflate_all(true, bad).has_value()); + } + // Garbage. + { + const auto garbage = from_hex("deadbeefdeadbeef"); + Void::Testing::expect(!inflate_all(true, garbage).has_value()); + } + // Trailing data after a complete member. + { + auto trailing = good; + trailing.push_back(std::byte{0x00}); + Void::Testing::expect(!inflate_all(true, trailing).has_value()); + } +} + +Void::Testing::Test gzip_encoder_rejects_reuse_after_finish() +{ + auto deflater = Deflater::create_gzip(); + Void::Testing::require(deflater.has_value()); + std::string out; + Void::Testing::require(deflater->finish(out).has_value()); + Void::Testing::expect(!deflater->finish(out).has_value()); + Void::Testing::expect(!deflater->feed({}, out).has_value()); +} + +Void::Testing::Test gzip_stored_encoder_round_trips() +{ + for (const std::size_t size : {0U, 1U, 1000U, 65535U, 65536U, 200000U}) { + std::string data(size, '\0'); + for (std::size_t i = 0; i < size; ++i) { + data[i] = static_cast((i * 31 + 7) & 0xFF); + } + for (const bool gzip : {true, false}) { + auto deflater = + gzip ? Deflater::create_gzip() : Deflater::create_deflate(); + Void::Testing::require(deflater.has_value()); + std::string encoded; + for (std::size_t pos = 0; pos < data.size(); pos += 1000) { + const std::size_t count = + std::min(1000, data.size() - pos); + const auto chunk = std::span{ + reinterpret_cast(data.data()) + pos, count}; + Void::Testing::require( + deflater->feed(chunk, encoded).has_value()); + } + Void::Testing::require(deflater->finish(encoded).has_value()); + + const auto bytes = std::span{ + reinterpret_cast(encoded.data()), + encoded.size()}; + auto inflated = inflate_all(gzip, bytes, 777); + Void::Testing::require(inflated.has_value()); + Void::Testing::expect_eq(*inflated, data); + } + } +} + +Void::Testing::Test gzip_enforces_the_output_limit() +{ + const auto bytes = from_hex(kHelloGz); + auto limited = inflate_all(true, bytes, 0, + GzipLimits{.max_output_bytes = 4}); + Void::Testing::expect(!limited.has_value()); +}