]> git.sesse.net Git - plocate/blob - serializer.cpp
Move Serializer into its own file.
[plocate] / serializer.cpp
1 #include <inttypes.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <chrono>
5 #include <memory>
6 #include <utility>
7
8 #include "dprintf.h"
9 #include "serializer.h"
10
11 using namespace std;
12 using namespace std::chrono;
13
14 extern steady_clock::time_point start;
15
16 void apply_limit()
17 {
18         if (--limit_left > 0) {
19                 return;
20         }
21         dprintf("Done in %.1f ms, found %" PRId64 " matches.\n",
22                 1e3 * duration<float>(steady_clock::now() - start).count(), limit_matches);
23         if (only_count) {
24                 printf("%" PRId64 "\n", limit_matches);
25         }
26         exit(0);
27 }
28
29 void Serializer::print(uint64_t seq, uint64_t skip, const string msg)
30 {
31         if (only_count) {
32                 if (!msg.empty()) {
33                         apply_limit();
34                 }
35                 return;
36         }
37
38         if (next_seq != seq) {
39                 pending.push(Element{ seq, skip, move(msg) });
40                 return;
41         }
42
43         if (!msg.empty()) {
44                 if (print_nul) {
45                         printf("%s%c", msg.c_str(), 0);
46                 } else {
47                         printf("%s\n", msg.c_str());
48                 }
49                 apply_limit();
50         }
51         next_seq += skip;
52
53         // See if any delayed prints can now be dealt with.
54         while (!pending.empty() && pending.top().seq == next_seq) {
55                 if (!pending.top().msg.empty()) {
56                         if (print_nul) {
57                                 printf("%s%c", pending.top().msg.c_str(), 0);
58                         } else {
59                                 printf("%s\n", pending.top().msg.c_str());
60                         }
61                         apply_limit();
62                 }
63                 next_seq += pending.top().skip;
64                 pending.pop();
65         }
66 }
67