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