╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ search.zig ───────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
21 22 // move `doc_key` from `old_text`'s words to `new_text`'s. the words they share 23 // are left alone, so editing a long description costs what the edit changed 24 // rather than the whole text. an empty side adds or drops the document. 25 pub fn replace( 26 comptime DB: type, 27 index: DB.SortedMap(.read_write), 28 allocator: std.mem.Allocator, 29 doc_key: []const u8, 30 old_text: []const u8, 31 new_text: []const u8, 32 ) !void { 33 var arena = std.heap.ArenaAllocator.init(allocator); 34 defer arena.deinit(); 35 const aa = arena.allocator(); 36 const old_words = try tokenize(aa, old_text); 37 const new_words = try tokenize(aa, new_text); 38 39 for (old_words) |word| { 40 if (!contains(new_words, word)) try removeWord(DB, index, doc_key, word); 41 } 42 for (new_words) |word| { 43 if (!contains(old_words, word)) try addWord(DB, index, doc_key, word); 44 } 45 } 46 47 // a document contributes at most max_words_per_doc words, so a scan costs less 48 // than building a second map 49 fn contains(words: []const []const u8, word: []const u8) bool { 50 for (words) |candidate| { 51 if (std.mem.eql(u8, candidate, word)) return true; 52 } 53 return false; 54 } 55 56 fn addWord(comptime DB: type, index: DB.SortedMap(.read_write), doc_key: []const u8, word: []const u8) !void { 57 const set = try DB.SortedSet(.read_write).init(try index.putCursor(word)); 58 try set.put(doc_key); 59 } 60 61 fn removeWord(comptime DB: type, index: DB.SortedMap(.read_write), doc_key: []const u8, word: []const u8) !void { 62 if (null == try index.getCursor(word)) return; 63 const set = try DB.SortedSet(.read_write).init(try index.putCursor(word)); 64 _ = try set.remove(doc_key); 65 if (0 == try set.count()) _ = try index.remove(word); 66 } 67 68 // the doc keys holding every typed word, in key order. a stream, so callers 69 // stop at their page size. 70 pub fn Query(comptime DB: type) type { 71 return struct { 72 // one per typed word; empty when nothing can match 73 terms: std.ArrayList(Term), 74 // the key the next result starts from, plus room for the one byte that 75 // steps past a returned key 76 pos: [max_doc_key_len + 1]u8 = undefined, 77 pos_len: usize = 0, 78 // whether `pos` holds a key that was already returned 79 returned: bool = false, 80 81 const Self = @This(); 82 83 // one typed word: the doc keys of every indexed word it expands to, 84 // merged into one ascending stream. 85 const Term = struct { 86 postings: []Posting, 87 88 // the smallest doc key at or after `key`, or null when the term is 89 // exhausted. 90 fn seek(self: *Term, key: []const u8) !?[]const u8 { 91 var best: ?[]const u8 = null; 92 for (self.postings) |*posting| { 93 try posting.advance(key); 94 if (posting.done) continue; 95 const current = posting.key[0..posting.key_len]; 96 if (best) |found| { 97 if (std.mem.order(u8, current, found) == .lt) best = current; 98 } else best = current; 99 } 100 return best; 101 } 102 }; 103 104 // one indexed word's doc keys, positioned at the current one. 105 const Posting = struct { 106 set: DB.SortedSet(.read_only), 107 iter: DB.Cursor(.read_only).Iter = undefined, 108 key: [max_doc_key_len]u8 = undefined, 109 key_len: usize = 0, 110 done: bool = false, 111 started: bool = false, 112 113 // move to the first key at or after `key`. one step reaches it in 114 // a dense posting, and a seek skips the rest of a sparse one. 115 fn advance(self: *Posting, key: []const u8) !void { 116 if (self.done) return; 117 if (self.started) { 118 if (std.mem.order(u8, self.key[0..self.key_len], key) != .lt) return; 119 try self.step(); 120 if (self.done or std.mem.order(u8, self.key[0..self.key_len], key) != .lt) return; 121 } 122 self.iter = try self.set.iteratorFrom(key); 123 self.started = true; 124 try self.step(); 125 } 126 127 fn step(self: *Posting) !void { 128 const cursor = (try self.iter.next()) orelse { 129 self.done = true; 130 return; 131 }; 132 const pair = try cursor.readKeyValuePair(); 133 self.key_len = (try pair.key_cursor.readBytes(&self.key)).len; 134 } 135 }; 136 137 pub fn init(index: DB.SortedMap(.read_only), aa: std.mem.Allocator, text: []const u8) !Self { 138 var terms: std.ArrayList(Term) = .empty; 139 for (try tokenize(aa, text)) |word| { 140 var postings: std.ArrayList(Posting) = .empty; 141 var iter = try index.iteratorFrom(word); 142 while (try iter.next()) |cursor| { 143 if (postings.items.len == max_expansions) break; 144 const pair = try cursor.readKeyValuePair(); 145 var buffer: [max_word_len]u8 = undefined; 146 const indexed = try pair.key_cursor.readBytes(&buffer); 147 if (!std.mem.startsWith(u8, indexed, word)) break; 148 try postings.append(aa, .{ .set = try DB.SortedSet(.read_only).init(pair.value_cursor) }); 149 } 150 // a word nothing starts with rules out every document 151 if (postings.items.len == 0) return .{ .terms = .empty }; 152 try terms.append(aa, .{ .postings = postings.items }); 153 } 154 return .{ .terms = terms }; 155 } 156 157 // narrow the results to the doc keys in `set`. it is one more term, 158 // with that set as its only posting. a query nothing can match stays 159 // empty, since requiring a set would turn it into every doc key in it. 160 pub fn require(self: *Self, aa: std.mem.Allocator, set: DB.SortedSet(.read_only)) !void { 161 if (self.terms.items.len == 0) return; 162 const postings = try aa.alloc(Posting, 1); 163 postings[0] = .{ .set = set }; 164 try self.terms.append(aa, .{ .postings = postings }); 165 } 166 167 // start the next result at `key` rather than the first one. 168 pub fn seek(self: *Self, key: []const u8) void { 169 @memcpy(self.pos[0..key.len], key); 170 self.pos_len = key.len; 171 self.returned = false; 172 } 173 174 pub fn next(self: *Self) !?[]const u8 { 175 if (self.terms.items.len == 0) return null; 176 if (self.returned) { 177 // doc keys are at most max_doc_key_len, so appending a byte 178 // lands strictly after the one just returned 179 self.pos[self.pos_len] = 0; 180 self.pos_len += 1; 181 self.returned = false; 182 } 183 // intersect by seeking: a term that lands past the candidate makes 184 // its key the new candidate and the others seek up to it. 185 var i: usize = 0; 186 while (i < self.terms.items.len) { 187 const key = (try self.terms.items[i].seek(self.pos[0..self.pos_len])) orelse return null; 188 if (std.mem.order(u8, key, self.pos[0..self.pos_len]) == .gt) { 189 @memcpy(self.pos[0..key.len], key); 190 self.pos_len = key.len; 191 i = 0; 192 continue; 193 } 194 i += 1; 195 } 196 self.returned = true; 197 return self.pos[0..self.pos_len]; 198 } 199 }; 200 } 201 202 // the unique lowercased words of `text`, in the order they first appear. 203 fn tokenize(aa: std.mem.Allocator, text: []const u8) ![]const []const u8 { 204 var words: std.StringArrayHashMapUnmanaged(void) = .empty; 205 const limit = @min(text.len, max_indexed_bytes); 206 var i: usize = 0; 207 while (i < limit) { 208 if (!isWordByte(text[i])) { 209 i += 1; 210 continue; 211 } 212 const start = i; 213 while (i < limit and isWordByte(text[i])) i += 1; 214 const word = text[start..@min(i, start + max_word_len)]; 215 if (word.len < min_word_len) continue; 216 const lowered = try aa.alloc(u8, word.len); 217 _ = std.ascii.lowerString(lowered, word); 218 try words.put(aa, lowered, {}); 219 if (words.count() == max_words_per_doc) break; 220 } 221 return words.keys(); 222 } 223 224 // a word is a run of ascii alphanumerics and non-ascii bytes. 225 fn isWordByte(byte: u8) bool { 226 return std.ascii.isAlphanumeric(byte) or byte >= 0x80; 227 } 228