2 #include "turbopfor-encode.h"
16 #include <sys/types.h>
18 #include <unordered_map>
22 #define P4NENC_BOUND(n) ((n + 127) / 128 + (n + 32) * sizeof(uint32_t))
24 //#define dprintf(...) fprintf(stderr, __VA_ARGS__);
26 #define NUM_TRIGRAMS 16777216
29 using namespace std::chrono;
31 string zstd_compress(const string &src, string *tempbuf);
33 constexpr unsigned num_overflow_slots = 16;
35 static inline uint32_t read_unigram(const string_view s, size_t idx)
38 return (unsigned char)s[idx];
44 static inline uint32_t read_trigram(const string_view s, size_t start)
46 return read_unigram(s, start) |
47 (read_unigram(s, start + 1) << 8) |
48 (read_unigram(s, start + 2) << 16);
52 DBE_NORMAL = 0, /* A non-directory file */
53 DBE_DIRECTORY = 1, /* A directory */
54 DBE_END = 2 /* End of directory contents; contains no name */
62 uint8_t check_visibility;
73 class PostingListBuilder {
75 inline void add_docid(uint32_t docid);
79 size_t num_docids = 0;
82 void write_header(uint32_t docid);
85 vector<uint32_t> pending_deltas;
87 uint32_t last_block_end, last_docid = -1;
90 void PostingListBuilder::add_docid(uint32_t docid)
92 // Deduplicate against the last inserted value, if any.
93 if (docid == last_docid) {
97 if (num_docids == 0) {
101 last_block_end = last_docid = docid;
105 pending_deltas.push_back(docid - last_docid - 1);
107 if (pending_deltas.size() == 128) {
109 pending_deltas.clear();
110 last_block_end = docid;
115 void PostingListBuilder::finish()
117 if (pending_deltas.empty()) {
121 assert(!encoded.empty()); // write_header() should already have run.
123 // No interleaving for partial blocks.
124 unsigned char buf[P4NENC_BOUND(128)];
125 unsigned char *end = encode_pfor_single_block<128>(pending_deltas.data(), pending_deltas.size(), /*interleaved=*/false, buf);
126 encoded.append(reinterpret_cast<char *>(buf), reinterpret_cast<char *>(end));
129 void PostingListBuilder::append_block()
131 unsigned char buf[P4NENC_BOUND(128)];
132 assert(pending_deltas.size() == 128);
133 unsigned char *end = encode_pfor_single_block<128>(pending_deltas.data(), 128, /*interleaved=*/true, buf);
134 encoded.append(reinterpret_cast<char *>(buf), reinterpret_cast<char *>(end));
137 void PostingListBuilder::write_header(uint32_t docid)
139 unsigned char buf[P4NENC_BOUND(1)];
140 unsigned char *end = write_baseval(docid, buf);
141 encoded.append(reinterpret_cast<char *>(buf), end - buf);
146 Corpus(FILE *outfp, size_t block_size)
147 : invindex(new PostingListBuilder *[NUM_TRIGRAMS]), outfp(outfp), block_size(block_size) {
148 fill(invindex.get(), invindex.get() + NUM_TRIGRAMS, nullptr);
151 for (unsigned i = 0; i < NUM_TRIGRAMS; ++i) {
156 void add_file(string filename);
159 vector<uint64_t> filename_blocks;
160 size_t num_files = 0, num_files_in_block = 0, num_blocks = 0;
161 bool seen_trigram(uint32_t trgm)
163 return invindex[trgm] != nullptr;
165 PostingListBuilder &get_pl_builder(uint32_t trgm)
167 if (invindex[trgm] == nullptr) {
168 invindex[trgm] = new PostingListBuilder;
170 return *invindex[trgm];
174 unique_ptr<PostingListBuilder *[]> invindex;
176 string current_block;
178 const size_t block_size;
181 void Corpus::add_file(string filename)
184 if (!current_block.empty()) {
185 current_block.push_back('\0');
187 current_block += filename;
188 if (++num_files_in_block == block_size) {
193 void Corpus::flush_block()
195 if (current_block.empty()) {
199 uint32_t docid = num_blocks;
202 const char *ptr = current_block.c_str();
203 while (ptr < current_block.c_str() + current_block.size()) {
206 for (size_t j = 0; j < s.size() - 2; ++j) {
207 uint32_t trgm = read_trigram(s, j);
208 get_pl_builder(trgm).add_docid(docid);
214 // Compress and add the filename block.
215 filename_blocks.push_back(ftell(outfp));
216 string compressed = zstd_compress(current_block, &tempbuf);
217 if (fwrite(compressed.data(), compressed.size(), 1, outfp) != 1) {
222 current_block.clear();
223 num_files_in_block = 0;
227 string read_cstr(FILE *fp)
243 void handle_directory(FILE *fp, Corpus *corpus)
246 if (fread(&dummy, sizeof(dummy), 1, fp) != 1) {
254 string dir_path = read_cstr(fp);
255 if (dir_path == "/") {
261 if (type == DBE_NORMAL) {
262 string filename = read_cstr(fp);
263 corpus->add_file(dir_path + "/" + filename);
264 } else if (type == DBE_DIRECTORY) {
265 string dirname = read_cstr(fp);
266 corpus->add_file(dir_path + "/" + dirname);
268 return; // Probably end.
273 void read_mlocate(const char *filename, Corpus *corpus)
275 FILE *fp = fopen(filename, "rb");
282 if (fread(&hdr, sizeof(hdr), 1, fp) != 1) {
283 perror("short read");
287 // TODO: Care about the base path.
288 string path = read_cstr(fp);
290 handle_directory(fp, corpus);
295 string zstd_compress(const string &src, string *tempbuf)
297 size_t max_size = ZSTD_compressBound(src.size());
298 if (tempbuf->size() < max_size) {
299 tempbuf->resize(max_size);
301 size_t size = ZSTD_compress(&(*tempbuf)[0], max_size, src.data(), src.size(), /*level=*/6);
302 return string(tempbuf->data(), size);
305 bool is_prime(uint32_t x)
307 if ((x % 2) == 0 || (x % 3) == 0) {
310 uint32_t limit = ceil(sqrt(x));
311 for (uint32_t factor = 5; factor <= limit; ++factor) {
312 if ((x % factor) == 0) {
319 uint32_t next_prime(uint32_t x)
324 while (!is_prime(x)) {
330 unique_ptr<Trigram[]> create_hashtable(Corpus &corpus, const vector<uint32_t> &all_trigrams, uint32_t ht_size, uint32_t num_overflow_slots)
332 unique_ptr<Trigram[]> ht(new Trigram[ht_size + num_overflow_slots + 1]); // 1 for the sentinel element at the end.
333 for (unsigned i = 0; i < ht_size + num_overflow_slots + 1; ++i) {
334 ht[i].trgm = uint32_t(-1);
335 ht[i].num_docids = 0;
338 for (uint32_t trgm : all_trigrams) {
339 // We don't know offset yet, so set it to zero.
340 Trigram to_insert{ trgm, uint32_t(corpus.get_pl_builder(trgm).num_docids), 0 };
342 uint32_t bucket = hash_trigram(trgm, ht_size);
343 unsigned distance = 0;
344 while (ht[bucket].num_docids != 0) {
345 // Robin Hood hashing; reduces the longest distance by a lot.
346 unsigned other_distance = bucket - hash_trigram(ht[bucket].trgm, ht_size);
347 if (distance > other_distance) {
348 swap(to_insert, ht[bucket]);
349 distance = other_distance;
352 ++bucket, ++distance;
353 if (distance > num_overflow_slots) {
357 ht[bucket] = to_insert;
362 void do_build(const char *infile, const char *outfile, int block_size)
364 steady_clock::time_point start __attribute__((unused)) = steady_clock::now();
367 FILE *outfp = fopen(outfile, "wb");
371 memcpy(hdr.magic, "\0plocate", 8);
372 hdr.version = -1; // Mark as broken.
373 hdr.hashtable_size = 0; // Not known yet.
374 hdr.extra_ht_slots = num_overflow_slots;
376 hdr.hash_table_offset_bytes = -1; // We don't know these offsets yet.
377 hdr.filename_index_offset_bytes = -1;
378 fwrite(&hdr, sizeof(hdr), 1, outfp);
380 Corpus corpus(outfp, block_size);
382 read_mlocate(infile, &corpus);
383 if (false) { // To read a plain text file.
384 FILE *fp = fopen(infile, "r");
387 if (fgets(buf, 1024, fp) == nullptr || feof(fp)) {
391 if (s.back() == '\n')
393 corpus.add_file(move(s));
397 corpus.flush_block();
398 dprintf("Read %zu files from %s\n", corpus.num_files, infile);
399 hdr.num_docids = corpus.filename_blocks.size();
401 // Stick an empty block at the end as sentinel.
402 corpus.filename_blocks.push_back(ftell(outfp));
403 const size_t bytes_for_filenames = corpus.filename_blocks.back() - corpus.filename_blocks.front();
405 // Write the offsets to the filenames.
406 hdr.filename_index_offset_bytes = ftell(outfp);
407 const size_t bytes_for_filename_index = corpus.filename_blocks.size() * sizeof(uint64_t);
408 fwrite(corpus.filename_blocks.data(), corpus.filename_blocks.size(), sizeof(uint64_t), outfp);
409 corpus.filename_blocks.clear();
410 corpus.filename_blocks.shrink_to_fit();
412 // Finish up encoding the posting lists.
413 size_t trigrams = 0, longest_posting_list = 0;
414 size_t bytes_for_posting_lists = 0;
415 for (unsigned trgm = 0; trgm < NUM_TRIGRAMS; ++trgm) {
416 if (!corpus.seen_trigram(trgm))
418 PostingListBuilder &pl_builder = corpus.get_pl_builder(trgm);
420 longest_posting_list = max(longest_posting_list, pl_builder.num_docids);
421 trigrams += pl_builder.num_docids;
422 bytes_for_posting_lists += pl_builder.encoded.size();
424 dprintf("%zu files, %zu different trigrams, %zu entries, avg len %.2f, longest %zu\n",
425 corpus.num_files, corpus.invindex.size(), trigrams, double(trigrams) / corpus.invindex.size(), longest_posting_list);
426 dprintf("%zu bytes used for posting lists (%.2f bits/entry)\n", bytes_for_posting_lists, 8 * bytes_for_posting_lists / double(trigrams));
428 dprintf("Building posting lists took %.1f ms.\n\n", 1e3 * duration<float>(steady_clock::now() - start).count());
430 // Find the used trigrams.
431 vector<uint32_t> all_trigrams;
432 for (unsigned trgm = 0; trgm < NUM_TRIGRAMS; ++trgm) {
433 if (corpus.seen_trigram(trgm)) {
434 all_trigrams.push_back(trgm);
438 // Create the hash table.
439 unique_ptr<Trigram[]> hashtable;
440 uint32_t ht_size = next_prime(all_trigrams.size());
442 hashtable = create_hashtable(corpus, all_trigrams, ht_size, num_overflow_slots);
443 if (hashtable == nullptr) {
444 dprintf("Failed creating hash table of size %u, increasing by 5%% and trying again.\n", ht_size);
445 ht_size = next_prime(ht_size * 1.05);
447 dprintf("Created hash table of size %u.\n\n", ht_size);
452 // Find the offsets for each posting list.
453 size_t bytes_for_hashtable = (ht_size + num_overflow_slots + 1) * sizeof(Trigram);
454 uint64_t offset = ftell(outfp) + bytes_for_hashtable;
455 for (unsigned i = 0; i < ht_size + num_overflow_slots + 1; ++i) {
456 hashtable[i].offset = offset; // Needs to be there even for empty slots.
457 if (hashtable[i].num_docids == 0) {
461 const string &encoded = corpus.get_pl_builder(hashtable[i].trgm).encoded;
462 offset += encoded.size();
465 // Write the hash table.
466 hdr.hash_table_offset_bytes = ftell(outfp);
467 hdr.hashtable_size = ht_size;
468 fwrite(hashtable.get(), ht_size + num_overflow_slots + 1, sizeof(Trigram), outfp);
470 // Write the actual posting lists.
471 for (unsigned i = 0; i < ht_size + num_overflow_slots + 1; ++i) {
472 if (hashtable[i].num_docids == 0) {
475 const string &encoded = corpus.get_pl_builder(hashtable[i].trgm).encoded;
476 fwrite(encoded.data(), encoded.size(), 1, outfp);
479 // Rewind, and write the updated header.
481 fseek(outfp, 0, SEEK_SET);
482 fwrite(&hdr, sizeof(hdr), 1, outfp);
485 size_t total_bytes __attribute__((unused)) = (bytes_for_hashtable + bytes_for_posting_lists + bytes_for_filename_index + bytes_for_filenames);
487 dprintf("Block size: %7d files\n", block_size);
488 dprintf("Hash table: %'7.1f MB\n", bytes_for_hashtable / 1048576.0);
489 dprintf("Posting lists: %'7.1f MB\n", bytes_for_posting_lists / 1048576.0);
490 dprintf("Filename index: %'7.1f MB\n", bytes_for_filename_index / 1048576.0);
491 dprintf("Filenames: %'7.1f MB\n", bytes_for_filenames / 1048576.0);
492 dprintf("Total: %'7.1f MB\n", total_bytes / 1048576.0);
496 int main(int argc, char **argv)
498 do_build(argv[1], argv[2], 32);