Platform.Data.Doublets C++
Loading...
Searching...
No Matches
UnitedMemoryLinksBase.h
Go to the documentation of this file.
2{
3
4 template <typename TSelf, typename TLinkOptions, typename TMemory, typename TSourceTreeMethods,
5 typename TTargetTreeMethods, typename TUnusedLinks, typename... TBase>
6 struct UnitedMemoryLinksBase : public Interfaces::Polymorph<TSelf, TBase...>
7 {
8 public:
9 using LinksOptionsType = TLinkOptions;
10 using LinkAddressType = typename LinksOptionsType::LinkAddressType;
11 using LinkType = typename LinksOptionsType::LinkType;
12 using WriteHandlerType = typename LinksOptionsType::WriteHandlerType;
13 using ReadHandlerType = typename LinksOptionsType::ReadHandlerType;
14 static constexpr LinksConstants<LinkAddressType> Constants = LinksOptionsType::Constants;
15
16 public:
17 static constexpr std::size_t LinkSizeInBytes = sizeof(RawLink<LinkAddressType>);
18
19 static constexpr std::size_t LinkHeaderSizeInBytes = sizeof(LinksHeader<LinkAddressType>);
20
21 static constexpr std::size_t DefaultLinksSizeStep = LinkSizeInBytes * 1024 * 1024;
22
23 public:
24 TMemory _memory;
25
26 private:
27 std::byte* _header;
28
29 private:
30 std::byte* _links;
31
32 const std::size_t _memoryReservationStep;
33
34 std::unique_ptr<TTargetTreeMethods> _TargetsTreeMethods;
35
36 std::unique_ptr<TSourceTreeMethods> _SourcesTreeMethods;
37
38 std::unique_ptr<TUnusedLinks> _UnusedLinksListMethods;
39
40 LinksHeader<LinkAddressType>& GetHeaderReference()
41 {
42 return *reinterpret_cast<LinksHeader<LinkAddressType>*>(_header);
43 }
44
45 const LinksHeader<LinkAddressType>& GetHeaderReference() const
46 {
47 return *reinterpret_cast<LinksHeader<LinkAddressType>*>(_header);
48 }
49
50 const RawLink<LinkAddressType>& GetLinkReference(LinkAddressType linkIndex) const
51 {
52 return reinterpret_cast<const RawLink<LinkAddressType>*>(_links)[linkIndex];
53 }
54
55 RawLink<LinkAddressType>& GetLinkReference(LinkAddressType linkIndex)
56 {
57 return reinterpret_cast<RawLink<LinkAddressType>*>(_links)[linkIndex];
58 }
59
60 LinkAddressType GetTotal() const
61 {
62 auto& header = this->GetHeaderReference();
63 return header.AllocatedLinks - header.FreeLinks;
64 }
65
66 public:
67 public:
69
70 UnitedMemoryLinksBase(TMemory&& memory, std::uint64_t memoryReservationStep)
71 : _memory(std::move(memory)), _memoryReservationStep(memoryReservationStep)
72 {
73 Init(_memory, memoryReservationStep);
74 }
75
76 void Init(TMemory& memory, std::size_t memoryReservationStep)
77 {
78
79 if (memory.ReservedCapacity() < memoryReservationStep)
80 {
81 memory.ReservedCapacity(memoryReservationStep);
82 }
83 SetPointers(memory);
84
85 auto& header = this->GetHeaderReference();
86 memory.UsedCapacity((header.AllocatedLinks * LinkSizeInBytes) + LinkHeaderSizeInBytes);
87 header.ReservedLinks = (memory.ReservedCapacity() - LinkHeaderSizeInBytes) / LinkSizeInBytes;
88 }
89
90 public:
91 LinkAddressType Count(const LinkType& restriction) const
92 {
93 // Restriction length determines which parts of a stored link are constrained.
94 // An empty restriction counts live records, excluding entries on the free list.
95 if (std::ranges::size(restriction) == 0)
96 {
97 return GetTotal();
98 }
99 auto any = Constants.Any;
100 auto index = restriction[Constants.IndexPart];
101 if (std::ranges::size(restriction) == 1)
102 {
103 if (index == any)
104 {
105 return GetTotal();
106 }
107 return Exists(index) ? LinkAddressType{1} : LinkAddressType{};
108 }
109 if (std::ranges::size(restriction) == 2)
110 {
111 // A two-part query matches the value in either the source or target index.
112 auto value = restriction[1];
113 if (index == any)
114 {
115 if (value == any)
116 {
117 return GetTotal(); // Any - как отсутствие ограничения
118 }
119 LinkAddressType count{};
120 if (value == Constants.Null)
121 {
122 Each(restriction, [&](const auto&) {
123 ++count;
124 return Constants.Continue;
125 });
126 return count;
127 }
128 count = _SourcesTreeMethods->CountUsages(value);
129 // Add target-only matches, retaining distinct records with equal endpoints.
130 _TargetsTreeMethods->EachUsage(value, [&](const auto& link) {
131 if (link[Constants.SourcePart] != value)
132 ++count;
133 return Constants.Continue;
134 });
135 return count;
136 }
137 else
138 {
139 if (!Exists(index))
140 {
141 return LinkAddressType{};
142 }
143 if (value == any)
144 {
145 return LinkAddressType{1};
146 }
147 auto& storedLinkValue = GetLinkReference(index);
148 if (storedLinkValue.Source == value || storedLinkValue.Target == value)
149 {
150 return LinkAddressType{1};
151 }
152 return LinkAddressType{};
153 }
154 }
155 if (std::ranges::size(restriction) == 3)
156 {
157 // Wildcards select the relevant usage index; two concrete values use a pair lookup.
158 auto source = restriction[Constants.SourcePart];
159 auto target = restriction[Constants.TargetPart];
160 if (index == any)
161 {
162 if (source == any && target == any)
163 {
164 return GetTotal();
165 }
166 else if (source == any)
167 {
168 return _TargetsTreeMethods->CountUsages(target);
169 }
170 else if (target == any)
171 {
172 return _SourcesTreeMethods->CountUsages(source);
173 }
174 else // if(source != Any && target != Any)
175 {
176 auto link = _SourcesTreeMethods->Search(source, target);
177 return link == Constants.Null ? LinkAddressType{} : LinkAddressType{1};
178 }
179 }
180 else
181 {
182 // A concrete address must exist before its stored values can be compared.
183 if (!Exists(index))
184 {
185 return LinkAddressType{};
186 }
187 if (source == any && target == any)
188 {
189 return LinkAddressType{1};
190 }
191 auto& storedLinkValue = GetLinkReference(index);
192 // Three-part restrictions match each endpoint in its own position.
193 if ((source == any || storedLinkValue.Source == source) &&
194 (target == any || storedLinkValue.Target == target))
195 {
196 return LinkAddressType{1};
197 }
198 return LinkAddressType{};
199 }
200 }
201 throw std::logic_error("Not supported exception.");
202 }
203
204 public:
205 LinkAddressType Each(const LinkType& restriction, const ReadHandlerType& handler) const
206 {
207 auto $continue{Constants.Continue};
208 auto $break = Constants.Break;
209 if (std::ranges::size(restriction) == 0)
210 {
211 for (auto link = LinkAddressType{1}; link <= this->GetHeaderReference().AllocatedLinks; ++link)
212 {
213 if (Exists(link) && (handler(GetLinkStruct(link)) == $break))
214 {
215 return $break;
216 }
217 }
218 return $continue;
219 }
220 auto _continue = Constants.Continue;
221 auto any = Constants.Any;
222 auto index = restriction[Constants.IndexPart];
223 if (std::ranges::size(restriction) == 1)
224 {
225 if (index == any)
226 {
227 return Data::Each(*this, handler);
228 }
229 if (!Exists(index))
230 {
231 return _continue;
232 }
233 return handler(GetLinkStruct(index));
234 }
235 if (std::ranges::size(restriction) == 2)
236 {
237 auto value = restriction[1];
238 if (index == any)
239 {
240 if (value == any)
241 {
242 return Data::Each(*this, handler);
243 }
244 if (value == Constants.Null)
245 {
246 // Null endpoints are absent from the usage indexes.
247 return Each(LinkType{}, [&](const auto& link) {
248 return link[Constants.SourcePart] == value || link[Constants.TargetPart] == value
249 ? handler(link)
250 : _continue;
251 });
252 }
253 if (Each(LinkType{index, value, any}, handler) == $break)
254 {
255 return $break;
256 }
257 return Each(LinkType{index, any, value}, [&](const auto& link) {
258 return link[Constants.SourcePart] == value ? _continue : handler(link);
259 });
260 }
261 else
262 {
263 if (!Exists(index))
264 {
265 return _continue;
266 }
267 if (value == any)
268 {
269 return handler(GetLinkStruct(index));
270 }
271 auto& storedLinkValue = GetLinkReference(index);
272 if ((storedLinkValue.Source == value) || (storedLinkValue.Target == value))
273 {
274 return handler(GetLinkStruct(index));
275 }
276 return _continue;
277 }
278 }
279 if (std::ranges::size(restriction) == 3)
280 {
281 auto source = restriction[Constants.SourcePart];
282 auto target = restriction[Constants.TargetPart];
283 if (index == any)
284 {
285 if (source == any && target == any)
286 {
287 return Data::Each(*this, handler);
288 }
289 else if (source == any)
290 {
291 return _TargetsTreeMethods->EachUsage(target, handler);
292 }
293 else if (target == any)
294 {
295 return _SourcesTreeMethods->EachUsage(source, handler);
296 }
297 else // if(source != Any && target != Any)
298 {
299 auto link = _SourcesTreeMethods->Search(source, target);
300 return (link == Constants.Null) ? _continue : handler(GetLinkStruct(link));
301 }
302 }
303 else
304 {
305 if (!Exists(index))
306 {
307 return _continue;
308 }
309 if (source == any && target == any)
310 {
311 return handler(GetLinkStruct(index));
312 }
313 // TODO: 'ref locals' are not converted by C# to C++ Converter:
314 // ORIGINAL LINE: ref var storedLinkValue = ref GetLinkReference(index);
315 auto& storedLinkValue = GetLinkReference(index);
316 // Three-part restrictions match each endpoint in its own position.
317 if ((source == any || storedLinkValue.Source == source) &&
318 (target == any || storedLinkValue.Target == target))
319 {
320 return handler(GetLinkStruct(index));
321 }
322 return _continue;
323 }
324 }
325 throw std::logic_error("Not supported exception.");
326 }
327
328 // / <remarks>
329 // / TODO: Возможно можно перемещать значения, если указан индекс, но значение существует в другом месте (но не
330 // в менеджере памяти, а в логике Links) / </remarks> NOTE: The following .NET attribute has no direct
331 // equivalent in C++: ORIGINAL LINE: [MethodImpl(MethodImplOptions.AggressiveInlining)] public LinkAddressType
332 // Update(IList<LinkAddressType> restriction, IList<LinkAddressType> substitution)
333 public:
334 LinkAddressType Update(const LinkType& restriction, const LinkType& substitution,
335 const WriteHandlerType& handler)
336 {
337 auto null = Constants.Null;
338 auto linkIndex = restriction[Constants.IndexPart];
339 // TODO: 'ref locals' are not converted by C# to C++ Converter:
340 // ORIGINAL LINE: ref var link = ref GetLinkReference(linkIndex);
341 auto& link = GetLinkReference(linkIndex);
342 LinkType before{linkIndex, link.Source, link.Target};
343 // TODO: 'ref locals' are not converted by C# to C++ Converter:
344 // ORIGINAL LINE: ref var header = ref GetHeaderReference();
345 auto& header = this->GetHeaderReference();
346 // TODO: 'ref locals' are not converted by C# to C++ Converter:
347 // ORIGINAL LINE: ref var firstAsSource = ref header.RootAsSource;
348 auto& firstAsSource = header.RootAsSource;
349 // TODO: 'ref locals' are not converted by C# to C++ Converter:
350 // ORIGINAL LINE: ref var firstAsTarget = ref header.RootAsTarget;
351 auto& firstAsTarget = header.RootAsTarget;
352 // Будет корректно работать только в том случае, если пространство выделенной связи предварительно заполнено
353 // нулями
354 if (link.Source != null)
355 {
356 _SourcesTreeMethods->Detach(firstAsSource, linkIndex);
357 }
358 if (link.Target != null)
359 {
360 _TargetsTreeMethods->Detach(firstAsTarget, linkIndex);
361 }
362 link.Source = substitution[Constants.SourcePart];
363 link.Target = substitution[Constants.TargetPart];
364 if (link.Source != null)
365 {
366 _SourcesTreeMethods->Attach(firstAsSource, linkIndex);
367 }
368 if (link.Target != null)
369 {
370 _TargetsTreeMethods->Attach(firstAsTarget, linkIndex);
371 }
372 return handler(before, LinkType{linkIndex, link.Source, link.Target});
373 }
374
375 // TODO: Возможно нужно будет заполнение нулями, если внешнее API ими не заполняет пространство
376 public:
378 {
379 auto* header = &this->GetHeaderReference();
380 auto freeLink = header->FirstFreeLink;
381 if (freeLink != Constants.Null)
382 {
383 _UnusedLinksListMethods->Detach(freeLink);
384 }
385 else
386 {
387 auto maximumPossibleInnerReference = Constants.InternalReferencesRange.Maximum;
388 if (header->AllocatedLinks >= maximumPossibleInnerReference)
389 {
390 throw Platform::Exceptions::LinksLimitReachedException();
391 }
392 if (header->AllocatedLinks >= (header->ReservedLinks - 1))
393 {
394 _memory.ReservedCapacity(_memory.ReservedCapacity() + _memoryReservationStep);
396 header = &this->GetHeaderReference();
397 header->ReservedLinks = _memory.ReservedCapacity() / LinkSizeInBytes;
398 }
399 ++header->AllocatedLinks;
400 freeLink = header->AllocatedLinks;
401 _memory.UsedCapacity(_memory.UsedCapacity() + LinkSizeInBytes);
402 }
403 return handler(LinkType{0, 0, 0}, LinkType{freeLink, 0, 0});
404 }
405
406 public:
407 LinkAddressType Delete(const LinkType& restriction, const WriteHandlerType& handler)
408 {
409 auto& header = this->GetHeaderReference();
410 auto linkAddress = restriction[Constants.IndexPart];
411 auto before = GetLinkStruct(linkAddress);
412 if (linkAddress < header.AllocatedLinks)
413 {
414 _UnusedLinksListMethods->AttachAsFirst(linkAddress);
415 return handler ? handler(before, LinkType{}) : Constants.Continue;
416 }
417 else if (linkAddress == header.AllocatedLinks)
418 {
419 --header.AllocatedLinks;
420 _memory.UsedCapacity(_memory.UsedCapacity() - LinkSizeInBytes);
421 while ((header.AllocatedLinks > LinkAddressType{}) && IsUnusedLink(header.AllocatedLinks))
422 {
423 _UnusedLinksListMethods->Detach(header.AllocatedLinks);
424 --header.AllocatedLinks;
425 _memory.UsedCapacity(_memory.UsedCapacity() - LinkSizeInBytes);
426 }
427 return handler ? handler(before, LinkType{}) : Constants.Continue;
428 }
429 return Constants.Continue;
430 }
431
433 {
434 auto& link = this->GetLinkReference(linkIndex);
435 return LinkType{linkIndex, link.Source, link.Target};
436 }
437
438 // TODO: Возможно это должно быть событием, вызываемым из IMemory, в том случае, если адрес реально поменялся
439 //
440 // Указатель this.storage может быть в том же месте,
441 // так как 0-я связь не используется и имеет такой же размер как Header,
442 // поэтому header размещается в том же месте, что и 0-я связь
443 public:
444 void SetPointers(TMemory& memory)
445 {
446 _links = static_cast<std::byte*>(memory.Pointer());
447 _header = _links;
448 _SourcesTreeMethods = std::make_unique<TSourceTreeMethods>(_links, _header);
449 _TargetsTreeMethods = std::make_unique<TTargetTreeMethods>(_links, _header);
450 _UnusedLinksListMethods = std::make_unique<TUnusedLinks>(_links, _header);
451 }
452
453 bool Exists(LinkAddressType linkAddress) const
454 {
455 if (IsExternalReference<LinkAddressType, Constants>(linkAddress))
456 {
457 return false;
458 }
459 return (linkAddress >= Constants.InternalReferencesRange.Minimum) &&
460 (linkAddress <= this->GetHeaderReference().AllocatedLinks) && !IsUnusedLink(linkAddress);
461 }
462
463 bool IsUnusedLink(LinkAddressType linkIndex) const
464 {
465 if (GetHeaderReference().FirstFreeLink != linkIndex) // May be this check is not needed
466 {
467 auto& link = GetLinkReference(linkIndex);
468 return (link.SizeAsSource == LinkAddressType{}) && (link.Source != LinkAddressType{});
469 }
470 else
471 {
472 return true;
473 }
474 }
475 };
476} // namespace Platform::Data::Doublets::Memory::United::Generic
Definition LinksAvlBalancedTreeMethodsBase.h:2
Definition RawLinkDataPart.h:38
UnitedMemoryLinksBase(TMemory &&memory)
Definition UnitedMemoryLinksBase.h:68
LinkAddressType Update(const LinkType &restriction, const LinkType &substitution, const WriteHandlerType &handler)
Definition UnitedMemoryLinksBase.h:334
LinkAddressType Create(const LinkType &, const WriteHandlerType &handler)
Definition UnitedMemoryLinksBase.h:377
LinkAddressType Delete(const LinkType &restriction, const WriteHandlerType &handler)
Definition UnitedMemoryLinksBase.h:407
UnitedMemoryLinksBase(TMemory &&memory, std::uint64_t memoryReservationStep)
Definition UnitedMemoryLinksBase.h:70
LinkAddressType Count(const LinkType &restriction) const
Definition UnitedMemoryLinksBase.h:91