Nix 2.36.0
Nix, the purely functional package manager; unstable internal interfaces
Loading...
Searching...
No Matches
pos-table.hh
Go to the documentation of this file.
1#pragma once
3
4#include <cstdint>
5#include <vector>
6
8#include "nix/util/pos-idx.hh"
10#include "nix/util/sync.hh"
11
12namespace nix {
13
14class PosTable
15{
16public:
17 class Origin
18 {
19 friend PosTable;
20 private:
21 uint32_t offset;
22
23 Origin(Pos::Origin origin, uint32_t offset, size_t size)
24 : offset(offset)
25 , origin(origin)
26 , size(size)
27 {
28 }
29
30 public:
31 const Pos::Origin origin;
32 const size_t size;
33
34 uint32_t offsetOf(PosIdx p) const
35 {
36 return p.id - 1 - offset;
37 }
38 };
39
40private:
46 using Lines = std::vector<uint32_t>;
50 using LinesCache = LRUCache<uint32_t, Lines>;
51
52 Sync<std::map<uint32_t, Origin>> origins_;
53
54 mutable Sync<LinesCache> linesCache;
55
56 const Origin * resolve(PosIdx p) const
57 {
58 if (p.id == 0)
59 return nullptr;
60
61 const auto idx = p.id - 1;
62 /* we want the last key <= idx, so we'll take prev(first key > idx).
63 this is guaranteed to never rewind origin.begin because the first
64 key is always 0. */
65 auto origins(origins_.readLock());
66 const auto pastOrigin = origins->upper_bound(idx);
67 return &std::prev(pastOrigin)->second;
68 }
69
70public:
71 PosTable(std::size_t linesCacheCapacity = 65536)
72 : linesCache(linesCacheCapacity)
73 {
74 }
75
76 Origin addOrigin(Pos::Origin origin, size_t size)
77 {
78 auto origins(origins_.lock());
79 uint32_t offset = 0;
80 if (auto it = origins->rbegin(); it != origins->rend())
81 offset = it->first + it->second.size;
82 // +1 because all PosIdx are offset by 1 to begin with, and
83 // another +1 to ensure that all origins can point to EOF, eg
84 // on (invalid) empty inputs.
85 if (2 + offset + size < offset)
86 return Origin{origin, offset, 0};
87 return origins->emplace(offset, Origin{origin, offset, size}).first->second;
88 }
89
90 PosIdx add(const Origin & origin, size_t offset)
91 {
92 if (offset > origin.size)
93 return PosIdx();
94 return PosIdx(1 + origin.offset + offset);
95 }
96
108 Pos operator[](PosIdx p) const;
109
110 Pos::Origin originOf(PosIdx p) const
111 {
112 if (auto o = resolve(p))
113 return o->origin;
114 return std::monostate{};
115 }
116
120 void clear()
121 {
122 linesCache.lock()->clear();
123 origins_.lock()->clear();
124 }
125};
126
127} // namespace nix
Definition lru-cache.hh:16
Definition pos-idx.hh:10
Definition pos-table.hh:18
Definition pos-table.hh:15
Pos operator[](PosIdx p) const
Definition pos-table.cc:9
void clear()
Definition pos-table.hh:120
WriteLock lock()
Definition sync.hh:139
Pos and AbstractPos.