Zig 0.17.0-dev (Split by item)

This is an example of documentation generated by ZigDoc, an alternative to Zig's built-in Auto Doc feature. See also examples in other modes/formats. The project being documented here (as the example) is the Zig library itself.

addHash

Compress.addHash
fn addHash(c: *Compress, i: usize, h: Hash) void

File

lib/std/compress/flate/Compress.zig:543

Code

fn addHash(c: *Compress, i: usize, h: Hash) void {
    assert(h == hash(mem.readInt(Seq, c.writer.buffer[i..][0..seq_bytes], .big)));

    const l = &c.lookup;
    l.chain_pos +%= 1;

    // Equivilent to the below, however LLVM 21 does not optimize `@subWithOverflow` well at all.
    // const replaced_i, const no_replace = @subWithOverflow(i, flate.history_len);
    // if (no_replace == 0) {
    if (i >= flate.history_len) {
        @branchHint(.likely);
        const replaced_i = i - flate.history_len;
        // The following is the same as the below except uses a 32-bit load to help optimizations
        // const replaced_seq = mem.readInt(Seq, c.writer.buffer[replaced_i..][0..seq_bytes], .big);
        comptime assert(@sizeOf(Seq) <= @sizeOf(u32));
        const replaced_u32 = mem.readInt(u32, c.writer.buffered()[replaced_i..][0..4], .big);
        const replaced_seq: Seq = @intCast(replaced_u32 >> (32 - @bitSizeOf(Seq)));

        const replaced_h = hash(replaced_seq);
        // The following is equivilent to the below since LLVM 21 doesn't optimize it well.
        // l.head[replaced_h].is_null = l.head[replaced_h].is_null or
        //     l.head[replaced_h].int() == l.chain_pos;
        const empty_head = l.head[replaced_h].int() == l.chain_pos;
        const null_flag = PackedOptionalU15.int(.{ .is_null = empty_head, .value = 0 });
        l.head[replaced_h] = @bitCast(l.head[replaced_h].int() | null_flag);
    }

    const prev_chain_index = l.head[h];
    l.chain[l.chain_pos] = @bitCast((l.chain_pos -% prev_chain_index.value) |
        (prev_chain_index.int() & PackedOptionalU15.null_bit.int())); // Preserves null
    l.head[h] = .{ .value = l.chain_pos, .is_null = false };
}