]> git.sesse.net Git - plocate/blob - database-builder.cpp
cc88ea0489000618f781a920b4716be48befbae6
[plocate] / database-builder.cpp
1 #include "database-builder.h"
2
3 #include "dprintf.h"
4 #include "turbopfor-encode.h"
5
6 #include <algorithm>
7 #include <assert.h>
8 #ifdef HAS_ENDIAN_H
9 #include <endian.h>
10 #endif
11 #include <fcntl.h>
12 #include <string.h>
13 #include <string_view>
14 #include <sys/stat.h>
15 #include <sys/time.h>
16 #include <sys/types.h>
17 #include <unistd.h>
18 #include <zdict.h>
19 #include <zstd.h>
20
21 #define P4NENC_BOUND(n) ((n + 127) / 128 + (n + 32) * sizeof(uint32_t))
22
23 #define NUM_TRIGRAMS 16777216
24
25 using namespace std;
26 using namespace std::chrono;
27
28 constexpr unsigned num_overflow_slots = 16;
29
30 string zstd_compress(const string &src, ZSTD_CDict *cdict, string *tempbuf);
31
32 // NOTE: Will read one byte past the end of the trigram, but it's OK,
33 // since we always call it from contexts where there's a terminating zero byte.
34 static inline uint32_t read_trigram(const string_view s, size_t start)
35 {
36         uint32_t trgm;
37         memcpy(&trgm, s.data() + start, sizeof(trgm));
38         trgm = le32toh(trgm);
39         return trgm & 0xffffff;
40 }
41
42 class PostingListBuilder {
43 public:
44         inline void add_docid(uint32_t docid);
45         inline void add_first_docid(uint32_t docid);
46         void finish();
47
48         vector<unsigned char> encoded;
49         size_t get_num_docids() const {
50                 // Updated only when we flush, so check that we're finished.
51                 assert(pending_deltas.empty());
52                 return num_docids;
53         }
54
55 private:
56         void write_header(uint32_t docid);
57         void append_block();
58
59         vector<uint32_t> pending_deltas;
60
61         uint32_t num_docids = 0;  // Should be size_t, except the format only supports 2^32 docids per posting list anyway.
62         uint32_t last_docid = -1;
63 };
64
65 void PostingListBuilder::add_docid(uint32_t docid)
66 {
67         // Deduplicate against the last inserted value, if any.
68         if (docid == last_docid) {
69                 return;
70         }
71
72         pending_deltas.push_back(docid - last_docid - 1);
73         last_docid = docid;
74         if (pending_deltas.size() == 128) {
75                 append_block();
76                 pending_deltas.clear();
77                 num_docids += 128;
78         }
79 }
80
81 void PostingListBuilder::add_first_docid(uint32_t docid)
82 {
83         write_header(docid);
84         ++num_docids;
85         last_docid = docid;
86 }
87
88 void PostingListBuilder::finish()
89 {
90         if (pending_deltas.empty()) {
91                 return;
92         }
93
94         assert(!encoded.empty());  // write_header() should already have run.
95
96         // No interleaving for partial blocks.
97         unsigned char buf[P4NENC_BOUND(128)];
98         unsigned char *end = encode_pfor_single_block<128>(pending_deltas.data(), pending_deltas.size(), /*interleaved=*/false, buf);
99         encoded.insert(encoded.end(), buf, end);
100
101         num_docids += pending_deltas.size();
102         pending_deltas.clear();
103 }
104
105 void PostingListBuilder::append_block()
106 {
107         unsigned char buf[P4NENC_BOUND(128)];
108         assert(pending_deltas.size() == 128);
109         unsigned char *end = encode_pfor_single_block<128>(pending_deltas.data(), 128, /*interleaved=*/true, buf);
110         encoded.insert(encoded.end(), buf, end);
111 }
112
113 void PostingListBuilder::write_header(uint32_t docid)
114 {
115         unsigned char buf[P4NENC_BOUND(1)];
116         unsigned char *end = write_baseval(docid, buf);
117         encoded.insert(encoded.end(), buf, end);
118 }
119
120 void DictionaryBuilder::add_file(string filename, dir_time)
121 {
122         if (keep_current_block) {  // Only bother saving the filenames if we're actually keeping the block.
123                 if (!current_block.empty()) {
124                         current_block.push_back('\0');
125                 }
126                 current_block += filename;
127         }
128         if (++num_files_in_block == block_size) {
129                 flush_block();
130         }
131 }
132
133 void DictionaryBuilder::flush_block()
134 {
135         if (keep_current_block) {
136                 if (slot_for_current_block == -1) {
137                         lengths.push_back(current_block.size());
138                         sampled_blocks.push_back(move(current_block));
139                 } else {
140                         lengths[slot_for_current_block] = current_block.size();
141                         sampled_blocks[slot_for_current_block] = move(current_block);
142                 }
143         }
144         current_block.clear();
145         num_files_in_block = 0;
146         ++block_num;
147
148         if (block_num < blocks_to_keep) {
149                 keep_current_block = true;
150                 slot_for_current_block = -1;
151         } else {
152                 // Keep every block with equal probability (reservoir sampling).
153                 uint64_t idx = uniform_int_distribution<uint64_t>(0, block_num)(reservoir_rand);
154                 keep_current_block = (idx < blocks_to_keep);
155                 slot_for_current_block = idx;
156         }
157 }
158
159 string DictionaryBuilder::train(size_t buf_size)
160 {
161         string dictionary_buf;
162         sort(sampled_blocks.begin(), sampled_blocks.end());  // Seemingly important for decompression speed.
163         for (const string &block : sampled_blocks) {
164                 dictionary_buf += block;
165         }
166
167         string buf;
168         buf.resize(buf_size);
169         size_t ret = ZDICT_trainFromBuffer(&buf[0], buf_size, dictionary_buf.data(), lengths.data(), lengths.size());
170         if (ZDICT_isError(ret)) {
171                 return "";
172         }
173         dprintf("Sampled %zu bytes in %zu blocks, built a dictionary of size %zu\n", dictionary_buf.size(), lengths.size(), ret);
174         buf.resize(ret);
175
176         sampled_blocks.clear();
177         lengths.clear();
178
179         return buf;
180 }
181
182 class EncodingCorpus : public DatabaseReceiver {
183 public:
184         EncodingCorpus(FILE *outfp, size_t block_size, ZSTD_CDict *cdict, bool store_dir_times);
185         ~EncodingCorpus();
186
187         void add_file(std::string filename, dir_time dt) override;
188         void flush_block() override;
189         void finish() override;
190
191         std::vector<uint64_t> filename_blocks;
192         size_t num_files = 0, num_files_in_block = 0, num_blocks = 0;
193         bool seen_trigram(uint32_t trgm)
194         {
195                 return invindex[trgm] != nullptr;
196         }
197         size_t num_files_seen() const override { return num_files; }
198         PostingListBuilder &get_pl_builder(uint32_t trgm)
199         {
200                 return *invindex[trgm];
201         }
202
203         void add_docid(uint32_t trgm, uint32_t docid)
204         {
205                 if (invindex[trgm] == nullptr) {
206                         invindex[trgm] = new PostingListBuilder;
207                         invindex[trgm]->add_first_docid(docid);
208                 } else {
209                         invindex[trgm]->add_docid(docid);
210                 }
211         }
212
213         size_t num_trigrams() const;
214         std::string get_compressed_dir_times();
215
216 private:
217         void compress_dir_times(size_t allowed_slop);
218
219         std::unique_ptr<PostingListBuilder *[]> invindex;
220         FILE *outfp;
221         std::string current_block;
222         std::string tempbuf;
223         const size_t block_size;
224         const bool store_dir_times;
225         ZSTD_CDict *cdict;
226
227         ZSTD_CStream *dir_time_ctx = nullptr;
228         std::string dir_times;  // Buffer of still-uncompressed data.
229         std::string dir_times_compressed;
230 };
231
232
233 EncodingCorpus::EncodingCorpus(FILE *outfp, size_t block_size, ZSTD_CDict *cdict, bool store_dir_times)
234         : invindex(new PostingListBuilder *[NUM_TRIGRAMS]), outfp(outfp), block_size(block_size), store_dir_times(store_dir_times), cdict(cdict)
235 {
236         fill(invindex.get(), invindex.get() + NUM_TRIGRAMS, nullptr);
237         if (store_dir_times) {
238                 dir_time_ctx = ZSTD_createCStream();
239                 ZSTD_initCStream(dir_time_ctx, /*level=*/6);
240         }
241 }
242
243 EncodingCorpus::~EncodingCorpus()
244 {
245         for (unsigned i = 0; i < NUM_TRIGRAMS; ++i) {
246                 delete invindex[i];
247         }
248 }
249
250 void EncodingCorpus::add_file(string filename, dir_time dt)
251 {
252         ++num_files;
253         if (!current_block.empty()) {
254                 current_block.push_back('\0');
255         }
256         current_block += filename;
257         if (++num_files_in_block == block_size) {
258                 flush_block();
259         }
260
261         if (store_dir_times) {
262                 if (dt.sec == -1) {
263                         // Not a directory.
264                         dir_times.push_back('\0');
265                 } else {
266                         dir_times.push_back('\1');
267                         dir_times.append(reinterpret_cast<char *>(&dt.sec), sizeof(dt.sec));
268                         dir_times.append(reinterpret_cast<char *>(&dt.nsec), sizeof(dt.nsec));
269                 }
270                 compress_dir_times(/*allowed_slop=*/4096);
271         }
272 }
273
274 void EncodingCorpus::compress_dir_times(size_t allowed_slop)
275 {
276         while (dir_times.size() >= allowed_slop) {
277                 size_t old_size = dir_times_compressed.size();
278                 dir_times_compressed.resize(old_size + 4096);
279
280                 ZSTD_outBuffer outbuf;
281                 outbuf.dst = dir_times_compressed.data() + old_size;
282                 outbuf.size = 4096;
283                 outbuf.pos = 0;
284
285                 ZSTD_inBuffer inbuf;
286                 inbuf.src = dir_times.data();
287                 inbuf.size = dir_times.size();
288                 inbuf.pos = 0;
289
290                 int ret = ZSTD_compressStream(dir_time_ctx, &outbuf, &inbuf);
291                 if (ret < 0) {
292                         fprintf(stderr, "ZSTD_compressStream() failed\n");
293                         exit(1);
294                 }
295
296                 dir_times_compressed.resize(old_size + outbuf.pos);
297                 dir_times.erase(dir_times.begin(), dir_times.begin() + inbuf.pos);
298
299                 if (outbuf.pos == 0 && inbuf.pos == 0) {
300                         // Nothing happened (not enough data?), try again later.
301                         return;
302                 }
303         }
304 }
305
306 void EncodingCorpus::flush_block()
307 {
308         if (current_block.empty()) {
309                 return;
310         }
311
312         uint32_t docid = num_blocks;
313
314         // Create trigrams.
315         const char *ptr = current_block.c_str();
316         while (ptr < current_block.c_str() + current_block.size()) {
317                 string_view s(ptr);
318                 if (s.size() >= 3) {
319                         for (size_t j = 0; j < s.size() - 2; ++j) {
320                                 uint32_t trgm = read_trigram(s, j);
321                                 add_docid(trgm, docid);
322                         }
323                 }
324                 ptr += s.size() + 1;
325         }
326
327         // Compress and add the filename block.
328         filename_blocks.push_back(ftell(outfp));
329         string compressed = zstd_compress(current_block, cdict, &tempbuf);
330         if (fwrite(compressed.data(), compressed.size(), 1, outfp) != 1) {
331                 perror("fwrite()");
332                 exit(1);
333         }
334
335         current_block.clear();
336         num_files_in_block = 0;
337         ++num_blocks;
338 }
339
340 void EncodingCorpus::finish()
341 {
342         flush_block();
343 }
344
345 size_t EncodingCorpus::num_trigrams() const
346 {
347         size_t num = 0;
348         for (unsigned trgm = 0; trgm < NUM_TRIGRAMS; ++trgm) {
349                 if (invindex[trgm] != nullptr) {
350                         ++num;
351                 }
352         }
353         return num;
354 }
355
356 string EncodingCorpus::get_compressed_dir_times()
357 {
358         if (!store_dir_times) {
359                 return "";
360         }
361         compress_dir_times(/*allowed_slop=*/0);
362         assert(dir_times.empty());
363
364         for (;;) {
365                 size_t old_size = dir_times_compressed.size();
366                 dir_times_compressed.resize(old_size + 4096);
367
368                 ZSTD_outBuffer outbuf;
369                 outbuf.dst = dir_times_compressed.data() + old_size;
370                 outbuf.size = 4096;
371                 outbuf.pos = 0;
372
373                 int ret = ZSTD_endStream(dir_time_ctx, &outbuf);
374                 if (ret < 0) {
375                         fprintf(stderr, "ZSTD_compressStream() failed\n");
376                         exit(1);
377                 }
378
379                 dir_times_compressed.resize(old_size + outbuf.pos);
380
381                 if (ret == 0) {
382                         // All done.
383                         break;
384                 }
385         }
386
387         return dir_times_compressed;
388 }
389
390 string zstd_compress(const string &src, ZSTD_CDict *cdict, string *tempbuf)
391 {
392         static ZSTD_CCtx *ctx = nullptr;
393         if (ctx == nullptr) {
394                 ctx = ZSTD_createCCtx();
395         }
396
397         size_t max_size = ZSTD_compressBound(src.size());
398         if (tempbuf->size() < max_size) {
399                 tempbuf->resize(max_size);
400         }
401         size_t size;
402         if (cdict == nullptr) {
403                 size = ZSTD_compressCCtx(ctx, &(*tempbuf)[0], max_size, src.data(), src.size(), /*level=*/6);
404         } else {
405                 size = ZSTD_compress_usingCDict(ctx, &(*tempbuf)[0], max_size, src.data(), src.size(), cdict);
406         }
407         return string(tempbuf->data(), size);
408 }
409
410 bool is_prime(uint32_t x)
411 {
412         if ((x % 2) == 0 || (x % 3) == 0) {
413                 return false;
414         }
415         uint32_t limit = ceil(sqrt(x));
416         for (uint32_t factor = 5; factor <= limit; ++factor) {
417                 if ((x % factor) == 0) {
418                         return false;
419                 }
420         }
421         return true;
422 }
423
424 uint32_t next_prime(uint32_t x)
425 {
426         if ((x % 2) == 0) {
427                 ++x;
428         }
429         while (!is_prime(x)) {
430                 x += 2;
431         }
432         return x;
433 }
434
435 unique_ptr<Trigram[]> create_hashtable(EncodingCorpus &corpus, const vector<uint32_t> &all_trigrams, uint32_t ht_size, uint32_t num_overflow_slots)
436 {
437         unique_ptr<Trigram[]> ht(new Trigram[ht_size + num_overflow_slots + 1]);  // 1 for the sentinel element at the end.
438         for (unsigned i = 0; i < ht_size + num_overflow_slots + 1; ++i) {
439                 ht[i].trgm = uint32_t(-1);
440                 ht[i].num_docids = 0;
441                 ht[i].offset = 0;
442         }
443         for (uint32_t trgm : all_trigrams) {
444                 // We don't know offset yet, so set it to zero.
445                 Trigram to_insert{ trgm, uint32_t(corpus.get_pl_builder(trgm).get_num_docids()), 0 };
446
447                 uint32_t bucket = hash_trigram(trgm, ht_size);
448                 unsigned distance = 0;
449                 while (ht[bucket].num_docids != 0) {
450                         // Robin Hood hashing; reduces the longest distance by a lot.
451                         unsigned other_distance = bucket - hash_trigram(ht[bucket].trgm, ht_size);
452                         if (distance > other_distance) {
453                                 swap(to_insert, ht[bucket]);
454                                 distance = other_distance;
455                         }
456
457                         ++bucket, ++distance;
458                         if (distance > num_overflow_slots) {
459                                 return nullptr;
460                         }
461                 }
462                 ht[bucket] = to_insert;
463         }
464         return ht;
465 }
466
467 DatabaseBuilder::DatabaseBuilder(const char *outfile, gid_t owner, int block_size, string dictionary, bool check_visibility)
468         : outfile(outfile), block_size(block_size)
469 {
470         umask(0027);
471
472         string path = outfile;
473         path.resize(path.find_last_of('/') + 1);
474         if (path.empty()) {
475                 path = ".";
476         }
477 #ifdef O_TMPFILE
478         int fd = open(path.c_str(), O_WRONLY | O_TMPFILE, 0640);
479         if (fd == -1) {
480                 perror(path.c_str());
481                 exit(1);
482         }
483 #else
484         temp_filename = string(outfile) + ".XXXXXX";
485         int fd = mkstemp(&temp_filename[0]);
486         if (fd == -1) {
487                 perror(temp_filename.c_str());
488                 exit(1);
489         }
490         if (fchmod(fd, 0640) == -1) {
491                 perror("fchmod");
492                 exit(1);
493         }
494 #endif
495
496         if (owner != (gid_t)-1) {
497                 if (fchown(fd, (uid_t)-1, owner) == -1) {
498                         perror("fchown");
499                         exit(1);
500                 }
501         }
502
503         outfp = fdopen(fd, "wb");
504         if (outfp == nullptr) {
505                 perror(outfile);
506                 exit(1);
507         }
508
509         // Write the header.
510         memcpy(hdr.magic, "\0plocate", 8);
511         hdr.version = -1;  // Mark as broken.
512         hdr.hashtable_size = 0;  // Not known yet.
513         hdr.extra_ht_slots = num_overflow_slots;
514         hdr.num_docids = 0;
515         hdr.hash_table_offset_bytes = -1;  // We don't know these offsets yet.
516         hdr.max_version = 2;
517         hdr.filename_index_offset_bytes = -1;
518         hdr.zstd_dictionary_length_bytes = -1;
519         hdr.check_visibility = check_visibility;
520         fwrite(&hdr, sizeof(hdr), 1, outfp);
521
522         if (dictionary.empty()) {
523                 hdr.zstd_dictionary_offset_bytes = 0;
524                 hdr.zstd_dictionary_length_bytes = 0;
525         } else {
526                 hdr.zstd_dictionary_offset_bytes = ftell(outfp);
527                 fwrite(dictionary.data(), dictionary.size(), 1, outfp);
528                 hdr.zstd_dictionary_length_bytes = dictionary.size();
529                 cdict = ZSTD_createCDict(dictionary.data(), dictionary.size(), /*level=*/6);
530         }
531
532         hdr.directory_data_length_bytes = 0;
533         hdr.directory_data_offset_bytes = 0;
534         hdr.next_zstd_dictionary_length_bytes = 0;
535         hdr.next_zstd_dictionary_offset_bytes = 0;
536         hdr.conf_block_length_bytes = 0;
537         hdr.conf_block_offset_bytes = 0;
538 }
539
540 DatabaseReceiver *DatabaseBuilder::start_corpus(bool store_dir_times)
541 {
542         corpus_start = steady_clock::now();
543         corpus = new EncodingCorpus(outfp, block_size, cdict, store_dir_times);
544         return corpus;
545 }
546
547 void DatabaseBuilder::set_next_dictionary(std::string next_dictionary)
548 {
549         this->next_dictionary = move(next_dictionary);
550 }
551
552 void DatabaseBuilder::set_conf_block(std::string conf_block)
553 {
554         this->conf_block = move(conf_block);
555 }
556
557 void DatabaseBuilder::finish_corpus()
558 {
559         corpus->finish();
560         hdr.num_docids = corpus->filename_blocks.size();
561
562         // Stick an empty block at the end as sentinel.
563         corpus->filename_blocks.push_back(ftell(outfp));
564         const size_t bytes_for_filenames = corpus->filename_blocks.back() - corpus->filename_blocks.front();
565
566         // Write the offsets to the filenames.
567         hdr.filename_index_offset_bytes = ftell(outfp);
568         const size_t bytes_for_filename_index = corpus->filename_blocks.size() * sizeof(uint64_t);
569         fwrite(corpus->filename_blocks.data(), corpus->filename_blocks.size(), sizeof(uint64_t), outfp);
570         corpus->filename_blocks.clear();
571         corpus->filename_blocks.shrink_to_fit();
572
573         // Finish up encoding the posting lists.
574         size_t trigrams = 0, longest_posting_list = 0;
575         size_t bytes_for_posting_lists = 0;
576         for (unsigned trgm = 0; trgm < NUM_TRIGRAMS; ++trgm) {
577                 if (!corpus->seen_trigram(trgm))
578                         continue;
579                 PostingListBuilder &pl_builder = corpus->get_pl_builder(trgm);
580                 pl_builder.finish();
581                 longest_posting_list = max(longest_posting_list, pl_builder.get_num_docids());
582                 trigrams += pl_builder.get_num_docids();
583                 bytes_for_posting_lists += pl_builder.encoded.size();
584         }
585         size_t num_trigrams = corpus->num_trigrams();
586         dprintf("%zu files, %zu different trigrams, %zu entries, avg len %.2f, longest %zu\n",
587                 corpus->num_files, num_trigrams, trigrams, double(trigrams) / num_trigrams, longest_posting_list);
588         dprintf("%zu bytes used for posting lists (%.2f bits/entry)\n", bytes_for_posting_lists, 8 * bytes_for_posting_lists / double(trigrams));
589
590         dprintf("Building posting lists took %.1f ms.\n\n", 1e3 * duration<float>(steady_clock::now() - corpus_start).count());
591
592         // Find the used trigrams.
593         vector<uint32_t> all_trigrams;
594         for (unsigned trgm = 0; trgm < NUM_TRIGRAMS; ++trgm) {
595                 if (corpus->seen_trigram(trgm)) {
596                         all_trigrams.push_back(trgm);
597                 }
598         }
599
600         // Create the hash table.
601         unique_ptr<Trigram[]> hashtable;
602         uint32_t ht_size = next_prime(all_trigrams.size());
603         for (;;) {
604                 hashtable = create_hashtable(*corpus, all_trigrams, ht_size, num_overflow_slots);
605                 if (hashtable == nullptr) {
606                         dprintf("Failed creating hash table of size %u, increasing by 5%% and trying again.\n", ht_size);
607                         ht_size = next_prime(ht_size * 1.05);
608                 } else {
609                         dprintf("Created hash table of size %u.\n\n", ht_size);
610                         break;
611                 }
612         }
613
614         // Find the offsets for each posting list.
615         size_t bytes_for_hashtable = (ht_size + num_overflow_slots + 1) * sizeof(Trigram);
616         uint64_t offset = ftell(outfp) + bytes_for_hashtable;
617         for (unsigned i = 0; i < ht_size + num_overflow_slots + 1; ++i) {
618                 hashtable[i].offset = offset;  // Needs to be there even for empty slots.
619                 if (hashtable[i].num_docids == 0) {
620                         continue;
621                 }
622
623                 const vector<unsigned char> &encoded = corpus->get_pl_builder(hashtable[i].trgm).encoded;
624                 offset += encoded.size();
625         }
626
627         // Write the hash table.
628         hdr.hash_table_offset_bytes = ftell(outfp);
629         hdr.hashtable_size = ht_size;
630         fwrite(hashtable.get(), ht_size + num_overflow_slots + 1, sizeof(Trigram), outfp);
631
632         // Write the actual posting lists.
633         for (unsigned i = 0; i < ht_size + num_overflow_slots + 1; ++i) {
634                 if (hashtable[i].num_docids == 0) {
635                         continue;
636                 }
637                 const vector<unsigned char> &encoded = corpus->get_pl_builder(hashtable[i].trgm).encoded;
638                 fwrite(encoded.data(), encoded.size(), 1, outfp);
639         }
640
641         // Finally, write the directory times (for updatedb).
642         string compressed_dir_times = corpus->get_compressed_dir_times();
643         size_t bytes_for_compressed_dir_times = 0;
644         if (!compressed_dir_times.empty()) {
645                 hdr.directory_data_offset_bytes = ftell(outfp);
646                 hdr.directory_data_length_bytes = compressed_dir_times.size();
647                 fwrite(compressed_dir_times.data(), compressed_dir_times.size(), 1, outfp);
648                 bytes_for_compressed_dir_times = compressed_dir_times.size();
649                 compressed_dir_times.clear();
650         }
651
652         // Write the recommended dictionary for next update.
653         if (!next_dictionary.empty()) {
654                 hdr.next_zstd_dictionary_offset_bytes = ftell(outfp);
655                 hdr.next_zstd_dictionary_length_bytes = next_dictionary.size();
656                 fwrite(next_dictionary.data(), next_dictionary.size(), 1, outfp);
657         }
658
659         // And the configuration block.
660         if (!conf_block.empty()) {
661                 hdr.conf_block_offset_bytes = ftell(outfp);
662                 hdr.conf_block_length_bytes = conf_block.size();
663                 fwrite(conf_block.data(), conf_block.size(), 1, outfp);
664         }
665
666         // Rewind, and write the updated header.
667         hdr.version = 1;
668         fseek(outfp, 0, SEEK_SET);
669         fwrite(&hdr, sizeof(hdr), 1, outfp);
670
671 #ifdef O_TMPFILE
672         // Give the file a proper name, making it visible in the file system.
673         // TODO: It would be nice to be able to do this atomically, like with rename.
674         unlink(outfile.c_str());
675         char procpath[256];
676         snprintf(procpath, sizeof(procpath), "/proc/self/fd/%d", fileno(outfp));
677         if (linkat(AT_FDCWD, procpath, AT_FDCWD, outfile.c_str(), AT_SYMLINK_FOLLOW) == -1) {
678                 perror("linkat");
679                 exit(1);
680         }
681 #else
682         if (rename(temp_filename.c_str(), outfile.c_str()) == -1) {
683                 perror("rename");
684                 exit(1);
685         }
686 #endif
687
688         fclose(outfp);
689
690         size_t total_bytes = (bytes_for_hashtable + bytes_for_posting_lists + bytes_for_filename_index + bytes_for_filenames + bytes_for_compressed_dir_times);
691
692         dprintf("Block size:     %7d files\n", block_size);
693         dprintf("Dictionary:     %'7.1f MB\n", hdr.zstd_dictionary_length_bytes / 1048576.0);
694         dprintf("Hash table:     %'7.1f MB\n", bytes_for_hashtable / 1048576.0);
695         dprintf("Posting lists:  %'7.1f MB\n", bytes_for_posting_lists / 1048576.0);
696         dprintf("Filename index: %'7.1f MB\n", bytes_for_filename_index / 1048576.0);
697         dprintf("Filenames:      %'7.1f MB\n", bytes_for_filenames / 1048576.0);
698         if (bytes_for_compressed_dir_times != 0) {
699                 dprintf("Modify times:   %'7.1f MB\n", bytes_for_compressed_dir_times / 1048576.0);
700         }
701         dprintf("Total:          %'7.1f MB\n", total_bytes / 1048576.0);
702         dprintf("\n");
703 }