16 #include <sys/types.h>
18 #include <unordered_map>
24 #define P4NENC_BOUND(n) ((n + 127) / 128 + (n + 32) * sizeof(uint32_t))
26 //#define dprintf(...) fprintf(stderr, __VA_ARGS__);
29 using namespace std::chrono;
31 string zstd_compress(const string &src, string *tempbuf);
33 static inline uint32_t read_unigram(const string_view s, size_t idx)
36 return (unsigned char)s[idx];
42 static inline uint32_t read_trigram(const string_view s, size_t start)
44 return read_unigram(s, start) |
45 (read_unigram(s, start + 1) << 8) |
46 (read_unigram(s, start + 2) << 16);
50 DBE_NORMAL = 0, /* A non-directory file */
51 DBE_DIRECTORY = 1, /* A directory */
52 DBE_END = 2 /* End of directory contents; contains no name */
60 uint8_t check_visibility;
71 class PostingListBuilder {
73 void add_docid(uint32_t docid);
77 size_t num_docids = 0;
80 void write_header(uint32_t docid);
83 vector<uint32_t> pending_docids;
85 uint32_t last_block_end;
88 void PostingListBuilder::add_docid(uint32_t docid)
90 // Deduplicate against the last inserted value, if any.
91 if (pending_docids.empty()) {
92 if (encoded.empty()) {
96 last_block_end = docid;
98 } else if (docid == last_block_end) {
102 if (docid == pending_docids.back()) {
107 pending_docids.push_back(docid);
108 if (pending_docids.size() == 128) {
110 pending_docids.clear();
111 last_block_end = docid;
116 void PostingListBuilder::finish()
118 if (pending_docids.empty()) {
122 assert(!encoded.empty()); // write_header() should already have run.
124 // No interleaving for partial blocks.
125 unsigned char buf[P4NENC_BOUND(128)];
126 unsigned char *end = p4d1enc32(pending_docids.data(), pending_docids.size(), buf, last_block_end);
127 encoded.append(reinterpret_cast<char *>(buf), reinterpret_cast<char *>(end));
130 void PostingListBuilder::append_block()
132 unsigned char buf[P4NENC_BOUND(128)];
133 assert(pending_docids.size() == 128);
134 unsigned char *end = p4d1enc128v32(pending_docids.data(), 128, buf, last_block_end);
135 encoded.append(reinterpret_cast<char *>(buf), reinterpret_cast<char *>(end));
138 void PostingListBuilder::write_header(uint32_t docid)
140 unsigned char buf[P4NENC_BOUND(1)];
141 size_t bytes = p4nd1enc128v32(&docid, 1, buf);
142 encoded.append(reinterpret_cast<char *>(buf), bytes);
147 Corpus(size_t block_size)
148 : block_size(block_size) {}
149 void add_file(string filename);
152 vector<string> filename_blocks;
153 unordered_map<uint32_t, PostingListBuilder> invindex;
154 size_t num_files = 0, num_files_in_block = 0, num_blocks = 0;
157 string current_block;
159 const size_t block_size;
162 void Corpus::add_file(string filename)
165 if (!current_block.empty()) {
166 current_block.push_back('\0');
168 current_block += filename;
169 if (++num_files_in_block == block_size) {
174 void Corpus::flush_block()
176 if (current_block.empty()) {
180 uint32_t docid = num_blocks;
183 const char *ptr = current_block.c_str();
184 while (ptr < current_block.c_str() + current_block.size()) {
187 for (size_t j = 0; j < s.size() - 2; ++j) {
188 uint32_t trgm = read_trigram(s, j);
189 invindex[trgm].add_docid(docid);
195 // Compress and add the filename block.
196 filename_blocks.push_back(zstd_compress(current_block, &tempbuf));
198 current_block.clear();
199 num_files_in_block = 0;
203 const char *handle_directory(const char *ptr, Corpus *corpus)
205 ptr += sizeof(db_directory);
207 string dir_path = ptr;
208 ptr += dir_path.size() + 1;
209 if (dir_path == "/") {
214 uint8_t type = *ptr++;
215 if (type == DBE_NORMAL) {
216 string filename = ptr;
217 corpus->add_file(dir_path + "/" + filename);
218 ptr += filename.size() + 1;
219 } else if (type == DBE_DIRECTORY) {
220 string dirname = ptr;
221 corpus->add_file(dir_path + "/" + dirname);
222 ptr += dirname.size() + 1;
229 void read_mlocate(const char *filename, Corpus *corpus)
231 int fd = open(filename, O_RDONLY);
236 off_t len = lseek(fd, 0, SEEK_END);
241 const char *data = (char *)mmap(nullptr, len, PROT_READ, MAP_SHARED, fd, /*offset=*/0);
242 if (data == MAP_FAILED) {
247 const db_header *hdr = (const db_header *)data;
249 // TODO: Care about the base path.
250 string path = data + sizeof(db_header);
251 uint64_t offset = sizeof(db_header) + path.size() + 1 + ntohl(hdr->conf_size);
253 const char *ptr = data + offset;
254 while (ptr < data + len) {
255 ptr = handle_directory(ptr, corpus);
258 munmap((void *)data, len);
262 string zstd_compress(const string &src, string *tempbuf)
264 size_t max_size = ZSTD_compressBound(src.size());
265 if (tempbuf->size() < max_size) {
266 tempbuf->resize(max_size);
268 size_t size = ZSTD_compress(&(*tempbuf)[0], max_size, src.data(), src.size(), /*level=*/6);
269 return string(tempbuf->data(), size);
272 bool is_prime(uint32_t x)
274 if ((x % 2) == 0 || (x % 3) == 0) {
277 uint32_t limit = ceil(sqrt(x));
278 for (uint32_t factor = 5; factor <= limit; ++factor) {
279 if ((x % factor) == 0) {
286 uint32_t next_prime(uint32_t x)
291 while (!is_prime(x)) {
297 unique_ptr<Trigram[]> create_hashtable(const Corpus &corpus, const vector<uint32_t> &all_trigrams, uint32_t ht_size, uint32_t num_overflow_slots)
299 unique_ptr<Trigram[]> ht(new Trigram[ht_size + num_overflow_slots + 1]); // 1 for the sentinel element at the end.
300 for (unsigned i = 0; i < ht_size + num_overflow_slots + 1; ++i) {
301 ht[i].trgm = uint32_t(-1);
302 ht[i].num_docids = 0;
305 for (uint32_t trgm : all_trigrams) {
306 // We don't know offset yet, so set it to zero.
307 Trigram to_insert{trgm, uint32_t(corpus.invindex.find(trgm)->second.num_docids), 0};
309 uint32_t bucket = hash_trigram(trgm, ht_size);
310 unsigned distance = 0;
311 while (ht[bucket].num_docids != 0) {
312 // Robin Hood hashing; reduces the longest distance by a lot.
313 unsigned other_distance = bucket - hash_trigram(ht[bucket].trgm, ht_size);
314 if (distance > other_distance) {
315 swap(to_insert, ht[bucket]);
316 distance = other_distance;
319 ++bucket, ++distance;
320 if (distance > num_overflow_slots) {
324 ht[bucket] = to_insert;
329 void do_build(const char *infile, const char *outfile, int block_size)
331 steady_clock::time_point start __attribute__((unused)) = steady_clock::now();
333 Corpus corpus(block_size);
335 read_mlocate(infile, &corpus);
336 if (false) { // To read a plain text file.
337 FILE *fp = fopen(infile, "r");
340 if (fgets(buf, 1024, fp) == nullptr || feof(fp)) {
344 if (s.back() == '\n')
346 corpus.add_file(move(s));
350 corpus.flush_block();
351 dprintf("Read %zu files from %s\n", corpus.num_files, infile);
353 size_t trigrams = 0, longest_posting_list = 0;
354 size_t bytes_used = 0;
355 for (auto &[trigram, pl_builder] : corpus.invindex) {
357 longest_posting_list = max(longest_posting_list, pl_builder.num_docids);
358 trigrams += pl_builder.num_docids;
359 bytes_used += pl_builder.encoded.size();
361 dprintf("%zu files, %zu different trigrams, %zu entries, avg len %.2f, longest %zu\n",
362 corpus.num_files, corpus.invindex.size(), trigrams, double(trigrams) / corpus.invindex.size(), longest_posting_list);
363 dprintf("%zu bytes used for posting lists (%.2f bits/entry)\n", bytes_used, 8 * bytes_used / double(trigrams));
365 dprintf("Building posting lists took %.1f ms.\n\n", 1e3 * duration<float>(steady_clock::now() - start).count());
367 // Sort the trigrams, mostly to get a consistent result every time
368 // (the hash table will put things in random order anyway).
369 vector<uint32_t> all_trigrams;
370 for (auto &[trigram, pl_builder] : corpus.invindex) {
371 all_trigrams.push_back(trigram);
373 sort(all_trigrams.begin(), all_trigrams.end());
375 unique_ptr<Trigram[]> hashtable;
376 uint32_t ht_size = next_prime(all_trigrams.size());
377 constexpr unsigned num_overflow_slots = 16;
379 hashtable = create_hashtable(corpus, all_trigrams, ht_size, num_overflow_slots);
380 if (hashtable == nullptr) {
381 dprintf("Failed creating hash table of size %u, increasing by 5%% and trying again.\n", ht_size);
382 ht_size = next_prime(ht_size * 1.05);
384 dprintf("Created hash table of size %u.\n\n", ht_size);
390 FILE *outfp = fopen(outfile, "wb");
392 // Find the offsets for each posting list.
393 size_t bytes_for_hashtable = (ht_size + num_overflow_slots + 1) * sizeof(Trigram);
394 uint64_t offset = sizeof(Header) + bytes_for_hashtable;
395 for (unsigned i = 0; i < ht_size + num_overflow_slots + 1; ++i) {
396 hashtable[i].offset = offset; // Needs to be there even for empty slots.
397 if (hashtable[i].num_docids == 0) {
401 const PostingListBuilder &pl_builder = corpus.invindex[hashtable[i].trgm];
402 offset += pl_builder.encoded.size();
407 memcpy(hdr.magic, "\0plocate", 8);
409 hdr.hashtable_size = ht_size;
410 hdr.extra_ht_slots = num_overflow_slots;
411 hdr.hash_table_offset_bytes = sizeof(hdr); // This member is just there for flexibility.
412 hdr.filename_index_offset_bytes = offset;
413 fwrite(&hdr, sizeof(hdr), 1, outfp);
415 // Write the hash table.
416 fwrite(hashtable.get(), ht_size + num_overflow_slots + 1, sizeof(Trigram), outfp);
418 // Write the actual posting lists.
419 size_t bytes_for_posting_lists = 0;
420 for (unsigned i = 0; i < ht_size + num_overflow_slots + 1; ++i) {
421 if (hashtable[i].num_docids == 0) {
424 const string &encoded = corpus.invindex[hashtable[i].trgm].encoded;
425 fwrite(encoded.data(), encoded.size(), 1, outfp);
426 bytes_for_posting_lists += encoded.size();
429 // Stick an empty block at the end as sentinel.
430 corpus.filename_blocks.push_back("");
432 // Write the offsets to the filenames.
433 size_t bytes_for_filename_index = 0, bytes_for_filenames = 0;
434 offset = hdr.filename_index_offset_bytes + corpus.filename_blocks.size() * sizeof(offset);
435 for (const string &filename : corpus.filename_blocks) {
436 fwrite(&offset, sizeof(offset), 1, outfp);
437 offset += filename.size();
438 bytes_for_filename_index += sizeof(offset);
439 bytes_for_filenames += filename.size();
442 // Write the actual filenames.
443 for (const string &filename : corpus.filename_blocks) {
444 fwrite(filename.data(), filename.size(), 1, outfp);
449 size_t total_bytes __attribute__((unused)) = (bytes_for_hashtable + bytes_for_posting_lists + bytes_for_filename_index + bytes_for_filenames);
451 dprintf("Block size: %7d files\n", block_size);
452 dprintf("Hash table: %'7.1f MB\n", bytes_for_hashtable / 1048576.0);
453 dprintf("Posting lists: %'7.1f MB\n", bytes_for_posting_lists / 1048576.0);
454 dprintf("Filename index: %'7.1f MB\n", bytes_for_filename_index / 1048576.0);
455 dprintf("Filenames: %'7.1f MB\n", bytes_for_filenames / 1048576.0);
456 dprintf("Total: %'7.1f MB\n", total_bytes / 1048576.0);
460 int main(int argc, char **argv)
462 do_build(argv[1], argv[2], 32);