// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Finds static dictionary words, transformed, at a position in the input. //! //! Every word of the dictionary is filed under a hash of its first four //! bytes with ASCII letters folded to lower case, so that one lookup finds a //! word whether the input has it as it is or with capitals, which two //! families of transforms produce. Only transforms with no prefix are tried, //! since the lookup is keyed on the word's own first bytes; those are 86 of //! the 121, and between them they cover a word followed by a space, by //! punctuation, by " the " and the like, a word cut short at the end, and //! words capitalized or in capitals. //! //! Every match is checked by applying the transform to the word and //! comparing the result with the input, so nothing found here can decompress //! to anything but what was there. const std = @import("std"); const dictionary = @import("dictionary.zig"); const transform = @import("transform.zig"); const DictionaryIndex = @This(); /// How many words the dictionary holds. pub const num_words = blk: { var n: usize = 0; for (dictionary.min_word_length..dictionary.max_word_length + 1) |len| { n += @as(usize, 1) << dictionary.size_bits_by_length[len]; } break :blk n; }; const hash_bits = 15; const empty = std.math.maxInt(u16); /// For each bucket, the first word filed there, as an index into `words`. head: *const [1 << hash_bits]u16, /// For each word, the next in the same bucket. next: *const [num_words]u16, /// Each word as its length and index, `length << 11 | index`. words: *const [num_words]u16, /// The index, built the first time any compressor in the process wants it /// and shared by all of them from then on. It is about 118 KiB and takes /// microseconds to build. Building it while compiling would spare even /// that, but costs the compiler gigabytes. pub fn shared() *const DictionaryIndex { if (shared_state.load(.acquire) == ready) return &shared_index; if (shared_state.cmpxchgStrong(unbuilt, building, .acquire, .monotonic) == null) { build(&shared_head, &shared_next, &shared_words); shared_state.store(ready, .release); } else { // Another thread is building it; it will not be long. while (shared_state.load(.acquire) != ready) std.atomic.spinLoopHint(); } return &shared_index; } const unbuilt = 0; const building = 1; const ready = 2; var shared_state: std.atomic.Value(u8) = .init(unbuilt); var shared_head: [1 << hash_bits]u16 = undefined; var shared_next: [num_words]u16 = undefined; var shared_words: [num_words]u16 = undefined; const shared_index: DictionaryIndex = .{ .head = &shared_head, .next = &shared_next, .words = &shared_words }; fn build(head: *[1 << hash_bits]u16, next: *[num_words]u16, words: *[num_words]u16) void { @memset(head, empty); var n: u16 = 0; // Longest words last, so that a bucket's chain starts with them: a // longer match is the better one, and is found first. for (dictionary.min_word_length..dictionary.max_word_length + 1) |len| { for (0..@as(usize, 1) << dictionary.size_bits_by_length[len]) |index| { const word = dictionary.word(len, index); const h = hash(word[0..4]); words[n] = @intCast(len << 11 | index); next[n] = head[h]; head[h] = n; n += 1; } } } fn hash(bytes: *const [4]u8) usize { var folded: [4]u8 = undefined; for (bytes, &folded) |b, *f| f.* = std.ascii.toLower(b); const v = std.mem.readInt(u32, &folded, .little); return @intCast((v *% 0x1E35A7BD) >> (32 - hash_bits)); } /// A transformed dictionary word found in the input. pub const Match = struct { /// How many bytes of input it stands for. output_length: u32, /// The length of the base word, which is the copy length the command /// carries. word_length: u32, /// The word's index among those of its length, and the transform. word_index: u32, transform_id: u32, /// The distance that refers to it, from a position where copies can /// reach `max_distance` back (RFC 7932 §8). pub fn distance(m: Match, max_distance: u32) u32 { const id = m.word_index | (m.transform_id << dictionary.size_bits_by_length[m.word_length]); return max_distance + 1 + id; } }; /// Transform IDs with no prefix, grouped by what they do to the word. const Groups = struct { identity: []const u8, omit_last: []const u8, ferment: []const u8, /// The identity transforms with a suffix, by the suffix's first byte, /// longest suffix first, so that the first that fits is the best. by_suffix: [256][]const u8, }; const groups: Groups = blk: { var identity: []const u8 = &.{}; var omit_last: []const u8 = &.{}; var ferment: []const u8 = &.{}; for (transform.transforms, 0..) |t, id| { if (t.prefix.len != 0) continue; switch (t.op) { .identity => identity = identity ++ .{id}, .omit_last => omit_last = omit_last ++ .{id}, .ferment_first, .ferment_all => ferment = ferment ++ .{id}, .omit_first => {}, } } var by_suffix: [256][]const u8 = @splat(&.{}); for (identity) |id| { const suffix = transform.transforms[id].suffix; if (suffix.len == 0) continue; by_suffix[suffix[0]] = by_suffix[suffix[0]] ++ .{id}; } @setEvalBranchQuota(100_000); for (&by_suffix) |*list| { var sorted: [list.len]u8 = list.*[0..list.len].*; std.mem.sort(u8, &sorted, {}, struct { fn lessThan(_: void, a: u8, b: u8) bool { const la = transform.transforms[a].suffix.len; const lb = transform.transforms[b].suffix.len; return la > lb or (la == lb and a < b); } }.lessThan); const final = sorted; list.* = &final; } break :blk .{ .identity = identity, .omit_last = omit_last, .ferment = ferment, .by_suffix = by_suffix }; }; /// The longest a transformed word can be. pub const max_output_length = transform.max_word_length; /// The longest transformed word that `input` starts with, if any is four /// bytes or longer. pub fn find(d: *const DictionaryIndex, input: []const u8) ?Match { if (input.len < dictionary.min_word_length) return null; var best: ?Match = null; var e = d.head[hash(input[0..4])]; while (e != empty) : (e = d.next[e]) { const len: u32 = d.words[e] >> 11; const index: u32 = d.words[e] & 0x7ff; const word = dictionary.word(len, index); if (!std.ascii.eqlIgnoreCase(word[0..4], input[0..4])) continue; // How much of the word the input has exactly as it is. var exact: u32 = 0; while (exact < len and exact < input.len and word[exact] == input[exact]) exact += 1; if (exact == len) { consider(&best, len, len, index, 0); if (input.len > len) { for (groups.by_suffix[input[len]]) |id| { const suffix = transform.transforms[id].suffix; if (std.mem.startsWith(u8, input[len..], suffix)) { consider(&best, len + @as(u32, @intCast(suffix.len)), len, index, id); break; } } } } for (groups.omit_last) |id| { const t = transform.transforms[id]; if (t.op.omit_last >= len) continue; const body = len - t.op.omit_last; if (body > exact) continue; if (std.mem.startsWith(u8, input[body..], t.suffix)) { consider(&best, body + @as(u32, @intCast(t.suffix.len)), len, index, id); } } // Capitals: only worth trying where the word differs from the input // and folding case makes them agree. if (exact < len and len <= input.len and std.ascii.eqlIgnoreCase(word, input[0..len])) { for (groups.ferment) |id| { const t = transform.transforms[id]; var buf: [transform.max_word_length]u8 = undefined; const n = transform.apply(t, word, &buf); if (std.mem.startsWith(u8, input, buf[0..n])) { consider(&best, @intCast(n), len, index, id); } } } } return best; } fn consider(best: *?Match, output_length: u32, word_length: u32, word_index: u32, transform_id: u32) void { if (output_length < dictionary.min_word_length) return; if (best.*) |b| { // Longer is better; on a tie, a smaller transform ID makes a // smaller distance. if (output_length < b.output_length) return; if (output_length == b.output_length and transform_id >= b.transform_id) return; } best.* = .{ .output_length = output_length, .word_length = word_length, .word_index = word_index, .transform_id = transform_id, }; } test "finds words, transformed, and only what is there" { const d = shared(); try std.testing.expectEqual(transform.transforms.len - 35, groups.identity.len + groups.omit_last.len + groups.ferment.len + 8); const cases = [_][]const u8{ "time", "time is", "Time ", "TIME, ", "times of the year", "the end", "abcd efgh", }; for (cases) |input| { const m = d.find(input) orelse continue; // Whatever it found must be what the decompressor would make. var buf: [transform.max_word_length]u8 = undefined; const word = dictionary.word(m.word_length, m.word_index); const n = transform.apply(transform.transforms[m.transform_id], word, &buf); try std.testing.expectEqual(m.output_length, n); try std.testing.expectEqualStrings(input[0..n], buf[0..n]); } // "time in" with its last byte cut off beats "time" and a space. try std.testing.expectEqual(6, d.find("time is").?.output_length); try std.testing.expectEqual(5, d.find("Time ").?.output_length); try std.testing.expectEqual(null, d.find("xqzv")); }