Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RFieldSequenceContainer.cxx
Go to the documentation of this file.
1/// \file RFieldSequenceContainer.cxx
2/// \author Jonas Hahnfeld <jonas.hahnfeld@cern.ch>
3/// \date 2024-11-19
4
5#include <ROOT/BitUtils.hxx>
6#include <ROOT/RField.hxx>
7#include <ROOT/RFieldBase.hxx>
10
11#include <limits>
12#include <memory>
13#include <new> // hardware_destructive_interference_size, operator new
14
15namespace {
16
17std::vector<ROOT::RFieldBase::RValue> SplitVector(const std::shared_ptr<void> &valuePtr, ROOT::RFieldBase &itemField)
18{
19 auto *vec = static_cast<std::vector<char> *>(valuePtr.get());
20 const auto itemSize = itemField.GetValueSize();
21 R__ASSERT(itemSize > 0);
22 R__ASSERT((vec->size() % itemSize) == 0);
23 const auto nItems = vec->size() / itemSize;
24 std::vector<ROOT::RFieldBase::RValue> result;
25 result.reserve(nItems);
26 for (unsigned i = 0; i < nItems; ++i) {
27 result.emplace_back(itemField.BindValue(std::shared_ptr<void>(valuePtr, vec->data() + (i * itemSize))));
28 }
29 return result;
30}
31
32std::size_t GetSizeOfVector()
33{
34 return sizeof(std::vector<char>);
35}
36
37std::size_t GetAlignOfVector()
38{
39 return alignof(std::vector<char>);
40}
41
42void ConstructVector(void *where, std::size_t alignOfValue)
43{
44 static_assert(ROOT::RVectorField::kMaxItemAlignment == 4096);
45 // clang-format off
46 switch (alignOfValue) {
47 case 1: new (where) std::vector<ROOT::Internal::RAlignedStorage< 1>>(); break;
48 case 2: new (where) std::vector<ROOT::Internal::RAlignedStorage< 2>>(); break;
49 case 4: new (where) std::vector<ROOT::Internal::RAlignedStorage< 4>>(); break;
50 case 8: new (where) std::vector<ROOT::Internal::RAlignedStorage< 8>>(); break;
51 case 16: new (where) std::vector<ROOT::Internal::RAlignedStorage< 16>>(); break;
52 case 32: new (where) std::vector<ROOT::Internal::RAlignedStorage< 32>>(); break;
53 case 64: new (where) std::vector<ROOT::Internal::RAlignedStorage< 64>>(); break;
54 case 128: new (where) std::vector<ROOT::Internal::RAlignedStorage< 128>>(); break;
55 case 256: new (where) std::vector<ROOT::Internal::RAlignedStorage< 256>>(); break;
56 case 512: new (where) std::vector<ROOT::Internal::RAlignedStorage< 512>>(); break;
57 case 1024: new (where) std::vector<ROOT::Internal::RAlignedStorage<1024>>(); break;
58 case 2048: new (where) std::vector<ROOT::Internal::RAlignedStorage<2048>>(); break;
59 case 4096: new (where) std::vector<ROOT::Internal::RAlignedStorage<4096>>(); break;
60 default: throw ROOT::RException(R__FAIL(std::string("Unsupported alignment: ") + std::to_string(alignOfValue)));
61 }
62 // clang-format on
63}
64
65} // anonymous namespace
66
67ROOT::RArrayField::RArrayField(std::string_view fieldName, std::unique_ptr<RFieldBase> itemField,
68 std::size_t arrayLength)
69 : ROOT::RFieldBase(fieldName,
70 "std::array<" + itemField->GetTypeName() + "," +
71 Internal::GetNormalizedInteger(static_cast<unsigned long long>(arrayLength)) + ">",
72 ROOT::ENTupleStructure::kPlain, false /* isSimple */, arrayLength),
73 fItemSize(itemField->GetValueSize()),
74 fArrayLength(arrayLength)
75{
76 Internal::EnsureTypedChildField(*itemField, *this);
77 if (arrayLength == 0) {
78 throw RException(R__FAIL("invalid zero-length array field " + GetQualifiedFieldName()));
79 }
80 fTraits |= itemField->GetTraits() & ~kTraitMappable;
81 if (!itemField->GetTypeAlias().empty()) {
82 SetTypeAlias("std::array<" + itemField->GetTypeAlias() + "," +
83 Internal::GetNormalizedInteger(static_cast<unsigned long long>(arrayLength)) + ">");
84 }
85 Attach(std::move(itemField), "_0");
86}
87
88std::unique_ptr<ROOT::RFieldBase> ROOT::RArrayField::CloneImpl(std::string_view newName) const
89{
90 auto newItemField = fSubfields[0]->Clone(fSubfields[0]->GetFieldName());
91 return std::make_unique<RArrayField>(newName, std::move(newItemField), fArrayLength);
92}
93
94std::size_t ROOT::RArrayField::AppendImpl(const void *from)
95{
96 std::size_t nbytes = 0;
97 if (fSubfields[0]->IsSimple()) {
98 GetPrincipalColumnOf(*fSubfields[0])->ForWriting()->AppendV(from, fArrayLength);
99 nbytes += fArrayLength * GetPrincipalColumnOf(*fSubfields[0])->GetElement()->GetPackedSize();
100 } else {
101 auto arrayPtr = static_cast<const unsigned char *>(from);
102 for (unsigned i = 0; i < fArrayLength; ++i) {
103 nbytes += CallAppendOn(*fSubfields[0], arrayPtr + (i * fItemSize));
104 }
105 }
106 return nbytes;
107}
108
110{
111 if (fSubfields[0]->IsSimple()) {
112 GetPrincipalColumnOf(*fSubfields[0])->ForReading()->ReadV(globalIndex * fArrayLength, fArrayLength, to);
113 } else {
114 auto arrayPtr = static_cast<unsigned char *>(to);
115 for (unsigned i = 0; i < fArrayLength; ++i) {
116 CallReadOn(*fSubfields[0], globalIndex * fArrayLength + i, arrayPtr + (i * fItemSize));
117 }
118 }
119}
120
122{
123 if (fSubfields[0]->IsSimple()) {
124 GetPrincipalColumnOf(*fSubfields[0])->ForReading()->ReadV(localIndex * fArrayLength, fArrayLength, to);
125 } else {
126 auto arrayPtr = static_cast<unsigned char *>(to);
127 for (unsigned i = 0; i < fArrayLength; ++i) {
128 CallReadOn(*fSubfields[0], localIndex * fArrayLength + i, arrayPtr + (i * fItemSize));
129 }
130 }
131}
132
133std::size_t ROOT::RArrayField::ReadBulkImpl(const RBulkSpec &bulkSpec)
134{
135 if (!fSubfields[0]->IsSimple())
136 return RFieldBase::ReadBulkImpl(bulkSpec);
137
138 GetPrincipalColumnOf(*fSubfields[0])
139 ->ForReading()
140 ->ReadV(bulkSpec.fFirstIndex * fArrayLength, bulkSpec.fCount * fArrayLength, bulkSpec.fValues);
141 return RBulkSpec::kAllSet;
142}
143
145{
146 static const std::vector<std::string> prefixes = {"std::array<"};
147
148 EnsureMatchingOnDiskField(desc, kDiffTypeName).ThrowOnError();
149 EnsureMatchingTypePrefix(desc, prefixes).ThrowOnError();
150}
151
153{
154 if (fSubfields[0]->GetTraits() & kTraitTriviallyConstructible)
155 return;
156
157 auto arrayPtr = reinterpret_cast<unsigned char *>(where);
158 for (unsigned i = 0; i < fArrayLength; ++i) {
159 CallConstructValueOn(*fSubfields[0], arrayPtr + (i * fItemSize));
160 }
161}
162
163void ROOT::RArrayField::RArrayDeleter::operator()(void *objPtr, bool dtorOnly)
164{
165 if (fItemDeleter) {
166 for (unsigned i = 0; i < fArrayLength; ++i) {
167 fItemDeleter->operator()(reinterpret_cast<unsigned char *>(objPtr) + i * fItemSize, true /* dtorOnly */);
168 }
169 }
170 RDeleter::operator()(objPtr, dtorOnly);
171}
172
173std::unique_ptr<ROOT::RFieldBase::RDeleter> ROOT::RArrayField::GetDeleter() const
174{
175 if (!(fSubfields[0]->GetTraits() & kTraitTriviallyDestructible))
176 return std::make_unique<RArrayDeleter>(fItemSize, fArrayLength, GetAlignment(), GetDeleterOf(*fSubfields[0]));
177 return std::make_unique<RDeleter>(GetAlignment());
178}
179
180std::vector<ROOT::RFieldBase::RValue> ROOT::RArrayField::SplitValue(const RValue &value) const
181{
182 auto valuePtr = value.GetPtr<void>();
183 auto arrayPtr = static_cast<unsigned char *>(valuePtr.get());
184 std::vector<RValue> result;
185 result.reserve(fArrayLength);
186 for (unsigned i = 0; i < fArrayLength; ++i) {
187 result.emplace_back(fSubfields[0]->BindValue(std::shared_ptr<void>(valuePtr, arrayPtr + (i * fItemSize))));
188 }
189 return result;
190}
191
193{
194 visitor.VisitArrayField(*this);
195}
196
197//------------------------------------------------------------------------------
198
199ROOT::RRVecField::RRVecField(std::string_view fieldName, std::unique_ptr<RFieldBase> itemField)
200 : ROOT::RFieldBase(fieldName, "ROOT::VecOps::RVec<" + itemField->GetTypeName() + ">",
201 ROOT::ENTupleStructure::kCollection, false /* isSimple */),
202 fItemSize(itemField->GetValueSize()),
203 fNWritten(0)
204{
205 Internal::EnsureTypedChildField(*itemField, *this);
206 if (itemField->GetAlignment() > sizeof(std::max_align_t)) {
207 // RVec uses operator new without alignment info
208 throw RException(R__FAIL("RVec does not support over-aligned types"));
209 }
210
211 if (!(itemField->GetTraits() & kTraitTriviallyDestructible))
212 fItemDeleter = GetDeleterOf(*itemField);
213 if (!itemField->GetTypeAlias().empty())
214 SetTypeAlias("ROOT::VecOps::RVec<" + itemField->GetTypeAlias() + ">");
215 Attach(std::move(itemField), "_0");
216 fValueSize =
218
219 // Determine if we can optimimize bulk reading
220 if (fSubfields[0]->IsSimple()) {
221 fBulkSubfield = fSubfields[0].get();
222 } else {
223 if (auto f = dynamic_cast<RArrayField *>(fSubfields[0].get())) {
224 auto grandChildFields = fSubfields[0]->GetMutableSubfields();
225 if (grandChildFields[0]->IsSimple()) {
226 fBulkSubfield = grandChildFields[0];
227 fBulkNRepetition = f->GetLength();
228 }
229 }
230 }
231}
232
233std::unique_ptr<ROOT::RFieldBase> ROOT::RRVecField::CloneImpl(std::string_view newName) const
234{
235 auto newItemField = fSubfields[0]->Clone(fSubfields[0]->GetFieldName());
236 return std::make_unique<RRVecField>(newName, std::move(newItemField));
237}
238
239std::size_t ROOT::RRVecField::AppendImpl(const void *from)
240{
241 auto [beginPtr, sizePtr, _] = Internal::GetRVecDataMembers(from);
242
243 std::size_t nbytes = 0;
244 if (fSubfields[0]->IsSimple() && *sizePtr) {
245 GetPrincipalColumnOf(*fSubfields[0])->ForWriting()->AppendV(*beginPtr, *sizePtr);
246 nbytes += *sizePtr * GetPrincipalColumnOf(*fSubfields[0])->GetElement()->GetPackedSize();
247 } else {
248 for (std::int32_t i = 0; i < *sizePtr; ++i) {
249 nbytes += CallAppendOn(*fSubfields[0], *beginPtr + i * fItemSize);
250 }
251 }
252
253 fNWritten += *sizePtr;
254 fPrincipalColumn->ForWriting()->Append(&fNWritten);
255 return nbytes + fPrincipalColumn->GetElement()->GetPackedSize();
256}
257
258unsigned char *ROOT::RRVecField::ResizeRVec(void *rvec, std::size_t nItems, std::size_t itemSize,
259 const RFieldBase *itemField, RDeleter *itemDeleter)
260
261{
262 if (nItems > static_cast<std::size_t>(std::numeric_limits<std::int32_t>::max())) {
263 throw RException(R__FAIL("RVec too large: " + std::to_string(nItems)));
264 }
265
266 auto [beginPtr, sizePtr, capacityPtr] = Internal::GetRVecDataMembers(rvec);
267 const std::size_t oldSize = *sizePtr;
268
269 if (oldSize == nItems) {
270 // If neither shrink nor grow is necessary, do nothing.
271 // Note that this case preserves a memory adopting RVec as such. All real resizes in either direction
272 // transform a memory adopting RVec into an owning RVec.
273 return *beginPtr;
274 }
275
276 // See "semantics of reading non-trivial objects" in RNTuple's Architecture.md for details
277 // on the element construction/destrution.
278 const bool owns = (*capacityPtr != -1);
279 const bool needsConstruct = !(itemField->GetTraits() & kTraitTriviallyConstructible);
280 const bool needsDestruct = owns && itemDeleter;
281
282 // Destroy excess elements, if any
283 if (needsDestruct) {
284 for (std::size_t i = nItems; i < oldSize; ++i) {
285 itemDeleter->operator()(*beginPtr + (i * itemSize), true /* dtorOnly */);
286 }
287 }
288
289 // Resize RVec (capacity and size)
290 // In the regime between 0 and 16 items, grow by doubling the size. Grow larger vectors by a factor 1.5 at most.
291 // If the new size is larger than the grown capacity, set the new capacity to the new size (i.e., don't allocate
292 // a larger capacity for vectors the are suddenly vastly larger than their previous state).
293 // TODO(jblomer): investigate a longer look back window to avoid shrinking for an unusual small entry and consider
294 // returning to average or median size (see TBasket::WriteReset()).
295 static constexpr std::int32_t kSmallThreshold = 16;
296 if ((std::int32_t(nItems) > *capacityPtr) || /* must grow */
297 ((std::int32_t(nItems) > kSmallThreshold) && (std::int32_t(nItems) < *capacityPtr / 4))) /* must shrink */ {
298 // Destroy old elements: useless work for trivial types, but in case the element type's constructor
299 // allocates memory we need to release it here to avoid memleaks (e.g. if this is an RVec<RVec<int>>)
300 if (needsDestruct) {
301 // Excess elements were destructed earlier.
302 for (std::size_t i = 0u; i < std::min(oldSize, nItems); ++i) {
303 itemDeleter->operator()(*beginPtr + (i * itemSize), true /* dtorOnly */);
304 }
305 }
306
307 // Increment / decrement capacity geometrically
308 std::size_t newCapacity = nItems;
309 if (*capacityPtr > 0) {
310 constexpr std::size_t maxSize = static_cast<std::size_t>(std::numeric_limits<std::int32_t>::max());
311 const std::size_t oldCap = static_cast<std::size_t>(*capacityPtr);
312 if (nItems > oldCap) {
313 const std::size_t grown = oldCap + ((oldCap < kSmallThreshold) ? oldCap : (oldCap / 2));
314 newCapacity = std::min(maxSize, std::max(nItems, grown));
315 } else {
316 newCapacity = oldCap / 2;
317 assert(nItems <= newCapacity);
318 }
319 }
320
321 Internal::DestroyRVecWithChecks(itemField->GetAlignment(), beginPtr, capacityPtr);
322 // We checked that the item type is not over-aligned
323 *beginPtr = static_cast<unsigned char *>(::operator new(newCapacity * itemSize, std::nothrow));
324 R__ASSERT(*beginPtr != nullptr);
325 *capacityPtr = static_cast<std::int32_t>(newCapacity);
326
327 // Placement new for elements that were already there before the resize. When shrank, we only need to construct
328 // nItems items, because that's what we going to read. When grown, the remaining elements from oldSize until
329 // nItems is constructed a few lines down (we need to do this always when the size grows, even when not changing
330 // the capacity).
331 if (needsConstruct) {
332 for (std::size_t i = 0u; i < std::min(oldSize, nItems); ++i)
333 CallConstructValueOn(*itemField, *beginPtr + (i * itemSize));
334 }
335 }
336 *sizePtr = nItems;
337
338 // Placement new for new elements, if any
339 if (needsConstruct) {
340 for (std::size_t i = oldSize; i < nItems; ++i)
341 CallConstructValueOn(*itemField, *beginPtr + (i * itemSize));
342 }
343
344 return *beginPtr;
345}
346
348{
349 // TODO as a performance optimization, we could assign values to elements of the inline buffer:
350 // if size < inline buffer size: we save one allocation here and usage of the RVec skips a pointer indirection
351
352 // Read collection info for this entry
353 ROOT::NTupleSize_t nItems;
354 RNTupleLocalIndex collectionStart;
355 fPrincipalColumn->ForReading()->GetCollectionInfo(globalIndex, &collectionStart, &nItems);
356
357 auto begin = ResizeRVec(to, nItems, fItemSize, fSubfields[0].get(), fItemDeleter.get());
358
359 if (fSubfields[0]->IsSimple() && nItems) {
360 GetPrincipalColumnOf(*fSubfields[0])->ForReading()->ReadV(collectionStart, nItems, begin);
361 return;
362 }
363
364 // Read the new values into the collection elements
365 for (std::size_t i = 0; i < nItems; ++i) {
366 CallReadOn(*fSubfields[0], collectionStart + i, begin + (i * fItemSize));
367 }
368}
369
370std::size_t ROOT::RRVecField::ReadBulkImpl(const RBulkSpec &bulkSpec)
371{
372 if (!fBulkSubfield)
373 return RFieldBase::ReadBulkImpl(bulkSpec);
374
375 if (bulkSpec.fAuxData->empty()) {
376 /// Initialize auxiliary memory: the first sizeof(size_t) bytes store the value size of the item field.
377 /// The following bytes store the item values, consecutively.
378 bulkSpec.fAuxData->resize(sizeof(std::size_t));
379 *reinterpret_cast<std::size_t *>(bulkSpec.fAuxData->data()) = fBulkNRepetition * fBulkSubfield->GetValueSize();
380 }
381 const auto itemValueSize = *reinterpret_cast<std::size_t *>(bulkSpec.fAuxData->data());
382 unsigned char *itemValueArray = bulkSpec.fAuxData->data() + sizeof(std::size_t);
383 auto [beginPtr, sizePtr, capacityPtr] = Internal::GetRVecDataMembers(bulkSpec.fValues);
384
385 // Get size of the first RVec of the bulk
386 RNTupleLocalIndex firstItemIndex;
387 ROOT::NTupleSize_t collectionSize;
388 fPrincipalColumn->ForReading()->GetCollectionInfo(bulkSpec.fFirstIndex, &firstItemIndex, &collectionSize);
389 *beginPtr = itemValueArray;
390 *sizePtr = collectionSize;
391 *capacityPtr = -1;
392
393 // Set the size of the remaining RVecs of the bulk, going page by page through the RNTuple offset column.
394 // We optimistically assume that bulkSpec.fAuxData is already large enough to hold all the item values in the
395 // given range. If not, we'll fix up the pointers afterwards.
396 auto lastOffset = firstItemIndex.GetIndexInCluster() + collectionSize;
397 ROOT::NTupleSize_t nRemainingValues = bulkSpec.fCount - 1;
398 std::size_t nValues = 1;
399 std::size_t nItems = collectionSize;
400 while (nRemainingValues > 0) {
401 ROOT::NTupleSize_t nElementsUntilPageEnd;
402 const auto offsets = fPrincipalColumn->ForReading()->MapV<ROOT::Internal::RColumnIndex>(
403 bulkSpec.fFirstIndex + nValues, nElementsUntilPageEnd);
404 const std::size_t nBatch = std::min(nRemainingValues, nElementsUntilPageEnd);
405 for (std::size_t i = 0; i < nBatch; ++i) {
406 const auto size = offsets[i] - lastOffset;
407 std::tie(beginPtr, sizePtr, capacityPtr) = Internal::GetRVecDataMembers(
408 reinterpret_cast<unsigned char *>(bulkSpec.fValues) + (nValues + i) * fValueSize);
409 *beginPtr = itemValueArray + nItems * itemValueSize;
410 *sizePtr = size;
411 *capacityPtr = -1;
412
413 nItems += size;
414 lastOffset = offsets[i];
415 }
416 nRemainingValues -= nBatch;
417 nValues += nBatch;
418 }
419
420 bulkSpec.fAuxData->resize(sizeof(std::size_t) + nItems * itemValueSize);
421 // If the vector got reallocated, we need to fix-up the RVecs begin pointers.
422 const auto delta = itemValueArray - (bulkSpec.fAuxData->data() + sizeof(std::size_t));
423 if (delta != 0) {
424 auto beginPtrAsUChar = reinterpret_cast<unsigned char *>(bulkSpec.fValues);
425 for (std::size_t i = 0; i < bulkSpec.fCount; ++i) {
426 *reinterpret_cast<unsigned char **>(beginPtrAsUChar) -= delta;
427 beginPtrAsUChar += fValueSize;
428 }
429 }
430
431 GetPrincipalColumnOf(*fBulkSubfield)
432 ->ForReading()
433 ->ReadV(firstItemIndex * fBulkNRepetition, nItems * fBulkNRepetition, itemValueArray - delta);
434 return RBulkSpec::kAllSet;
435}
436
446
448{
449 GenerateColumnsImpl<ROOT::Internal::RColumnIndex>();
450}
451
453{
454 GenerateColumnsImpl<ROOT::Internal::RColumnIndex>(desc);
455}
456
457std::unique_ptr<ROOT::RFieldBase> ROOT::RRVecField::BeforeConnectPageSource(Internal::RPageSource &pageSource)
458{
459 if (GetOnDiskId() == kInvalidDescriptorId)
460 return nullptr;
461
462 auto descGuard = pageSource.GetSharedDescriptorGuard();
463 const auto &fieldDesc = descGuard->GetFieldDescriptor(GetOnDiskId());
464 if (fieldDesc.GetTypeName().rfind("std::array<", 0) == 0) {
465 auto substitute = std::make_unique<RArrayAsRVecField>(
466 GetFieldName(), fSubfields[0]->Clone(fSubfields[0]->GetFieldName()), fieldDesc.GetNRepetitions());
467 substitute->SetOnDiskId(GetOnDiskId());
468 return substitute;
469 }
470 return nullptr;
471}
472
474{
475 EnsureMatchingOnDiskCollection(desc).ThrowOnError();
476}
477
478void ROOT::RRVecField::ConstructValue(void *where) const
479{
480 // initialize data members fBegin, fSize, fCapacity
481 // currently the inline buffer is left uninitialized
482 void **beginPtr = new (where)(void *)(nullptr);
483 std::int32_t *sizePtr = new (reinterpret_cast<void *>(beginPtr + 1)) std::int32_t(0);
484 new (sizePtr + 1) std::int32_t(-1);
485}
486
487void ROOT::RRVecField::RRVecDeleter::operator()(void *objPtr, bool dtorOnly)
488{
489 auto [beginPtr, sizePtr, capacityPtr] = Internal::GetRVecDataMembers(objPtr);
490
491 if (fItemDeleter) {
492 for (std::int32_t i = 0; i < *sizePtr; ++i) {
493 fItemDeleter->operator()(*beginPtr + i * fItemSize, true /* dtorOnly */);
494 }
495 }
496
497 Internal::DestroyRVecWithChecks(fItemAlignment, beginPtr, capacityPtr);
498 RDeleter::operator()(objPtr, dtorOnly);
499}
500
501std::unique_ptr<ROOT::RFieldBase::RDeleter> ROOT::RRVecField::GetDeleter() const
502{
503 if (fItemDeleter)
504 return std::make_unique<RRVecDeleter>(fSubfields[0]->GetAlignment(), fItemSize, GetDeleterOf(*fSubfields[0]));
505 return std::make_unique<RRVecDeleter>(fSubfields[0]->GetAlignment());
506}
507
508std::vector<ROOT::RFieldBase::RValue> ROOT::RRVecField::SplitValue(const RValue &value) const
509{
510 auto [beginPtr, sizePtr, _] = Internal::GetRVecDataMembers(value.GetPtr<void>().get());
511
512 std::vector<RValue> result;
513 result.reserve(*sizePtr);
514 for (std::int32_t i = 0; i < *sizePtr; ++i) {
515 result.emplace_back(
516 fSubfields[0]->BindValue(std::shared_ptr<void>(value.GetPtr<void>(), *beginPtr + i * fItemSize)));
517 }
518 return result;
519}
520
522{
523 return fValueSize;
524}
525
527{
528 return Internal::EvalRVecAlignment(fSubfields[0]->GetAlignment());
529}
530
532{
533 visitor.VisitRVecField(*this);
534}
535
536//------------------------------------------------------------------------------
537
538ROOT::RVectorField::RVectorField(std::string_view fieldName, std::unique_ptr<RFieldBase> itemField,
539 const ROOT::RFieldDescriptor *emulatedFrom)
540 : ROOT::RFieldBase(fieldName,
541 emulatedFrom ? emulatedFrom->GetTypeName() : "std::vector<" + itemField->GetTypeName() + ">",
542 ROOT::ENTupleStructure::kCollection, false /* isSimple */),
543 fItemSize(itemField->GetValueSize()),
544 fNWritten(0)
545{
546 if (itemField->GetAlignment() > kMaxItemAlignment) {
547 throw RException(
548 R__FAIL(std::string("Unsupported vector item alignment: ") + std::to_string(itemField->GetAlignment())));
549 }
550
551 if (emulatedFrom && !emulatedFrom->GetTypeName().empty()) {
553 if (emulatedFrom->IsSoACollection())
555 fEmulatedTypeVersion = emulatedFrom->GetTypeVersion();
556 fEmulatedTypeChecksum = emulatedFrom->GetTypeChecksum().value_or(0);
557 }
558
559 if (!itemField->GetTypeAlias().empty())
560 SetTypeAlias("std::vector<" + itemField->GetTypeAlias() + ">");
561
562 if (!(itemField->GetTraits() & kTraitTriviallyDestructible))
563 fItemDeleter = GetDeleterOf(*itemField);
564 Attach(std::move(itemField), "_0");
565}
566
567ROOT::RVectorField::RVectorField(std::string_view fieldName, std::unique_ptr<RFieldBase> itemField)
568 : RVectorField(fieldName, std::move(itemField), nullptr)
569{
571}
572
573std::unique_ptr<ROOT::RVectorField>
574ROOT::RVectorField::CreateUntyped(std::string_view fieldName, std::unique_ptr<RFieldBase> itemField)
575{
577 return std::unique_ptr<ROOT::RVectorField>(new RVectorField(fieldName, itemField->Clone("_0"), &desc));
578}
579
580std::unique_ptr<ROOT::RFieldBase> ROOT::RVectorField::CloneImpl(std::string_view newName) const
581{
582 auto newItemField = fSubfields[0]->Clone(fSubfields[0]->GetFieldName());
583 auto isUntyped = GetTypeName().empty() || ((fTraits & kTraitEmulatedField) != 0);
585 if (isUntyped) {
587 desc = builder.TypeVersion(GetTypeVersion())
588 .TypeChecksum(GetTypeChecksum())
589 .TypeName(GetTypeName())
590 // we need an Id for MoveDescriptor to succeed, but we're not going to use it.
591 .FieldId(42)
592 // we also need a Structure for the same reason.
595 .Unwrap();
596 }
597 return std::unique_ptr<ROOT::RVectorField>(
598 new RVectorField(newName, std::move(newItemField), isUntyped ? &desc : nullptr));
599}
600
601std::size_t ROOT::RVectorField::AppendImpl(const void *from)
602{
603 auto typedValue = static_cast<const std::vector<char> *>(from);
604 // The order is important here: Profiling showed that the integer division is on the critical path. By moving the
605 // computation of count before R__ASSERT, the compiler can use the result of a single instruction (on x86) also for
606 // the modulo operation. Otherwise, it must perform the division twice because R__ASSERT expands to an external call
607 // of Fatal() in case of failure, which could have side effects that the compiler cannot analyze.
608 auto count = typedValue->size() / fItemSize;
609 R__ASSERT((typedValue->size() % fItemSize) == 0);
610 std::size_t nbytes = 0;
611
612 if (fSubfields[0]->IsSimple() && count) {
613 GetPrincipalColumnOf(*fSubfields[0])->ForWriting()->AppendV(typedValue->data(), count);
614 nbytes += count * GetPrincipalColumnOf(*fSubfields[0])->GetElement()->GetPackedSize();
615 } else {
616 for (unsigned i = 0; i < count; ++i) {
617 nbytes += CallAppendOn(*fSubfields[0], typedValue->data() + (i * fItemSize));
618 }
619 }
620
621 fNWritten += count;
622 fPrincipalColumn->ForWriting()->Append(&fNWritten);
623 return nbytes + fPrincipalColumn->GetElement()->GetPackedSize();
624}
625
626void ROOT::RVectorField::ResizeVector(void *vec, std::size_t nItems, std::size_t itemSize, const RFieldBase &itemField,
627 RDeleter *itemDeleter)
628{
629 auto typedValue = static_cast<std::vector<char> *>(vec);
630
631 // See "semantics of reading non-trivial objects" in RNTuple's Architecture.md
632 assert(itemSize > 0);
633 const auto oldNItems = typedValue->size() / itemSize;
634 const auto availNItems = typedValue->capacity() / itemSize;
635 assert((typedValue->size() % itemSize == 0) && (typedValue->capacity() % itemSize == 0));
636
637 const bool canRealloc = availNItems < nItems;
638 bool allDeallocated = false;
639 if (itemDeleter) {
640 allDeallocated = canRealloc;
641 for (std::size_t i = allDeallocated ? 0 : nItems; i < oldNItems; ++i) {
642 itemDeleter->operator()(typedValue->data() + (i * itemSize), true /* dtorOnly */);
643 }
644 }
645
646 // Resize the vector with correct alignment
647 const auto itemAlignment = itemField.GetAlignment();
648 const auto nbytes = nItems * itemSize;
649
650 auto fnAlignedResize = [](auto &vecOfAlignedStorage, std::size_t targetSize) {
651 constexpr auto valueTypeSize = sizeof(typename std::decay_t<decltype(vecOfAlignedStorage)>::value_type);
652 constexpr auto valueTypeAlignment = alignof(typename std::decay_t<decltype(vecOfAlignedStorage)>::value_type);
653 // Ensure that this function is used with RAlignedStorage as a template argument.
654 // In general, the actual (user-defined) item type may have larger size than alignment.
655 static_assert(valueTypeSize == valueTypeAlignment);
656 assert(targetSize % valueTypeAlignment == 0);
657 vecOfAlignedStorage.resize(targetSize / valueTypeSize);
658 };
659
660 static_assert(kMaxItemAlignment == 4096);
661 // clang-format off
662 switch (itemAlignment) {
663 case 1: fnAlignedResize(*static_cast<std::vector<Internal::RAlignedStorage< 1>> *>(vec), nbytes); break;
664 case 2: fnAlignedResize(*static_cast<std::vector<Internal::RAlignedStorage< 2>> *>(vec), nbytes); break;
665 case 4: fnAlignedResize(*static_cast<std::vector<Internal::RAlignedStorage< 4>> *>(vec), nbytes); break;
666 case 8: fnAlignedResize(*static_cast<std::vector<Internal::RAlignedStorage< 8>> *>(vec), nbytes); break;
667 case 16: fnAlignedResize(*static_cast<std::vector<Internal::RAlignedStorage< 16>> *>(vec), nbytes); break;
668 case 32: fnAlignedResize(*static_cast<std::vector<Internal::RAlignedStorage< 32>> *>(vec), nbytes); break;
669 case 64: fnAlignedResize(*static_cast<std::vector<Internal::RAlignedStorage< 64>> *>(vec), nbytes); break;
670 case 128: fnAlignedResize(*static_cast<std::vector<Internal::RAlignedStorage< 128>> *>(vec), nbytes); break;
671 case 256: fnAlignedResize(*static_cast<std::vector<Internal::RAlignedStorage< 256>> *>(vec), nbytes); break;
672 case 512: fnAlignedResize(*static_cast<std::vector<Internal::RAlignedStorage< 512>> *>(vec), nbytes); break;
673 case 1024: fnAlignedResize(*static_cast<std::vector<Internal::RAlignedStorage<1024>> *>(vec), nbytes); break;
674 case 2048: fnAlignedResize(*static_cast<std::vector<Internal::RAlignedStorage<2048>> *>(vec), nbytes); break;
675 case 4096: fnAlignedResize(*static_cast<std::vector<Internal::RAlignedStorage<4096>> *>(vec), nbytes); break;
676 default: throw RException(R__FAIL(std::string("Unsupported alignment: ") + std::to_string(itemAlignment)));
677 }
678 // clang-format on
679
680 if (!(itemField.GetTraits() & kTraitTriviallyConstructible)) {
681 for (std::size_t i = allDeallocated ? 0 : oldNItems; i < nItems; ++i) {
682 CallConstructValueOn(itemField, typedValue->data() + (i * itemSize));
683 }
684 }
685}
686
688{
689 auto typedValue = static_cast<std::vector<char> *>(to);
690
691 ROOT::NTupleSize_t nItems;
692 RNTupleLocalIndex collectionStart;
693 fPrincipalColumn->ForReading()->GetCollectionInfo(globalIndex, &collectionStart, &nItems);
694
695 if (fSubfields[0]->IsSimple()) {
696 typedValue->resize(nItems * fItemSize);
697 if (nItems)
698 GetPrincipalColumnOf(*fSubfields[0])->ForReading()->ReadV(collectionStart, nItems, typedValue->data());
699 return;
700 }
701
702 ResizeVector(to, nItems, fItemSize, *fSubfields[0], fItemDeleter.get());
703
704 for (std::size_t i = 0; i < nItems; ++i) {
705 CallReadOn(*fSubfields[0], collectionStart + i, typedValue->data() + (i * fItemSize));
706 }
707}
708
718
720{
721 GenerateColumnsImpl<ROOT::Internal::RColumnIndex>();
722}
723
725{
726 GenerateColumnsImpl<ROOT::Internal::RColumnIndex>(desc);
727}
728
729std::unique_ptr<ROOT::RFieldBase> ROOT::RVectorField::BeforeConnectPageSource(Internal::RPageSource &pageSource)
730{
731 if (GetOnDiskId() == kInvalidDescriptorId)
732 return nullptr;
733
734 auto descGuard = pageSource.GetSharedDescriptorGuard();
735 const auto &fieldDesc = descGuard->GetFieldDescriptor(GetOnDiskId());
736 if (fieldDesc.GetTypeName().rfind("std::array<", 0) == 0) {
737 auto substitute = std::make_unique<RArrayAsVectorField>(
738 GetFieldName(), fSubfields[0]->Clone(fSubfields[0]->GetFieldName()), fieldDesc.GetNRepetitions());
739 substitute->SetOnDiskId(GetOnDiskId());
740 return substitute;
741 }
742 return nullptr;
743}
744
746{
747 EnsureMatchingOnDiskCollection(desc).ThrowOnError();
748}
749
751{
752 ConstructVector(where, fSubfields[0]->GetAlignment());
753}
754
756 : RDeleter(GetAlignOfVector()), fItemAlignment(itemAlignment)
757{
758}
759
760ROOT::RVectorField::RVectorDeleter::RVectorDeleter(std::size_t itemSize, std::size_t itemAlignment,
761 std::unique_ptr<RDeleter> itemDeleter)
762 : RDeleter(GetAlignOfVector()),
763 fItemSize(itemSize),
764 fItemAlignment(itemAlignment),
765 fItemDeleter(std::move(itemDeleter))
766{
767}
768
769void ROOT::RVectorField::RVectorDeleter::operator()(void *objPtr, bool dtorOnly)
770{
771 auto vecPtr = static_cast<std::vector<char> *>(objPtr);
772 if (fItemDeleter) {
773 assert(fItemSize > 0);
774 auto nItems = vecPtr->size() / fItemSize;
775 assert((vecPtr->size() % fItemSize) == 0);
776 for (std::size_t i = 0; i < nItems; ++i) {
777 fItemDeleter->operator()(vecPtr->data() + (i * fItemSize), true /* dtorOnly */);
778 }
779 }
780
781 static_assert(kMaxItemAlignment == 4096);
782 // clang-format off
783 switch (fItemAlignment) {
784 case 1: std::destroy_at(static_cast<std::vector<Internal::RAlignedStorage< 1>> *>(objPtr)); break;
785 case 2: std::destroy_at(static_cast<std::vector<Internal::RAlignedStorage< 2>> *>(objPtr)); break;
786 case 4: std::destroy_at(static_cast<std::vector<Internal::RAlignedStorage< 4>> *>(objPtr)); break;
787 case 8: std::destroy_at(static_cast<std::vector<Internal::RAlignedStorage< 8>> *>(objPtr)); break;
788 case 16: std::destroy_at(static_cast<std::vector<Internal::RAlignedStorage< 16>> *>(objPtr)); break;
789 case 32: std::destroy_at(static_cast<std::vector<Internal::RAlignedStorage< 32>> *>(objPtr)); break;
790 case 64: std::destroy_at(static_cast<std::vector<Internal::RAlignedStorage< 64>> *>(objPtr)); break;
791 case 128: std::destroy_at(static_cast<std::vector<Internal::RAlignedStorage< 128>> *>(objPtr)); break;
792 case 256: std::destroy_at(static_cast<std::vector<Internal::RAlignedStorage< 256>> *>(objPtr)); break;
793 case 512: std::destroy_at(static_cast<std::vector<Internal::RAlignedStorage< 512>> *>(objPtr)); break;
794 case 1024: std::destroy_at(static_cast<std::vector<Internal::RAlignedStorage<1024>> *>(objPtr)); break;
795 case 2048: std::destroy_at(static_cast<std::vector<Internal::RAlignedStorage<2048>> *>(objPtr)); break;
796 case 4096: std::destroy_at(static_cast<std::vector<Internal::RAlignedStorage<4096>> *>(objPtr)); break;
797 default: throw ROOT::RException(R__FAIL(std::string("Unsupported alignment: ") + std::to_string(fItemAlignment)));
798 }
799 // clang-format on
800
801 RDeleter::operator()(objPtr, dtorOnly);
802}
803
804std::unique_ptr<ROOT::RFieldBase::RDeleter> ROOT::RVectorField::GetDeleter() const
805{
806 if (fItemDeleter)
807 return std::make_unique<RVectorDeleter>(fItemSize, fSubfields[0]->GetAlignment(), GetDeleterOf(*fSubfields[0]));
808 return std::make_unique<RVectorDeleter>(fSubfields[0]->GetAlignment());
809}
810
811std::vector<ROOT::RFieldBase::RValue> ROOT::RVectorField::SplitValue(const RValue &value) const
812{
813 return SplitVector(value.GetPtr<void>(), *fSubfields[0]);
814}
815
817{
818 return GetSizeOfVector();
819}
820
822{
823 return GetAlignOfVector();
824}
825
827{
828 visitor.VisitVectorField(*this);
829}
830
831//------------------------------------------------------------------------------
832
833ROOT::RField<std::vector<bool>>::RField(std::string_view name)
834 : ROOT::RFieldBase(name, "std::vector<bool>", ROOT::ENTupleStructure::kCollection, false /* isSimple */)
835{
836 Attach(std::make_unique<RField<bool>>("_0"));
837}
838
839std::size_t ROOT::RField<std::vector<bool>>::AppendImpl(const void *from)
840{
841 auto typedValue = static_cast<const std::vector<bool> *>(from);
842 auto count = typedValue->size();
843 for (unsigned i = 0; i < count; ++i) {
844 bool bval = (*typedValue)[i];
845 CallAppendOn(*fSubfields[0], &bval);
846 }
847 fNWritten += count;
848 fPrincipalColumn->ForWriting()->Append(&fNWritten);
849 return count + fPrincipalColumn->GetElement()->GetPackedSize();
850}
851
852void ROOT::RField<std::vector<bool>>::ReadGlobalImpl(ROOT::NTupleSize_t globalIndex, void *to)
853{
854 auto typedValue = static_cast<std::vector<bool> *>(to);
855
856 if (fOnDiskNRepetitions == 0) {
857 ROOT::NTupleSize_t nItems;
858 RNTupleLocalIndex collectionStart;
859 fPrincipalColumn->ForReading()->GetCollectionInfo(globalIndex, &collectionStart, &nItems);
860 typedValue->resize(nItems);
861 for (std::size_t i = 0; i < nItems; ++i) {
862 bool bval;
863 CallReadOn(*fSubfields[0], collectionStart + i, &bval);
864 (*typedValue)[i] = bval;
865 }
866 } else {
867 typedValue->resize(fOnDiskNRepetitions);
868 for (std::size_t i = 0; i < fOnDiskNRepetitions; ++i) {
869 bool bval;
870 CallReadOn(*fSubfields[0], globalIndex * fOnDiskNRepetitions + i, &bval);
871 (*typedValue)[i] = bval;
872 }
873 }
874}
875
876void ROOT::RField<std::vector<bool>>::ReadInClusterImpl(ROOT::RNTupleLocalIndex localIndex, void *to)
877{
878 auto typedValue = static_cast<std::vector<bool> *>(to);
879
880 if (fOnDiskNRepetitions == 0) {
881 ROOT::NTupleSize_t nItems;
882 RNTupleLocalIndex collectionStart;
883 fPrincipalColumn->ForReading()->GetCollectionInfo(localIndex, &collectionStart, &nItems);
884 typedValue->resize(nItems);
885 for (std::size_t i = 0; i < nItems; ++i) {
886 bool bval;
887 CallReadOn(*fSubfields[0], collectionStart + i, &bval);
888 (*typedValue)[i] = bval;
889 }
890 } else {
891 typedValue->resize(fOnDiskNRepetitions);
892 for (std::size_t i = 0; i < fOnDiskNRepetitions; ++i) {
893 bool bval;
894 CallReadOn(*fSubfields[0], localIndex * fOnDiskNRepetitions + i, &bval);
895 (*typedValue)[i] = bval;
896 }
897 }
898}
899
900const ROOT::RFieldBase::RColumnRepresentations &ROOT::RField<std::vector<bool>>::GetColumnRepresentations() const
901{
902 static RColumnRepresentations representations({{ENTupleColumnType::kSplitIndex64},
906 {{}});
907 return representations;
908}
909
910void ROOT::RField<std::vector<bool>>::GenerateColumns()
911{
912 R__ASSERT(fOnDiskNRepetitions == 0); // fOnDiskNRepetitions must only be used for reading
913 GenerateColumnsImpl<ROOT::Internal::RColumnIndex>();
914}
915
916void ROOT::RField<std::vector<bool>>::GenerateColumns(const ROOT::RNTupleDescriptor &desc)
917{
918 if (fOnDiskNRepetitions == 0)
919 GenerateColumnsImpl<ROOT::Internal::RColumnIndex>(desc);
920}
921
922void ROOT::RField<std::vector<bool>>::ReconcileOnDiskField(const RNTupleDescriptor &desc)
923{
924 const auto &fieldDesc = desc.GetFieldDescriptor(GetOnDiskId());
925
926 if (fieldDesc.GetTypeName().rfind("std::array<", 0) == 0) {
927 EnsureMatchingOnDiskField(desc, kDiffTypeName | kDiffStructure | kDiffNRepetitions).ThrowOnError();
928
929 if (fieldDesc.GetNRepetitions() == 0) {
930 throw RException(R__FAIL("fixed-size array --> std::vector<bool>: expected repetition count > 0\n" +
931 Internal::GetTypeTraceReport(*this, desc)));
932 }
933 if (fieldDesc.GetStructure() != ENTupleStructure::kPlain) {
934 throw RException(R__FAIL("fixed-size array --> std::vector<bool>: expected plain on-disk field\n" +
935 Internal::GetTypeTraceReport(*this, desc)));
936 }
937 fOnDiskNRepetitions = fieldDesc.GetNRepetitions();
938 } else {
939 EnsureMatchingOnDiskCollection(desc).ThrowOnError();
940 }
941}
942
943std::vector<ROOT::RFieldBase::RValue> ROOT::RField<std::vector<bool>>::SplitValue(const RValue &value) const
944{
945 const auto &typedValue = value.GetRef<std::vector<bool>>();
946 auto count = typedValue.size();
947 std::vector<RValue> result;
948 result.reserve(count);
949 for (unsigned i = 0; i < count; ++i) {
950 if (typedValue[i]) {
951 result.emplace_back(fSubfields[0]->BindValue(std::shared_ptr<bool>(new bool(true))));
952 } else {
953 result.emplace_back(fSubfields[0]->BindValue(std::shared_ptr<bool>(new bool(false))));
954 }
955 }
956 return result;
957}
958
959void ROOT::RField<std::vector<bool>>::AcceptVisitor(ROOT::Detail::RFieldVisitor &visitor) const
960{
961 visitor.VisitVectorBoolField(*this);
962}
963
964//------------------------------------------------------------------------------
965
966ROOT::RArrayAsRVecField::RArrayAsRVecField(std::string_view fieldName, std::unique_ptr<ROOT::RFieldBase> itemField,
967 std::size_t arrayLength)
968 : ROOT::RFieldBase(fieldName, "ROOT::VecOps::RVec<" + itemField->GetTypeName() + ">",
969 ROOT::ENTupleStructure::kCollection, false /* isSimple */),
970 fItemSize(itemField->GetValueSize()),
971 fArrayLength(arrayLength)
972{
973 if (!itemField->GetTypeAlias().empty())
974 SetTypeAlias("ROOT::VecOps::RVec<" + itemField->GetTypeAlias() + ">");
975 Attach(std::move(itemField), "_0");
976 fValueSize =
980}
981
982std::unique_ptr<ROOT::RFieldBase> ROOT::RArrayAsRVecField::CloneImpl(std::string_view newName) const
983{
984 auto newItemField = fSubfields[0]->Clone(fSubfields[0]->GetFieldName());
985 return std::make_unique<RArrayAsRVecField>(newName, std::move(newItemField), fArrayLength);
986}
987
989{
990 // initialize data members fBegin, fSize, fCapacity
991 // currently the inline buffer is left uninitialized
992 void **beginPtr = new (where)(void *)(nullptr);
993 std::int32_t *sizePtr = new (static_cast<void *>(beginPtr + 1)) std::int32_t(0);
994 new (sizePtr + 1) std::int32_t(-1);
995}
996
997std::unique_ptr<ROOT::RFieldBase::RDeleter> ROOT::RArrayAsRVecField::GetDeleter() const
998{
999 if (fItemDeleter) {
1000 return std::make_unique<RRVecField::RRVecDeleter>(fSubfields[0]->GetAlignment(), fItemSize,
1001 GetDeleterOf(*fSubfields[0]));
1002 }
1003 return std::make_unique<RRVecField::RRVecDeleter>(fSubfields[0]->GetAlignment());
1004}
1005
1007{
1008 auto begin = RRVecField::ResizeRVec(to, fArrayLength, fItemSize, fSubfields[0].get(), fItemDeleter.get());
1009
1010 if (fSubfields[0]->IsSimple()) {
1011 GetPrincipalColumnOf(*fSubfields[0])->ForReading()->ReadV(globalIndex * fArrayLength, fArrayLength, begin);
1012 return;
1013 }
1014
1015 // Read the new values into the collection elements
1016 for (std::size_t i = 0; i < fArrayLength; ++i) {
1017 CallReadOn(*fSubfields[0], globalIndex * fArrayLength + i, begin + (i * fItemSize));
1018 }
1019}
1020
1022{
1023 auto begin = RRVecField::ResizeRVec(to, fArrayLength, fItemSize, fSubfields[0].get(), fItemDeleter.get());
1024
1025 if (fSubfields[0]->IsSimple()) {
1026 GetPrincipalColumnOf(*fSubfields[0])->ForReading()->ReadV(localIndex * fArrayLength, fArrayLength, begin);
1027 return;
1028 }
1029
1030 // Read the new values into the collection elements
1031 for (std::size_t i = 0; i < fArrayLength; ++i) {
1032 CallReadOn(*fSubfields[0], localIndex * fArrayLength + i, begin + (i * fItemSize));
1033 }
1034}
1035
1037{
1038 EnsureMatchingOnDiskField(desc, kDiffTypeName | kDiffStructure | kDiffNRepetitions).ThrowOnError();
1039 const auto &fieldDesc = desc.GetFieldDescriptor(GetOnDiskId());
1040 if (fieldDesc.GetTypeName().rfind("std::array<", 0) != 0) {
1041 throw RException(R__FAIL("RArrayAsRVecField " + GetQualifiedFieldName() + " expects an on-disk array field\n" +
1042 Internal::GetTypeTraceReport(*this, desc)));
1043 }
1044}
1045
1047{
1048 return Internal::EvalRVecAlignment(fSubfields[0]->GetAlignment());
1049}
1050
1051std::vector<ROOT::RFieldBase::RValue> ROOT::RArrayAsRVecField::SplitValue(const ROOT::RFieldBase::RValue &value) const
1052{
1053 auto arrayPtr = value.GetPtr<unsigned char>().get();
1054 std::vector<ROOT::RFieldBase::RValue> result;
1055 result.reserve(fArrayLength);
1056 for (unsigned i = 0; i < fArrayLength; ++i) {
1057 result.emplace_back(
1058 fSubfields[0]->BindValue(std::shared_ptr<void>(value.GetPtr<void>(), arrayPtr + (i * fItemSize))));
1059 }
1060 return result;
1061}
1062
1067
1068//------------------------------------------------------------------------------
1069
1070ROOT::RArrayAsVectorField::RArrayAsVectorField(std::string_view fieldName, std::unique_ptr<ROOT::RFieldBase> itemField,
1071 std::size_t arrayLength)
1072 : ROOT::RFieldBase(fieldName, "std::vector<" + itemField->GetTypeName() + ">", ROOT::ENTupleStructure::kCollection,
1073 false /* isSimple */),
1074 fItemSize(itemField->GetValueSize()),
1075 fArrayLength(arrayLength)
1076{
1077 if (!itemField->GetTypeAlias().empty())
1078 SetTypeAlias("std::vector<" + itemField->GetTypeAlias() + ">");
1079 Attach(std::move(itemField), "_0");
1082}
1083
1084std::unique_ptr<ROOT::RFieldBase> ROOT::RArrayAsVectorField::CloneImpl(std::string_view newName) const
1085{
1086 auto newItemField = fSubfields[0]->Clone(fSubfields[0]->GetFieldName());
1087 return std::make_unique<RArrayAsVectorField>(newName, std::move(newItemField), fArrayLength);
1088}
1089
1091{
1092 throw RException(R__FAIL("RArrayAsVectorField fields must only be used for reading"));
1093}
1094
1096{
1097 ConstructVector(where, fSubfields[0]->GetAlignment());
1098}
1099
1100std::unique_ptr<ROOT::RFieldBase::RDeleter> ROOT::RArrayAsVectorField::GetDeleter() const
1101{
1102 if (fItemDeleter) {
1103 return std::make_unique<RVectorField::RVectorDeleter>(fItemSize, fSubfields[0]->GetAlignment(),
1104 GetDeleterOf(*fSubfields[0]));
1105 }
1106 return std::make_unique<RVectorField::RVectorDeleter>(fSubfields[0]->GetAlignment());
1107}
1108
1110{
1111 auto typedValue = static_cast<std::vector<char> *>(to);
1112
1113 if (fSubfields[0]->IsSimple()) {
1114 typedValue->resize(fArrayLength * fItemSize);
1115 GetPrincipalColumnOf(*fSubfields[0])
1116 ->ForReading()
1117 ->ReadV(globalIndex * fArrayLength, fArrayLength, typedValue->data());
1118 return;
1119 }
1120
1121 RVectorField::ResizeVector(to, fArrayLength, fItemSize, *fSubfields[0], fItemDeleter.get());
1122
1123 for (std::size_t i = 0; i < fArrayLength; ++i) {
1124 CallReadOn(*fSubfields[0], globalIndex * fArrayLength + i, typedValue->data() + (i * fItemSize));
1125 }
1126}
1127
1129{
1130 auto typedValue = static_cast<std::vector<char> *>(to);
1131
1132 if (fSubfields[0]->IsSimple()) {
1133 typedValue->resize(fArrayLength * fItemSize);
1134 GetPrincipalColumnOf(*fSubfields[0])
1135 ->ForReading()
1136 ->ReadV(localIndex * fArrayLength, fArrayLength, typedValue->data());
1137 return;
1138 }
1139
1140 RVectorField::ResizeVector(to, fArrayLength, fItemSize, *fSubfields[0], fItemDeleter.get());
1141
1142 for (std::size_t i = 0; i < fArrayLength; ++i) {
1143 CallReadOn(*fSubfields[0], localIndex * fArrayLength + i, typedValue->data() + (i * fItemSize));
1144 }
1145}
1146
1148{
1149 EnsureMatchingOnDiskField(desc, kDiffTypeName | kDiffStructure | kDiffNRepetitions);
1150
1151 const auto &fieldDesc = desc.GetFieldDescriptor(GetOnDiskId());
1152 if (fieldDesc.GetTypeName().rfind("std::array<", 0) != 0) {
1153 throw RException(R__FAIL("RArrayAsVectorField " + GetQualifiedFieldName() + " expects an on-disk array field\n" +
1154 Internal::GetTypeTraceReport(*this, desc)));
1155 }
1156}
1157
1158std::vector<ROOT::RFieldBase::RValue> ROOT::RArrayAsVectorField::SplitValue(const ROOT::RFieldBase::RValue &value) const
1159{
1160 return SplitVector(value.GetPtr<void>(), *fSubfields[0]);
1161}
1162
1164{
1165 return GetSizeOfVector();
1166}
1167
1169{
1170 return GetAlignOfVector();
1171}
1172
size_t fValueSize
#define R__FAIL(msg)
Short-hand to return an RResult<T> in an error state; the RError is implicitly converted into RResult...
Definition RError.hxx:322
#define f(i)
Definition RSha256.hxx:104
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
#define R__ASSERT(e)
Checks condition e and reports a fatal error if it's false.
Definition TError.h:139
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
char name[80]
Definition TGX11.cxx:142
#define _(A, B)
Definition cfortran.h:112
Abstract base class for classes implementing the visitor design pattern.
virtual void VisitVectorField(const ROOT::RVectorField &field)
virtual void VisitVectorBoolField(const ROOT::RField< std::vector< bool > > &field)
virtual void VisitRVecField(const ROOT::RRVecField &field)
virtual void VisitArrayAsRVecField(const ROOT::RArrayAsRVecField &field)
virtual void VisitArrayAsVectorField(const ROOT::RArrayAsVectorField &field)
virtual void VisitArrayField(const ROOT::RArrayField &field)
The in-memory representation of a 32bit or 64bit on-disk index column.
A helper class for piece-wise construction of an RFieldDescriptor.
RResult< RFieldDescriptor > MoveDescriptor()
Attempt to make a field descriptor.
RFieldDescriptorBuilder & Structure(const ROOT::ENTupleStructure &structure)
RFieldDescriptorBuilder & TypeVersion(std::uint32_t typeVersion)
Abstract interface to read data from an ntuple.
RSharedDescriptorGuard GetSharedDescriptorGuard() const
Takes the read lock for the descriptor.
std::unique_ptr< RDeleter > fItemDeleter
void ReadInClusterImpl(RNTupleLocalIndex localIndex, void *to) final
RArrayAsRVecField(std::string_view fieldName, std::unique_ptr< RFieldBase > itemField, std::size_t arrayLength)
Constructor of the field.
std::size_t GetAlignment() const final
What alignof(T) for this type returns.
std::unique_ptr< RDeleter > GetDeleter() const final
Returns an RRVecField::RRVecDeleter.
void AcceptVisitor(ROOT::Detail::RFieldVisitor &visitor) const final
std::unique_ptr< RFieldBase > CloneImpl(std::string_view newName) const final
The size of a value of this field, i.e. an RVec.
std::vector< RFieldBase::RValue > SplitValue(const RFieldBase::RValue &value) const final
Creates the list of direct child values given an existing value for this field.
void ReconcileOnDiskField(const RNTupleDescriptor &desc) final
For non-artificial fields, check compatibility of the in-memory field and the on-disk field.
std::size_t GetValueSize() const final
What sizeof(T) for this type returns.
void ReadGlobalImpl(ROOT::NTupleSize_t globalIndex, void *to) final
std::size_t fValueSize
The length of the arrays in this field.
void ConstructValue(void *where) const final
Constructs value in a given location of size at least GetValueSize(). Called by the base class' Creat...
std::unique_ptr< RDeleter > GetDeleter() const final
Returns an RVectorField::RVectorDeleter.
void ReadGlobalImpl(ROOT::NTupleSize_t globalIndex, void *to) final
std::unique_ptr< RDeleter > fItemDeleter
void ReconcileOnDiskField(const RNTupleDescriptor &desc) final
For non-artificial fields, check compatibility of the in-memory field and the on-disk field.
void AcceptVisitor(ROOT::Detail::RFieldVisitor &visitor) const final
RArrayAsVectorField(std::string_view fieldName, std::unique_ptr< RFieldBase > itemField, std::size_t arrayLength)
The itemField argument represents the inner item of the on-disk array, i.e.
void GenerateColumns() final
Implementations in derived classes should create the backing columns corresponding to the field type ...
void ReadInClusterImpl(RNTupleLocalIndex localIndex, void *to) final
void ConstructValue(void *where) const final
Constructs value in a given location of size at least GetValueSize(). Called by the base class' Creat...
std::vector< RFieldBase::RValue > SplitValue(const RFieldBase::RValue &value) const final
Creates the list of direct child values given an existing value for this field.
std::unique_ptr< RFieldBase > CloneImpl(std::string_view newName) const final
The length of the arrays in this field.
std::size_t GetAlignment() const final
What alignof(T) for this type returns.
std::size_t GetValueSize() const final
What sizeof(T) for this type returns.
void operator()(void *objPtr, bool dtorOnly) final
Template specializations for C++ std::array and C-style arrays.
std::unique_ptr< RDeleter > GetDeleter() const final
RArrayField(std::string_view fieldName, std::unique_ptr< RFieldBase > itemField, std::size_t arrayLength)
void ReadGlobalImpl(ROOT::NTupleSize_t globalIndex, void *to) final
void AcceptVisitor(ROOT::Detail::RFieldVisitor &visitor) const final
std::size_t AppendImpl(const void *from) final
Operations on values of complex types, e.g.
std::size_t ReadBulkImpl(const RBulkSpec &bulkSpec) final
General implementation of bulk read.
void ReadInClusterImpl(RNTupleLocalIndex localIndex, void *to) final
std::unique_ptr< RFieldBase > CloneImpl(std::string_view newName) const final
Called by Clone(), which additionally copies the on-disk ID.
void ConstructValue(void *where) const final
Constructs value in a given location of size at least GetValueSize(). Called by the base class' Creat...
void ReconcileOnDiskField(const RNTupleDescriptor &desc) final
For non-artificial fields, check compatibility of the in-memory field and the on-disk field.
std::vector< RValue > SplitValue(const RValue &value) const final
Creates the list of direct child values given an existing value for this field.
Base class for all ROOT issued exceptions.
Definition RError.hxx:78
The list of column representations a field can have.
A functor to release the memory acquired by CreateValue() (memory and constructor).
Points to an object with RNTuple I/O support and keeps a pointer to the corresponding field.
A field translates read and write calls from/to underlying columns to/from tree values.
virtual size_t GetValueSize() const =0
What sizeof(T) for this type returns.
void Attach(std::unique_ptr< RFieldBase > child, std::string_view expectedChildName="")
Add a new subfield to the list of nested fields.
virtual size_t GetAlignment() const =0
What alignof(T) for this type returns.
std::vector< std::unique_ptr< RFieldBase > > fSubfields
Collections and classes own subfields.
void SetTypeAlias(std::string_view typeAlias)
Can only be set on unconnected fields.
static std::unique_ptr< RDeleter > GetDeleterOf(const RFieldBase &other)
std::string GetQualifiedFieldName() const
Returns the field name and parent field names separated by dots (grandparent.parent....
@ kTraitEmulatedField
This field is a user defined type that was missing dictionaries and was reconstructed from the on-dis...
@ kTraitTriviallyDestructible
The type is cleaned up just by freeing its memory. I.e. the destructor performs a no-op.
@ kTraitSoACollection
The field represents a collection in SoA layout.
std::uint32_t fTraits
Properties of the type that allow for optimizations of collections of that type.
bool IsSimple() const
std::uint32_t GetTraits() const
RValue BindValue(std::shared_ptr< void > objPtr)
Creates a value from a memory location with an already constructed object.
virtual std::size_t ReadBulkImpl(const RBulkSpec &bulkSpec)
General implementation of bulk read.
Metadata stored for every field of an RNTuple.
std::optional< std::uint32_t > GetTypeChecksum() const
std::uint32_t GetTypeVersion() const
const std::string & GetTypeName() const
Classes with dictionaries that can be inspected by TClass.
Definition RField.hxx:352
The on-storage metadata of an RNTuple.
const RFieldDescriptor & GetFieldDescriptor(ROOT::DescriptorId_t fieldId) const
Addresses a column element or field item relative to a particular cluster, instead of a global NTuple...
ROOT::NTupleSize_t GetIndexInCluster() const
void operator()(void *objPtr, bool dtorOnly) final
void AcceptVisitor(ROOT::Detail::RFieldVisitor &visitor) const final
std::vector< RValue > SplitValue(const RValue &value) const final
Creates the list of direct child values given an existing value for this field.
void GenerateColumns() final
Implementations in derived classes should create the backing columns corresponding to the field type ...
size_t GetAlignment() const final
What alignof(T) for this type returns.
std::size_t ReadBulkImpl(const RBulkSpec &bulkSpec) final
General implementation of bulk read.
RRVecField(std::string_view fieldName, std::unique_ptr< RFieldBase > itemField)
void ReconcileOnDiskField(const RNTupleDescriptor &desc) final
For non-artificial fields, check compatibility of the in-memory field and the on-disk field.
std::unique_ptr< RFieldBase > BeforeConnectPageSource(ROOT::Internal::RPageSource &pageSource) final
Called by ConnectPageSource() before connecting; derived classes may override this as appropriate,...
size_t GetValueSize() const final
What sizeof(T) for this type returns.
std::size_t AppendImpl(const void *from) final
Operations on values of complex types, e.g.
static unsigned char * ResizeRVec(void *rvec, std::size_t nItems, std::size_t itemSize, const RFieldBase *itemField, RDeleter *itemDeleter)
std::unique_ptr< RDeleter > fItemDeleter
const RColumnRepresentations & GetColumnRepresentations() const final
Implementations in derived classes should return a static RColumnRepresentations object.
RFieldBase * fBulkSubfield
May be a direct PoD subfield or a sub-subfield of a fixed-size array of PoD.
std::unique_ptr< RFieldBase > CloneImpl(std::string_view newName) const final
Called by Clone(), which additionally copies the on-disk ID.
void ReadGlobalImpl(ROOT::NTupleSize_t globalIndex, void *to) final
void ConstructValue(void *where) const final
Constructs value in a given location of size at least GetValueSize(). Called by the base class' Creat...
std::unique_ptr< RDeleter > GetDeleter() const final
void operator()(void *objPtr, bool dtorOnly) final
Template specializations for C++ std::vector.
static std::unique_ptr< RVectorField > CreateUntyped(std::string_view fieldName, std::unique_ptr< RFieldBase > itemField)
void GenerateColumns() final
Implementations in derived classes should create the backing columns corresponding to the field type ...
std::size_t GetValueSize() const final
What sizeof(T) for this type returns.
std::unique_ptr< RFieldBase > BeforeConnectPageSource(ROOT::Internal::RPageSource &pageSource) final
Called by ConnectPageSource() before connecting; derived classes may override this as appropriate,...
void AcceptVisitor(ROOT::Detail::RFieldVisitor &visitor) const final
void ReconcileOnDiskField(const RNTupleDescriptor &desc) final
For non-artificial fields, check compatibility of the in-memory field and the on-disk field.
std::unique_ptr< RFieldBase > CloneImpl(std::string_view newName) const final
Called by Clone(), which additionally copies the on-disk ID.
static void ResizeVector(void *vec, std::size_t nItems, std::size_t itemSize, const RFieldBase &itemField, RDeleter *itemDeleter)
const RColumnRepresentations & GetColumnRepresentations() const final
Implementations in derived classes should return a static RColumnRepresentations object.
std::size_t AppendImpl(const void *from) final
Operations on values of complex types, e.g.
RVectorField(std::string_view fieldName, std::unique_ptr< RFieldBase > itemField, const ROOT::RFieldDescriptor *emulatedFrom)
Creates a possibly-untyped VectorField.
std::size_t GetAlignment() const final
What alignof(T) for this type returns.
void ConstructValue(void *where) const final
Constructs value in a given location of size at least GetValueSize(). Called by the base class' Creat...
std::vector< RValue > SplitValue(const RValue &value) const final
Creates the list of direct child values given an existing value for this field.
std::unique_ptr< RDeleter > fItemDeleter
static constexpr std::size_t kMaxItemAlignment
Maximum alignment of the vector's value type.
std::unique_ptr< RDeleter > GetDeleter() const final
void ReadGlobalImpl(ROOT::NTupleSize_t globalIndex, void *to) final
std::tuple< unsigned char **, std::int32_t *, std::int32_t * > GetRVecDataMembers(void *rvecPtr)
Retrieve the addresses of the data members of a generic RVec from a pointer to the beginning of the R...
void DestroyRVecWithChecks(std::size_t alignOfT, unsigned char **beginPtr, std::int32_t *capacityPtr)
std::string GetNormalizedInteger(const std::string &intTemplateArg)
Appends 'll' or 'ull' to the where necessary and strips the suffix if not needed.
std::string GetTypeTraceReport(const RFieldBase &field, const RNTupleDescriptor &desc)
Prints the hierarchy of types with their field names and field IDs for the given in-memory field and ...
void EnsureTypedChildField(const RFieldBase &child, const RFieldBase &parent)
Makes sure that the type name is not empty. Used to prevent untyped fields as C++ inner types.
std::size_t EvalRVecAlignment(std::size_t alignOfSubfield)
std::size_t EvalRVecValueSize(std::size_t alignOfT, std::size_t sizeOfT, std::size_t alignOfRVecT)
std::uint64_t NTupleSize_t
Integer type long enough to hold the maximum number of entries in a column.
constexpr DescriptorId_t kInvalidDescriptorId
ENTupleStructure
The fields in the RNTuple data model tree can carry different structural information about the type s...
Storage type whose alignment matches AlignT bytes.
Definition BitUtils.hxx:53
Input parameter to RFieldBase::ReadBulk() and RFieldBase::ReadBulkImpl().
RNTupleLocalIndex fFirstIndex
Start of the bulk range.
void * fValues
The destination area, which has to be an array of valid objects of the correct type large enough to h...
std::size_t fCount
Size of the bulk range.
std::vector< unsigned char > * fAuxData
Reference to memory owned by the RBulkValues class.