| ... | ... | @@ -1,332 +1,2550 @@ |
| 1 | | //! Default compression algorithm. Has two steps: tokenization and token |
| 2 | | //! encoding. |
| 1 | //! Allocates statically ~224K (128K lookup, 96K tokens). |
| 3 | 2 | //! |
| 4 | | //! Tokenization takes uncompressed input stream and produces list of tokens. |
| 5 | | //! Each token can be literal (byte of data) or match (backrefernce to previous |
| 6 | | //! data with length and distance). Tokenization accumulators 32K tokens, when |
| 7 | | //! full or `flush` is called tokens are passed to the `block_writer`. Level |
| 8 | | //! defines how hard (how slow) it tries to find match. |
| 9 | | //! |
| 10 | | //! Block writer will decide which type of deflate block to write (stored, fixed, |
| 11 | | //! dynamic) and encode tokens to the output byte stream. Client has to call |
| 12 | | //! `finish` to write block with the final bit set. |
| 13 | | //! |
| 14 | | //! Container defines type of header and footer which can be gzip, zlib or raw. |
| 15 | | //! They all share same deflate body. Raw has no header or footer just deflate |
| 16 | | //! body. |
| 17 | | //! |
| 18 | | //! Compression algorithm explained in rfc-1951 (slightly edited for this case): |
| 19 | | //! |
| 20 | | //! The compressor uses a chained hash table `lookup` to find duplicated |
| 21 | | //! strings, using a hash function that operates on 4-byte sequences. At any |
| 22 | | //! given point during compression, let XYZW be the next 4 input bytes |
| 23 | | //! (lookahead) to be examined (not necessarily all different, of course). |
| 24 | | //! First, the compressor examines the hash chain for XYZW. If the chain is |
| 25 | | //! empty, the compressor simply writes out X as a literal byte and advances |
| 26 | | //! one byte in the input. If the hash chain is not empty, indicating that the |
| 27 | | //! sequence XYZW (or, if we are unlucky, some other 4 bytes with the same |
| 28 | | //! hash function value) has occurred recently, the compressor compares all |
| 29 | | //! strings on the XYZW hash chain with the actual input data sequence |
| 30 | | //! starting at the current point, and selects the longest match. |
| 31 | | //! |
| 32 | | //! To improve overall compression, the compressor defers the selection of |
| 33 | | //! matches ("lazy matching"): after a match of length N has been found, the |
| 34 | | //! compressor searches for a longer match starting at the next input byte. If |
| 35 | | //! it finds a longer match, it truncates the previous match to a length of |
| 36 | | //! one (thus producing a single literal byte) and then emits the longer |
| 37 | | //! match. Otherwise, it emits the original match, and, as described above, |
| 38 | | //! advances N bytes before continuing. |
| 39 | | //! |
| 40 | | //! |
| 41 | | //! Allocates statically ~400K (192K lookup, 128K tokens, 64K window). |
| 3 | //! The source of an `error.WriteFailed` is always the backing writer. After an |
| 4 | //! `error.WriteFailed`, the `.writer` becomes `.failing` and is unrecoverable. |
| 5 | //! After a `flush`, the writer also becomes `.failing` since the stream has |
| 6 | //! been finished. This behavior also applies to `Raw` and `Huffman`. |
| 7 | |
| 8 | // Implementation details: |
| 9 | // A chained hash table is used to find matches. `drain` always preserves `flate.history_len` |
| 10 | // bytes to use as a history and avoids tokenizing the final bytes since they can be part of |
| 11 | // a longer match with unwritten bytes (unless it is a `flush`). The minimum match searched |
| 12 | // for is of length `seq_bytes`. If a match is made, a longer match is also checked for at |
| 13 | // the next byte (lazy matching) if the last match does not meet the `Options.lazy` threshold. |
| 14 | // |
| 15 | // Up to `block_token` tokens are accumalated in `buffered_tokens` and are outputted in |
| 16 | // `write_block` which determines the optimal block type and frequencies. |
| 42 | 17 | |
| 43 | 18 | const builtin = @import("builtin"); |
| 44 | 19 | const std = @import("std"); |
| 45 | | const assert = std.debug.assert; |
| 46 | | const testing = std.testing; |
| 47 | | const expect = testing.expect; |
| 48 | 20 | const mem = std.mem; |
| 49 | 21 | const math = std.math; |
| 50 | | const Writer = std.Io.Writer; |
| 22 | const assert = std.debug.assert; |
| 23 | const Io = std.Io; |
| 24 | const Writer = Io.Writer; |
| 51 | 25 | |
| 52 | 26 | const Compress = @This(); |
| 53 | | const Token = @import("Token.zig"); |
| 54 | | const BlockWriter = @import("BlockWriter.zig"); |
| 27 | const token = @import("token.zig"); |
| 55 | 28 | const flate = @import("../flate.zig"); |
| 56 | | const Container = flate.Container; |
| 57 | | const Lookup = @import("Lookup.zig"); |
| 58 | | const HuffmanEncoder = flate.HuffmanEncoder; |
| 59 | | const LiteralNode = HuffmanEncoder.LiteralNode; |
| 60 | | |
| 61 | | lookup: Lookup = .{}, |
| 62 | | tokens: Tokens = .{}, |
| 63 | | block_writer: BlockWriter, |
| 64 | | level: LevelArgs, |
| 65 | | hasher: Container.Hasher, |
| 66 | | writer: Writer, |
| 67 | | state: State, |
| 68 | 29 | |
| 69 | | // Match and literal at the previous position. |
| 70 | | // Used for lazy match finding in processWindow. |
| 71 | | prev_match: ?Token = null, |
| 72 | | prev_literal: ?u8 = null, |
| 30 | /// Until #104 is implemented, a ?u15 takes 4 bytes, which is unacceptable |
| 31 | /// as it doubles the size of this already massive structure. |
| 32 | /// |
| 33 | /// Also, there are no `to` / `from` methods because LLVM 21 does not |
| 34 | /// optimize away the conversion from and to `?u15`. |
| 35 | const PackedOptionalU15 = packed struct(u16) { |
| 36 | value: u15, |
| 37 | is_null: bool, |
| 73 | 38 | |
| 74 | | pub const State = enum { header, middle, ended }; |
| 39 | pub fn int(p: PackedOptionalU15) u16 { |
| 40 | return @bitCast(p); |
| 41 | } |
| 75 | 42 | |
| 76 | | /// Trades between speed and compression size. |
| 77 | | /// Starts with level 4: in [zlib](https://github.com/madler/zlib/blob/abd3d1a28930f89375d4b41408b39f6c1be157b2/deflate.c#L115C1-L117C43) |
| 78 | | /// levels 1-3 are using different algorithm to perform faster but with less |
| 79 | | /// compression. That is not implemented here. |
| 80 | | pub const Level = enum(u4) { |
| 81 | | level_4 = 4, |
| 82 | | level_5 = 5, |
| 83 | | level_6 = 6, |
| 84 | | level_7 = 7, |
| 85 | | level_8 = 8, |
| 86 | | level_9 = 9, |
| 87 | | |
| 88 | | fast = 0xb, |
| 89 | | default = 0xc, |
| 90 | | best = 0xd, |
| 43 | pub const null_bit: PackedOptionalU15 = .{ .value = 0, .is_null = true }; |
| 91 | 44 | }; |
| 92 | 45 | |
| 93 | | /// Number of tokens to accumulate in deflate before starting block encoding. |
| 94 | | /// |
| 95 | | /// In zlib this depends on memlevel: 6 + memlevel, where default memlevel is |
| 96 | | /// 8 and max 9 that gives 14 or 15 bits. |
| 97 | | pub const n_tokens = 1 << 15; |
| 98 | | |
| 99 | | /// Algorithm knobs for each level. |
| 100 | | const LevelArgs = struct { |
| 101 | | good: u16, // Do less lookups if we already have match of this length. |
| 102 | | nice: u16, // Stop looking for better match if we found match with at least this length. |
| 103 | | lazy: u16, // Don't do lazy match find if got match with at least this length. |
| 104 | | chain: u16, // How many lookups for previous match to perform. |
| 105 | | |
| 106 | | pub fn get(level: Level) LevelArgs { |
| 107 | | return switch (level) { |
| 108 | | .fast, .level_4 => .{ .good = 4, .lazy = 4, .nice = 16, .chain = 16 }, |
| 109 | | .level_5 => .{ .good = 8, .lazy = 16, .nice = 32, .chain = 32 }, |
| 110 | | .default, .level_6 => .{ .good = 8, .lazy = 16, .nice = 128, .chain = 128 }, |
| 111 | | .level_7 => .{ .good = 8, .lazy = 32, .nice = 128, .chain = 256 }, |
| 112 | | .level_8 => .{ .good = 32, .lazy = 128, .nice = 258, .chain = 1024 }, |
| 113 | | .best, .level_9 => .{ .good = 32, .lazy = 258, .nice = 258, .chain = 4096 }, |
| 46 | /// After `flush` is called, all vtable calls with result in `error.WriteFailed.` |
| 47 | writer: Writer, |
| 48 | has_history: bool, |
| 49 | bit_writer: BitWriter, |
| 50 | buffered_tokens: struct { |
| 51 | /// List of `TokenBufferEntryHeader`s and their trailing data. |
| 52 | list: [@as(usize, block_tokens) * 3]u8, |
| 53 | pos: u32, |
| 54 | n: u16, |
| 55 | lit_freqs: [286]u16, |
| 56 | dist_freqs: [30]u16, |
| 57 | |
| 58 | pub const empty: @This() = .{ |
| 59 | .list = undefined, |
| 60 | .pos = 0, |
| 61 | .n = 0, |
| 62 | .lit_freqs = @splat(0), |
| 63 | .dist_freqs = @splat(0), |
| 64 | }; |
| 65 | }, |
| 66 | lookup: struct { |
| 67 | /// Indexes are the hashes of four-bytes sequences. |
| 68 | /// |
| 69 | /// Values are the positions in `chain` of the previous four bytes with the same hash. |
| 70 | head: [1 << lookup_hash_bits]PackedOptionalU15, |
| 71 | /// Values are the non-zero number of bytes backwards in the history with the same hash. |
| 72 | /// |
| 73 | /// The relationship of chain indexes and bytes relative to the latest history byte is |
| 74 | /// `chain_pos -% chain_index = history_index`. |
| 75 | chain: [32768]PackedOptionalU15, |
| 76 | /// The index in `chain` which is of the newest byte of the history. |
| 77 | chain_pos: u15, |
| 78 | }, |
| 79 | container: flate.Container, |
| 80 | hasher: flate.Container.Hasher, |
| 81 | opts: Options, |
| 82 | |
| 83 | const BitWriter = struct { |
| 84 | output: *Writer, |
| 85 | buffered: u7, |
| 86 | buffered_n: u3, |
| 87 | |
| 88 | pub fn init(w: *Writer) BitWriter { |
| 89 | return .{ |
| 90 | .output = w, |
| 91 | .buffered = 0, |
| 92 | .buffered_n = 0, |
| 114 | 93 | }; |
| 115 | 94 | } |
| 95 | |
| 96 | /// Asserts `bits` is zero-extended |
| 97 | pub fn write(b: *BitWriter, bits: u56, n: u6) Writer.Error!void { |
| 98 | assert(@as(u8, b.buffered) >> b.buffered_n == 0); |
| 99 | assert(@as(u57, bits) >> n == 0); // n may be 56 so u57 is needed |
| 100 | const combined = @shlExact(@as(u64, bits), b.buffered_n) | b.buffered; |
| 101 | const combined_bits = @as(u6, b.buffered_n) + n; |
| 102 | |
| 103 | const out = try b.output.writableSliceGreedy(8); |
| 104 | mem.writeInt(u64, out[0..8], combined, .little); |
| 105 | b.output.advance(combined_bits / 8); |
| 106 | |
| 107 | b.buffered_n = @truncate(combined_bits); |
| 108 | b.buffered = @intCast(combined >> (combined_bits - b.buffered_n)); |
| 109 | } |
| 110 | |
| 111 | /// Assserts one byte can be written to `b.otuput` without rebasing. |
| 112 | pub fn byteAlign(b: *BitWriter) void { |
| 113 | b.output.unusedCapacitySlice()[0] = b.buffered; |
| 114 | b.output.advance(@intFromBool(b.buffered_n != 0)); |
| 115 | b.buffered = 0; |
| 116 | b.buffered_n = 0; |
| 117 | } |
| 118 | |
| 119 | pub fn writeClen( |
| 120 | b: *BitWriter, |
| 121 | hclen: u4, |
| 122 | clen_values: []u8, |
| 123 | clen_extra: []u8, |
| 124 | clen_codes: [19]u16, |
| 125 | clen_bits: [19]u4, |
| 126 | ) Writer.Error!void { |
| 127 | // Write the first four clen entries seperately since they are always present, |
| 128 | // and writing them all at once takes too many bits. |
| 129 | try b.write(clen_bits[token.codegen_order[0]] | |
| 130 | @shlExact(@as(u6, clen_bits[token.codegen_order[1]]), 3) | |
| 131 | @shlExact(@as(u9, clen_bits[token.codegen_order[2]]), 6) | |
| 132 | @shlExact(@as(u12, clen_bits[token.codegen_order[3]]), 9), 12); |
| 133 | |
| 134 | var i = hclen; |
| 135 | var clen_bits_table: u45 = 0; |
| 136 | while (i != 0) { |
| 137 | i -= 1; |
| 138 | clen_bits_table <<= 3; |
| 139 | clen_bits_table |= clen_bits[token.codegen_order[4..][i]]; |
| 140 | } |
| 141 | try b.write(clen_bits_table, @as(u6, hclen) * 3); |
| 142 | |
| 143 | for (clen_values, clen_extra) |value, extra| { |
| 144 | try b.write( |
| 145 | clen_codes[value] | @shlExact(@as(u16, extra), clen_bits[value]), |
| 146 | clen_bits[value] + @as(u3, switch (value) { |
| 147 | 0...15 => 0, |
| 148 | 16 => 2, |
| 149 | 17 => 3, |
| 150 | 18 => 7, |
| 151 | else => unreachable, |
| 152 | }), |
| 153 | ); |
| 154 | } |
| 155 | } |
| 156 | }; |
| 157 | |
| 158 | /// Number of tokens to accumulate before outputing as a block. |
| 159 | /// The maximum value is `math.maxInt(u16) - 1` since one token is reserved for end-of-block. |
| 160 | const block_tokens: u16 = 1 << 15; |
| 161 | const lookup_hash_bits = 15; |
| 162 | const Hash = u16; // `u[lookup_hash_bits]` is not used due to worse optimization (with LLVM 21) |
| 163 | const seq_bytes = 3; // not intended to be changed |
| 164 | const Seq = std.meta.Int(.unsigned, seq_bytes * 8); |
| 165 | |
| 166 | const TokenBufferEntryHeader = packed struct(u16) { |
| 167 | kind: enum(u1) { |
| 168 | /// Followed by non-zero `data` byte literals. |
| 169 | bytes, |
| 170 | /// Followed by the length as a byte |
| 171 | match, |
| 172 | }, |
| 173 | data: u15, |
| 174 | }; |
| 175 | |
| 176 | const BlockHeader = packed struct(u3) { |
| 177 | final: bool, |
| 178 | kind: enum(u2) { stored, fixed, dynamic, _ }, |
| 179 | |
| 180 | pub fn int(h: BlockHeader) u3 { |
| 181 | return @bitCast(h); |
| 182 | } |
| 183 | |
| 184 | pub const Dynamic = packed struct(u17) { |
| 185 | regular: BlockHeader, |
| 186 | hlit: u5, |
| 187 | hdist: u5, |
| 188 | hclen: u4, |
| 189 | |
| 190 | pub fn int(h: Dynamic) u17 { |
| 191 | return @bitCast(h); |
| 192 | } |
| 193 | }; |
| 116 | 194 | }; |
| 117 | 195 | |
| 196 | fn outputMatch(c: *Compress, dist: u15, len: u8) Writer.Error!void { |
| 197 | // This must come first. Instead of ensuring a full block is never left buffered, |
| 198 | // draining it is defered to allow end of stream to be indicated. |
| 199 | if (c.buffered_tokens.n == block_tokens) { |
| 200 | @branchHint(.unlikely); // LLVM 21 optimizes this branch as the more likely without |
| 201 | try c.writeBlock(false); |
| 202 | } |
| 203 | const header: TokenBufferEntryHeader = .{ .kind = .match, .data = dist }; |
| 204 | c.buffered_tokens.list[c.buffered_tokens.pos..][0..2].* = @bitCast(header); |
| 205 | c.buffered_tokens.list[c.buffered_tokens.pos + 2] = len; |
| 206 | c.buffered_tokens.pos += 3; |
| 207 | c.buffered_tokens.n += 1; |
| 208 | |
| 209 | c.buffered_tokens.lit_freqs[@as(usize, 257) + token.LenCode.fromVal(len).toInt()] += 1; |
| 210 | c.buffered_tokens.dist_freqs[token.DistCode.fromVal(dist).toInt()] += 1; |
| 211 | } |
| 212 | |
| 213 | fn outputBytes(c: *Compress, bytes: []const u8) Writer.Error!void { |
| 214 | var remaining = bytes; |
| 215 | while (remaining.len != 0) { |
| 216 | if (c.buffered_tokens.n == block_tokens) { |
| 217 | @branchHint(.unlikely); // LLVM 21 optimizes this branch as the more likely without |
| 218 | try c.writeBlock(false); |
| 219 | } |
| 220 | |
| 221 | const n = @min(remaining.len, block_tokens - c.buffered_tokens.n, math.maxInt(u15)); |
| 222 | assert(n != 0); |
| 223 | const header: TokenBufferEntryHeader = .{ .kind = .bytes, .data = n }; |
| 224 | c.buffered_tokens.list[c.buffered_tokens.pos..][0..2].* = @bitCast(header); |
| 225 | @memcpy(c.buffered_tokens.list[c.buffered_tokens.pos + 2 ..][0..n], remaining[0..n]); |
| 226 | c.buffered_tokens.pos += @as(u32, 2) + n; |
| 227 | c.buffered_tokens.n += n; |
| 228 | |
| 229 | for (remaining[0..n]) |b| { |
| 230 | c.buffered_tokens.lit_freqs[b] += 1; |
| 231 | } |
| 232 | remaining = remaining[n..]; |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | fn hash(x: u32) Hash { |
| 237 | return @intCast((x *% 0x9E3779B1) >> (32 - lookup_hash_bits)); |
| 238 | } |
| 239 | |
| 240 | /// Trades between speed and compression size. |
| 241 | /// |
| 242 | /// Default paramaters are [taken from zlib] |
| 243 | /// (https://github.com/madler/zlib/blob/v1.3.1/deflate.c#L112) |
| 118 | 244 | pub const Options = struct { |
| 119 | | level: Level = .default, |
| 120 | | container: Container = .raw, |
| 245 | /// Perform less lookups when a match of at least this length has been found. |
| 246 | good: u16, |
| 247 | /// Stop when a match of at least this length has been found. |
| 248 | nice: u16, |
| 249 | /// Don't attempt a lazy match find when a match of at least this length has been found. |
| 250 | lazy: u16, |
| 251 | /// Check this many previous locations with the same hash for longer matches. |
| 252 | chain: u16, |
| 253 | |
| 254 | // zig fmt: off |
| 255 | pub const level_1: Options = .{ .good = 4, .nice = 8, .lazy = 0, .chain = 4 }; |
| 256 | pub const level_2: Options = .{ .good = 4, .nice = 16, .lazy = 0, .chain = 8 }; |
| 257 | pub const level_3: Options = .{ .good = 4, .nice = 32, .lazy = 0, .chain = 32 }; |
| 258 | pub const level_4: Options = .{ .good = 4, .nice = 16, .lazy = 4, .chain = 16 }; |
| 259 | pub const level_5: Options = .{ .good = 8, .nice = 32, .lazy = 16, .chain = 32 }; |
| 260 | pub const level_6: Options = .{ .good = 8, .nice = 128, .lazy = 16, .chain = 128 }; |
| 261 | pub const level_7: Options = .{ .good = 8, .nice = 128, .lazy = 32, .chain = 256 }; |
| 262 | pub const level_8: Options = .{ .good = 32, .nice = 258, .lazy = 128, .chain = 1024 }; |
| 263 | pub const level_9: Options = .{ .good = 32, .nice = 258, .lazy = 258, .chain = 4096 }; |
| 264 | // zig fmt: on |
| 265 | pub const fastest = level_1; |
| 266 | pub const default = level_6; |
| 267 | pub const best = level_9; |
| 121 | 268 | }; |
| 122 | 269 | |
| 123 | | pub fn init(output: *Writer, buffer: []u8, options: Options) Compress { |
| 270 | /// It is asserted `buffer` is least `flate.max_history_len` bytes. |
| 271 | /// It is asserted `output` has a capacity of at least 8 bytes. |
| 272 | pub fn init( |
| 273 | output: *Writer, |
| 274 | buffer: []u8, |
| 275 | container: flate.Container, |
| 276 | opts: Options, |
| 277 | ) Writer.Error!Compress { |
| 278 | assert(output.buffer.len > 8); |
| 279 | assert(buffer.len >= flate.max_window_len); |
| 280 | |
| 281 | // note that disallowing some of these simplifies matching logic |
| 282 | assert(opts.chain != 0); // use `Huffman`, disallowing this simplies matching |
| 283 | assert(opts.good >= 3 and opts.nice >= 3); // a match will (usually) not be found |
| 284 | assert(opts.good <= 258 and opts.nice <= 258); // a longer match will not be found |
| 285 | assert(opts.lazy <= opts.nice); // a longer match will (usually) not be found |
| 286 | if (opts.good <= opts.lazy) assert(opts.chain >= 1 << 2); // chain can be reduced to zero |
| 287 | |
| 288 | try output.writeAll(container.header()); |
| 124 | 289 | return .{ |
| 125 | | .block_writer = .init(output), |
| 126 | | .level = .get(options.level), |
| 127 | | .hasher = .init(options.container), |
| 128 | | .state = .header, |
| 129 | 290 | .writer = .{ |
| 130 | 291 | .buffer = buffer, |
| 131 | | .vtable = &.{ .drain = drain }, |
| 292 | .vtable = &.{ |
| 293 | .drain = drain, |
| 294 | .flush = flush, |
| 295 | .rebase = rebase, |
| 296 | }, |
| 297 | }, |
| 298 | .has_history = false, |
| 299 | .bit_writer = .init(output), |
| 300 | .buffered_tokens = .empty, |
| 301 | .lookup = .{ |
| 302 | // init `value` is max so there is 0xff pattern |
| 303 | .head = @splat(.{ .value = math.maxInt(u15), .is_null = true }), |
| 304 | .chain = undefined, |
| 305 | .chain_pos = math.maxInt(u15), |
| 132 | 306 | }, |
| 307 | .container = container, |
| 308 | .opts = opts, |
| 309 | .hasher = .init(container), |
| 133 | 310 | }; |
| 134 | 311 | } |
| 135 | 312 | |
| 136 | | // Tokens store |
| 137 | | const Tokens = struct { |
| 138 | | list: [n_tokens]Token = undefined, |
| 139 | | pos: usize = 0, |
| 313 | fn drain(w: *Writer, data: []const []const u8, splat: usize) Writer.Error!usize { |
| 314 | errdefer w.* = .failing; |
| 315 | // There may have not been enough space in the buffer and the write was sent directly here. |
| 316 | // However, it is required that all data goes through the buffer to keep a history. |
| 317 | // |
| 318 | // Additionally, ensuring the buffer is always full ensures there is always a full history |
| 319 | // after. |
| 320 | const data_n = w.buffer.len - w.end; |
| 321 | _ = w.fixedDrain(data, splat) catch {}; |
| 322 | assert(w.end == w.buffer.len); |
| 323 | try rebaseInner(w, 0, 1, false); |
| 324 | return data_n; |
| 325 | } |
| 326 | |
| 327 | fn flush(w: *Writer) Writer.Error!void { |
| 328 | defer w.* = .failing; |
| 329 | const c: *Compress = @fieldParentPtr("writer", w); |
| 330 | try rebaseInner(w, 0, w.buffer.len - flate.history_len, true); |
| 331 | try c.bit_writer.output.rebase(0, 1); |
| 332 | c.bit_writer.byteAlign(); |
| 333 | try c.hasher.writeFooter(c.bit_writer.output); |
| 334 | } |
| 335 | |
| 336 | fn rebase(w: *Writer, preserve: usize, capacity: usize) Writer.Error!void { |
| 337 | return rebaseInner(w, preserve, capacity, false); |
| 338 | } |
| 339 | |
| 340 | pub const rebase_min_preserve = flate.history_len; |
| 341 | pub const rebase_reserved_capacity = (token.max_length + 1) + seq_bytes; |
| 342 | |
| 343 | fn rebaseInner(w: *Writer, preserve: usize, capacity: usize, eos: bool) Writer.Error!void { |
| 344 | if (!eos) { |
| 345 | assert(@max(preserve, rebase_min_preserve) + (capacity + rebase_reserved_capacity) <= w.buffer.len); |
| 346 | assert(w.end >= flate.history_len + rebase_reserved_capacity); // Above assert should |
| 347 | // fail since rebase is only called when `capacity` is not present. This assertion is |
| 348 | // important because a full history is required at the end. |
| 349 | } else { |
| 350 | assert(preserve == 0 and capacity == w.buffer.len - flate.history_len); |
| 351 | } |
| 352 | |
| 353 | const c: *Compress = @fieldParentPtr("writer", w); |
| 354 | const buffered = w.buffered(); |
| 355 | |
| 356 | const start = @as(usize, flate.history_len) * @intFromBool(c.has_history); |
| 357 | const lit_end: usize = if (!eos) |
| 358 | buffered.len - rebase_reserved_capacity - (preserve -| flate.history_len) |
| 359 | else |
| 360 | buffered.len -| (seq_bytes - 1); |
| 361 | |
| 362 | var i = start; |
| 363 | var last_unmatched = i; |
| 364 | // Read from `w.buffer` instead of `buffered` since the latter may not |
| 365 | // have enough bytes. If this is the case, this variable is not used. |
| 366 | var seq: Seq = mem.readInt( |
| 367 | std.meta.Int(.unsigned, (seq_bytes - 1) * 8), |
| 368 | w.buffer[i..][0 .. seq_bytes - 1], |
| 369 | .big, |
| 370 | ); |
| 371 | if (buffered[i..].len < seq_bytes - 1) { |
| 372 | @branchHint(.unlikely); |
| 373 | assert(eos); |
| 374 | seq = undefined; |
| 375 | assert(i >= lit_end); |
| 376 | } |
| 377 | |
| 378 | while (i < lit_end) { |
| 379 | var match_start = i; |
| 380 | seq <<= 8; |
| 381 | seq |= buffered[i + (seq_bytes - 1)]; |
| 382 | var match = c.matchAndAddHash(i, hash(seq), token.min_length - 1, c.opts.chain, c.opts.good); |
| 383 | i += 1; |
| 384 | if (match.len < token.min_length) continue; |
| 385 | |
| 386 | var match_unadded = match.len - 1; |
| 387 | lazy: { |
| 388 | if (match.len >= c.opts.lazy) break :lazy; |
| 389 | if (match.len >= c.writer.buffered()[i..].len) { |
| 390 | @branchHint(.unlikely); // Only end of stream |
| 391 | break :lazy; |
| 392 | } |
| 140 | 393 | |
| 141 | | fn add(self: *Tokens, t: Token) void { |
| 142 | | self.list[self.pos] = t; |
| 143 | | self.pos += 1; |
| 394 | var chain = c.opts.chain; |
| 395 | var good = c.opts.good; |
| 396 | if (match.len >= good) { |
| 397 | chain >>= 2; |
| 398 | good = math.maxInt(u8); // Reduce only once |
| 399 | } |
| 400 | |
| 401 | seq <<= 8; |
| 402 | seq |= buffered[i + (seq_bytes - 1)]; |
| 403 | const lazy = c.matchAndAddHash(i, hash(seq), match.len, chain, good); |
| 404 | match_unadded -= 1; |
| 405 | i += 1; |
| 406 | |
| 407 | if (lazy.len > match.len) { |
| 408 | match_start += 1; |
| 409 | match = lazy; |
| 410 | match_unadded = match.len - 1; |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | assert(i + match_unadded == match_start + match.len); |
| 415 | assert(mem.eql( |
| 416 | u8, |
| 417 | buffered[match_start..][0..match.len], |
| 418 | buffered[match_start - 1 - match.dist ..][0..match.len], |
| 419 | )); // This assert also seems to help codegen. |
| 420 | |
| 421 | try c.outputBytes(buffered[last_unmatched..match_start]); |
| 422 | try c.outputMatch(@intCast(match.dist), @intCast(match.len - 3)); |
| 423 | |
| 424 | last_unmatched = match_start + match.len; |
| 425 | if (last_unmatched + seq_bytes >= w.end) { |
| 426 | @branchHint(.unlikely); |
| 427 | assert(eos); |
| 428 | i = undefined; |
| 429 | break; |
| 430 | } |
| 431 | |
| 432 | while (true) { |
| 433 | seq <<= 8; |
| 434 | seq |= buffered[i + (seq_bytes - 1)]; |
| 435 | _ = c.addHash(i, hash(seq)); |
| 436 | i += 1; |
| 437 | |
| 438 | match_unadded -= 1; |
| 439 | if (match_unadded == 0) break; |
| 440 | } |
| 441 | assert(i == match_start + match.len); |
| 144 | 442 | } |
| 145 | 443 | |
| 146 | | fn full(self: *Tokens) bool { |
| 147 | | return self.pos == self.list.len; |
| 444 | if (eos) { |
| 445 | i = undefined; // (from match hashing logic) |
| 446 | try c.outputBytes(buffered[last_unmatched..]); |
| 447 | c.hasher.update(buffered[start..]); |
| 448 | try c.writeBlock(true); |
| 449 | return; |
| 148 | 450 | } |
| 149 | 451 | |
| 150 | | fn reset(self: *Tokens) void { |
| 151 | | self.pos = 0; |
| 452 | try c.outputBytes(buffered[last_unmatched..i]); |
| 453 | c.hasher.update(buffered[start..i]); |
| 454 | |
| 455 | const preserved = buffered[i - flate.history_len ..]; |
| 456 | assert(preserved.len > @max(rebase_min_preserve, preserve)); |
| 457 | @memmove(w.buffer[0..preserved.len], preserved); |
| 458 | w.end = preserved.len; |
| 459 | c.has_history = true; |
| 460 | } |
| 461 | |
| 462 | fn addHash(c: *Compress, i: usize, h: Hash) void { |
| 463 | assert(h == hash(mem.readInt(Seq, c.writer.buffer[i..][0..seq_bytes], .big))); |
| 464 | |
| 465 | const l = &c.lookup; |
| 466 | l.chain_pos +%= 1; |
| 467 | |
| 468 | // Equivilent to the below, however LLVM 21 does not optimize `@subWithOverflow` well at all. |
| 469 | // const replaced_i, const no_replace = @subWithOverflow(i, flate.history_len); |
| 470 | // if (no_replace == 0) { |
| 471 | if (i >= flate.history_len) { |
| 472 | @branchHint(.likely); |
| 473 | const replaced_i = i - flate.history_len; |
| 474 | // The following is the same as the below except uses a 32-bit load to help optimizations |
| 475 | // const replaced_seq = mem.readInt(Seq, c.writer.buffer[replaced_i..][0..seq_bytes], .big); |
| 476 | comptime assert(@sizeOf(Seq) <= @sizeOf(u32)); |
| 477 | const replaced_u32 = mem.readInt(u32, c.writer.buffered()[replaced_i..][0..4], .big); |
| 478 | const replaced_seq: Seq = @intCast(replaced_u32 >> (32 - @bitSizeOf(Seq))); |
| 479 | |
| 480 | const replaced_h = hash(replaced_seq); |
| 481 | // The following is equivilent to the below since LLVM 21 doesn't optimize it well. |
| 482 | // l.head[replaced_h].is_null = l.head[replaced_h].is_null or |
| 483 | // l.head[replaced_h].int() == l.chain_pos; |
| 484 | const empty_head = l.head[replaced_h].int() == l.chain_pos; |
| 485 | const null_flag = PackedOptionalU15.int(.{ .is_null = empty_head, .value = 0 }); |
| 486 | l.head[replaced_h] = @bitCast(l.head[replaced_h].int() | null_flag); |
| 152 | 487 | } |
| 153 | 488 | |
| 154 | | fn tokens(self: *Tokens) []const Token { |
| 155 | | return self.list[0..self.pos]; |
| 489 | const prev_chain_index = l.head[h]; |
| 490 | l.chain[l.chain_pos] = @bitCast((l.chain_pos -% prev_chain_index.value) | |
| 491 | (prev_chain_index.int() & PackedOptionalU15.null_bit.int())); // Preserves null |
| 492 | l.head[h] = .{ .value = l.chain_pos, .is_null = false }; |
| 493 | } |
| 494 | |
| 495 | /// If the match is shorter, the returned value can be any value `<= old`. |
| 496 | fn betterMatchLen(old: u16, prev: []const u8, bytes: []const u8) u16 { |
| 497 | assert(old < @min(bytes.len, token.max_length)); |
| 498 | assert(prev.len >= bytes.len); |
| 499 | assert(bytes.len >= token.min_length); |
| 500 | |
| 501 | var i: u16 = 0; |
| 502 | const Block = std.meta.Int(.unsigned, @min(math.divCeil( |
| 503 | comptime_int, |
| 504 | math.ceilPowerOfTwoAssert(usize, @bitSizeOf(usize)), |
| 505 | 8, |
| 506 | ) catch unreachable, 256) * 8); |
| 507 | |
| 508 | if (bytes.len < token.max_length) { |
| 509 | @branchHint(.unlikely); // Only end of stream |
| 510 | |
| 511 | while (bytes[i..].len >= @sizeOf(Block)) { |
| 512 | const a = mem.readInt(Block, prev[i..][0..@sizeOf(Block)], .little); |
| 513 | const b = mem.readInt(Block, bytes[i..][0..@sizeOf(Block)], .little); |
| 514 | const diff = a ^ b; |
| 515 | if (diff != 0) { |
| 516 | @branchHint(.likely); |
| 517 | i += @ctz(diff) / 8; |
| 518 | return i; |
| 519 | } |
| 520 | i += @sizeOf(Block); |
| 521 | } |
| 522 | |
| 523 | while (i != bytes.len and prev[i] == bytes[i]) { |
| 524 | i += 1; |
| 525 | } |
| 526 | assert(i < token.max_length); |
| 527 | return i; |
| 156 | 528 | } |
| 157 | | }; |
| 158 | 529 | |
| 159 | | fn drain(me: *Writer, data: []const []const u8, splat: usize) Writer.Error!usize { |
| 160 | | _ = data; |
| 161 | | _ = splat; |
| 162 | | const c: *Compress = @fieldParentPtr("writer", me); |
| 163 | | const out = c.block_writer.output; |
| 164 | | switch (c.state) { |
| 165 | | .header => { |
| 166 | | c.state = .middle; |
| 167 | | const header = c.hasher.container().header(); |
| 168 | | try out.writeAll(header); |
| 169 | | return header.len; |
| 170 | | }, |
| 171 | | .middle => {}, |
| 172 | | .ended => unreachable, |
| 530 | if (old >= @sizeOf(Block)) { |
| 531 | // Check that a longer end is present, otherwise the match is always worse |
| 532 | const a = mem.readInt(Block, prev[old + 1 - @sizeOf(Block) ..][0..@sizeOf(Block)], .little); |
| 533 | const b = mem.readInt(Block, bytes[old + 1 - @sizeOf(Block) ..][0..@sizeOf(Block)], .little); |
| 534 | if (a != b) return i; |
| 535 | } |
| 536 | |
| 537 | while (true) { |
| 538 | const a = mem.readInt(Block, prev[i..][0..@sizeOf(Block)], .little); |
| 539 | const b = mem.readInt(Block, bytes[i..][0..@sizeOf(Block)], .little); |
| 540 | const diff = a ^ b; |
| 541 | if (diff != 0) { |
| 542 | i += @ctz(diff) / 8; |
| 543 | return i; |
| 544 | } |
| 545 | i += @sizeOf(Block); |
| 546 | if (i == 256) break; |
| 547 | } |
| 548 | |
| 549 | const a = mem.readInt(u16, prev[i..][0..2], .little); |
| 550 | const b = mem.readInt(u16, bytes[i..][0..2], .little); |
| 551 | const diff = a ^ b; |
| 552 | i += @ctz(diff) / 8; |
| 553 | assert(i <= token.max_length); |
| 554 | return i; |
| 555 | } |
| 556 | |
| 557 | test betterMatchLen { |
| 558 | try std.testing.fuzz({}, testFuzzedMatchLen, .{}); |
| 559 | } |
| 560 | |
| 561 | fn testFuzzedMatchLen(_: void, input: []const u8) !void { |
| 562 | @disableInstrumentation(); |
| 563 | var r: Io.Reader = .fixed(input); |
| 564 | var buf: [1024]u8 = undefined; |
| 565 | var w: Writer = .fixed(&buf); |
| 566 | var old = r.takeLeb128(u9) catch 0; |
| 567 | var bytes_off = @max(1, r.takeLeb128(u10) catch 258); |
| 568 | const prev_back = @max(1, r.takeLeb128(u10) catch 258); |
| 569 | |
| 570 | while (r.takeByte()) |byte| { |
| 571 | const op: packed struct(u8) { |
| 572 | kind: enum(u2) { splat, copy, insert_imm, insert }, |
| 573 | imm: u6, |
| 574 | |
| 575 | pub fn immOrByte(op_s: @This(), r_s: *Io.Reader) usize { |
| 576 | return if (op_s.imm == 0) op_s.imm else @as(usize, r_s.takeByte() catch 0) + 64; |
| 577 | } |
| 578 | } = @bitCast(byte); |
| 579 | (switch (op.kind) { |
| 580 | .splat => w.splatByteAll(r.takeByte() catch 0, op.immOrByte(&r)), |
| 581 | .copy => write: { |
| 582 | const start = w.buffered().len -| op.immOrByte(&r); |
| 583 | const len = @min(w.buffered().len - start, r.takeByte() catch 3); |
| 584 | break :write w.writeAll(w.buffered()[start..][0..len]); |
| 585 | }, |
| 586 | .insert_imm => w.writeByte(op.imm), |
| 587 | .insert => w.writeAll(r.take( |
| 588 | @min(r.bufferedLen(), @as(usize, op.imm) + 1), |
| 589 | ) catch unreachable), |
| 590 | }) catch break; |
| 591 | } else |_| {} |
| 592 | |
| 593 | w.splatByteAll(0, (1 + 3) -| w.buffered().len) catch unreachable; |
| 594 | bytes_off = @min(bytes_off, @as(u10, @intCast(w.buffered().len - 3))); |
| 595 | const prev_off = bytes_off -| prev_back; |
| 596 | assert(prev_off < bytes_off); |
| 597 | const prev = w.buffered()[prev_off..]; |
| 598 | const bytes = w.buffered()[bytes_off..]; |
| 599 | old = @min(old, bytes.len - 1, token.max_length - 1); |
| 600 | |
| 601 | const diff_index = mem.indexOfDiff(u8, prev, bytes).?; // unwrap since lengths are not same |
| 602 | const expected_len = @min(diff_index, 258); |
| 603 | errdefer std.debug.print( |
| 604 | \\prev : '{any}' |
| 605 | \\bytes: '{any}' |
| 606 | \\old : {} |
| 607 | \\expected: {?} |
| 608 | \\actual : {} |
| 609 | ++ "\n", .{ |
| 610 | prev, bytes, old, |
| 611 | if (old < expected_len) expected_len else null, betterMatchLen(old, prev, bytes), |
| 612 | }); |
| 613 | if (old < expected_len) { |
| 614 | try std.testing.expectEqual(expected_len, betterMatchLen(old, prev, bytes)); |
| 615 | } else { |
| 616 | try std.testing.expect(betterMatchLen(old, prev, bytes) <= old); |
| 617 | } |
| 618 | } |
| 619 | |
| 620 | fn matchAndAddHash(c: *Compress, i: usize, h: Hash, gt: u16, max_chain: u16, good_: u16) struct { |
| 621 | dist: u16, |
| 622 | len: u16, |
| 623 | } { |
| 624 | const l = &c.lookup; |
| 625 | const buffered = c.writer.buffered(); |
| 626 | |
| 627 | var chain_limit = max_chain; |
| 628 | var best_dist: u16 = undefined; |
| 629 | var best_len = gt; |
| 630 | const nice = @min(c.opts.nice, buffered[i..].len); |
| 631 | var good = good_; |
| 632 | |
| 633 | search: { |
| 634 | if (l.head[h].is_null) break :search; |
| 635 | // Actually a u15, but LLVM 21 does not optimize that as well (it truncates it each use). |
| 636 | var dist: u16 = l.chain_pos -% l.head[h].value; |
| 637 | while (true) { |
| 638 | chain_limit -= 1; |
| 639 | |
| 640 | const match_len = betterMatchLen(best_len, buffered[i - 1 - dist ..], buffered[i..]); |
| 641 | if (match_len > best_len) { |
| 642 | best_dist = dist; |
| 643 | best_len = match_len; |
| 644 | if (best_len >= nice) break; |
| 645 | if (best_len >= good) { |
| 646 | chain_limit >>= 2; |
| 647 | good = math.maxInt(u8); // Reduce only once |
| 648 | } |
| 649 | } |
| 650 | |
| 651 | if (chain_limit == 0) break; |
| 652 | const next_chain_index = l.chain_pos -% @as(u15, @intCast(dist)); |
| 653 | // Equivilent to the below, however LLVM 21 optimizes the below worse. |
| 654 | // if (l.chain[next_chain_index].is_null) break; |
| 655 | // dist, const out_of_window = @addWithOverflow(dist, l.chain[next_chain_index].value); |
| 656 | // if (out_of_window == 1) break; |
| 657 | dist +%= l.chain[next_chain_index].int(); // wrapping for potential null bit |
| 658 | comptime assert(flate.history_len == PackedOptionalU15.int(.null_bit)); |
| 659 | // Also, doing >= flate.history_len gives worse codegen with LLVM 21. |
| 660 | if ((dist | l.chain[next_chain_index].int()) & flate.history_len != 0) break; |
| 661 | } |
| 662 | } |
| 663 | |
| 664 | c.addHash(i, h); |
| 665 | return .{ .dist = best_dist, .len = best_len }; |
| 666 | } |
| 667 | |
| 668 | fn clenHlen(freqs: [19]u16) u4 { |
| 669 | // Note that the first four codes (16, 17, 18, and 0) are always present. |
| 670 | if (builtin.mode != .ReleaseSmall and (std.simd.suggestVectorLength(u16) orelse 1) >= 8) { |
| 671 | const V = @Vector(16, u16); |
| 672 | const hlen_mul: V = comptime m: { |
| 673 | var hlen_mul: [16]u16 = undefined; |
| 674 | for (token.codegen_order[3..], 0..) |i, hlen| { |
| 675 | hlen_mul[i] = hlen; |
| 676 | } |
| 677 | break :m hlen_mul; |
| 678 | }; |
| 679 | const encoded = freqs[0..16].* != @as(V, @splat(0)); |
| 680 | return @intCast(@reduce(.Max, @intFromBool(encoded) * hlen_mul)); |
| 681 | } else { |
| 682 | var max: u4 = 0; |
| 683 | for (token.codegen_order[4..], 1..) |i, len| { |
| 684 | max = if (freqs[i] == 0) max else @intCast(len); |
| 685 | } |
| 686 | return max; |
| 687 | } |
| 688 | } |
| 689 | |
| 690 | test clenHlen { |
| 691 | var freqs: [19]u16 = @splat(0); |
| 692 | try std.testing.expectEqual(0, clenHlen(freqs)); |
| 693 | for (token.codegen_order, 1..) |i, len| { |
| 694 | freqs[i] = 1; |
| 695 | try std.testing.expectEqual(len -| 4, clenHlen(freqs)); |
| 696 | freqs[i] = 0; |
| 697 | } |
| 698 | } |
| 699 | |
| 700 | /// Returns the number of values followed by the bitsize of the extra bits. |
| 701 | fn buildClen( |
| 702 | dyn_bits: []const u4, |
| 703 | out_values: []u8, |
| 704 | out_extra: []u8, |
| 705 | out_freqs: *[19]u16, |
| 706 | ) struct { u16, u16 } { |
| 707 | assert(dyn_bits.len <= out_values.len); |
| 708 | assert(out_values.len == out_extra.len); |
| 709 | |
| 710 | var len: u16 = 0; |
| 711 | var extra_bitsize: u16 = 0; |
| 712 | |
| 713 | var remaining_bits = dyn_bits; |
| 714 | var prev: u4 = 0; |
| 715 | while (true) { |
| 716 | const b = remaining_bits[0]; |
| 717 | const n_max = @min(@as(u8, if (b != 0) |
| 718 | if (b != prev) 1 else 6 |
| 719 | else |
| 720 | 138), remaining_bits.len); |
| 721 | prev = b; |
| 722 | |
| 723 | var n: u8 = 0; |
| 724 | while (true) { |
| 725 | remaining_bits = remaining_bits[1..]; |
| 726 | n += 1; |
| 727 | if (n == n_max or remaining_bits[0] != b) break; |
| 728 | } |
| 729 | const code, const extra, const xsize = switch (n) { |
| 730 | 0 => unreachable, |
| 731 | 1...2 => .{ b, 0, 0 }, |
| 732 | 3...10 => .{ |
| 733 | @as(u8, 16) + @intFromBool(b == 0), |
| 734 | n - 3, |
| 735 | @as(u8, 2) + @intFromBool(b == 0), |
| 736 | }, |
| 737 | 11...138 => .{ 18, n - 11, 7 }, |
| 738 | else => unreachable, |
| 739 | }; |
| 740 | while (true) { |
| 741 | out_values[len] = code; |
| 742 | out_extra[len] = extra; |
| 743 | out_freqs[code] += 1; |
| 744 | extra_bitsize += xsize; |
| 745 | len += 1; |
| 746 | if (n != 2) { |
| 747 | @branchHint(.likely); |
| 748 | break; |
| 749 | } |
| 750 | // Code needs outputted once more |
| 751 | n = 1; |
| 752 | } |
| 753 | if (remaining_bits.len == 0) break; |
| 754 | } |
| 755 | |
| 756 | return .{ len, extra_bitsize }; |
| 757 | } |
| 758 | |
| 759 | test buildClen { |
| 760 | //dyn_bits: []u4, |
| 761 | //out_values: *[288 + 30]u8, |
| 762 | //out_extra: *[288 + 30]u8, |
| 763 | //out_freqs: *[19]u16, |
| 764 | //struct { u16, u16 } |
| 765 | var out_values: [288 + 30]u8 = undefined; |
| 766 | var out_extra: [288 + 30]u8 = undefined; |
| 767 | var out_freqs: [19]u16 = @splat(0); |
| 768 | const len, const extra_bitsize = buildClen(&([_]u4{ |
| 769 | 1, // A |
| 770 | 2, 2, // B |
| 771 | 3, 3, 3, // C |
| 772 | 4, 4, 4, 4, // D |
| 773 | 5, // E |
| 774 | 5, 5, 5, 5, 5, 5, // |
| 775 | 5, 5, 5, 5, 5, 5, |
| 776 | 5, 5, |
| 777 | 0, 1, // F |
| 778 | 0, 0, 1, // G |
| 779 | } ++ @as([138 + 10]u4, @splat(0)) // H |
| 780 | ), &out_values, &out_extra, &out_freqs); |
| 781 | try std.testing.expectEqualSlices(u8, &.{ |
| 782 | 1, // A |
| 783 | 2, 2, // B |
| 784 | 3, 3, 3, // C |
| 785 | 4, 16, // D |
| 786 | 5, 16, 16, 5, 5, // E |
| 787 | 0, 1, // F |
| 788 | 0, 0, 1, // G |
| 789 | 18, 17, // H |
| 790 | }, out_values[0..len]); |
| 791 | try std.testing.expectEqualSlices(u8, &.{ |
| 792 | 0, // A |
| 793 | 0, 0, // B |
| 794 | 0, 0, 0, // C |
| 795 | 0, (0), // D |
| 796 | 0, (3), (3), 0, 0, // E |
| 797 | 0, 0, // F |
| 798 | 0, 0, 0, // G |
| 799 | (127), (7), // H |
| 800 | }, out_extra[0..len]); |
| 801 | try std.testing.expectEqual(2 + 2 + 2 + 7 + 3, extra_bitsize); |
| 802 | try std.testing.expectEqualSlices(u16, &.{ |
| 803 | 3, 3, 2, 3, 1, 3, 0, 0, |
| 804 | 0, 0, 0, 0, 0, 0, 0, 0, |
| 805 | 3, 1, 1, |
| 806 | }, &out_freqs); |
| 807 | } |
| 808 | |
| 809 | fn writeBlock(c: *Compress, eos: bool) Writer.Error!void { |
| 810 | const toks = &c.buffered_tokens; |
| 811 | if (!eos) assert(toks.n == block_tokens); |
| 812 | assert(toks.lit_freqs[256] == 0); |
| 813 | toks.lit_freqs[256] = 1; |
| 814 | |
| 815 | var dyn_codes_buf: [286 + 30]u16 = undefined; |
| 816 | var dyn_bits_buf: [286 + 30]u4 = @splat(0); |
| 817 | |
| 818 | const dyn_lit_codes_bitsize, const dyn_last_lit = huffman.build( |
| 819 | &toks.lit_freqs, |
| 820 | dyn_codes_buf[0..286], |
| 821 | dyn_bits_buf[0..286], |
| 822 | 15, |
| 823 | true, |
| 824 | ); |
| 825 | const dyn_lit_len = @max(257, dyn_last_lit + 1); |
| 826 | |
| 827 | const dyn_dist_codes_bitsize, const dyn_last_dist = huffman.build( |
| 828 | &toks.dist_freqs, |
| 829 | dyn_codes_buf[dyn_lit_len..][0..30], |
| 830 | dyn_bits_buf[dyn_lit_len..][0..30], |
| 831 | 15, |
| 832 | true, |
| 833 | ); |
| 834 | const dyn_dist_len = @max(1, dyn_last_dist + 1); |
| 835 | |
| 836 | var clen_values: [288 + 30]u8 = undefined; |
| 837 | var clen_extra: [288 + 30]u8 = undefined; |
| 838 | var clen_freqs: [19]u16 = @splat(0); |
| 839 | const clen_len, const clen_extra_bitsize = buildClen( |
| 840 | dyn_bits_buf[0 .. dyn_lit_len + dyn_dist_len], |
| 841 | &clen_values, |
| 842 | &clen_extra, |
| 843 | &clen_freqs, |
| 844 | ); |
| 845 | |
| 846 | var clen_codes: [19]u16 = undefined; |
| 847 | var clen_bits: [19]u4 = @splat(0); |
| 848 | const clen_codes_bitsize, _ = huffman.build( |
| 849 | &clen_freqs, |
| 850 | &clen_codes, |
| 851 | &clen_bits, |
| 852 | 7, |
| 853 | false, |
| 854 | ); |
| 855 | const hclen = clenHlen(clen_freqs); |
| 856 | |
| 857 | const dynamic_bitsize = @as(u32, 14) + |
| 858 | (4 + @as(u6, hclen)) * 3 + clen_codes_bitsize + clen_extra_bitsize + |
| 859 | dyn_lit_codes_bitsize + dyn_dist_codes_bitsize; |
| 860 | const fixed_bitsize = n: { |
| 861 | const freq7 = 1; // eos |
| 862 | var freq8: u16 = 0; |
| 863 | var freq9: u16 = 0; |
| 864 | var freq12: u16 = 0; // 7 + 5 - match freqs always have corresponding 5-bit dist freq |
| 865 | var freq13: u16 = 0; // 8 + 5 |
| 866 | for (toks.lit_freqs[0..144]) |f| freq8 += f; |
| 867 | for (toks.lit_freqs[144..256]) |f| freq9 += f; |
| 868 | assert(toks.lit_freqs[256] == 1); |
| 869 | for (toks.lit_freqs[257..280]) |f| freq12 += f; |
| 870 | for (toks.lit_freqs[280..286]) |f| freq13 += f; |
| 871 | break :n @as(u32, freq7) * 7 + |
| 872 | @as(u32, freq8) * 8 + @as(u32, freq9) * 9 + |
| 873 | @as(u32, freq12) * 12 + @as(u32, freq13) * 13; |
| 874 | }; |
| 875 | |
| 876 | stored: { |
| 877 | for (toks.dist_freqs) |n| if (n != 0) break :stored; |
| 878 | // No need to check len frequencies since they each have a corresponding dist frequency |
| 879 | assert(for (toks.lit_freqs[257..]) |f| (if (f != 0) break false) else true); |
| 880 | |
| 881 | // No matches. If the stored size is smaller than the huffman-encoded version, it will be |
| 882 | // outputed in a store block. This is not done with matches since the original input would |
| 883 | // need to be stored since the window may slid, and it may also exceed 65535 bytes. This |
| 884 | // should be OK since most inputs with matches should be more compressable anyways. |
| 885 | const stored_align_bits = -%(c.bit_writer.buffered_n +% 3); |
| 886 | const stored_bitsize = stored_align_bits + @as(u32, 32) + @as(u32, toks.n) * 8; |
| 887 | if (@min(dynamic_bitsize, fixed_bitsize) < stored_bitsize) break :stored; |
| 888 | |
| 889 | try c.bit_writer.write(BlockHeader.int(.{ .kind = .stored, .final = eos }), 3); |
| 890 | try c.bit_writer.output.rebase(0, 5); |
| 891 | c.bit_writer.byteAlign(); |
| 892 | c.bit_writer.output.writeInt(u16, c.buffered_tokens.n, .little) catch unreachable; |
| 893 | c.bit_writer.output.writeInt(u16, ~c.buffered_tokens.n, .little) catch unreachable; |
| 894 | |
| 895 | // Relatively small buffer since regular draining will |
| 896 | // always consume slightly less than 2 << 15 bytes. |
| 897 | var vec_buf: [4][]const u8 = undefined; |
| 898 | var vec_n: usize = 0; |
| 899 | var i: usize = 0; |
| 900 | |
| 901 | assert(c.buffered_tokens.pos != 0); |
| 902 | while (i != c.buffered_tokens.pos) { |
| 903 | const h: TokenBufferEntryHeader = @bitCast(toks.list[i..][0..2].*); |
| 904 | assert(h.kind == .bytes); |
| 905 | |
| 906 | i += 2; |
| 907 | vec_buf[vec_n] = toks.list[i..][0..h.data]; |
| 908 | i += h.data; |
| 909 | |
| 910 | vec_n += 1; |
| 911 | if (i == c.buffered_tokens.pos or vec_n == vec_buf.len) { |
| 912 | try c.bit_writer.output.writeVecAll(vec_buf[0..vec_n]); |
| 913 | vec_n = 0; |
| 914 | } |
| 915 | } |
| 916 | |
| 917 | toks.* = .empty; |
| 918 | return; |
| 919 | } |
| 920 | |
| 921 | const lit_codes, const lit_bits, const dist_codes, const dist_bits = |
| 922 | if (dynamic_bitsize < fixed_bitsize) codes: { |
| 923 | try c.bit_writer.write(BlockHeader.Dynamic.int(.{ |
| 924 | .regular = .{ .final = eos, .kind = .dynamic }, |
| 925 | .hlit = @intCast(dyn_lit_len - 257), |
| 926 | .hdist = @intCast(dyn_dist_len - 1), |
| 927 | .hclen = hclen, |
| 928 | }), 17); |
| 929 | try c.bit_writer.writeClen( |
| 930 | hclen, |
| 931 | clen_values[0..clen_len], |
| 932 | clen_extra[0..clen_len], |
| 933 | clen_codes, |
| 934 | clen_bits, |
| 935 | ); |
| 936 | break :codes .{ |
| 937 | dyn_codes_buf[0..dyn_lit_len], |
| 938 | dyn_bits_buf[0..dyn_lit_len], |
| 939 | dyn_codes_buf[dyn_lit_len..][0..dyn_dist_len], |
| 940 | dyn_bits_buf[dyn_lit_len..][0..dyn_dist_len], |
| 941 | }; |
| 942 | } else codes: { |
| 943 | try c.bit_writer.write(BlockHeader.int(.{ .final = eos, .kind = .fixed }), 3); |
| 944 | break :codes .{ |
| 945 | &token.fixed_lit_codes, |
| 946 | &token.fixed_lit_bits, |
| 947 | &token.fixed_dist_codes, |
| 948 | &token.fixed_dist_bits, |
| 949 | }; |
| 950 | }; |
| 951 | |
| 952 | var i: usize = 0; |
| 953 | while (i != toks.pos) { |
| 954 | const h: TokenBufferEntryHeader = @bitCast(toks.list[i..][0..2].*); |
| 955 | i += 2; |
| 956 | if (h.kind == .bytes) { |
| 957 | for (toks.list[i..][0..h.data]) |b| { |
| 958 | try c.bit_writer.write(lit_codes[b], lit_bits[b]); |
| 959 | } |
| 960 | i += h.data; |
| 961 | } else { |
| 962 | const dist = h.data; |
| 963 | const len = toks.list[i]; |
| 964 | i += 1; |
| 965 | const dist_code = token.DistCode.fromVal(dist); |
| 966 | const len_code = token.LenCode.fromVal(len); |
| 967 | const dist_val = dist_code.toInt(); |
| 968 | const lit_val = @as(u16, 257) + len_code.toInt(); |
| 969 | |
| 970 | var out: u48 = lit_codes[lit_val]; |
| 971 | var out_bits: u6 = lit_bits[lit_val]; |
| 972 | out |= @shlExact(@as(u20, len - len_code.base()), @intCast(out_bits)); |
| 973 | out_bits += len_code.extraBits(); |
| 974 | |
| 975 | out |= @shlExact(@as(u35, dist_codes[dist_val]), out_bits); |
| 976 | out_bits += dist_bits[dist_val]; |
| 977 | out |= @shlExact(@as(u48, dist - dist_code.base()), out_bits); |
| 978 | out_bits += dist_code.extraBits(); |
| 979 | |
| 980 | try c.bit_writer.write(out, out_bits); |
| 981 | } |
| 982 | } |
| 983 | try c.bit_writer.write(lit_codes[256], lit_bits[256]); |
| 984 | |
| 985 | toks.* = .empty; |
| 986 | } |
| 987 | |
| 988 | /// Huffman tree construction. |
| 989 | /// |
| 990 | /// The approach for building the huffman tree is [taken from zlib] |
| 991 | /// (https://github.com/madler/zlib/blob/v1.3.1/trees.c#L625) with some modifications. |
| 992 | const huffman = struct { |
| 993 | const max_leafs = 286; |
| 994 | const max_nodes = max_leafs * 2; |
| 995 | |
| 996 | const Node = struct { |
| 997 | freq: u16, |
| 998 | depth: u16, |
| 999 | |
| 1000 | pub const Index = u16; |
| 1001 | |
| 1002 | pub fn smaller(a: Node, b: Node) bool { |
| 1003 | return if (a.freq != b.freq) a.freq < b.freq else a.depth < b.depth; |
| 1004 | } |
| 1005 | }; |
| 1006 | |
| 1007 | fn heapSiftDown(nodes: []Node, heap: []Node.Index, start: usize) void { |
| 1008 | var i = start; |
| 1009 | while (true) { |
| 1010 | var min = i; |
| 1011 | const l = i * 2 + 1; |
| 1012 | const r = l + 1; |
| 1013 | min = if (l < heap.len and nodes[heap[l]].smaller(nodes[heap[min]])) l else min; |
| 1014 | min = if (r < heap.len and nodes[heap[r]].smaller(nodes[heap[min]])) r else min; |
| 1015 | if (i == min) break; |
| 1016 | mem.swap(Node.Index, &heap[i], &heap[min]); |
| 1017 | i = min; |
| 1018 | } |
| 1019 | } |
| 1020 | |
| 1021 | fn heapRemoveRoot(nodes: []Node, heap: []Node.Index) void { |
| 1022 | heap[0] = heap[heap.len - 1]; |
| 1023 | heapSiftDown(nodes, heap[0 .. heap.len - 1], 0); |
| 1024 | } |
| 1025 | |
| 1026 | /// Returns the total bits to encode `freqs` followed by the index of the last non-zero bits. |
| 1027 | /// For `freqs[i]` == 0, `out_codes[i]` will be undefined. |
| 1028 | /// It is asserted `out_bits` is zero-filled. |
| 1029 | /// It is asserted `out_bits.len` is at least a length of |
| 1030 | /// one if ncomplete trees are allowed and two otherwise. |
| 1031 | pub fn build( |
| 1032 | freqs: []const u16, |
| 1033 | out_codes: []u16, |
| 1034 | out_bits: []u4, |
| 1035 | max_bits: u4, |
| 1036 | incomplete_allowed: bool, |
| 1037 | ) struct { u32, u16 } { |
| 1038 | assert(out_codes.len - 1 >= @intFromBool(incomplete_allowed)); |
| 1039 | // freqs and out_codes are in the loop to assert they are all the same length |
| 1040 | for (freqs, out_codes, out_bits) |_, _, n| assert(n == 0); |
| 1041 | assert(out_codes.len <= @as(u16, 1) << max_bits); |
| 1042 | |
| 1043 | // Indexes 0..freqs are leafs, indexes max_leafs.. are internal nodes. |
| 1044 | var tree_nodes: [max_nodes]Node = undefined; |
| 1045 | var tree_parent_nodes: [max_nodes]Node.Index = undefined; |
| 1046 | var nodes_end: u16 = max_leafs; |
| 1047 | // Dual-purpose buffer. Nodes are ordered by least frequency or when equal, least depth. |
| 1048 | // The start is a min heap of level-zero nodes. |
| 1049 | // The end is a sorted buffer of nodes with the greatest first. |
| 1050 | var node_buf: [max_nodes]Node.Index = undefined; |
| 1051 | var heap_end: u16 = 0; |
| 1052 | var sorted_start: u16 = node_buf.len; |
| 1053 | |
| 1054 | for (0.., freqs) |n, freq| { |
| 1055 | tree_nodes[n] = .{ .freq = freq, .depth = 0 }; |
| 1056 | node_buf[heap_end] = @intCast(n); |
| 1057 | heap_end += @intFromBool(freq != 0); |
| 1058 | } |
| 1059 | |
| 1060 | // There must be at least one code at minimum, |
| 1061 | node_buf[heap_end] = 0; |
| 1062 | heap_end += @intFromBool(heap_end == 0); |
| 1063 | // and at least two if incomplete must be avoided. |
| 1064 | if (heap_end == 1 and incomplete_allowed) { |
| 1065 | @branchHint(.unlikely); // LLVM 21 optimizes this branch as the more likely without |
| 1066 | |
| 1067 | // Codes must have at least one-bit, so this is a special case. |
| 1068 | out_bits[node_buf[0]] = 1; |
| 1069 | out_codes[node_buf[0]] = 0; |
| 1070 | return .{ freqs[node_buf[0]], node_buf[0] }; |
| 1071 | } |
| 1072 | const last_nonzero = @max(node_buf[heap_end - 1], 1); // For heap_end > 1, last is not be 0 |
| 1073 | node_buf[heap_end] = @intFromBool(node_buf[0] == 0); |
| 1074 | heap_end += @intFromBool(heap_end == 1); |
| 1075 | |
| 1076 | // Heapify the array of frequencies |
| 1077 | const heapify_final = heap_end - 1; |
| 1078 | const heapify_start = (heapify_final - 1) / 2; // Parent of final node |
| 1079 | var heapify_i = heapify_start; |
| 1080 | while (true) { |
| 1081 | heapSiftDown(&tree_nodes, node_buf[0..heap_end], heapify_i); |
| 1082 | if (heapify_i == 0) break; |
| 1083 | heapify_i -= 1; |
| 1084 | } |
| 1085 | |
| 1086 | // Build optimal tree. `max_bits` is not enforced yet. |
| 1087 | while (heap_end > 1) { |
| 1088 | const a = node_buf[0]; |
| 1089 | heapRemoveRoot(&tree_nodes, node_buf[0..heap_end]); |
| 1090 | heap_end -= 1; |
| 1091 | const b = node_buf[0]; |
| 1092 | |
| 1093 | sorted_start -= 2; |
| 1094 | node_buf[sorted_start..][0..2].* = .{ b, a }; |
| 1095 | |
| 1096 | tree_nodes[nodes_end] = .{ |
| 1097 | .freq = tree_nodes[a].freq + tree_nodes[b].freq, |
| 1098 | .depth = @max(tree_nodes[a].depth, tree_nodes[b].depth) + 1, |
| 1099 | }; |
| 1100 | defer nodes_end += 1; |
| 1101 | tree_parent_nodes[a] = nodes_end; |
| 1102 | tree_parent_nodes[b] = nodes_end; |
| 1103 | |
| 1104 | node_buf[0] = nodes_end; |
| 1105 | heapSiftDown(&tree_nodes, node_buf[0..heap_end], 0); |
| 1106 | } |
| 1107 | sorted_start -= 1; |
| 1108 | node_buf[sorted_start] = node_buf[0]; |
| 1109 | |
| 1110 | var bit_counts: [16]u16 = @splat(0); |
| 1111 | buildBits(out_bits, &bit_counts, &tree_parent_nodes, node_buf[sorted_start..], max_bits); |
| 1112 | return .{ buildValues(freqs, out_codes, out_bits, bit_counts), last_nonzero }; |
| 1113 | } |
| 1114 | |
| 1115 | fn buildBits( |
| 1116 | out_bits: []u4, |
| 1117 | bit_counts: *[16]u16, |
| 1118 | parent_nodes: *[max_nodes]Node.Index, |
| 1119 | sorted: []Node.Index, |
| 1120 | max_bits: u4, |
| 1121 | ) void { |
| 1122 | var internal_node_bits: [max_nodes - max_leafs]u4 = undefined; |
| 1123 | var overflowed: u16 = 0; |
| 1124 | |
| 1125 | internal_node_bits[sorted[0] - max_leafs] = 0; // root |
| 1126 | for (sorted[1..]) |i| { |
| 1127 | const parent_bits = internal_node_bits[parent_nodes[i] - max_leafs]; |
| 1128 | overflowed += @intFromBool(parent_bits == max_bits); |
| 1129 | const bits = parent_bits + @intFromBool(parent_bits != max_bits); |
| 1130 | bit_counts[bits] += @intFromBool(i < max_leafs); |
| 1131 | (if (i >= max_leafs) &internal_node_bits[i - max_leafs] else &out_bits[i]).* = bits; |
| 1132 | } |
| 1133 | |
| 1134 | if (overflowed == 0) { |
| 1135 | @branchHint(.likely); |
| 1136 | return; |
| 1137 | } |
| 1138 | |
| 1139 | outer: while (true) { |
| 1140 | var deepest: u4 = max_bits - 1; |
| 1141 | while (bit_counts[deepest] == 0) deepest -= 1; |
| 1142 | while (overflowed != 0) { |
| 1143 | // Insert an internal node under the leaf and move an overflow as its sibling |
| 1144 | bit_counts[deepest] -= 1; |
| 1145 | bit_counts[deepest + 1] += 2; |
| 1146 | // Only overflow moved. Its sibling's depth is one less, however is still >= depth. |
| 1147 | bit_counts[max_bits] -= 1; |
| 1148 | overflowed -= 2; |
| 1149 | |
| 1150 | if (overflowed == 0) break :outer; |
| 1151 | deepest += 1; |
| 1152 | if (deepest == max_bits) continue :outer; |
| 1153 | } |
| 1154 | } |
| 1155 | |
| 1156 | // Reassign bit lengths |
| 1157 | assert(bit_counts[0] == 0); |
| 1158 | var i: usize = 0; |
| 1159 | for (1.., bit_counts[1..]) |bits, all| { |
| 1160 | var remaining = all; |
| 1161 | while (remaining != 0) { |
| 1162 | defer i += 1; |
| 1163 | if (sorted[i] >= max_leafs) continue; |
| 1164 | out_bits[sorted[i]] = @intCast(bits); |
| 1165 | remaining -= 1; |
| 1166 | } |
| 1167 | } |
| 1168 | assert(for (sorted[i..]) |n| { // all leafs consumed |
| 1169 | if (n < max_leafs) break false; |
| 1170 | } else true); |
| 1171 | } |
| 1172 | |
| 1173 | fn buildValues(freqs: []const u16, out_codes: []u16, bits: []u4, bit_counts: [16]u16) u32 { |
| 1174 | var code: u16 = 0; |
| 1175 | var base: [16]u16 = undefined; |
| 1176 | assert(bit_counts[0] == 0); |
| 1177 | for (bit_counts[1..], base[1..]) |c, *b| { |
| 1178 | b.* = code; |
| 1179 | code +%= c; |
| 1180 | code <<= 1; |
| 1181 | } |
| 1182 | var freq_sums: [16]u16 = @splat(0); |
| 1183 | for (out_codes, bits, freqs) |*c, b, f| { |
| 1184 | c.* = @bitReverse(base[b]) >> -%b; |
| 1185 | base[b] += 1; // For `b == 0` this is fine since v is specified to be undefined. |
| 1186 | freq_sums[b] += f; |
| 1187 | } |
| 1188 | return @reduce(.Add, @as(@Vector(16, u32), freq_sums) * std.simd.iota(u32, 16)); |
| 1189 | } |
| 1190 | |
| 1191 | test build { |
| 1192 | var codes: [8]u16 = undefined; |
| 1193 | var bits: [8]u4 = undefined; |
| 1194 | |
| 1195 | const regular_freqs: [8]u16 = .{ 1, 1, 0, 8, 8, 0, 2, 4 }; |
| 1196 | // The optimal tree for the above frequencies is |
| 1197 | // 4 1 1 |
| 1198 | // \ / |
| 1199 | // 3 2 # |
| 1200 | // \ / |
| 1201 | // 2 8 8 4 # |
| 1202 | // \ / \ / |
| 1203 | // 1 # # |
| 1204 | // \ / |
| 1205 | // 0 # |
| 1206 | bits = @splat(0); |
| 1207 | var n, var lnz = build(&regular_freqs, &codes, &bits, 15, true); |
| 1208 | codes[2] = 0; |
| 1209 | codes[5] = 0; |
| 1210 | try std.testing.expectEqualSlices(u4, &.{ 4, 4, 0, 2, 2, 0, 3, 2 }, &bits); |
| 1211 | try std.testing.expectEqualSlices(u16, &.{ |
| 1212 | 0b0111, 0b1111, 0, 0b00, 0b10, 0, 0b011, 0b01, |
| 1213 | }, &codes); |
| 1214 | try std.testing.expectEqual(54, n); |
| 1215 | try std.testing.expectEqual(7, lnz); |
| 1216 | // When constrained to 3 bits, it becomes |
| 1217 | // 3 1 1 2 4 |
| 1218 | // \ / \ / |
| 1219 | // 2 8 8 # # |
| 1220 | // \ / \ / |
| 1221 | // 1 # # |
| 1222 | // \ / |
| 1223 | // 0 # |
| 1224 | bits = @splat(0); |
| 1225 | n, lnz = build(&regular_freqs, &codes, &bits, 3, true); |
| 1226 | codes[2] = 0; |
| 1227 | codes[5] = 0; |
| 1228 | try std.testing.expectEqualSlices(u4, &.{ 3, 3, 0, 2, 2, 0, 3, 3 }, &bits); |
| 1229 | try std.testing.expectEqualSlices(u16, &.{ |
| 1230 | 0b001, 0b101, 0, 0b00, 0b10, 0, 0b011, 0b111, |
| 1231 | }, &codes); |
| 1232 | try std.testing.expectEqual(56, n); |
| 1233 | try std.testing.expectEqual(7, lnz); |
| 1234 | |
| 1235 | // Empty tree. At least one code should be present |
| 1236 | bits = @splat(0); |
| 1237 | n, lnz = build(&.{ 0, 0 }, codes[0..2], bits[0..2], 15, true); |
| 1238 | try std.testing.expectEqualSlices(u4, &.{ 1, 0 }, bits[0..2]); |
| 1239 | try std.testing.expectEqual(0b0, codes[0]); |
| 1240 | try std.testing.expectEqual(0, n); |
| 1241 | try std.testing.expectEqual(0, lnz); |
| 1242 | |
| 1243 | // Check all incompletable frequencies are completed |
| 1244 | for ([_][2]u16{ .{ 0, 0 }, .{ 0, 1 }, .{ 1, 0 } }) |incomplete| { |
| 1245 | // Empty tree. Both codes should be present to prevent incomplete trees |
| 1246 | bits = @splat(0); |
| 1247 | n, lnz = build(&incomplete, codes[0..2], bits[0..2], 15, false); |
| 1248 | try std.testing.expectEqualSlices(u4, &.{ 1, 1 }, bits[0..2]); |
| 1249 | try std.testing.expectEqualSlices(u16, &.{ 0b0, 0b1 }, codes[0..2]); |
| 1250 | try std.testing.expectEqual(incomplete[0] + incomplete[1], n); |
| 1251 | try std.testing.expectEqual(1, lnz); |
| 1252 | } |
| 1253 | |
| 1254 | try std.testing.fuzz({}, checkFuzzedBuildFreqs, .{}); |
| 173 | 1255 | } |
| 174 | 1256 | |
| 175 | | const buffered = me.buffered(); |
| 176 | | const min_lookahead = Token.min_length + Token.max_length; |
| 177 | | const history_plus_lookahead_len = flate.history_len + min_lookahead; |
| 178 | | if (buffered.len < history_plus_lookahead_len) return 0; |
| 179 | | const lookahead = buffered[flate.history_len..]; |
| 1257 | fn checkFuzzedBuildFreqs(_: void, freqs: []const u8) !void { |
| 1258 | @disableInstrumentation(); |
| 1259 | var r: Io.Reader = .fixed(freqs); |
| 1260 | var freqs_limit: u16 = 65535; |
| 1261 | var freqs_buf: [max_leafs]u16 = undefined; |
| 1262 | var nfreqs: u15 = 0; |
| 1263 | |
| 1264 | const params: packed struct(u8) { |
| 1265 | max_bits: u4, |
| 1266 | _: u3, |
| 1267 | incomplete_allowed: bool, |
| 1268 | } = @bitCast(r.takeByte() catch 255); |
| 1269 | while (nfreqs != freqs_buf.len) { |
| 1270 | const leb = r.takeLeb128(u16); |
| 1271 | const f = if (leb) |f| @min(f, freqs_limit) else |e| switch (e) { |
| 1272 | error.ReadFailed => unreachable, |
| 1273 | error.EndOfStream => 0, |
| 1274 | error.Overflow => freqs_limit, |
| 1275 | }; |
| 1276 | freqs_buf[nfreqs] = f; |
| 1277 | nfreqs += 1; |
| 1278 | freqs_limit -= f; |
| 1279 | if (leb == error.EndOfStream and nfreqs - 1 > @intFromBool(params.incomplete_allowed)) |
| 1280 | break; |
| 1281 | } |
| 1282 | |
| 1283 | var codes_buf: [max_leafs]u16 = undefined; |
| 1284 | var bits_buf: [max_leafs]u4 = @splat(0); |
| 1285 | const total_bits, const last_nonzero = build( |
| 1286 | freqs_buf[0..nfreqs], |
| 1287 | codes_buf[0..nfreqs], |
| 1288 | bits_buf[0..nfreqs], |
| 1289 | @max(math.log2_int_ceil(u15, nfreqs), params.max_bits), |
| 1290 | params.incomplete_allowed, |
| 1291 | ); |
| 1292 | |
| 1293 | var has_bitlen_one: bool = false; |
| 1294 | var expected_total_bits: u32 = 0; |
| 1295 | var expected_last_nonzero: ?u16 = null; |
| 1296 | var weighted_sum: u32 = 0; |
| 1297 | for (freqs_buf[0..nfreqs], bits_buf[0..nfreqs], 0..) |f, nb, i| { |
| 1298 | has_bitlen_one = has_bitlen_one or nb == 1; |
| 1299 | weighted_sum += @shlExact(@as(u16, 1), 15 - nb) & ((1 << 15) - 1); |
| 1300 | expected_total_bits += @as(u32, f) * nb; |
| 1301 | if (nb != 0) expected_last_nonzero = @intCast(i); |
| 1302 | } |
| 1303 | |
| 1304 | errdefer std.log.err( |
| 1305 | \\ params: {} |
| 1306 | \\ freqs: {any} |
| 1307 | \\ bits: {any} |
| 1308 | \\ # freqs: {} |
| 1309 | \\ max bits: {} |
| 1310 | \\ weighted sum: {} |
| 1311 | \\ has_bitlen_one: {} |
| 1312 | \\ expected/actual total bits: {}/{} |
| 1313 | \\ expected/actual last nonzero: {?}/{} |
| 1314 | ++ "\n", .{ |
| 1315 | params, |
| 1316 | freqs_buf[0..nfreqs], |
| 1317 | bits_buf[0..nfreqs], |
| 1318 | nfreqs, |
| 1319 | @max(math.log2_int_ceil(u15, nfreqs), params.max_bits), |
| 1320 | weighted_sum, |
| 1321 | has_bitlen_one, |
| 1322 | expected_total_bits, |
| 1323 | total_bits, |
| 1324 | expected_last_nonzero, |
| 1325 | last_nonzero, |
| 1326 | }); |
| 1327 | |
| 1328 | try std.testing.expectEqual(expected_total_bits, total_bits); |
| 1329 | try std.testing.expectEqual(expected_last_nonzero, last_nonzero); |
| 1330 | if (weighted_sum > 1 << 15) |
| 1331 | return error.OversubscribedHuffmanTree; |
| 1332 | if (weighted_sum < 1 << 15 and |
| 1333 | !(params.incomplete_allowed and has_bitlen_one and weighted_sum == 1 << 14)) |
| 1334 | return error.IncompleteHuffmanTree; |
| 1335 | } |
| 1336 | }; |
| 180 | 1337 | |
| 181 | | // TODO tokenize |
| 182 | | _ = lookahead; |
| 183 | | //c.hasher.update(lookahead[0..n]); |
| 184 | | @panic("TODO"); |
| 1338 | test { |
| 1339 | _ = huffman; |
| 185 | 1340 | } |
| 186 | 1341 | |
| 187 | | pub fn end(c: *Compress) !void { |
| 188 | | try endUnflushed(c); |
| 189 | | const out = c.block_writer.output; |
| 190 | | try out.flush(); |
| 1342 | /// [0] is a gradient where the probability of lower values decreases across it |
| 1343 | /// [1] is completely random and hence uncompressable |
| 1344 | fn testingFreqBufs() !*[2][65536]u8 { |
| 1345 | const fbufs = try std.testing.allocator.create([2][65536]u8); |
| 1346 | var prng: std.Random.DefaultPrng = .init(std.testing.random_seed); |
| 1347 | prng.random().bytes(&fbufs[0]); |
| 1348 | prng.random().bytes(&fbufs[1]); |
| 1349 | for (0.., &fbufs[0], fbufs[1]) |i, *grad, rand| { |
| 1350 | const prob = @as(u8, @intCast(255 - i / (fbufs[0].len * 256))); |
| 1351 | grad.* /= @max(1, rand / @max(1, prob)); |
| 1352 | } |
| 1353 | return fbufs; |
| 191 | 1354 | } |
| 192 | 1355 | |
| 193 | | pub fn endUnflushed(c: *Compress) !void { |
| 194 | | while (c.writer.end != 0) _ = try drain(&c.writer, &.{""}, 1); |
| 195 | | c.state = .ended; |
| 1356 | fn testingCheckDecompressedMatches( |
| 1357 | flate_bytes: []const u8, |
| 1358 | expected_size: u32, |
| 1359 | expected_hash: flate.Container.Hasher, |
| 1360 | ) !void { |
| 1361 | const container: flate.Container = expected_hash; |
| 1362 | var data_hash: flate.Container.Hasher = .init(container); |
| 1363 | var data_size: u32 = 0; |
| 1364 | var flate_r: Io.Reader = .fixed(flate_bytes); |
| 1365 | var deflate_buf: [flate.max_window_len]u8 = undefined; |
| 1366 | var deflate: flate.Decompress = .init(&flate_r, container, &deflate_buf); |
| 196 | 1367 | |
| 197 | | const out = c.block_writer.output; |
| 1368 | while (deflate.reader.peekGreedy(1)) |bytes| { |
| 1369 | data_size += @intCast(bytes.len); |
| 1370 | data_hash.update(bytes); |
| 1371 | deflate.reader.toss(bytes.len); |
| 1372 | } else |e| switch (e) { |
| 1373 | error.ReadFailed => return deflate.err.?, |
| 1374 | error.EndOfStream => {}, |
| 1375 | } |
| 198 | 1376 | |
| 199 | | // TODO flush tokens |
| 1377 | try testingCheckContainerHash( |
| 1378 | expected_size, |
| 1379 | expected_hash, |
| 1380 | data_hash, |
| 1381 | data_size, |
| 1382 | deflate.container_metadata, |
| 1383 | ); |
| 1384 | } |
| 200 | 1385 | |
| 201 | | switch (c.hasher) { |
| 202 | | .gzip => |*gzip| { |
| 203 | | // GZIP 8 bytes footer |
| 204 | | // - 4 bytes, CRC32 (CRC-32) |
| 205 | | // - 4 bytes, ISIZE (Input SIZE) - size of the original (uncompressed) input data modulo 2^32 |
| 206 | | const footer = try out.writableArray(8); |
| 207 | | std.mem.writeInt(u32, footer[0..4], gzip.crc.final(), .little); |
| 208 | | std.mem.writeInt(u32, footer[4..8], @truncate(gzip.count), .little); |
| 1386 | fn testingCheckContainerHash( |
| 1387 | expected_size: u32, |
| 1388 | expected_hash: flate.Container.Hasher, |
| 1389 | actual_hash: flate.Container.Hasher, |
| 1390 | actual_size: u32, |
| 1391 | actual_meta: flate.Container.Metadata, |
| 1392 | ) !void { |
| 1393 | try std.testing.expectEqual(expected_size, actual_size); |
| 1394 | switch (actual_hash) { |
| 1395 | .raw => {}, |
| 1396 | .gzip => |gz| { |
| 1397 | const expected_crc = expected_hash.gzip.crc.final(); |
| 1398 | try std.testing.expectEqual(expected_size, actual_meta.gzip.count); |
| 1399 | try std.testing.expectEqual(expected_crc, gz.crc.final()); |
| 1400 | try std.testing.expectEqual(expected_crc, actual_meta.gzip.crc); |
| 209 | 1401 | }, |
| 210 | | .zlib => |*zlib| { |
| 211 | | // ZLIB (RFC 1950) is big-endian, unlike GZIP (RFC 1952). |
| 212 | | // 4 bytes of ADLER32 (Adler-32 checksum) |
| 213 | | // Checksum value of the uncompressed data (excluding any |
| 214 | | // dictionary data) computed according to Adler-32 |
| 215 | | // algorithm. |
| 216 | | std.mem.writeInt(u32, try out.writableArray(4), zlib.adler, .big); |
| 1402 | .zlib => |zl| { |
| 1403 | const expected_adler = expected_hash.zlib.adler; |
| 1404 | try std.testing.expectEqual(expected_adler, zl.adler); |
| 1405 | try std.testing.expectEqual(expected_adler, actual_meta.zlib.adler); |
| 217 | 1406 | }, |
| 218 | | .raw => {}, |
| 219 | 1407 | } |
| 220 | 1408 | } |
| 221 | 1409 | |
| 222 | | pub const Simple = struct { |
| 223 | | /// Note that store blocks are limited to 65535 bytes. |
| 224 | | buffer: []u8, |
| 225 | | wp: usize, |
| 226 | | block_writer: BlockWriter, |
| 227 | | hasher: Container.Hasher, |
| 228 | | strategy: Strategy, |
| 1410 | const PackedContainer = packed struct(u2) { |
| 1411 | raw: bool, |
| 1412 | other: enum(u1) { gzip, zlib }, |
| 1413 | |
| 1414 | pub fn val(c: @This()) flate.Container { |
| 1415 | return if (c.raw) .raw else switch (c.other) { |
| 1416 | .gzip => .gzip, |
| 1417 | .zlib => .zlib, |
| 1418 | }; |
| 1419 | } |
| 1420 | }; |
| 1421 | |
| 1422 | test Compress { |
| 1423 | const fbufs = try testingFreqBufs(); |
| 1424 | defer if (!builtin.fuzz) std.testing.allocator.destroy(fbufs); |
| 1425 | try std.testing.fuzz(fbufs, testFuzzedCompressInput, .{}); |
| 1426 | } |
| 1427 | |
| 1428 | fn testFuzzedCompressInput(fbufs: *const [2][65536]u8, input: []const u8) !void { |
| 1429 | var in: Io.Reader = .fixed(input); |
| 1430 | var opts: packed struct(u51) { |
| 1431 | container: PackedContainer, |
| 1432 | buf_size: u16, |
| 1433 | good: u8, |
| 1434 | nice: u8, |
| 1435 | lazy: u8, |
| 1436 | /// Not a `u16` to limit it for performance |
| 1437 | chain: u9, |
| 1438 | } = @bitCast(in.takeLeb128(u51) catch 0); |
| 1439 | var expected_hash: flate.Container.Hasher = .init(opts.container.val()); |
| 1440 | var expected_size: u32 = 0; |
| 1441 | |
| 1442 | var flate_buf: [128 * 1024]u8 = undefined; |
| 1443 | var flate_w: Writer = .fixed(&flate_buf); |
| 1444 | var deflate_buf: [flate.max_window_len * 2]u8 = undefined; |
| 1445 | var deflate_w = try Compress.init( |
| 1446 | &flate_w, |
| 1447 | deflate_buf[0 .. flate.max_window_len + @as(usize, opts.buf_size)], |
| 1448 | opts.container.val(), |
| 1449 | .{ |
| 1450 | .good = @as(u16, opts.good) + 3, |
| 1451 | .nice = @as(u16, opts.nice) + 3, |
| 1452 | .lazy = @as(u16, @min(opts.lazy, opts.nice)) + 3, |
| 1453 | .chain = @max(1, opts.chain, @as(u8, 4) * @intFromBool(opts.good <= opts.lazy)), |
| 1454 | }, |
| 1455 | ); |
| 1456 | |
| 1457 | // It is ensured that more bytes are not written then this to ensure this run |
| 1458 | // does not take too long and that `flate_buf` does not run out of space. |
| 1459 | const flate_buf_blocks = flate_buf.len / block_tokens; |
| 1460 | // Allow a max overhead of 64 bytes per block since the implementation does not gaurauntee it |
| 1461 | // writes store blocks when optimal. This comes from taking less than 32 bytes to write an |
| 1462 | // optimal dynamic block header of mostly bitlen 8 codes and the end of block literal plus |
| 1463 | // `(65536 / 256) / 8`, which is is the maximum number of extra bytes from bitlen 9 codes. An |
| 1464 | // extra 32 bytes is reserved on top of that for container headers and footers. |
| 1465 | const max_size = flate_buf.len - (flate_buf_blocks * 64 + 32); |
| 1466 | |
| 1467 | while (true) { |
| 1468 | const data: packed struct(u36) { |
| 1469 | is_rebase: bool, |
| 1470 | is_bytes: bool, |
| 1471 | params: packed union { |
| 1472 | copy: packed struct(u34) { |
| 1473 | len_lo: u5, |
| 1474 | dist: u15, |
| 1475 | len_hi: u4, |
| 1476 | _: u10, |
| 1477 | }, |
| 1478 | bytes: packed struct(u34) { |
| 1479 | kind: enum(u1) { gradient, random }, |
| 1480 | off_hi: u4, |
| 1481 | len_lo: u10, |
| 1482 | off_mi: u4, |
| 1483 | len_hi: u5, |
| 1484 | off_lo: u8, |
| 1485 | _: u2, |
| 1486 | }, |
| 1487 | rebase: packed struct(u34) { |
| 1488 | preserve: u17, |
| 1489 | capacity: u17, |
| 1490 | }, |
| 1491 | }, |
| 1492 | } = @bitCast(in.takeLeb128(u36) catch |e| switch (e) { |
| 1493 | error.ReadFailed => unreachable, |
| 1494 | error.Overflow => 0, |
| 1495 | error.EndOfStream => break, |
| 1496 | }); |
| 1497 | |
| 1498 | const buffered = deflate_w.writer.buffered(); |
| 1499 | // Required for repeating patterns and since writing from `buffered` is illegal |
| 1500 | var copy_buf: [512]u8 = undefined; |
| 1501 | |
| 1502 | if (data.is_rebase) { |
| 1503 | const usable_capacity = deflate_w.writer.buffer.len - rebase_reserved_capacity; |
| 1504 | const preserve = @min(data.params.rebase.preserve, usable_capacity); |
| 1505 | const capacity = @min(data.params.rebase.capacity, usable_capacity - |
| 1506 | @max(rebase_min_preserve, preserve)); |
| 1507 | try deflate_w.writer.rebase(preserve, capacity); |
| 1508 | continue; |
| 1509 | } |
| 1510 | |
| 1511 | const max_bytes = max_size -| expected_size; |
| 1512 | const bytes = if (!data.is_bytes and buffered.len != 0) bytes: { |
| 1513 | const dist = @min(buffered.len, @as(u32, data.params.copy.dist) + 1); |
| 1514 | const len = @min( |
| 1515 | @max(@shlExact(@as(u9, data.params.copy.len_hi), 5) | data.params.copy.len_lo, 1), |
| 1516 | max_bytes, |
| 1517 | ); |
| 1518 | // Reuse the implementation's history. Otherwise our own would need maintained. |
| 1519 | const bytes_start = buffered[buffered.len - dist ..]; |
| 1520 | const history_bytes = bytes_start[0..@min(bytes_start.len, len)]; |
| 1521 | |
| 1522 | @memcpy(copy_buf[0..history_bytes.len], history_bytes); |
| 1523 | const new_history = len - history_bytes.len; |
| 1524 | if (history_bytes.len != len) for ( // check needed for `- dist` |
| 1525 | copy_buf[history_bytes.len..][0..new_history], |
| 1526 | copy_buf[history_bytes.len - dist ..][0..new_history], |
| 1527 | ) |*next, prev| { |
| 1528 | next.* = prev; |
| 1529 | }; |
| 1530 | break :bytes copy_buf[0..len]; |
| 1531 | } else bytes: { |
| 1532 | const off = @shlExact(@as(u16, data.params.bytes.off_hi), 12) | |
| 1533 | @shlExact(@as(u16, data.params.bytes.off_mi), 8) | |
| 1534 | data.params.bytes.off_lo; |
| 1535 | const len = @shlExact(@as(u16, data.params.bytes.len_hi), 10) | |
| 1536 | data.params.bytes.len_lo; |
| 1537 | const fbuf = &fbufs[@intFromEnum(data.params.bytes.kind)]; |
| 1538 | break :bytes fbuf[off..][0..@min(len, fbuf.len - off, max_bytes)]; |
| 1539 | }; |
| 1540 | assert(bytes.len <= max_bytes); |
| 1541 | try deflate_w.writer.writeAll(bytes); |
| 1542 | expected_hash.update(bytes); |
| 1543 | expected_size += @intCast(bytes.len); |
| 1544 | } |
| 1545 | |
| 1546 | try deflate_w.writer.flush(); |
| 1547 | try testingCheckDecompressedMatches(flate_w.buffered(), expected_size, expected_hash); |
| 1548 | } |
| 1549 | |
| 1550 | /// Does not compress data |
| 1551 | pub const Raw = struct { |
| 1552 | /// After `flush` is called, all vtable calls with result in `error.WriteFailed.` |
| 1553 | writer: Writer, |
| 1554 | output: *Writer, |
| 1555 | hasher: flate.Container.Hasher, |
| 229 | 1556 | |
| 230 | | pub const Strategy = enum { huffman, store }; |
| 1557 | const max_block_size: u16 = 65535; |
| 1558 | const full_header: [5]u8 = .{ |
| 1559 | BlockHeader.int(.{ .final = false, .kind = .stored }), |
| 1560 | 255, |
| 1561 | 255, |
| 1562 | 0, |
| 1563 | 0, |
| 1564 | }; |
| 231 | 1565 | |
| 232 | | pub fn init(output: *Writer, buffer: []u8, container: Container, strategy: Strategy) !Simple { |
| 233 | | const header = container.header(); |
| 234 | | try output.writeAll(header); |
| 1566 | /// While there is no minimum buffer size, it is recommended |
| 1567 | /// to be at least `flate.max_window_len` for optimal output. |
| 1568 | pub fn init(output: *Writer, buffer: []u8, container: flate.Container) Writer.Error!Raw { |
| 1569 | try output.writeAll(container.header()); |
| 235 | 1570 | return .{ |
| 236 | | .buffer = buffer, |
| 237 | | .wp = 0, |
| 238 | | .block_writer = .init(output), |
| 1571 | .writer = .{ |
| 1572 | .buffer = buffer, |
| 1573 | .vtable = &.{ |
| 1574 | .drain = Raw.drain, |
| 1575 | .flush = Raw.flush, |
| 1576 | .rebase = Raw.rebase, |
| 1577 | }, |
| 1578 | }, |
| 1579 | .output = output, |
| 239 | 1580 | .hasher = .init(container), |
| 240 | | .strategy = strategy, |
| 241 | 1581 | }; |
| 242 | 1582 | } |
| 243 | 1583 | |
| 244 | | pub fn flush(self: *Simple) !void { |
| 245 | | try self.flushBuffer(false); |
| 246 | | try self.block_writer.storedBlock("", false); |
| 247 | | try self.block_writer.flush(); |
| 1584 | fn drain(w: *Writer, data: []const []const u8, splat: usize) Writer.Error!usize { |
| 1585 | errdefer w.* = .failing; |
| 1586 | const r: *Raw = @fieldParentPtr("writer", w); |
| 1587 | const min_block = @min(w.buffer.len, max_block_size); |
| 1588 | const pattern = data[data.len - 1]; |
| 1589 | var partial_header: [5]u8 = undefined; |
| 1590 | |
| 1591 | var vecs: [16][]const u8 = undefined; |
| 1592 | var vecs_n: usize = 0; |
| 1593 | const data_bytes = Writer.countSplat(data, splat); |
| 1594 | const total_bytes = w.end + data_bytes; |
| 1595 | var rem_bytes = total_bytes; |
| 1596 | var rem_splat = splat; |
| 1597 | var rem_data = data; |
| 1598 | var rem_data_elem: []const u8 = w.buffered(); |
| 1599 | |
| 1600 | assert(rem_bytes > min_block); |
| 1601 | while (rem_bytes > min_block) { // not >= to allow `min_block` blocks to be marked as final |
| 1602 | // also, it handles the case of `min_block` being zero (no buffer) |
| 1603 | const block_size: u16 = @min(rem_bytes, max_block_size); |
| 1604 | rem_bytes -= block_size; |
| 1605 | |
| 1606 | if (vecs_n == vecs.len) { |
| 1607 | try r.output.writeVecAll(&vecs); |
| 1608 | vecs_n = 0; |
| 1609 | } |
| 1610 | vecs[vecs_n] = if (block_size == 65535) |
| 1611 | &full_header |
| 1612 | else header: { |
| 1613 | partial_header[0] = BlockHeader.int(.{ .final = false, .kind = .stored }); |
| 1614 | mem.writeInt(u16, partial_header[1..3], block_size, .little); |
| 1615 | mem.writeInt(u16, partial_header[3..5], ~block_size, .little); |
| 1616 | break :header &partial_header; |
| 1617 | }; |
| 1618 | vecs_n += 1; |
| 1619 | |
| 1620 | var block_limit: Io.Limit = .limited(block_size); |
| 1621 | while (true) { |
| 1622 | if (vecs_n == vecs.len) { |
| 1623 | try r.output.writeVecAll(&vecs); |
| 1624 | vecs_n = 0; |
| 1625 | } |
| 1626 | |
| 1627 | const vec = block_limit.sliceConst(rem_data_elem); |
| 1628 | vecs[vecs_n] = vec; |
| 1629 | vecs_n += 1; |
| 1630 | r.hasher.update(vec); |
| 1631 | |
| 1632 | const is_pattern = rem_splat != splat and vec.len == pattern.len; |
| 1633 | if (is_pattern) assert(pattern.len != 0); // exceeded countSplat |
| 1634 | |
| 1635 | if (!is_pattern or rem_splat == 0 or pattern.len > @intFromEnum(block_limit) / 2) { |
| 1636 | rem_data_elem = rem_data_elem[vec.len..]; |
| 1637 | block_limit = block_limit.subtract(vec.len).?; |
| 1638 | |
| 1639 | if (rem_data_elem.len == 0) { |
| 1640 | rem_data_elem = rem_data[0]; |
| 1641 | if (rem_data.len != 1) { |
| 1642 | rem_data = rem_data[1..]; |
| 1643 | } else if (rem_splat != 0) { |
| 1644 | rem_splat -= 1; |
| 1645 | } else { |
| 1646 | // All of `data` has been consumed. |
| 1647 | assert(block_limit == .nothing); |
| 1648 | assert(rem_bytes == 0); |
| 1649 | // Since `rem_bytes` and `block_limit` are zero, these won't be used. |
| 1650 | rem_data = undefined; |
| 1651 | rem_data_elem = undefined; |
| 1652 | rem_splat = undefined; |
| 1653 | } |
| 1654 | } |
| 1655 | if (block_limit == .nothing) break; |
| 1656 | } else { |
| 1657 | const out_splat = @intFromEnum(block_limit) / pattern.len; |
| 1658 | assert(out_splat >= 2); |
| 1659 | |
| 1660 | try r.output.writeSplatAll(vecs[0..vecs_n], out_splat); |
| 1661 | for (1..out_splat) |_| r.hasher.update(vec); |
| 1662 | |
| 1663 | vecs_n = 0; |
| 1664 | block_limit = block_limit.subtract(pattern.len * out_splat).?; |
| 1665 | if (rem_splat >= out_splat) { |
| 1666 | // `out_splat` contains `rem_data`, however one more needs subtracted |
| 1667 | // anyways since the next pattern is also being taken. |
| 1668 | rem_splat -= out_splat; |
| 1669 | } else { |
| 1670 | // All of `data` has been consumed. |
| 1671 | assert(block_limit == .nothing); |
| 1672 | assert(rem_bytes == 0); |
| 1673 | // Since `rem_bytes` and `block_limit` are zero, these won't be used. |
| 1674 | rem_data = undefined; |
| 1675 | rem_data_elem = undefined; |
| 1676 | rem_splat = undefined; |
| 1677 | } |
| 1678 | if (block_limit == .nothing) break; |
| 1679 | } |
| 1680 | } |
| 1681 | } |
| 1682 | |
| 1683 | if (vecs_n != 0) { // can be the case if a splat was sent |
| 1684 | try r.output.writeVecAll(vecs[0..vecs_n]); |
| 1685 | } |
| 1686 | |
| 1687 | if (rem_bytes > data_bytes) { |
| 1688 | assert(rem_bytes - data_bytes == rem_data_elem.len); |
| 1689 | assert(&rem_data_elem[0] == &w.buffer[total_bytes - rem_bytes]); |
| 1690 | } |
| 1691 | return w.consume(total_bytes - rem_bytes); |
| 1692 | } |
| 1693 | |
| 1694 | fn flush(w: *Writer) Writer.Error!void { |
| 1695 | defer w.* = .failing; |
| 1696 | try Raw.rebaseInner(w, 0, w.buffer.len, true); |
| 248 | 1697 | } |
| 249 | 1698 | |
| 250 | | pub fn finish(self: *Simple) !void { |
| 251 | | try self.flushBuffer(true); |
| 252 | | try self.block_writer.flush(); |
| 253 | | try self.hasher.container().writeFooter(&self.hasher, self.block_writer.output); |
| 1699 | fn rebase(w: *Writer, preserve: usize, capacity: usize) Writer.Error!void { |
| 1700 | errdefer w.* = .failing; |
| 1701 | try Raw.rebaseInner(w, preserve, capacity, false); |
| 254 | 1702 | } |
| 255 | 1703 | |
| 256 | | fn flushBuffer(self: *Simple, final: bool) !void { |
| 257 | | const buf = self.buffer[0..self.wp]; |
| 258 | | switch (self.strategy) { |
| 259 | | .huffman => try self.block_writer.huffmanBlock(buf, final), |
| 260 | | .store => try self.block_writer.storedBlock(buf, final), |
| 1704 | fn rebaseInner(w: *Writer, preserve: usize, capacity: usize, eos: bool) Writer.Error!void { |
| 1705 | const r: *Raw = @fieldParentPtr("writer", w); |
| 1706 | assert(preserve + capacity <= w.buffer.len); |
| 1707 | if (eos) assert(capacity == w.buffer.len); |
| 1708 | |
| 1709 | var partial_header: [5]u8 = undefined; |
| 1710 | var footer_buf: [8]u8 = undefined; |
| 1711 | const preserved = @min(w.end, preserve); |
| 1712 | var remaining = w.buffer[0 .. w.end - preserved]; |
| 1713 | |
| 1714 | var vecs: [16][]const u8 = undefined; |
| 1715 | var vecs_n: usize = 0; |
| 1716 | while (remaining.len > max_block_size) { // not >= so there is always a block down below |
| 1717 | if (vecs_n == vecs.len) { |
| 1718 | try r.output.writeVecAll(&vecs); |
| 1719 | vecs_n = 0; |
| 1720 | } |
| 1721 | vecs[vecs_n + 0] = &full_header; |
| 1722 | vecs[vecs_n + 1] = remaining[0..max_block_size]; |
| 1723 | r.hasher.update(vecs[vecs_n + 1]); |
| 1724 | vecs_n += 2; |
| 1725 | remaining = remaining[max_block_size..]; |
| 1726 | } |
| 1727 | |
| 1728 | // eos check required for empty block |
| 1729 | if (w.buffer.len - (remaining.len + preserved) < capacity or eos) { |
| 1730 | // A partial write is necessary to reclaim enough buffer space |
| 1731 | const block_size: u16 = @intCast(remaining.len); |
| 1732 | partial_header[0] = BlockHeader.int(.{ .final = eos, .kind = .stored }); |
| 1733 | mem.writeInt(u16, partial_header[1..3], block_size, .little); |
| 1734 | mem.writeInt(u16, partial_header[3..5], ~block_size, .little); |
| 1735 | |
| 1736 | if (vecs_n == vecs.len) { |
| 1737 | try r.output.writeVecAll(&vecs); |
| 1738 | vecs_n = 0; |
| 1739 | } |
| 1740 | vecs[vecs_n + 0] = &partial_header; |
| 1741 | vecs[vecs_n + 1] = remaining[0..block_size]; |
| 1742 | r.hasher.update(vecs[vecs_n + 1]); |
| 1743 | vecs_n += 2; |
| 1744 | remaining = remaining[block_size..]; |
| 1745 | assert(remaining.len == 0); |
| 1746 | |
| 1747 | if (eos and r.hasher != .raw) { |
| 1748 | // the footer is done here instead of `flush` so it can be included in the vector |
| 1749 | var footer_w: Writer = .fixed(&footer_buf); |
| 1750 | r.hasher.writeFooter(&footer_w) catch unreachable; |
| 1751 | assert(footer_w.end != 0); |
| 1752 | |
| 1753 | if (vecs_n == vecs.len) { |
| 1754 | try r.output.writeVecAll(&vecs); |
| 1755 | return r.output.writeAll(footer_w.buffered()); |
| 1756 | } else { |
| 1757 | vecs[vecs_n] = footer_w.buffered(); |
| 1758 | vecs_n += 1; |
| 1759 | } |
| 1760 | } |
| 261 | 1761 | } |
| 262 | | self.wp = 0; |
| 1762 | |
| 1763 | try r.output.writeVecAll(vecs[0..vecs_n]); |
| 1764 | _ = w.consume(w.end - preserved - remaining.len); |
| 263 | 1765 | } |
| 264 | 1766 | }; |
| 265 | 1767 | |
| 266 | | test "generate a Huffman code from an array of frequencies" { |
| 267 | | var freqs: [19]u16 = [_]u16{ |
| 268 | | 8, // 0 |
| 269 | | 1, // 1 |
| 270 | | 1, // 2 |
| 271 | | 2, // 3 |
| 272 | | 5, // 4 |
| 273 | | 10, // 5 |
| 274 | | 9, // 6 |
| 275 | | 1, // 7 |
| 276 | | 0, // 8 |
| 277 | | 0, // 9 |
| 278 | | 0, // 10 |
| 279 | | 0, // 11 |
| 280 | | 0, // 12 |
| 281 | | 0, // 13 |
| 282 | | 0, // 14 |
| 283 | | 0, // 15 |
| 284 | | 1, // 16 |
| 285 | | 3, // 17 |
| 286 | | 5, // 18 |
| 1768 | test Raw { |
| 1769 | const data_buf = try std.testing.allocator.create([4 * 65536]u8); |
| 1770 | defer if (!builtin.fuzz) std.testing.allocator.destroy(data_buf); |
| 1771 | var prng: std.Random.DefaultPrng = .init(std.testing.random_seed); |
| 1772 | prng.random().bytes(data_buf); |
| 1773 | try std.testing.fuzz(data_buf, testFuzzedRawInput, .{}); |
| 1774 | } |
| 1775 | |
| 1776 | fn countVec(data: []const []const u8) usize { |
| 1777 | var bytes: usize = 0; |
| 1778 | for (data) |d| bytes += d.len; |
| 1779 | return bytes; |
| 1780 | } |
| 1781 | |
| 1782 | fn testFuzzedRawInput(data_buf: *const [4 * 65536]u8, input: []const u8) !void { |
| 1783 | const HashedStoreWriter = struct { |
| 1784 | writer: Writer, |
| 1785 | state: enum { |
| 1786 | header, |
| 1787 | block_header, |
| 1788 | block_body, |
| 1789 | final_block_body, |
| 1790 | footer, |
| 1791 | end, |
| 1792 | }, |
| 1793 | block_remaining: u16, |
| 1794 | container: flate.Container, |
| 1795 | data_hash: flate.Container.Hasher, |
| 1796 | data_size: usize, |
| 1797 | footer_hash: u32, |
| 1798 | footer_size: u32, |
| 1799 | |
| 1800 | pub fn init(buf: []u8, container: flate.Container) @This() { |
| 1801 | return .{ |
| 1802 | .writer = .{ |
| 1803 | .vtable = &.{ |
| 1804 | .drain = @This().drain, |
| 1805 | .flush = @This().flush, |
| 1806 | }, |
| 1807 | .buffer = buf, |
| 1808 | }, |
| 1809 | .state = .header, |
| 1810 | .block_remaining = 0, |
| 1811 | .container = container, |
| 1812 | .data_hash = .init(container), |
| 1813 | .data_size = 0, |
| 1814 | .footer_hash = undefined, |
| 1815 | .footer_size = undefined, |
| 1816 | }; |
| 1817 | } |
| 1818 | |
| 1819 | /// Note that this implementation is somewhat dependent on the implementation of |
| 1820 | /// `Raw` by expecting headers / footers to be continous in data elements. It |
| 1821 | /// also expects the header to be the same as `flate.Container.header` and not |
| 1822 | /// for multiple streams to be concatenated. |
| 1823 | fn drain(w: *Writer, data: []const []const u8, splat: usize) Writer.Error!usize { |
| 1824 | errdefer w.* = .failing; |
| 1825 | var h: *@This() = @fieldParentPtr("writer", w); |
| 1826 | |
| 1827 | var rem_splat = splat; |
| 1828 | var rem_data = data; |
| 1829 | var rem_data_elem: []const u8 = w.buffered(); |
| 1830 | |
| 1831 | data_loop: while (true) { |
| 1832 | const wanted = switch (h.state) { |
| 1833 | .header => h.container.headerSize(), |
| 1834 | .block_header => 5, |
| 1835 | .block_body, .final_block_body => h.block_remaining, |
| 1836 | .footer => h.container.footerSize(), |
| 1837 | .end => 1, |
| 1838 | }; |
| 1839 | |
| 1840 | if (wanted != 0) { |
| 1841 | while (rem_data_elem.len == 0) { |
| 1842 | rem_data_elem = rem_data[0]; |
| 1843 | if (rem_data.len != 1) { |
| 1844 | rem_data = rem_data[1..]; |
| 1845 | } else { |
| 1846 | if (rem_splat == 0) { |
| 1847 | break :data_loop; |
| 1848 | } else { |
| 1849 | rem_splat -= 1; |
| 1850 | } |
| 1851 | } |
| 1852 | } |
| 1853 | } |
| 1854 | |
| 1855 | const bytes = Io.Limit.limited(wanted).sliceConst(rem_data_elem); |
| 1856 | rem_data_elem = rem_data_elem[bytes.len..]; |
| 1857 | |
| 1858 | switch (h.state) { |
| 1859 | .header => { |
| 1860 | if (bytes.len < wanted) |
| 1861 | return error.WriteFailed; // header eos |
| 1862 | if (!mem.eql(u8, bytes, h.container.header())) |
| 1863 | return error.WriteFailed; // wrong header |
| 1864 | h.state = .block_header; |
| 1865 | }, |
| 1866 | .block_header => { |
| 1867 | if (bytes.len < wanted) |
| 1868 | return error.WriteFailed; // store block header eos |
| 1869 | const header: BlockHeader = @bitCast(@as(u3, @truncate(bytes[0]))); |
| 1870 | if (header.kind != .stored) |
| 1871 | return error.WriteFailed; // non-store block |
| 1872 | const len = mem.readInt(u16, bytes[1..3], .little); |
| 1873 | const nlen = mem.readInt(u16, bytes[3..5], .little); |
| 1874 | if (nlen != ~len) |
| 1875 | return error.WriteFailed; // wrong nlen |
| 1876 | h.block_remaining = len; |
| 1877 | h.state = if (!header.final) .block_body else .final_block_body; |
| 1878 | }, |
| 1879 | .block_body, .final_block_body => { |
| 1880 | h.data_hash.update(bytes); |
| 1881 | h.data_size += bytes.len; |
| 1882 | h.block_remaining -= @intCast(bytes.len); |
| 1883 | if (h.block_remaining == 0) { |
| 1884 | h.state = if (h.state != .final_block_body) .block_header else .footer; |
| 1885 | } |
| 1886 | }, |
| 1887 | .footer => { |
| 1888 | if (bytes.len < wanted) |
| 1889 | return error.WriteFailed; // footer eos |
| 1890 | switch (h.container) { |
| 1891 | .raw => {}, |
| 1892 | .gzip => { |
| 1893 | h.footer_hash = mem.readInt(u32, bytes[0..4], .little); |
| 1894 | h.footer_size = mem.readInt(u32, bytes[4..8], .little); |
| 1895 | }, |
| 1896 | .zlib => { |
| 1897 | h.footer_hash = mem.readInt(u32, bytes[0..4], .big); |
| 1898 | }, |
| 1899 | } |
| 1900 | h.state = .end; |
| 1901 | }, |
| 1902 | .end => return error.WriteFailed, // data past end |
| 1903 | } |
| 1904 | } |
| 1905 | |
| 1906 | w.end = 0; |
| 1907 | return Writer.countSplat(data, splat); |
| 1908 | } |
| 1909 | |
| 1910 | fn flush(w: *Writer) Writer.Error!void { |
| 1911 | defer w.* = .failing; // Clears buffer even if state hasn't reached `end` |
| 1912 | _ = try @This().drain(w, &.{""}, 0); |
| 1913 | } |
| 287 | 1914 | }; |
| 288 | 1915 | |
| 289 | | var codes: [19]HuffmanEncoder.Code = undefined; |
| 290 | | var enc: HuffmanEncoder = .{ |
| 291 | | .codes = &codes, |
| 292 | | .freq_cache = undefined, |
| 293 | | .bit_count = undefined, |
| 294 | | .lns = undefined, |
| 295 | | .lfs = undefined, |
| 1916 | var in: Io.Reader = .fixed(input); |
| 1917 | const opts: packed struct(u19) { |
| 1918 | container: PackedContainer, |
| 1919 | buf_len: u17, |
| 1920 | } = @bitCast(in.takeLeb128(u19) catch 0); |
| 1921 | var output: HashedStoreWriter = .init(&.{}, opts.container.val()); |
| 1922 | var r_buf: [2 * 65536]u8 = undefined; |
| 1923 | var r: Raw = try .init( |
| 1924 | &output.writer, |
| 1925 | r_buf[0 .. opts.buf_len +% flate.max_window_len], |
| 1926 | opts.container.val(), |
| 1927 | ); |
| 1928 | |
| 1929 | var data_base: u18 = 0; |
| 1930 | var expected_hash: flate.Container.Hasher = .init(opts.container.val()); |
| 1931 | var expected_size: u32 = 0; |
| 1932 | var vecs: [32][]const u8 = undefined; |
| 1933 | var vecs_n: usize = 0; |
| 1934 | |
| 1935 | while (in.seek != in.end) { |
| 1936 | const VecInfo = packed struct(u58) { |
| 1937 | output: bool, |
| 1938 | /// If set, `data_len` and `splat` are reinterpreted as `capacity` |
| 1939 | /// and `preserve_len` respectively and `output` is treated as set. |
| 1940 | rebase: bool, |
| 1941 | block_aligning_len: bool, |
| 1942 | block_aligning_splat: bool, |
| 1943 | data_len: u18, |
| 1944 | splat: u18, |
| 1945 | data_off: u18, |
| 1946 | }; |
| 1947 | var vec_info: VecInfo = @bitCast(in.takeLeb128(u58) catch |e| switch (e) { |
| 1948 | error.ReadFailed => unreachable, |
| 1949 | error.Overflow, error.EndOfStream => 0, |
| 1950 | }); |
| 1951 | |
| 1952 | { |
| 1953 | const buffered = r.writer.buffered().len + countVec(vecs[0..vecs_n]); |
| 1954 | const to_align = mem.alignForwardAnyAlign(usize, buffered, Raw.max_block_size) - buffered; |
| 1955 | assert((buffered + to_align) % Raw.max_block_size == 0); |
| 1956 | |
| 1957 | if (vec_info.block_aligning_len) { |
| 1958 | vec_info.data_len = @intCast(to_align); |
| 1959 | } else if (vec_info.block_aligning_splat and vec_info.data_len != 0 and |
| 1960 | to_align % vec_info.data_len == 0) |
| 1961 | { |
| 1962 | vec_info.splat = @divExact(@as(u18, @intCast(to_align)), vec_info.data_len) -% 1; |
| 1963 | } |
| 1964 | } |
| 1965 | |
| 1966 | var splat = if (vec_info.output and !vec_info.rebase) vec_info.splat +% 1 else 1; |
| 1967 | add_vec: { |
| 1968 | if (vec_info.rebase) break :add_vec; |
| 1969 | if (expected_size +| math.mulWide(u18, vec_info.data_len, splat) > |
| 1970 | 10 * (1 << 16)) |
| 1971 | { |
| 1972 | // Skip this vector to avoid this test taking too long. |
| 1973 | // 10 maximum sized blocks is choosen as the limit since it is two more |
| 1974 | // than the maximum the implementation can output in one drain. |
| 1975 | splat = 1; |
| 1976 | break :add_vec; |
| 1977 | } |
| 1978 | |
| 1979 | vecs[vecs_n] = data_buf[@min( |
| 1980 | data_base +% vec_info.data_off, |
| 1981 | data_buf.len - vec_info.data_len, |
| 1982 | )..][0..vec_info.data_len]; |
| 1983 | |
| 1984 | data_base +%= vec_info.data_len +% 3; // extra 3 to help catch aliasing bugs |
| 1985 | |
| 1986 | for (0..splat) |_| expected_hash.update(vecs[vecs_n]); |
| 1987 | expected_size += @as(u32, @intCast(vecs[vecs_n].len)) * splat; |
| 1988 | vecs_n += 1; |
| 1989 | } |
| 1990 | |
| 1991 | const want_drain = vecs_n == vecs.len or vec_info.output or vec_info.rebase or |
| 1992 | in.seek == in.end; |
| 1993 | if (want_drain and vecs_n != 0) { |
| 1994 | try r.writer.writeSplatAll(vecs[0..vecs_n], splat); |
| 1995 | vecs_n = 0; |
| 1996 | } else assert(splat == 1); |
| 1997 | |
| 1998 | if (vec_info.rebase) { |
| 1999 | try r.writer.rebase(vec_info.data_len, @min( |
| 2000 | r.writer.buffer.len -| vec_info.data_len, |
| 2001 | vec_info.splat, |
| 2002 | )); |
| 2003 | } |
| 2004 | } |
| 2005 | |
| 2006 | try r.writer.flush(); |
| 2007 | try output.writer.flush(); |
| 2008 | |
| 2009 | try std.testing.expectEqual(.end, output.state); |
| 2010 | try std.testing.expectEqual(expected_size, output.data_size); |
| 2011 | switch (output.data_hash) { |
| 2012 | .raw => {}, |
| 2013 | .gzip => |gz| { |
| 2014 | const expected_crc = expected_hash.gzip.crc.final(); |
| 2015 | try std.testing.expectEqual(expected_crc, gz.crc.final()); |
| 2016 | try std.testing.expectEqual(expected_crc, output.footer_hash); |
| 2017 | try std.testing.expectEqual(expected_size, output.footer_size); |
| 2018 | }, |
| 2019 | .zlib => |zl| { |
| 2020 | const expected_adler = expected_hash.zlib.adler; |
| 2021 | try std.testing.expectEqual(expected_adler, zl.adler); |
| 2022 | try std.testing.expectEqual(expected_adler, output.footer_hash); |
| 2023 | }, |
| 2024 | } |
| 2025 | } |
| 2026 | |
| 2027 | /// Only performs huffman compression on data, does no matching. |
| 2028 | pub const Huffman = struct { |
| 2029 | writer: Writer, |
| 2030 | bit_writer: BitWriter, |
| 2031 | hasher: flate.Container.Hasher, |
| 2032 | |
| 2033 | const max_tokens: u16 = 65535 - 1; // one is reserved for EOF |
| 2034 | |
| 2035 | /// While there is no minimum buffer size, it is recommended |
| 2036 | /// to be at least `flate.max_window_len` to improve compression. |
| 2037 | /// |
| 2038 | /// It is asserted `output` has a capacity of at least 8 bytes. |
| 2039 | pub fn init(output: *Writer, buffer: []u8, container: flate.Container) Writer.Error!Huffman { |
| 2040 | assert(output.buffer.len > 8); |
| 2041 | |
| 2042 | try output.writeAll(container.header()); |
| 2043 | return .{ |
| 2044 | .writer = .{ |
| 2045 | .buffer = buffer, |
| 2046 | .vtable = &.{ |
| 2047 | .drain = Huffman.drain, |
| 2048 | .flush = Huffman.flush, |
| 2049 | .rebase = Huffman.rebase, |
| 2050 | }, |
| 2051 | }, |
| 2052 | .bit_writer = .init(output), |
| 2053 | .hasher = .init(container), |
| 2054 | }; |
| 2055 | } |
| 2056 | |
| 2057 | fn drain(w: *Writer, data: []const []const u8, splat: usize) Writer.Error!usize { |
| 2058 | { |
| 2059 | //std.debug.print("drain {} (buffered)", .{w.buffered().len}); |
| 2060 | //for (data) |d| std.debug.print("\n\t+ {}", .{d.len}); |
| 2061 | //std.debug.print(" x {}\n\n", .{splat}); |
| 2062 | } |
| 2063 | |
| 2064 | const h: *Huffman = @fieldParentPtr("writer", w); |
| 2065 | const min_block = @min(w.buffer.len, max_tokens); |
| 2066 | const pattern = data[data.len - 1]; |
| 2067 | |
| 2068 | const data_bytes = Writer.countSplat(data, splat); |
| 2069 | const total_bytes = w.end + data_bytes; |
| 2070 | var rem_bytes = total_bytes; |
| 2071 | var rem_splat = splat; |
| 2072 | var rem_data = data; |
| 2073 | var rem_data_elem: []const u8 = w.buffered(); |
| 2074 | |
| 2075 | assert(rem_bytes > min_block); |
| 2076 | while (rem_bytes > min_block) { // not >= to allow `min_block` blocks to be marked as final |
| 2077 | // also, it handles the case of `min_block` being zero (no buffer) |
| 2078 | const block_size: u16 = @min(rem_bytes, max_tokens); |
| 2079 | rem_bytes -= block_size; |
| 2080 | |
| 2081 | // Count frequencies |
| 2082 | comptime assert(max_tokens != 65535); |
| 2083 | var freqs: [257]u16 = @splat(0); |
| 2084 | freqs[256] = 1; |
| 2085 | |
| 2086 | const start_splat = rem_splat; |
| 2087 | const start_data = rem_data; |
| 2088 | const start_data_elem = rem_data_elem; |
| 2089 | |
| 2090 | var block_limit: Io.Limit = .limited(block_size); |
| 2091 | while (true) { |
| 2092 | const bytes = block_limit.sliceConst(rem_data_elem); |
| 2093 | const is_pattern = rem_splat != splat and bytes.len == pattern.len; |
| 2094 | |
| 2095 | const mul = if (!is_pattern) 1 else @intFromEnum(block_limit) / pattern.len; |
| 2096 | assert(mul != 0); |
| 2097 | if (is_pattern) assert(mul <= rem_splat + 1); // one more for `rem_data` |
| 2098 | |
| 2099 | for (bytes) |b| freqs[b] += @intCast(mul); |
| 2100 | rem_data_elem = rem_data_elem[bytes.len..]; |
| 2101 | block_limit = block_limit.subtract(bytes.len * mul).?; |
| 2102 | |
| 2103 | if (rem_data_elem.len == 0) { |
| 2104 | rem_data_elem = rem_data[0]; |
| 2105 | if (rem_data.len != 1) { |
| 2106 | rem_data = rem_data[1..]; |
| 2107 | } else if (rem_splat >= mul) { |
| 2108 | // if the counter was not the pattern, `mul` is always one, otherwise, |
| 2109 | // `mul` contains `rem_data`, however one more needs subtracted anyways |
| 2110 | // since the next pattern is also being taken. |
| 2111 | rem_splat -= mul; |
| 2112 | } else { |
| 2113 | // All of `data` has been consumed. |
| 2114 | assert(block_limit == .nothing); |
| 2115 | assert(rem_bytes == 0); |
| 2116 | // Since `rem_bytes` and `block_limit` are zero, these won't be used. |
| 2117 | rem_data = undefined; |
| 2118 | rem_data_elem = undefined; |
| 2119 | rem_splat = undefined; |
| 2120 | } |
| 2121 | } |
| 2122 | if (block_limit == .nothing) break; |
| 2123 | } |
| 2124 | |
| 2125 | // Output block |
| 2126 | rem_splat = start_splat; |
| 2127 | rem_data = start_data; |
| 2128 | rem_data_elem = start_data_elem; |
| 2129 | block_limit = .limited(block_size); |
| 2130 | |
| 2131 | var codes_buf: CodesBuf = .init; |
| 2132 | if (try h.outputHeader(&freqs, &codes_buf, block_size, false)) |table| { |
| 2133 | while (true) { |
| 2134 | const bytes = block_limit.sliceConst(rem_data_elem); |
| 2135 | rem_data_elem = rem_data_elem[bytes.len..]; |
| 2136 | block_limit = block_limit.subtract(bytes.len).?; |
| 2137 | |
| 2138 | h.hasher.update(bytes); |
| 2139 | for (bytes) |b| { |
| 2140 | try h.bit_writer.write(table.codes[b], table.bits[b]); |
| 2141 | } |
| 2142 | |
| 2143 | if (rem_data_elem.len == 0) { |
| 2144 | rem_data_elem = rem_data[0]; |
| 2145 | if (rem_data.len != 1) { |
| 2146 | rem_data = rem_data[1..]; |
| 2147 | } else if (rem_splat != 0) { |
| 2148 | rem_splat -= 1; |
| 2149 | } else { |
| 2150 | // All of `data` has been consumed. |
| 2151 | assert(block_limit == .nothing); |
| 2152 | assert(rem_bytes == 0); |
| 2153 | // Since `rem_bytes` and `block_limit` are zero, these won't be used. |
| 2154 | rem_data = undefined; |
| 2155 | rem_data_elem = undefined; |
| 2156 | rem_splat = undefined; |
| 2157 | } |
| 2158 | } |
| 2159 | if (block_limit == .nothing) break; |
| 2160 | } |
| 2161 | try h.bit_writer.write(table.codes[256], table.bits[256]); |
| 2162 | } else while (true) { |
| 2163 | // Store block |
| 2164 | |
| 2165 | // Write data that is not a full vector element |
| 2166 | const in_pattern = rem_splat != splat; |
| 2167 | const vec_elem_i, const in_data = |
| 2168 | @subWithOverflow(data.len - (rem_data.len - @intFromBool(in_pattern)), 1); |
| 2169 | const is_elem = in_data == 0 and data[vec_elem_i].len == rem_data_elem.len; |
| 2170 | |
| 2171 | if (!is_elem or rem_data_elem.len > @intFromEnum(block_limit)) { |
| 2172 | block_limit = block_limit.subtract(rem_data_elem.len) orelse { |
| 2173 | try h.bit_writer.output.writeAll(rem_data_elem[0..@intFromEnum(block_limit)]); |
| 2174 | h.hasher.update(rem_data_elem[0..@intFromEnum(block_limit)]); |
| 2175 | rem_data_elem = rem_data_elem[@intFromEnum(block_limit)..]; |
| 2176 | assert(rem_data_elem.len != 0); |
| 2177 | break; |
| 2178 | }; |
| 2179 | try h.bit_writer.output.writeAll(rem_data_elem); |
| 2180 | h.hasher.update(rem_data_elem); |
| 2181 | } else { |
| 2182 | // Put `rem_data_elem` back in `rem_data` |
| 2183 | if (!in_pattern) { |
| 2184 | rem_data = data[vec_elem_i..]; |
| 2185 | } else { |
| 2186 | rem_splat += 1; |
| 2187 | } |
| 2188 | } |
| 2189 | rem_data_elem = undefined; // it is always updated below |
| 2190 | |
| 2191 | // Send through as much of the original vector as possible |
| 2192 | var vec_n: usize = 0; |
| 2193 | var vlimit = block_limit; |
| 2194 | const vec_splat = while (rem_data[vec_n..].len != 1) { |
| 2195 | vlimit = vlimit.subtract(rem_data[vec_n].len) orelse break 1; |
| 2196 | vec_n += 1; |
| 2197 | } else vec_splat: { |
| 2198 | // For `pattern.len == 0`, the value of `vec_splat` does not matter. |
| 2199 | const vec_splat = @intFromEnum(vlimit) / @max(1, pattern.len); |
| 2200 | if (pattern.len != 0) assert(vec_splat <= rem_splat + 1); |
| 2201 | vlimit = vlimit.subtract(pattern.len * vec_splat).?; |
| 2202 | vec_n += 1; |
| 2203 | break :vec_splat vec_splat; |
| 2204 | }; |
| 2205 | |
| 2206 | const n = if (vec_n != 0) n: { |
| 2207 | assert(@intFromEnum(block_limit) - @intFromEnum(vlimit) == |
| 2208 | Writer.countSplat(rem_data[0..vec_n], vec_splat)); |
| 2209 | break :n try h.bit_writer.output.writeSplat(rem_data[0..vec_n], vec_splat); |
| 2210 | } else 0; // Still go into the case below to advance the vector |
| 2211 | block_limit = block_limit.subtract(n).?; |
| 2212 | var consumed: Io.Limit = .limited(n); |
| 2213 | |
| 2214 | while (rem_data.len != 1) { |
| 2215 | const elem = rem_data[0]; |
| 2216 | rem_data = rem_data[1..]; |
| 2217 | consumed = consumed.subtract(elem.len) orelse { |
| 2218 | h.hasher.update(elem[0..@intFromEnum(consumed)]); |
| 2219 | rem_data_elem = elem[@intFromEnum(consumed)..]; |
| 2220 | break; |
| 2221 | }; |
| 2222 | h.hasher.update(elem); |
| 2223 | } else { |
| 2224 | if (pattern.len == 0) { |
| 2225 | // All of `data` has been consumed. However, the general |
| 2226 | // case below does not work since it divides by zero. |
| 2227 | assert(consumed == .nothing); |
| 2228 | assert(block_limit == .nothing); |
| 2229 | assert(rem_bytes == 0); |
| 2230 | // Since `rem_bytes` and `block_limit` are zero, these won't be used. |
| 2231 | rem_splat = undefined; |
| 2232 | rem_data = undefined; |
| 2233 | rem_data_elem = undefined; |
| 2234 | break; |
| 2235 | } |
| 2236 | |
| 2237 | const splatted = @intFromEnum(consumed) / pattern.len; |
| 2238 | const partial = @intFromEnum(consumed) % pattern.len; |
| 2239 | for (0..splatted) |_| h.hasher.update(pattern); |
| 2240 | h.hasher.update(pattern[0..partial]); |
| 2241 | |
| 2242 | const taken_splat = splatted + 1; |
| 2243 | if (rem_splat >= taken_splat) { |
| 2244 | rem_splat -= taken_splat; |
| 2245 | rem_data_elem = pattern[partial..]; |
| 2246 | } else { |
| 2247 | // All of `data` has been consumed. |
| 2248 | assert(partial == 0); |
| 2249 | assert(block_limit == .nothing); |
| 2250 | assert(rem_bytes == 0); |
| 2251 | // Since `rem_bytes` and `block_limit` are zero, these won't be used. |
| 2252 | rem_data = undefined; |
| 2253 | rem_data_elem = undefined; |
| 2254 | rem_splat = undefined; |
| 2255 | } |
| 2256 | } |
| 2257 | |
| 2258 | if (block_limit == .nothing) break; |
| 2259 | } |
| 2260 | } |
| 2261 | |
| 2262 | if (rem_bytes > data_bytes) { |
| 2263 | assert(rem_bytes - data_bytes == rem_data_elem.len); |
| 2264 | assert(&rem_data_elem[0] == &w.buffer[total_bytes - rem_bytes]); |
| 2265 | } |
| 2266 | return w.consume(total_bytes - rem_bytes); |
| 2267 | } |
| 2268 | |
| 2269 | fn flush(w: *Writer) Writer.Error!void { |
| 2270 | defer w.* = .failing; |
| 2271 | const h: *Huffman = @fieldParentPtr("writer", w); |
| 2272 | try Huffman.rebaseInner(w, 0, w.buffer.len, true); |
| 2273 | try h.bit_writer.output.rebase(0, 1); |
| 2274 | h.bit_writer.byteAlign(); |
| 2275 | try h.hasher.writeFooter(h.bit_writer.output); |
| 2276 | } |
| 2277 | |
| 2278 | fn rebase(w: *Writer, preserve: usize, capacity: usize) Writer.Error!void { |
| 2279 | errdefer w.* = .failing; |
| 2280 | try Huffman.rebaseInner(w, preserve, capacity, false); |
| 2281 | } |
| 2282 | |
| 2283 | fn rebaseInner(w: *Writer, preserve: usize, capacity: usize, eos: bool) Writer.Error!void { |
| 2284 | const h: *Huffman = @fieldParentPtr("writer", w); |
| 2285 | assert(preserve + capacity <= w.buffer.len); |
| 2286 | if (eos) assert(capacity == w.buffer.len); |
| 2287 | |
| 2288 | const preserved = @min(w.end, preserve); |
| 2289 | var remaining = w.buffer[0 .. w.end - preserved]; |
| 2290 | while (remaining.len > max_tokens) { // not >= so there is always a block down below |
| 2291 | const bytes = remaining[0..max_tokens]; |
| 2292 | remaining = remaining[max_tokens..]; |
| 2293 | try h.outputBytes(bytes, false); |
| 2294 | } |
| 2295 | |
| 2296 | // eos check required for empty block |
| 2297 | if (w.buffer.len - (remaining.len + preserved) < capacity or eos) { |
| 2298 | const bytes = remaining; |
| 2299 | remaining = &.{}; |
| 2300 | try h.outputBytes(bytes, eos); |
| 2301 | } |
| 2302 | |
| 2303 | _ = w.consume(w.end - preserved - remaining.len); |
| 2304 | } |
| 2305 | |
| 2306 | fn outputBytes(h: *Huffman, bytes: []const u8, eos: bool) Writer.Error!void { |
| 2307 | comptime assert(max_tokens != 65535); |
| 2308 | assert(bytes.len <= max_tokens); |
| 2309 | var freqs: [257]u16 = @splat(0); |
| 2310 | freqs[256] = 1; |
| 2311 | for (bytes) |b| freqs[b] += 1; |
| 2312 | h.hasher.update(bytes); |
| 2313 | |
| 2314 | var codes_buf: CodesBuf = .init; |
| 2315 | if (try h.outputHeader(&freqs, &codes_buf, @intCast(bytes.len), eos)) |table| { |
| 2316 | for (bytes) |b| { |
| 2317 | try h.bit_writer.write(table.codes[b], table.bits[b]); |
| 2318 | } |
| 2319 | try h.bit_writer.write(table.codes[256], table.bits[256]); |
| 2320 | } else { |
| 2321 | try h.bit_writer.output.writeAll(bytes); |
| 2322 | } |
| 2323 | } |
| 2324 | |
| 2325 | const CodesBuf = struct { |
| 2326 | dyn_codes: [258]u16, |
| 2327 | dyn_bits: [258]u4, |
| 2328 | |
| 2329 | pub const init: CodesBuf = .{ |
| 2330 | .dyn_codes = @as([257]u16, undefined) ++ .{0}, |
| 2331 | .dyn_bits = @as([257]u4, @splat(0)) ++ .{1}, |
| 2332 | }; |
| 296 | 2333 | }; |
| 297 | | enc.generate(freqs[0..], 7); |
| 298 | | |
| 299 | | try testing.expectEqual(@as(u32, 141), enc.bitLength(freqs[0..])); |
| 300 | | |
| 301 | | try testing.expectEqual(@as(usize, 3), enc.codes[0].len); |
| 302 | | try testing.expectEqual(@as(usize, 6), enc.codes[1].len); |
| 303 | | try testing.expectEqual(@as(usize, 6), enc.codes[2].len); |
| 304 | | try testing.expectEqual(@as(usize, 5), enc.codes[3].len); |
| 305 | | try testing.expectEqual(@as(usize, 3), enc.codes[4].len); |
| 306 | | try testing.expectEqual(@as(usize, 2), enc.codes[5].len); |
| 307 | | try testing.expectEqual(@as(usize, 2), enc.codes[6].len); |
| 308 | | try testing.expectEqual(@as(usize, 6), enc.codes[7].len); |
| 309 | | try testing.expectEqual(@as(usize, 0), enc.codes[8].len); |
| 310 | | try testing.expectEqual(@as(usize, 0), enc.codes[9].len); |
| 311 | | try testing.expectEqual(@as(usize, 0), enc.codes[10].len); |
| 312 | | try testing.expectEqual(@as(usize, 0), enc.codes[11].len); |
| 313 | | try testing.expectEqual(@as(usize, 0), enc.codes[12].len); |
| 314 | | try testing.expectEqual(@as(usize, 0), enc.codes[13].len); |
| 315 | | try testing.expectEqual(@as(usize, 0), enc.codes[14].len); |
| 316 | | try testing.expectEqual(@as(usize, 0), enc.codes[15].len); |
| 317 | | try testing.expectEqual(@as(usize, 6), enc.codes[16].len); |
| 318 | | try testing.expectEqual(@as(usize, 5), enc.codes[17].len); |
| 319 | | try testing.expectEqual(@as(usize, 3), enc.codes[18].len); |
| 320 | | |
| 321 | | try testing.expectEqual(@as(u16, 0x0), enc.codes[5].code); |
| 322 | | try testing.expectEqual(@as(u16, 0x2), enc.codes[6].code); |
| 323 | | try testing.expectEqual(@as(u16, 0x1), enc.codes[0].code); |
| 324 | | try testing.expectEqual(@as(u16, 0x5), enc.codes[4].code); |
| 325 | | try testing.expectEqual(@as(u16, 0x3), enc.codes[18].code); |
| 326 | | try testing.expectEqual(@as(u16, 0x7), enc.codes[3].code); |
| 327 | | try testing.expectEqual(@as(u16, 0x17), enc.codes[17].code); |
| 328 | | try testing.expectEqual(@as(u16, 0x0f), enc.codes[1].code); |
| 329 | | try testing.expectEqual(@as(u16, 0x2f), enc.codes[2].code); |
| 330 | | try testing.expectEqual(@as(u16, 0x1f), enc.codes[7].code); |
| 331 | | try testing.expectEqual(@as(u16, 0x3f), enc.codes[16].code); |
| 2334 | |
| 2335 | /// Returns null if the block is stored. |
| 2336 | fn outputHeader( |
| 2337 | h: *Huffman, |
| 2338 | freqs: *const [257]u16, |
| 2339 | buf: *CodesBuf, |
| 2340 | bytes: u16, |
| 2341 | eos: bool, |
| 2342 | ) Writer.Error!?struct { |
| 2343 | codes: *const [257]u16, |
| 2344 | bits: *const [257]u4, |
| 2345 | } { |
| 2346 | assert(freqs[256] == 1); |
| 2347 | const dyn_codes_bitsize, _ = huffman.build( |
| 2348 | freqs, |
| 2349 | buf.dyn_codes[0..257], |
| 2350 | buf.dyn_bits[0..257], |
| 2351 | 15, |
| 2352 | true, |
| 2353 | ); |
| 2354 | |
| 2355 | var clen_values: [258]u8 = undefined; |
| 2356 | var clen_extra: [258]u8 = undefined; |
| 2357 | var clen_freqs: [19]u16 = @splat(0); |
| 2358 | const clen_len, const clen_extra_bitsize = buildClen( |
| 2359 | &buf.dyn_bits, |
| 2360 | &clen_values, |
| 2361 | &clen_extra, |
| 2362 | &clen_freqs, |
| 2363 | ); |
| 2364 | |
| 2365 | var clen_codes: [19]u16 = undefined; |
| 2366 | var clen_bits: [19]u4 = @splat(0); |
| 2367 | const clen_codes_bitsize, _ = huffman.build( |
| 2368 | &clen_freqs, |
| 2369 | &clen_codes, |
| 2370 | &clen_bits, |
| 2371 | 7, |
| 2372 | false, |
| 2373 | ); |
| 2374 | const hclen = clenHlen(clen_freqs); |
| 2375 | |
| 2376 | const dynamic_bitsize = @as(u32, 14) + |
| 2377 | (4 + @as(u6, hclen)) * 3 + clen_codes_bitsize + clen_extra_bitsize + |
| 2378 | dyn_codes_bitsize; |
| 2379 | const fixed_bitsize = n: { |
| 2380 | const freq7 = 1; // eos |
| 2381 | var freq9: u16 = 0; |
| 2382 | for (freqs[144..256]) |f| freq9 += f; |
| 2383 | const freq8: u16 = bytes - freq9; |
| 2384 | break :n @as(u32, freq7) * 7 + @as(u32, freq8) * 8 + @as(u32, freq9) * 9; |
| 2385 | }; |
| 2386 | const stored_bitsize = n: { |
| 2387 | const stored_align_bits = -%(h.bit_writer.buffered_n +% 3); |
| 2388 | break :n stored_align_bits + @as(u32, 32) + @as(u32, bytes) * 8; |
| 2389 | }; |
| 2390 | |
| 2391 | //std.debug.print("@ {}{{{}}} ", .{ h.bit_writer.output.end, h.bit_writer.buffered_n }); |
| 2392 | //std.debug.print("#{} -> s {} f {} d {}\n", .{ bytes, stored_bitsize, fixed_bitsize, dynamic_bitsize }); |
| 2393 | |
| 2394 | if (stored_bitsize <= @min(dynamic_bitsize, fixed_bitsize)) { |
| 2395 | try h.bit_writer.write(BlockHeader.int(.{ .kind = .stored, .final = eos }), 3); |
| 2396 | try h.bit_writer.output.rebase(0, 5); |
| 2397 | h.bit_writer.byteAlign(); |
| 2398 | h.bit_writer.output.writeInt(u16, bytes, .little) catch unreachable; |
| 2399 | h.bit_writer.output.writeInt(u16, ~bytes, .little) catch unreachable; |
| 2400 | return null; |
| 2401 | } |
| 2402 | |
| 2403 | if (fixed_bitsize <= dynamic_bitsize) { |
| 2404 | try h.bit_writer.write(BlockHeader.int(.{ .final = eos, .kind = .fixed }), 3); |
| 2405 | return .{ |
| 2406 | .codes = token.fixed_lit_codes[0..257], |
| 2407 | .bits = token.fixed_lit_bits[0..257], |
| 2408 | }; |
| 2409 | } else { |
| 2410 | try h.bit_writer.write(BlockHeader.Dynamic.int(.{ |
| 2411 | .regular = .{ .final = eos, .kind = .dynamic }, |
| 2412 | .hlit = 0, |
| 2413 | .hdist = 0, |
| 2414 | .hclen = hclen, |
| 2415 | }), 17); |
| 2416 | try h.bit_writer.writeClen( |
| 2417 | hclen, |
| 2418 | clen_values[0..clen_len], |
| 2419 | clen_extra[0..clen_len], |
| 2420 | clen_codes, |
| 2421 | clen_bits, |
| 2422 | ); |
| 2423 | return .{ .codes = buf.dyn_codes[0..257], .bits = buf.dyn_bits[0..257] }; |
| 2424 | } |
| 2425 | } |
| 2426 | }; |
| 2427 | |
| 2428 | test Huffman { |
| 2429 | const fbufs = try testingFreqBufs(); |
| 2430 | defer if (!builtin.fuzz) std.testing.allocator.destroy(fbufs); |
| 2431 | try std.testing.fuzz(fbufs, testFuzzedHuffmanInput, .{}); |
| 2432 | } |
| 2433 | |
| 2434 | /// This function is derived from `testFuzzedRawInput` with a few changes for fuzzing `Huffman`. |
| 2435 | fn testFuzzedHuffmanInput(fbufs: *const [2][65536]u8, input: []const u8) !void { |
| 2436 | var in: Io.Reader = .fixed(input); |
| 2437 | const opts: packed struct(u19) { |
| 2438 | container: PackedContainer, |
| 2439 | buf_len: u17, |
| 2440 | } = @bitCast(in.takeLeb128(u19) catch 0); |
| 2441 | var flate_buf: [2 * 65536]u8 = undefined; |
| 2442 | var flate_w: Writer = .fixed(&flate_buf); |
| 2443 | var h_buf: [2 * 65536]u8 = undefined; |
| 2444 | var h: Huffman = try .init( |
| 2445 | &flate_w, |
| 2446 | h_buf[0 .. opts.buf_len +% flate.max_window_len], |
| 2447 | opts.container.val(), |
| 2448 | ); |
| 2449 | |
| 2450 | var expected_hash: flate.Container.Hasher = .init(opts.container.val()); |
| 2451 | var expected_size: u32 = 0; |
| 2452 | var vecs: [32][]const u8 = undefined; |
| 2453 | var vecs_n: usize = 0; |
| 2454 | |
| 2455 | while (in.seek != in.end) { |
| 2456 | const VecInfo = packed struct(u55) { |
| 2457 | output: bool, |
| 2458 | /// If set, `data_len` and `splat` are reinterpreted as `capacity` |
| 2459 | /// and `preserve_len` respectively and `output` is treated as set. |
| 2460 | rebase: bool, |
| 2461 | block_aligning_len: bool, |
| 2462 | block_aligning_splat: bool, |
| 2463 | data_off_hi: u8, |
| 2464 | random_data: u1, |
| 2465 | data_len: u16, |
| 2466 | splat: u18, |
| 2467 | /// This is less useful as each value is part of the same gradient 'step' |
| 2468 | data_off_lo: u8, |
| 2469 | }; |
| 2470 | var vec_info: VecInfo = @bitCast(in.takeLeb128(u55) catch |e| switch (e) { |
| 2471 | error.ReadFailed => unreachable, |
| 2472 | error.Overflow, error.EndOfStream => 0, |
| 2473 | }); |
| 2474 | |
| 2475 | { |
| 2476 | const buffered = h.writer.buffered().len + countVec(vecs[0..vecs_n]); |
| 2477 | const to_align = mem.alignForwardAnyAlign(usize, buffered, Huffman.max_tokens) - buffered; |
| 2478 | assert((buffered + to_align) % Huffman.max_tokens == 0); |
| 2479 | |
| 2480 | if (vec_info.block_aligning_len) { |
| 2481 | vec_info.data_len = @intCast(to_align); |
| 2482 | } else if (vec_info.block_aligning_splat and vec_info.data_len != 0 and |
| 2483 | to_align % vec_info.data_len == 0) |
| 2484 | { |
| 2485 | vec_info.splat = @divExact(@as(u18, @intCast(to_align)), vec_info.data_len) -% 1; |
| 2486 | } |
| 2487 | } |
| 2488 | |
| 2489 | var splat = if (vec_info.output and !vec_info.rebase) vec_info.splat +% 1 else 1; |
| 2490 | add_vec: { |
| 2491 | if (vec_info.rebase) break :add_vec; |
| 2492 | if (expected_size +| math.mulWide(u18, vec_info.data_len, splat) > 4 * (1 << 16)) { |
| 2493 | // Skip this vector to avoid this test taking too long. |
| 2494 | splat = 1; |
| 2495 | break :add_vec; |
| 2496 | } |
| 2497 | |
| 2498 | const data_buf = &fbufs[vec_info.random_data]; |
| 2499 | vecs[vecs_n] = data_buf[@min( |
| 2500 | (@as(u16, vec_info.data_off_hi) << 8) | vec_info.data_off_lo, |
| 2501 | data_buf.len - vec_info.data_len, |
| 2502 | )..][0..vec_info.data_len]; |
| 2503 | |
| 2504 | for (0..splat) |_| expected_hash.update(vecs[vecs_n]); |
| 2505 | expected_size += @as(u32, @intCast(vecs[vecs_n].len)) * splat; |
| 2506 | vecs_n += 1; |
| 2507 | } |
| 2508 | |
| 2509 | const want_drain = vecs_n == vecs.len or vec_info.output or vec_info.rebase or |
| 2510 | in.seek == in.end; |
| 2511 | if (want_drain and vecs_n != 0) { |
| 2512 | var n = h.writer.buffered().len + Writer.countSplat(vecs[0..vecs_n], splat); |
| 2513 | const oos = h.writer.writeSplatAll(vecs[0..vecs_n], splat) == error.WriteFailed; |
| 2514 | n -= h.writer.buffered().len; |
| 2515 | const block_lim = math.divCeil(usize, n, Huffman.max_tokens) catch unreachable; |
| 2516 | const lim = flate_w.end + 6 * block_lim + n; // 6 since block header may span two bytes |
| 2517 | if (flate_w.end > lim) return error.OverheadTooLarge; |
| 2518 | if (oos) return; |
| 2519 | |
| 2520 | vecs_n = 0; |
| 2521 | } else assert(splat == 1); |
| 2522 | |
| 2523 | if (vec_info.rebase) { |
| 2524 | const old_end = flate_w.end; |
| 2525 | var n = h.writer.buffered().len; |
| 2526 | const oos = h.writer.rebase(vec_info.data_len, @min( |
| 2527 | h.writer.buffer.len -| vec_info.data_len, |
| 2528 | vec_info.splat, |
| 2529 | )) == error.WriteFailed; |
| 2530 | n -= h.writer.buffered().len; |
| 2531 | const block_lim = math.divCeil(usize, n, Huffman.max_tokens) catch unreachable; |
| 2532 | const lim = old_end + 6 * block_lim + n; // 6 since block header may span two bytes |
| 2533 | if (flate_w.end > lim) return error.OverheadTooLarge; |
| 2534 | if (oos) return; |
| 2535 | } |
| 2536 | } |
| 2537 | |
| 2538 | { |
| 2539 | const old_end = flate_w.end; |
| 2540 | const n = h.writer.buffered().len; |
| 2541 | const oos = h.writer.flush() == error.WriteFailed; |
| 2542 | assert(h.writer.buffered().len == 0); |
| 2543 | const block_lim = @max(1, math.divCeil(usize, n, Huffman.max_tokens) catch unreachable); |
| 2544 | const lim = old_end + 6 * block_lim + n + opts.container.val().footerSize(); |
| 2545 | if (flate_w.end > lim) return error.OverheadTooLarge; |
| 2546 | if (oos) return; |
| 2547 | } |
| 2548 | |
| 2549 | try testingCheckDecompressedMatches(flate_w.buffered(), expected_size, expected_hash); |
| 332 | 2550 | } |