Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RFieldBase.cxx
Go to the documentation of this file.
1/// \file RFieldBase.cxx
2/// \author Jonas Hahnfeld <jonas.hahnfeld@cern.ch>
3/// \date 2024-11-19
4
5#include <ROOT/BitUtils.hxx>
6#include <ROOT/RError.hxx>
7#include <ROOT/RField.hxx>
8#include <ROOT/RFieldBase.hxx>
10#include <ROOT/RFieldUtils.hxx>
11#include <ROOT/RNTupleUtils.hxx>
12
13#include <TClass.h>
14#include <TClassEdit.h>
15#include <TEnum.h>
16
17#include <sstream>
18#include <string>
19#include <vector>
20
21namespace {
22
23/// Used as a thread local context storage for Create(); steers the behavior of the Create() call stack
24class CreateContextGuard;
25class CreateContext {
26 friend class CreateContextGuard;
27 /// All classes that were defined by Create() calls higher up in the stack. Finds cyclic type definitions.
28 std::vector<std::string> fClassesOnStack;
29 /// If set to true, Create() will create an RInvalidField on error instead of throwing an exception.
30 /// This is used in RFieldBase::Check() to identify unsupported sub fields.
31 bool fContinueOnError = false;
32
33public:
34 CreateContext() = default;
35 bool GetContinueOnError() const { return fContinueOnError; }
36};
37
38/// RAII for modifications of CreateContext
39class CreateContextGuard {
40 CreateContext &fCreateContext;
41 std::size_t fNOriginalClassesOnStack;
42 bool fOriginalContinueOnError;
43
44public:
45 CreateContextGuard(CreateContext &ctx)
46 : fCreateContext(ctx),
47 fNOriginalClassesOnStack(ctx.fClassesOnStack.size()),
48 fOriginalContinueOnError(ctx.fContinueOnError)
49 {
50 }
51 ~CreateContextGuard()
52 {
53 fCreateContext.fClassesOnStack.resize(fNOriginalClassesOnStack);
54 fCreateContext.fContinueOnError = fOriginalContinueOnError;
55 }
56
57 void AddClassToStack(const std::string &cl)
58 {
59 if (std::find(fCreateContext.fClassesOnStack.begin(), fCreateContext.fClassesOnStack.end(), cl) !=
60 fCreateContext.fClassesOnStack.end()) {
61 throw ROOT::RException(R__FAIL("cyclic class definition: " + cl));
62 }
63 fCreateContext.fClassesOnStack.emplace_back(cl);
64 }
65
66 void SetContinueOnError(bool value) { fCreateContext.fContinueOnError = value; }
67};
68
69} // anonymous namespace
70
80 ROOT::NTupleSize_t firstEntry)
81{
82 field.ConnectPageSink(sink, firstEntry);
83}
92std::shared_ptr<ROOT::Internal::RStringPool>
93ROOT::Internal::CallSetSharedStringPoolOnField(const std::shared_ptr<Internal::RStringPool> &pool)
94{
95 return RFieldBase::SetSharedStringPool(pool);
96}
97std::shared_ptr<ROOT::Internal::RStringPool> ROOT::Internal::GetStringPoolOfField(const ROOT::RFieldBase &field)
98{
99 return field.fStringPool;
100}
101
103ROOT::Internal::CallFieldBaseCreate(const std::string &fieldName, const std::string &typeName,
104 const ROOT::RCreateFieldOptions &options, const ROOT::RNTupleDescriptor *desc,
105 ROOT::DescriptorId_t fieldId)
106{
107 return RFieldBase::Create(fieldName, typeName, options, desc, fieldId);
108}
109
110//------------------------------------------------------------------------------
111
113{
114 operator delete(objPtr, std::align_val_t(fAlignment));
115}
116
117//------------------------------------------------------------------------------
118
120{
121 // A single representations with an empty set of columns
122 fSerializationTypes.emplace_back(ColumnRepresentation_t());
123 fDeserializationTypes.emplace_back(ColumnRepresentation_t());
124}
125
127 const Selection_t &deserializationExtraTypes)
128 : fSerializationTypes(serializationTypes), fDeserializationTypes(serializationTypes)
129{
130 fDeserializationTypes.insert(fDeserializationTypes.end(), deserializationExtraTypes.begin(),
131 deserializationExtraTypes.end());
132}
133
134//------------------------------------------------------------------------------
135
137{
138 // Set fObjPtr to an aliased shared_ptr of the input raw pointer. Note that
139 // fObjPtr will be non-empty but have use count zero.
140 fObjPtr = ROOT::Internal::MakeAliasedSharedPtr(rawPtr);
141}
142
143//------------------------------------------------------------------------------
144
146 : fField(other.fField),
147 fValueSize(other.fValueSize),
148 fCapacity(other.fCapacity),
149 fSize(other.fSize),
150 fIsAdopted(other.fIsAdopted),
151 fNValidValues(other.fNValidValues),
152 fFirstIndex(other.fFirstIndex)
153{
154 std::swap(fDeleter, other.fDeleter);
155 std::swap(fValues, other.fValues);
156 std::swap(fMaskAvail, other.fMaskAvail);
157}
158
160{
161 std::swap(fField, other.fField);
162 std::swap(fDeleter, other.fDeleter);
163 std::swap(fValues, other.fValues);
164 std::swap(fValueSize, other.fValueSize);
165 std::swap(fCapacity, other.fCapacity);
166 std::swap(fSize, other.fSize);
167 std::swap(fIsAdopted, other.fIsAdopted);
168 std::swap(fMaskAvail, other.fMaskAvail);
169 std::swap(fNValidValues, other.fNValidValues);
170 std::swap(fFirstIndex, other.fFirstIndex);
171 return *this;
172}
173
175{
176 if (fValues)
177 ReleaseValues();
178}
179
181{
182 if (fIsAdopted)
183 return;
184
185 if (!(fField->GetTraits() & RFieldBase::kTraitTriviallyDestructible)) {
186 for (std::size_t i = 0; i < fCapacity; ++i) {
187 fDeleter->operator()(GetValuePtrAt(i), true /* dtorOnly */);
188 }
189 }
190
191 operator delete(fValues, std::align_val_t(fField->GetAlignment()));
192}
193
195{
196 if (fCapacity < size) {
197 if (fIsAdopted) {
198 throw RException(R__FAIL("invalid attempt to bulk read beyond the adopted buffer"));
199 }
200 ReleaseValues();
201 fValues = operator new(size * fValueSize, std::align_val_t(fField->GetAlignment()));
202
203 if (!(fField->GetTraits() & RFieldBase::kTraitTriviallyConstructible)) {
204 for (std::size_t i = 0; i < size; ++i) {
205 fField->ConstructValue(GetValuePtrAt(i));
206 }
207 }
208
209 fMaskAvail = std::make_unique<bool[]>(size);
210 fCapacity = size;
211 }
212
213 std::fill(fMaskAvail.get(), fMaskAvail.get() + size, false);
214 fNValidValues = 0;
215
216 fFirstIndex = firstIndex;
217 fSize = size;
218}
219
221{
222 ReleaseValues();
223 fValues = buf;
224 fCapacity = capacity;
225 fSize = capacity;
226
227 fMaskAvail = std::make_unique<bool[]>(capacity);
228
229 fFirstIndex = RNTupleLocalIndex();
230
231 fIsAdopted = true;
232}
233
234//------------------------------------------------------------------------------
235
237{
238 R__LOG_WARNING(ROOT::Internal::NTupleLog()) << "possibly leaking object from RField<T>::CreateObject<void>";
239}
240
241template <>
242std::unique_ptr<void, typename ROOT::RFieldBase::RCreateObjectDeleter<void>::deleter>
243ROOT::RFieldBase::CreateObject<void>() const
244{
246 return std::unique_ptr<void, RCreateObjectDeleter<void>::deleter>(CreateObjectRawPtr(), gDeleter);
247}
248
249//------------------------------------------------------------------------------
250
251thread_local std::shared_ptr<ROOT::Internal::RStringPool> ROOT::RFieldBase::fgSharedStringPool;
252
253ROOT::RFieldBase::RFieldBase(std::string_view name, std::string_view type, ROOT::ENTupleStructure structure,
254 bool isSimple, std::size_t nRepetitions)
255 : fStructure(structure),
256 fNRepetitions(nRepetitions),
257 fIsSimple(isSimple),
258 fParent(nullptr),
259 fPrincipalColumn(nullptr),
260 fTraits(isSimple ? kTraitMappable : 0)
261{
263 fStringPool = fgSharedStringPool ? fgSharedStringPool : std::make_shared<Internal::RStringPool>();
264 fFieldName = fStringPool->Intern(name);
265 fTypeName = fStringPool->Intern(type);
266 fTypeAlias = fStringPool->Intern("");
267 fDescription = fStringPool->Intern("");
268}
269
271{
272 std::string result = GetFieldName();
273 auto parent = GetParent();
274 while (parent && !parent->GetFieldName().empty()) {
275 result = parent->GetFieldName() + "." + result;
276 parent = parent->GetParent();
277 }
278 return result;
279}
280
282ROOT::RFieldBase::Create(const std::string &fieldName, const std::string &typeName)
283{
284 return R__FORWARD_RESULT(
286}
287
288std::vector<ROOT::RFieldBase::RCheckResult>
289ROOT::RFieldBase::Check(const std::string &fieldName, const std::string &typeName)
290{
291 RFieldZero fieldZero;
293 cfOpts.SetReturnInvalidOnError(true);
294 cfOpts.SetEmulateUnknownTypes(false);
295 fieldZero.Attach(RFieldBase::Create(fieldName, typeName, cfOpts, nullptr, kInvalidDescriptorId).Unwrap());
296
297 std::vector<RCheckResult> result;
298 for (const auto &f : fieldZero) {
299 const bool isInvalidField = f.GetTraits() & RFieldBase::kTraitInvalidField;
300 if (!isInvalidField)
301 continue;
302
303 const auto &invalidField = static_cast<const RInvalidField &>(f);
304 result.emplace_back(
305 RCheckResult{invalidField.GetQualifiedFieldName(), invalidField.GetTypeName(), invalidField.GetError()});
306 }
307 return result;
308}
309
311ROOT::RFieldBase::Create(const std::string &fieldName, const std::string &typeName,
312 const ROOT::RCreateFieldOptions &options, const ROOT::RNTupleDescriptor *desc,
313 ROOT::DescriptorId_t fieldId)
314{
317
318 const auto resolvedType = ROOT::Internal::GetCanonicalTypePrefix(TClassEdit::ResolveTypedef(typeName.c_str()));
319
320 thread_local CreateContext createContext;
321 CreateContextGuard createContextGuard(createContext);
322 if (options.GetReturnInvalidOnError())
323 createContextGuard.SetContinueOnError(true);
324
325 auto fnFail = [&fieldName,
326 &resolvedType](const std::string &errMsg,
328 RInvalidField::ECategory::kTypeError) -> RResult<std::unique_ptr<RFieldBase>> {
329 if (createContext.GetContinueOnError()) {
330 return std::unique_ptr<RFieldBase>(std::make_unique<RInvalidField>(fieldName, resolvedType, errMsg, cat));
331 } else {
332 return R__FAIL(errMsg);
333 }
334 };
335
336 if (resolvedType.empty())
337 return R__FORWARD_RESULT(fnFail("no type name specified for field '" + fieldName + "'"));
338
339 // Ensure that parent and child fields use the same string pool to start with. Note that if a shared string pool
340 // is already present (e.g., in a recursive call), the existing one will be used over the new one.
342
343 std::unique_ptr<ROOT::RFieldBase> result;
344
345 const auto maybeGetChildId = [desc, fieldId](int childId) {
346 if (desc) {
347 const auto &fieldDesc = desc->GetFieldDescriptor(fieldId);
348 return fieldDesc.GetLinkIds().at(childId);
349 } else {
351 }
352 };
353
354 // try-catch block to intercept any exception that may be thrown by Unwrap() so that this
355 // function never throws but returns RResult::Error instead.
356 try {
357 if (resolvedType == "bool") {
358 result = std::make_unique<RField<bool>>(fieldName);
359 } else if (resolvedType == "char") {
360 result = std::make_unique<RField<char>>(fieldName);
361 } else if (resolvedType == "std::byte") {
362 result = std::make_unique<RField<std::byte>>(fieldName);
363 } else if (resolvedType == "std::int8_t") {
364 result = std::make_unique<RField<std::int8_t>>(fieldName);
365 } else if (resolvedType == "std::uint8_t") {
366 result = std::make_unique<RField<std::uint8_t>>(fieldName);
367 } else if (resolvedType == "std::int16_t") {
368 result = std::make_unique<RField<std::int16_t>>(fieldName);
369 } else if (resolvedType == "std::uint16_t") {
370 result = std::make_unique<RField<std::uint16_t>>(fieldName);
371 } else if (resolvedType == "std::int32_t") {
372 result = std::make_unique<RField<std::int32_t>>(fieldName);
373 } else if (resolvedType == "std::uint32_t") {
374 result = std::make_unique<RField<std::uint32_t>>(fieldName);
375 } else if (resolvedType == "std::int64_t") {
376 result = std::make_unique<RField<std::int64_t>>(fieldName);
377 } else if (resolvedType == "std::uint64_t") {
378 result = std::make_unique<RField<std::uint64_t>>(fieldName);
379 } else if (resolvedType == "float") {
380 result = std::make_unique<RField<float>>(fieldName);
381 } else if (resolvedType == "double") {
382 result = std::make_unique<RField<double>>(fieldName);
383 } else if (resolvedType == "Double32_t") {
384 result = std::make_unique<RField<double>>(fieldName);
385 static_cast<RField<double> *>(result.get())->SetDouble32();
386 // Prevent the type alias from being reset by returning early
387 return result;
388 } else if (resolvedType == "std::string") {
389 result = std::make_unique<RField<std::string>>(fieldName);
390 } else if (resolvedType == "TObject") {
391 result = std::make_unique<RField<TObject>>(fieldName);
392 } else if (resolvedType == "std::vector<bool>") {
393 result = std::make_unique<RField<std::vector<bool>>>(fieldName);
394 } else if (resolvedType.substr(0, 12) == "std::vector<") {
395 std::string itemTypeName = resolvedType.substr(12, resolvedType.length() - 13);
396 auto itemField = Create("_0", itemTypeName, options, desc, maybeGetChildId(0));
397 result = std::make_unique<RVectorField>(fieldName, itemField.Unwrap());
398 } else if (resolvedType.substr(0, 19) == "ROOT::VecOps::RVec<") {
399 std::string itemTypeName = resolvedType.substr(19, resolvedType.length() - 20);
400 auto itemField = Create("_0", itemTypeName, options, desc, maybeGetChildId(0));
401 result = std::make_unique<RRVecField>(fieldName, itemField.Unwrap());
402 } else if (resolvedType.substr(0, 11) == "std::array<") {
403 auto arrayDef = TokenizeTypeList(resolvedType.substr(11, resolvedType.length() - 12));
404 if (arrayDef.size() != 2) {
405 return R__FORWARD_RESULT(fnFail("the template list for std::array must have exactly two elements"));
406 }
407 auto arrayLength = ParseUIntTypeToken(arrayDef[1]);
408 auto itemField = Create("_0", arrayDef[0], options, desc, maybeGetChildId(0));
409 result = std::make_unique<RArrayField>(fieldName, itemField.Unwrap(), arrayLength);
410 } else if (resolvedType.substr(0, 13) == "std::variant<") {
411 auto innerTypes = TokenizeTypeList(resolvedType.substr(13, resolvedType.length() - 14));
412 std::vector<std::unique_ptr<RFieldBase>> items;
413 items.reserve(innerTypes.size());
414 for (unsigned int i = 0; i < innerTypes.size(); ++i) {
415 items.emplace_back(
416 Create("_" + std::to_string(i), innerTypes[i], options, desc, maybeGetChildId(i)).Unwrap());
417 }
418 result = std::make_unique<RVariantField>(fieldName, std::move(items));
419 } else if (resolvedType.substr(0, 10) == "std::pair<") {
420 auto innerTypes = TokenizeTypeList(resolvedType.substr(10, resolvedType.length() - 11));
421 if (innerTypes.size() != 2) {
422 return R__FORWARD_RESULT(fnFail("the type list for std::pair must have exactly two elements"));
423 }
424 std::array<std::unique_ptr<RFieldBase>, 2> items{
425 Create("_0", innerTypes[0], options, desc, maybeGetChildId(0)).Unwrap(),
426 Create("_1", innerTypes[1], options, desc, maybeGetChildId(1)).Unwrap()};
427 result = std::make_unique<RPairField>(fieldName, std::move(items));
428 } else if (resolvedType.substr(0, 11) == "std::tuple<") {
429 auto innerTypes = TokenizeTypeList(resolvedType.substr(11, resolvedType.length() - 12));
430 std::vector<std::unique_ptr<RFieldBase>> items;
431 items.reserve(innerTypes.size());
432 for (unsigned int i = 0; i < innerTypes.size(); ++i) {
433 items.emplace_back(
434 Create("_" + std::to_string(i), innerTypes[i], options, desc, maybeGetChildId(i)).Unwrap());
435 }
436 result = std::make_unique<RTupleField>(fieldName, std::move(items));
437 } else if (resolvedType.substr(0, 12) == "std::bitset<") {
438 auto size = ParseUIntTypeToken(resolvedType.substr(12, resolvedType.length() - 13));
439 result = std::make_unique<RBitsetField>(fieldName, size);
440 } else if (resolvedType.substr(0, 16) == "std::unique_ptr<") {
441 std::string itemTypeName = resolvedType.substr(16, resolvedType.length() - 17);
442 auto itemField = Create("_0", itemTypeName, options, desc, maybeGetChildId(0)).Unwrap();
443 result = std::make_unique<RUniquePtrField>(fieldName, std::move(itemField));
444 } else if (resolvedType.substr(0, 14) == "std::optional<") {
445 std::string itemTypeName = resolvedType.substr(14, resolvedType.length() - 15);
446 auto itemField = Create("_0", itemTypeName, options, desc, maybeGetChildId(0)).Unwrap();
447 result = std::make_unique<ROptionalField>(fieldName, std::move(itemField));
448 } else if (resolvedType.substr(0, 9) == "std::set<") {
449 std::string itemTypeName = resolvedType.substr(9, resolvedType.length() - 10);
450 auto itemField = Create("_0", itemTypeName, options, desc, maybeGetChildId(0)).Unwrap();
451 result = std::make_unique<RSetField>(fieldName, RSetField::ESetType::kSet, std::move(itemField));
452 } else if (resolvedType.substr(0, 19) == "std::unordered_set<") {
453 std::string itemTypeName = resolvedType.substr(19, resolvedType.length() - 20);
454 auto itemField = Create("_0", itemTypeName, options, desc, maybeGetChildId(0)).Unwrap();
455 result = std::make_unique<RSetField>(fieldName, RSetField::ESetType::kUnorderedSet, std::move(itemField));
456 } else if (resolvedType.substr(0, 14) == "std::multiset<") {
457 std::string itemTypeName = resolvedType.substr(14, resolvedType.length() - 15);
458 auto itemField = Create("_0", itemTypeName, options, desc, maybeGetChildId(0)).Unwrap();
459 result = std::make_unique<RSetField>(fieldName, RSetField::ESetType::kMultiSet, std::move(itemField));
460 } else if (resolvedType.substr(0, 24) == "std::unordered_multiset<") {
461 std::string itemTypeName = resolvedType.substr(24, resolvedType.length() - 25);
462 auto itemField = Create("_0", itemTypeName, options, desc, maybeGetChildId(0)).Unwrap();
463 result = std::make_unique<RSetField>(fieldName, RSetField::ESetType::kUnorderedMultiSet, std::move(itemField));
464 } else if (resolvedType.substr(0, 9) == "std::map<") {
465 auto innerTypes = TokenizeTypeList(resolvedType.substr(9, resolvedType.length() - 10));
466 if (innerTypes.size() != 2) {
467 return R__FORWARD_RESULT(fnFail("the type list for std::map must have exactly two elements"));
468 }
469 auto itemField =
470 Create("_0", "std::pair<" + innerTypes[0] + "," + innerTypes[1] + ">", options, desc, maybeGetChildId(0))
471 .Unwrap();
472 result = std::make_unique<RMapField>(fieldName, RMapField::EMapType::kMap, std::move(itemField));
473 } else if (resolvedType.substr(0, 19) == "std::unordered_map<") {
474 auto innerTypes = TokenizeTypeList(resolvedType.substr(19, resolvedType.length() - 20));
475 if (innerTypes.size() != 2)
476 return R__FORWARD_RESULT(fnFail("the type list for std::unordered_map must have exactly two elements"));
477 auto itemField =
478 Create("_0", "std::pair<" + innerTypes[0] + "," + innerTypes[1] + ">", options, desc, maybeGetChildId(0))
479 .Unwrap();
480 result = std::make_unique<RMapField>(fieldName, RMapField::EMapType::kUnorderedMap, std::move(itemField));
481 } else if (resolvedType.substr(0, 14) == "std::multimap<") {
482 auto innerTypes = TokenizeTypeList(resolvedType.substr(14, resolvedType.length() - 15));
483 if (innerTypes.size() != 2)
484 return R__FORWARD_RESULT(fnFail("the type list for std::multimap must have exactly two elements"));
485 auto itemField =
486 Create("_0", "std::pair<" + innerTypes[0] + "," + innerTypes[1] + ">", options, desc, maybeGetChildId(0))
487 .Unwrap();
488 result = std::make_unique<RMapField>(fieldName, RMapField::EMapType::kMultiMap, std::move(itemField));
489 } else if (resolvedType.substr(0, 24) == "std::unordered_multimap<") {
490 auto innerTypes = TokenizeTypeList(resolvedType.substr(24, resolvedType.length() - 25));
491 if (innerTypes.size() != 2)
492 return R__FORWARD_RESULT(
493 fnFail("the type list for std::unordered_multimap must have exactly two elements"));
494 auto itemField =
495 Create("_0", "std::pair<" + innerTypes[0] + "," + innerTypes[1] + ">", options, desc, maybeGetChildId(0))
496 .Unwrap();
497 result = std::make_unique<RMapField>(fieldName, RMapField::EMapType::kUnorderedMultiMap, std::move(itemField));
498 } else if (resolvedType.substr(0, 12) == "std::atomic<") {
499 std::string itemTypeName = resolvedType.substr(12, resolvedType.length() - 13);
500 auto itemField = Create("_0", itemTypeName, options, desc, maybeGetChildId(0)).Unwrap();
501 result = std::make_unique<RAtomicField>(fieldName, std::move(itemField));
502 } else if (resolvedType.substr(0, 25) == "ROOT::RNTupleCardinality<") {
503 auto innerTypes = TokenizeTypeList(resolvedType.substr(25, resolvedType.length() - 26));
504 if (innerTypes.size() != 1)
505 return R__FORWARD_RESULT(fnFail("invalid cardinality template: " + resolvedType));
506 const auto canonicalInnerType = ROOT::Internal::GetCanonicalTypePrefix(innerTypes[0]);
507 if (canonicalInnerType == "std::uint32_t") {
508 result = std::make_unique<RField<RNTupleCardinality<std::uint32_t>>>(fieldName);
509 } else if (canonicalInnerType == "std::uint64_t") {
510 result = std::make_unique<RField<RNTupleCardinality<std::uint64_t>>>(fieldName);
511 } else {
512 return R__FORWARD_RESULT(fnFail("invalid cardinality template: " + resolvedType));
513 }
514 }
515
516 if (!result) {
517 auto cl = TClass::GetClass(typeName.c_str());
518
519 if (cl && cl->GetState() > TClass::kForwardDeclared) {
520 createContextGuard.AddClassToStack(resolvedType);
521 if (cl->GetCollectionProxy()) {
522 result = std::make_unique<RProxiedCollectionField>(fieldName, typeName);
523 }
524 // NOTE: if the class is not at least "Interpreted" we currently don't try to construct
525 // the RClassField, as in that case we'd need to fetch the information from the StreamerInfo
526 // rather than from TClass. This might be desirable in the future, but for now in this
527 // situation we rely on field emulation instead.
528 else if (cl->GetState() >= TClass::kInterpreted) {
529 if (!ROOT::Internal::GetRNTupleSoARecord(cl).empty()) {
530 result = std::make_unique<RSoAField>(fieldName, typeName);
533 result = std::make_unique<RStreamerField>(fieldName, typeName);
534 } else {
535 result = std::make_unique<RClassField>(fieldName, typeName);
536 }
537 }
538 }
539 }
540
541 if (!result) {
542 auto e = TEnum::GetEnum(resolvedType.c_str());
543 if (e != nullptr) {
544 result = std::make_unique<REnumField>(fieldName, typeName);
545 }
546 }
547
548 // If we get here then we failed to meet all the conditions to create a "properly typed" field.
549 // Resort to field emulation if the user asked us to.
550 if (!result && options.GetEmulateUnknownTypes()) {
551 assert(desc);
552 const auto &fieldDesc = desc->GetFieldDescriptor(fieldId);
553 if (fieldDesc.GetStructure() == ENTupleStructure::kStreamer) {
554 auto streamerField = std::unique_ptr<RFieldBase>(new RStreamerField(fieldName, typeName));
555 streamerField->SetTypeAlias(fieldDesc.GetTypeAlias());
556 return streamerField;
557 } else if (fieldDesc.GetStructure() == ENTupleStructure::kRecord) {
558 std::vector<std::unique_ptr<RFieldBase>> memberFields;
559 memberFields.reserve(fieldDesc.GetLinkIds().size());
560 for (auto id : fieldDesc.GetLinkIds()) {
561 const auto &memberDesc = desc->GetFieldDescriptor(id);
562 auto field = Create(memberDesc.GetFieldName(), memberDesc.GetTypeName(), options, desc, id).Unwrap();
563 memberFields.emplace_back(std::move(field));
564 }
565 R__ASSERT(typeName == fieldDesc.GetTypeName());
566 auto recordField = Internal::CreateEmulatedRecordField(fieldName, std::move(memberFields), fieldDesc);
567 recordField->SetTypeAlias(fieldDesc.GetTypeAlias());
568 return recordField;
569 } else if (fieldDesc.GetStructure() == ENTupleStructure::kCollection) {
570 if (fieldDesc.GetLinkIds().size() != 1)
571 throw ROOT::RException(R__FAIL("invalid structure for collection field " + fieldName));
572
573 auto itemFieldId = fieldDesc.GetLinkIds()[0];
574 const auto &itemFieldDesc = desc->GetFieldDescriptor(itemFieldId);
575 auto itemField =
576 Create(itemFieldDesc.GetFieldName(), itemFieldDesc.GetTypeName(), options, desc, itemFieldId).Unwrap();
577 auto vecField = ROOT::Internal::CreateEmulatedVectorField(fieldName, std::move(itemField), fieldDesc);
578 vecField->SetTypeAlias(fieldDesc.GetTypeAlias());
579 return vecField;
580 } else if (ROOT::Internal::IsCustomEnumFieldDesc(*desc, fieldDesc)) {
581 R__ASSERT(!fieldDesc.GetLinkIds().empty());
582 auto underlyingIntFieldId = fieldDesc.GetLinkIds()[0];
583 const auto &underlyingIntFieldDesc = desc->GetFieldDescriptor(underlyingIntFieldId);
584 auto enumField = ROOT::Internal::CreateEmulatedEnumField(fieldName, fieldDesc.GetTypeName(),
585 underlyingIntFieldDesc.GetTypeName());
586 enumField->SetTypeAlias(fieldDesc.GetTypeAlias());
587 return enumField;
588 }
589 }
590 } catch (const RException &e) {
591 auto error = e.GetError();
592 if (createContext.GetContinueOnError()) {
593 return std::unique_ptr<RFieldBase>(std::make_unique<RInvalidField>(fieldName, typeName, error.GetReport(),
595 } else {
596 return error;
597 }
598 } catch (const std::logic_error &e) {
599 // Integer parsing error
600 if (createContext.GetContinueOnError()) {
601 return std::unique_ptr<RFieldBase>(
602 std::make_unique<RInvalidField>(fieldName, typeName, e.what(), RInvalidField::ECategory::kGeneric));
603 } else {
604 return R__FAIL(e.what());
605 }
606 }
607
608 if (result) {
609 const auto normOrigType = ROOT::Internal::GetNormalizedUnresolvedTypeName(typeName);
610 if (normOrigType != result->GetTypeName()) {
611 result->SetTypeAlias(normOrigType);
612 }
613 return result;
614 }
615 return R__FORWARD_RESULT(fnFail("unknown type: " + typeName, RInvalidField::ECategory::kUnknownType));
616}
617
619{
620 static RColumnRepresentations representations;
621 return representations;
622}
623
624std::unique_ptr<ROOT::RFieldBase> ROOT::RFieldBase::Clone(std::string_view newName) const
625{
626 auto clone = CloneImpl(newName);
627 clone->SetDescription(*fDescription);
628 clone->SetTypeAlias(*fTypeAlias);
629 clone->fOnDiskId = fOnDiskId;
630 // We can just copy the references because fColumnRepresentatives point into a static structure
631 clone->fColumnRepresentatives = fColumnRepresentatives;
632 return clone;
633}
634
635std::size_t ROOT::RFieldBase::AppendImpl(const void * /* from */)
636{
637 R__ASSERT(false && "A non-simple RField must implement its own AppendImpl");
638 return 0;
639}
640
642{
643 R__ASSERT(false);
644}
645
647{
648 ReadGlobalImpl(fPrincipalColumn->ForReading()->GetGlobalIndex(localIndex), to);
649}
650
651std::size_t ROOT::RFieldBase::ReadBulkImpl(const RBulkSpec &bulkSpec)
652{
653 const auto valueSize = GetValueSize();
654 std::size_t nRead = 0;
655 for (std::size_t i = 0; i < bulkSpec.fCount; ++i) {
656 // Value not needed
657 if (bulkSpec.fMaskReq && !bulkSpec.fMaskReq[i])
658 continue;
659
660 // Value already present
661 if (bulkSpec.fMaskAvail[i])
662 continue;
663
664 Read(bulkSpec.fFirstIndex + i, reinterpret_cast<unsigned char *>(bulkSpec.fValues) + i * valueSize);
665 bulkSpec.fMaskAvail[i] = true;
666 nRead++;
667 }
668 return nRead;
669}
670
672{
673 const auto align = GetAlignment();
674 void *where;
675 if (align <= sizeof(std::max_align_t)) {
676 // We use the normal operator new for regularly aligned types to not complicate the user code that
677 // deletes objects returned by CreateObject()
678 where = operator new(GetValueSize());
679 } else {
680 where = operator new(GetValueSize(), std::align_val_t(GetAlignment()));
681 }
682 R__ASSERT(where != nullptr);
683 ConstructValue(where);
684 return where;
685}
686
688{
689 void *obj = CreateObjectRawPtr();
690 return RValue(this, std::shared_ptr<void>(obj, RSharedPtrDeleter(GetDeleter())));
691}
692
693std::vector<ROOT::RFieldBase::RValue> ROOT::RFieldBase::SplitValue(const RValue & /*value*/) const
694{
695 return std::vector<RValue>();
696}
697
698void ROOT::RFieldBase::SetStringPool(const std::shared_ptr<Internal::RStringPool> &pool)
699{
700 fFieldName = pool->Intern(*fFieldName);
701 fTypeName = pool->Intern(*fTypeName);
702 fTypeAlias = pool->Intern(*fTypeAlias);
703 fDescription = pool->Intern(*fDescription);
704 fStringPool = pool;
705}
706
707std::shared_ptr<ROOT::Internal::RStringPool>
708ROOT::RFieldBase::SetSharedStringPool(const std::shared_ptr<Internal::RStringPool> &pool)
709{
710 // Don't nest different shared string pools. Always use the outer-most one but allow for it to be reset to null.
711 if (fgSharedStringPool && pool) {
712 return fgSharedStringPool;
713 }
714 return std::exchange(fgSharedStringPool, pool);
715}
716
717void ROOT::RFieldBase::Attach(std::unique_ptr<ROOT::RFieldBase> child, std::string_view expectedChildName)
718{
719 // Note that technically the zero field would not need to have the extensible trait: because only its sub fields
720 // get connected by RPageSink::UpdateSchema, it does not change its initial state.
721 if (!(fTraits & kTraitExtensible) && (fState != EState::kUnconnected))
722 throw RException(R__FAIL("invalid attempt to attach subfield to already connected, non-extensible field"));
723
724 if (!expectedChildName.empty() && child->GetFieldName() != expectedChildName) {
725 throw RException(R__FAIL(std::string("invalid subfield name: ") + child->GetFieldName() +
726 " expected: " + std::string(expectedChildName)));
727 }
728
729 if (fStringPool != child->fStringPool) {
730 child->SetStringPool(fStringPool);
731 for (auto &f : *child) {
732 f.SetStringPool(fStringPool);
733 }
734 }
735
736 child->fParent = this;
737 fSubfields.emplace_back(std::move(child));
738}
739
741{
742 ROOT::NTupleSize_t result = globalIndex;
743 for (auto f = this; f != nullptr; f = f->GetParent()) {
744 auto parent = f->GetParent();
745 if (parent && (parent->GetStructure() == ROOT::ENTupleStructure::kCollection ||
746 parent->GetStructure() == ROOT::ENTupleStructure::kVariant)) {
747 return 0U;
748 }
749 result *= std::max<ROOT::NTupleSize_t>(f->GetNRepetitions(), ROOT::NTupleSize_t{1U});
750 }
751 return result;
752}
753
754std::vector<ROOT::RFieldBase *> ROOT::RFieldBase::GetMutableSubfields()
755{
756 std::vector<RFieldBase *> result;
757 result.reserve(fSubfields.size());
758 for (const auto &f : fSubfields) {
759 result.emplace_back(f.get());
760 }
761 return result;
762}
763
764std::vector<const ROOT::RFieldBase *> ROOT::RFieldBase::GetConstSubfields() const
765{
766 std::vector<const RFieldBase *> result;
767 result.reserve(fSubfields.size());
768 for (const auto &f : fSubfields) {
769 result.emplace_back(f.get());
770 }
771 return result;
772}
773
775{
776 if (!fAvailableColumns.empty()) {
777 const auto activeRepresentationIndex = fPrincipalColumn->GetRepresentationIndex();
778 for (auto &column : fAvailableColumns) {
779 if (column->GetRepresentationIndex() == activeRepresentationIndex) {
780 column->ForWriting()->Flush();
781 }
782 }
783 }
784}
785
787{
788 if (!fAvailableColumns.empty()) {
789 const auto activeRepresentationIndex = fPrincipalColumn->GetRepresentationIndex();
790 for (auto &column : fAvailableColumns) {
791 if (column->GetRepresentationIndex() == activeRepresentationIndex) {
792 column->ForWriting()->Flush();
793 } else {
794 column->ForWriting()->CommitSuppressed();
795 }
796 }
797 }
798 CommitClusterImpl();
799}
800
801void ROOT::RFieldBase::SetDescription(std::string_view description)
802{
803 if (fState != EState::kUnconnected)
804 throw RException(R__FAIL("cannot set field description once field is connected"));
805 fDescription = fStringPool->Intern(description);
806}
807
808void ROOT::RFieldBase::SetTypeAlias(std::string_view typeAlias)
809{
810 if (fState != EState::kUnconnected)
811 throw RException(R__FAIL("cannot set type alias once field is connected"));
812 fTypeAlias = fStringPool->Intern(typeAlias);
813}
814
816{
817 if (fState != EState::kUnconnected)
818 throw RException(R__FAIL("cannot set field ID once field is connected"));
819 fOnDiskId = id;
820}
821
822/// Write the given value into columns. The value object has to be of the same type as the field.
823/// Returns the number of uncompressed bytes written.
824std::size_t ROOT::RFieldBase::Append(const void *from)
825{
826 if (~fTraits & kTraitMappable)
827 return AppendImpl(from);
828
829 fPrincipalColumn->ForWriting()->Append(from);
830 return fPrincipalColumn->GetElement()->GetPackedSize();
831}
832
837
839{
840 return RValue(this, std::move(objPtr));
841}
842
843std::size_t ROOT::RFieldBase::ReadBulk(const RBulkSpec &bulkSpec)
844{
845 if (fIsSimple) {
846 /// For simple types, ignore the mask and memcopy the values into the destination
847 fPrincipalColumn->ForReading()->ReadV(bulkSpec.fFirstIndex, bulkSpec.fCount, bulkSpec.fValues);
848 std::fill(bulkSpec.fMaskAvail, bulkSpec.fMaskAvail + bulkSpec.fCount, true);
849 return RBulkSpec::kAllSet;
850 }
851
852 if (fIsArtificial) {
853 // Artificial fields must not go through an optimized read
854 return RFieldBase::ReadBulkImpl(bulkSpec);
855 }
856
857 return ReadBulkImpl(bulkSpec);
858}
859
861{
862 return fSubfields.empty() ? RSchemaIterator(this, -1) : RSchemaIterator(fSubfields[0].get(), 0);
863}
864
869
871{
872 return fSubfields.empty() ? RConstSchemaIterator(this, -1) : RConstSchemaIterator(fSubfields[0].get(), 0);
873}
874
879
881{
882 return fSubfields.empty() ? RConstSchemaIterator(this, -1) : RConstSchemaIterator(fSubfields[0].get(), 0);
883}
884
889
891{
892 if (fColumnRepresentatives.empty()) {
893 return {GetColumnRepresentations().GetSerializationDefault()};
894 }
895
897 result.reserve(fColumnRepresentatives.size());
898 for (const auto &r : fColumnRepresentatives) {
899 result.emplace_back(r.get());
900 }
901 return result;
902}
903
905{
906 if (fState != EState::kUnconnected)
907 throw RException(R__FAIL("cannot set column representative once field is connected"));
908 const auto &validTypes = GetColumnRepresentations().GetSerializationTypes();
909 fColumnRepresentatives.clear();
910 fColumnRepresentatives.reserve(representatives.size());
911 for (const auto &r : representatives) {
912 auto itRepresentative = std::find(validTypes.begin(), validTypes.end(), r);
913 if (itRepresentative == std::end(validTypes))
914 throw RException(R__FAIL("invalid column representative"));
915
916 fColumnRepresentatives.emplace_back(*itRepresentative);
917 }
918}
919
922 std::uint16_t representationIndex) const
923{
924 static const ColumnRepresentation_t kEmpty;
925
926 if (fOnDiskId == ROOT::kInvalidDescriptorId)
927 throw RException(R__FAIL("No on-disk field information for `" + GetQualifiedFieldName() + "`"));
928
929 ColumnRepresentation_t onDiskTypes;
930 for (const auto &c : desc.GetColumnIterable(fOnDiskId)) {
931 if (c.GetRepresentationIndex() == representationIndex)
932 onDiskTypes.emplace_back(c.GetType());
933 }
934 if (onDiskTypes.empty()) {
935 if (representationIndex == 0) {
936 throw RException(R__FAIL("No on-disk column information for field `" + GetQualifiedFieldName() + "`"));
937 }
938 return kEmpty;
939 }
940
941 for (const auto &t : GetColumnRepresentations().GetDeserializationTypes()) {
942 if (t == onDiskTypes)
943 return t;
944 }
945
946 std::string columnTypeNames;
947 for (const auto &t : onDiskTypes) {
948 if (!columnTypeNames.empty())
949 columnTypeNames += ", ";
950 columnTypeNames += std::string("`") + ROOT::Internal::RColumnElementBase::GetColumnTypeName(t) + "`";
951 }
952 throw RException(R__FAIL("On-disk column types {" + columnTypeNames + "} for field `" + GetQualifiedFieldName() +
953 "` cannot be matched to its in-memory type `" + GetTypeName() + "` " +
954 "(representation index: " + std::to_string(representationIndex) + ")"));
955}
956
958{
959 // Sampled upfront: the block below sets representatives, which would clear the "default" state.
960 const bool hadDefaultRepresentative = HasDefaultColumnRepresentative();
961 if ((options.GetCompression() == 0) && hadDefaultRepresentative) {
962 ColumnRepresentation_t rep = GetColumnRepresentations().GetSerializationDefault();
963 for (auto &colType : rep) {
964 switch (colType) {
975 default: break;
976 }
977 }
978 SetColumnRepresentatives({rep});
979 }
980
981 // Only adjust Double32_t when the user did not pin a representation: an explicit representative must
982 // survive (see RNTupleMerger::ExtendDestinationModel), otherwise merging would silently reinterpret the
983 // raw copies of the source pages under a different encoding.
984 if ((*fTypeAlias == "Double32_t") && hadDefaultRepresentative) {
985 if (options.GetCompression() != 0)
986 SetColumnRepresentatives({{ROOT::ENTupleColumnType::kSplitReal32}});
987 else
988 SetColumnRepresentatives({{ROOT::ENTupleColumnType::kReal32}});
989 }
990
991 // An explicit representation pinned on a Double32_t field must contain a reduced-precision encoding:
992 // a 64-bit-only selection would store full doubles while the field promises Double32_t precision.
993 // A multi-column selection that also includes a reduced-precision representative stays legal.
994 if ((*fTypeAlias == "Double32_t") && !hadDefaultRepresentative) {
995 bool hasSubDoubleRep = false;
996 for (const auto &rep : GetColumnRepresentatives()) {
997 for (const auto colType : rep) {
999 hasSubDoubleRep = true;
1000 break;
1001 }
1002 }
1003 if (hasSubDoubleRep)
1004 break;
1005 }
1006 if (!hasSubDoubleRep) {
1007 throw RException(R__FAIL("explicit column representations of Double32_t field `" + GetFieldName() +
1008 "` must include a reduced-precision representation"));
1009 }
1010 }
1011}
1012
1014{
1015 if (dynamic_cast<ROOT::RFieldZero *>(this))
1016 throw RException(R__FAIL("invalid attempt to connect zero field to page sink"));
1017 if (fState != EState::kUnconnected)
1018 throw RException(R__FAIL("invalid attempt to connect an already connected field to a page sink"));
1019
1020 AutoAdjustColumnTypes(pageSink.GetWriteOptions());
1021
1022 GenerateColumns();
1023 for (auto &column : fAvailableColumns) {
1024 // Only the first column of every representation can be a deferred column. In all column representations,
1025 // larger column indexes are data columns of collections (string, streamer) and thus
1026 // they have no elements on late model extension
1027 auto firstElementIndex = (column->GetIndex() == 0) ? EntryToColumnElementIndex(firstEntry) : 0;
1028 column->ForWriting()->ConnectPageSink(fOnDiskId, pageSink, firstElementIndex);
1029 }
1030
1031 if (HasExtraTypeInfo()) {
1033 [this](ROOT::Internal::RPageSink &sink) { sink.UpdateExtraTypeInfo(GetExtraTypeInfo()); });
1034 }
1035
1036 fState = EState::kConnectedToSink;
1037}
1038
1040{
1041 if (dynamic_cast<ROOT::RFieldZero *>(this)) {
1042 for (auto &f : fSubfields)
1043 f->ConnectPageSource(pageSource);
1044 return;
1045 }
1046
1047 if (fState != EState::kUnconnected)
1048 throw RException(R__FAIL("invalid attempt to connect an already connected field to a page source"));
1049
1050 if (!fColumnRepresentatives.empty())
1051 throw RException(R__FAIL("fixed column representative only valid when connecting to a page sink"));
1052 if (!fDescription->empty())
1053 throw RException(R__FAIL("setting description only valid when connecting to a page sink"));
1054
1055 if (!fIsArtificial) {
1056 R__ASSERT(fOnDiskId != kInvalidDescriptorId);
1057 // Handle moving from on-disk std::atomic<T> to (compatible of) T in memory centrally because otherwise
1058 // we would need to handle it in each and every ReconcileOnDiskField()
1059 // Note that we have to do this before calling BeforeConnectPageSource(), which already may compare the field
1060 // to its on-disk description.
1061 auto descGuard = pageSource.GetSharedDescriptorGuard();
1062 if (!dynamic_cast<RAtomicField *>(this) &&
1063 Internal::IsStdAtomicFieldDesc(descGuard->GetFieldDescriptor(GetOnDiskId()))) {
1064 SetOnDiskId(descGuard->GetFieldDescriptor(GetOnDiskId()).GetLinkIds()[0]);
1065 }
1066 }
1067
1068 auto substitute = BeforeConnectPageSource(pageSource);
1069 if (substitute) {
1070 const RFieldBase *itr = this;
1071 while (itr->GetParent()) {
1072 itr = itr->GetParent();
1073 }
1074 if (typeid(*itr) == typeid(RFieldZero) && static_cast<const RFieldZero *>(itr)->GetAllowFieldSubstitutions()) {
1075 for (auto &f : fParent->fSubfields) {
1076 if (f.get() != this)
1077 continue;
1078
1079 f = std::move(substitute);
1080 f->ConnectPageSource(pageSource);
1081 return;
1082 }
1083 R__ASSERT(false); // never here
1084 } else {
1085 throw RException(R__FAIL("invalid attempt to substitute field " + GetQualifiedFieldName()));
1086 }
1087 }
1088
1089 if (!fIsArtificial) {
1090 auto descGuard = pageSource.GetSharedDescriptorGuard();
1091 ReconcileOnDiskField(descGuard.GetConstRef());
1092 }
1093
1094 for (auto &f : fSubfields) {
1095 if (f->GetOnDiskId() == ROOT::kInvalidDescriptorId) {
1096 f->SetOnDiskId(pageSource.GetSharedDescriptorGuard()->FindFieldId(f->GetFieldName(), GetOnDiskId()));
1097 }
1098 f->ConnectPageSource(pageSource);
1099 }
1100
1101 // Do not generate columns nor set fColumnRepresentatives for artificial fields.
1102 if (!fIsArtificial) {
1103 const auto descriptorGuard = pageSource.GetSharedDescriptorGuard();
1104 const ROOT::RNTupleDescriptor &desc = descriptorGuard.GetConstRef();
1105 GenerateColumns(desc);
1106 if (fColumnRepresentatives.empty()) {
1107 // If we didn't get columns from the descriptor, ensure that we actually expect a field without columns
1108 for (const auto &t : GetColumnRepresentations().GetDeserializationTypes()) {
1109 if (t.empty()) {
1110 fColumnRepresentatives = {t};
1111 break;
1112 }
1113 }
1114 }
1115 R__ASSERT(!fColumnRepresentatives.empty());
1116 if (fOnDiskId != ROOT::kInvalidDescriptorId) {
1117 const auto &fieldDesc = desc.GetFieldDescriptor(fOnDiskId);
1118 fOnDiskTypeVersion = fieldDesc.GetTypeVersion();
1119 if (fieldDesc.GetTypeChecksum().has_value())
1120 fOnDiskTypeChecksum = *fieldDesc.GetTypeChecksum();
1121 }
1122 }
1123 for (auto &column : fAvailableColumns)
1124 column->ForReading()->ConnectPageSource(fOnDiskId, pageSource);
1125
1126 fState = EState::kConnectedToSource;
1127}
1128
1130{
1131 // The default implementation throws an exception if there are any meaningful differences to the on-disk field.
1132 // Derived classes may overwrite this and relax the checks to support automatic schema evolution.
1133 EnsureMatchingOnDiskField(desc).ThrowOnError();
1134}
1135
1137ROOT::RFieldBase::EnsureMatchingOnDiskField(const RNTupleDescriptor &desc, std::uint32_t ignoreBits) const
1138{
1139 const auto &fieldDesc = desc.GetFieldDescriptor(GetOnDiskId());
1140 const std::uint32_t diffBits = CompareOnDiskField(fieldDesc, ignoreBits);
1141 if (diffBits == 0)
1142 return RResult<void>::Success();
1143
1144 std::ostringstream errMsg;
1145 errMsg << "in-memory field " << GetQualifiedFieldName() << " of type " << GetTypeName() << " is incompatible "
1146 << "with on-disk field " << fieldDesc.GetFieldName() << ":";
1147 if (diffBits & kDiffFieldVersion) {
1148 errMsg << " field version " << GetFieldVersion() << " vs. " << fieldDesc.GetFieldVersion() << ";";
1149 }
1150 if (diffBits & kDiffTypeVersion) {
1151 errMsg << " type version " << GetTypeVersion() << " vs. " << fieldDesc.GetTypeVersion() << ";";
1152 }
1153 if (diffBits & kDiffStructure) {
1154 errMsg << " structural role " << GetStructure() << " vs. " << fieldDesc.GetStructure() << ";";
1155 }
1156 if (diffBits & kDiffTypeName) {
1157 errMsg << " incompatible on-disk type name " << fieldDesc.GetTypeName() << ";";
1158 }
1159 if (diffBits & kDiffNRepetitions) {
1160 errMsg << " repetition count " << GetNRepetitions() << " vs. " << fieldDesc.GetNRepetitions() << ";";
1161 }
1162 return R__FAIL(errMsg.str() + "\n" + Internal::GetTypeTraceReport(*this, desc));
1163}
1164
1166{
1167 std::uint32_t ignoreBits = kDiffTypeName;
1168 if (desc.GetFieldDescriptor(GetOnDiskId()).IsSoACollection())
1169 ignoreBits |= kDiffTypeVersion;
1170 return EnsureMatchingOnDiskField(desc, ignoreBits);
1171}
1172
1174 const std::vector<std::string> &prefixes) const
1175{
1176 const auto &fieldDesc = desc.GetFieldDescriptor(GetOnDiskId());
1177 for (const auto &p : prefixes) {
1178 if (fieldDesc.GetTypeName().rfind(p, 0) == 0)
1179 return RResult<void>::Success();
1180 }
1181 return R__FAIL("incompatible type " + fieldDesc.GetTypeName() + " for field " + GetQualifiedFieldName() + "\n" +
1182 Internal::GetTypeTraceReport(*this, desc));
1183}
1184
1185std::uint32_t ROOT::RFieldBase::CompareOnDiskField(const RFieldDescriptor &fieldDesc, std::uint32_t ignoreBits) const
1186{
1187 std::uint32_t diffBits = 0;
1188 if ((~ignoreBits & kDiffFieldVersion) && (GetFieldVersion() != fieldDesc.GetFieldVersion()))
1189 diffBits |= kDiffFieldVersion;
1190 if ((~ignoreBits & kDiffTypeVersion) && (GetTypeVersion() != fieldDesc.GetTypeVersion()))
1191 diffBits |= kDiffTypeVersion;
1192 if ((~ignoreBits & kDiffStructure) && (GetStructure() != fieldDesc.GetStructure()))
1193 diffBits |= kDiffStructure;
1194 if ((~ignoreBits & kDiffTypeName) && (GetTypeName() != fieldDesc.GetTypeName()))
1195 diffBits |= kDiffTypeName;
1196 if ((~ignoreBits & kDiffNRepetitions) && (GetNRepetitions() != fieldDesc.GetNRepetitions()))
1197 diffBits |= kDiffNRepetitions;
1198
1199 return diffBits;
1200}
1201
1203{
1204 visitor.VisitField(*this);
1205}
size_t fValueSize
dim_t fSize
#define R__FORWARD_RESULT(res)
Short-hand to return an RResult<T> value from a subroutine to the calling stack frame.
Definition RError.hxx:324
#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 R__LOG_WARNING(...)
Definition RLogger.hxx:357
#define f(i)
Definition RSha256.hxx:104
#define c(i)
Definition RSha256.hxx:101
#define e(i)
Definition RSha256.hxx:103
std::size_t capacity
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
winID h TVirtualViewer3D TVirtualGLPainter p
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 r
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 id
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 Int_t Int_t Window_t child
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
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 Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t type
char name[80]
Definition TGX11.cxx:142
Abstract base class for classes implementing the visitor design pattern.
virtual void VisitField(const ROOT::RFieldBase &field)=0
static const char * GetColumnTypeName(ROOT::ENTupleColumnType type)
Set a common string pool for all field (hierarchies) created in a block.
Abstract interface to write data into an ntuple.
const ROOT::RNTupleWriteOptions & GetWriteOptions() const
virtual void UpdateExtraTypeInfo(const ROOT::RExtraTypeInfoDescriptor &extraTypeInfo)=0
Adds an extra type information record to schema.
void RegisterOnCommitDatasetCallback(const Callback_t &cb)
The registered callback is executed at the beginning of CommitDataset();.
Abstract interface to read data from an ntuple.
RSharedDescriptorGuard GetSharedDescriptorGuard() const
Takes the read lock for the descriptor.
Template specializations for C++ std::atomic.
Base class for all ROOT issued exceptions.
Definition RError.hxx:78
Points to an array of objects with RNTuple I/O support, used for bulk reading.
std::unique_ptr< bool[]> fMaskAvail
Masks invalid values in the array.
std::unique_ptr< RFieldBase::RDeleter > fDeleter
void Reset(RNTupleLocalIndex firstIndex, std::size_t size)
Sets a new range for the bulk.
void * fValues
Cached deleter of fField.
RBulkValues & operator=(const RBulkValues &)=delete
RBulkValues(RFieldBase *field)
void AdoptBuffer(void *buf, std::size_t capacity)
The list of column representations a field can have.
std::vector< ColumnRepresentation_t > Selection_t
A list of column representations.
Selection_t fDeserializationTypes
The union of the serialization types and the deserialization extra types passed during construction.
void DeleteAligned(void *objPtr) const
Iterates over the subtree of fields in depth-first search order.
Points to an object with RNTuple I/O support and keeps a pointer to the corresponding field.
void BindRawPtr(void *rawPtr)
A field translates read and write calls from/to underlying columns to/from tree values.
RSchemaIterator end()
void Attach(std::unique_ptr< RFieldBase > child, std::string_view expectedChildName="")
Add a new subfield to the list of nested fields.
void SetColumnRepresentatives(const RColumnRepresentations::Selection_t &representatives)
Fixes a column representative.
ROOT::Internal::RColumn * fPrincipalColumn
All fields that have columns have a distinct main column.
virtual void ReconcileOnDiskField(const RNTupleDescriptor &desc)
For non-artificial fields, check compatibility of the in-memory field and the on-disk field.
const std::string * fFieldName
The field name relative to its parent field.
ROOT::NTupleSize_t EntryToColumnElementIndex(ROOT::NTupleSize_t globalIndex) const
Translate an entry index to a column element index of the principal column.
virtual void AcceptVisitor(ROOT::Detail::RFieldVisitor &visitor) const
void FlushColumns()
Flushes data from active columns.
virtual void ReadGlobalImpl(ROOT::NTupleSize_t globalIndex, void *to)
virtual const RColumnRepresentations & GetColumnRepresentations() const
Implementations in derived classes should return a static RColumnRepresentations object.
std::shared_ptr< Internal::RStringPool > fStringPool
The string storage for name, type (alias), and description. The string pool is always shared with the...
bool fIsSimple
A field qualifies as simple if it is mappable (which implies it has a single principal column),...
RConstSchemaIterator cbegin() const
void AutoAdjustColumnTypes(const ROOT::RNTupleWriteOptions &options)
When connecting a field to a page sink, the field's default column representation is subject to adjus...
std::vector< const RFieldBase * > GetConstSubfields() const
void SetOnDiskId(ROOT::DescriptorId_t id)
void SetTypeAlias(std::string_view typeAlias)
Can only be set on unconnected fields.
const RFieldBase * GetParent() const
std::vector< RFieldBase * > GetMutableSubfields()
static std::vector< RCheckResult > Check(const std::string &fieldName, const std::string &typeName)
Checks if the given type is supported by RNTuple.
RSchemaIterator begin()
const std::string * fTypeAlias
A typedef or using name that was used when creating the field.
RResult< void > EnsureMatchingOnDiskCollection(const RNTupleDescriptor &desc) const
Convenience wrapper for the common case of calling EnsureMatchinOnDiskField() for collections.
RConstSchemaIterator cend() const
std::size_t fNRepetitions
For fixed sized arrays, the array length.
std::size_t Append(const void *from)
Write the given value into columns.
RValue CreateValue()
Generates an object of the field's type, wraps it in a shared pointer and returns it as an RValue con...
const ColumnRepresentation_t & EnsureCompatibleColumnTypes(const ROOT::RNTupleDescriptor &desc, std::uint16_t representationIndex) const
Returns the on-disk column types found in the provided descriptor for fOnDiskId and the given represe...
virtual std::vector< RValue > SplitValue(const RValue &value) const
Creates the list of direct child values given an existing value for this field.
std::string GetQualifiedFieldName() const
Returns the field name and parent field names separated by dots (grandparent.parent....
RBulkValues CreateBulk()
Creates a new, initially empty bulk.
@ kTraitTriviallyDestructible
The type is cleaned up just by freeing its memory. I.e. the destructor performs a no-op.
@ kTraitTriviallyConstructible
No constructor needs to be called, i.e.
@ kTraitMappable
A field of a fundamental type that can be directly mapped via RField<T>::Map(), i....
@ kTraitInvalidField
This field is an instance of RInvalidField and can be safely static_cast to it.
void ConnectPageSink(ROOT::Internal::RPageSink &pageSink, ROOT::NTupleSize_t firstEntry=0)
Fields and their columns live in the void until connected to a physical page storage.
std::size_t ReadBulk(const RBulkSpec &bulkSpec)
Returns the number of newly available values, that is the number of bools in bulkSpec....
std::vector< ROOT::ENTupleColumnType > ColumnRepresentation_t
const std::string * fTypeName
The C++ type captured by this field.
RResult< void > EnsureMatchingOnDiskField(const RNTupleDescriptor &desc, std::uint32_t ignoreBits=0) const
Compares the field to the corresponding on-disk field information in the provided descriptor.
virtual void ReadInClusterImpl(RNTupleLocalIndex localIndex, void *to)
static std::shared_ptr< Internal::RStringPool > SetSharedStringPool(const std::shared_ptr< Internal::RStringPool > &)
Used by the SharedStringPoolRaii.
std::uint32_t fTraits
Properties of the type that allow for optimizations of collections of that type.
virtual std::size_t AppendImpl(const void *from)
Operations on values of complex types, e.g.
RFieldBase * fParent
Subfields point to their mother field.
RFieldBase(std::string_view name, std::string_view type, ROOT::ENTupleStructure structure, bool isSimple, std::size_t nRepetitions=0)
The constructor creates the underlying column objects and connects them to either a sink or a source.
const std::string * fDescription
Free text set by the user.
void SetStringPool(const std::shared_ptr< Internal::RStringPool > &pool)
static RResult< std::unique_ptr< RFieldBase > > Create(const std::string &fieldName, const std::string &typeName, const ROOT::RCreateFieldOptions &options, const ROOT::RNTupleDescriptor *desc, ROOT::DescriptorId_t fieldId)
Factory method to resurrect a field from the stored on-disk type information.
std::uint32_t CompareOnDiskField(const RFieldDescriptor &fieldDesc, std::uint32_t ignoreBits) const
Returns a combination of kDiff... flags, indicating peroperties that are different between the field ...
RColumnRepresentations::Selection_t GetColumnRepresentatives() const
Returns the fColumnRepresentative pointee or, if unset (always the case for artificial fields),...
ROOT::ENTupleStructure fStructure
The role of this field in the data model structure.
RValue BindValue(std::shared_ptr< void > objPtr)
Creates a value from a memory location with an already constructed object.
void SetDescription(std::string_view description)
std::unique_ptr< RFieldBase > Clone(std::string_view newName) const
Copies the field and its subfields using a possibly new name and a new, unconnected set of columns.
void CommitCluster()
Flushes data from active columns to disk and calls CommitClusterImpl()
void ConnectPageSource(ROOT::Internal::RPageSource &pageSource)
Connects the field and its subfield tree to the given page source.
RResult< void > EnsureMatchingTypePrefix(const RNTupleDescriptor &desc, const std::vector< std::string > &prefixes) const
Many fields accept a range of type prefixes for schema evolution, e.g.
void * CreateObjectRawPtr() const
Factory method for the field's type. The caller owns the returned pointer.
static thread_local std::shared_ptr< Internal::RStringPool > fgSharedStringPool
Set by the SharedStringPoolRaii object to a pre-existing string pool used during all field constructi...
virtual std::size_t ReadBulkImpl(const RBulkSpec &bulkSpec)
General implementation of bulk read.
Metadata stored for every field of an RNTuple.
std::uint32_t GetFieldVersion() const
ROOT::ENTupleStructure GetStructure() const
const std::vector< ROOT::DescriptorId_t > & GetLinkIds() const
std::uint64_t GetNRepetitions() const
std::uint32_t GetTypeVersion() const
const std::string & GetTypeName() const
The container field for an ntuple model, which itself has no physical representation.
Definition RField.hxx:58
void Attach(std::unique_ptr< RFieldBase > child)
A public version of the Attach method that allows piece-wise construction of the zero field.
Definition RField.cxx:40
Classes with dictionaries that can be inspected by TClass.
Definition RField.hxx:352
Used in RFieldBase::Check() to record field creation failures.
Definition RField.hxx:96
@ kGeneric
Generic unrecoverable error.
@ kUnknownType
The type given to RFieldBase::Create was unknown.
@ kTypeError
The type given to RFieldBase::Create was invalid.
The on-storage metadata of an RNTuple.
const RFieldDescriptor & GetFieldDescriptor(ROOT::DescriptorId_t fieldId) const
RColumnDescriptorIterable GetColumnIterable() const
ROOT::DescriptorId_t FindFieldId(std::string_view fieldName, ROOT::DescriptorId_t parentId) const
Addresses a column element or field item relative to a particular cluster, instead of a global NTuple...
Common user-tunable settings for storing RNTuples.
std::uint32_t GetCompression() const
The class is used as a return type for operations that can fail; wraps a value of type T or an RError...
Definition RError.hxx:222
The field for a class using ROOT standard streaming.
Definition RField.hxx:255
@ kInterpreted
Definition TClass.h:129
@ kForwardDeclared
Definition TClass.h:127
static TClass * GetClass(const char *name, Bool_t load=kTRUE, Bool_t silent=kFALSE)
Static method returning pointer to TClass of the specified class name.
Definition TClass.cxx:2999
static TEnum * GetEnum(const std::type_info &ti, ESearchAction sa=kALoadAndInterpLookup)
Definition TEnum.cxx:181
std::unique_ptr< RFieldBase > CreateEmulatedVectorField(std::string_view fieldName, std::unique_ptr< RFieldBase > itemField, const RFieldDescriptor &emulatedFrom)
Definition RField.cxx:598
std::vector< std::string > TokenizeTypeList(std::string_view templateType, std::size_t maxArgs=0)
Used in RFieldBase::Create() in order to get the comma-separated list of template types E....
std::shared_ptr< RStringPool > CallSetSharedStringPoolOnField(const std::shared_ptr< Internal::RStringPool > &)
RResult< void > EnsureValidNameForRNTuple(std::string_view name, std::string_view where)
Check whether a given string is a valid name according to the RNTuple specification.
ROOT::RLogChannel & NTupleLog()
Log channel for RNTuple diagnostics.
void CallCommitClusterOnField(RFieldBase &)
void CallConnectPageSourceOnField(RFieldBase &, ROOT::Internal::RPageSource &)
unsigned long long ParseUIntTypeToken(const std::string &uintToken)
std::string GetRNTupleSoARecord(const TClass *cl)
Checks if the "rntuple.SoARecord" class attribute is set in the dictionary.
ROOT::RResult< std::unique_ptr< ROOT::RFieldBase > > CallFieldBaseCreate(const std::string &fieldName, const std::string &typeName, const ROOT::RCreateFieldOptions &options, const ROOT::RNTupleDescriptor *desc, ROOT::DescriptorId_t fieldId)
std::unique_ptr< RFieldBase > CreateEmulatedRecordField(std::string_view fieldName, std::vector< std::unique_ptr< RFieldBase > > itemFields, const RFieldDescriptor &emulatedFrom)
Definition RField.cxx:590
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 ...
auto MakeAliasedSharedPtr(T *rawPtr)
std::string GetCanonicalTypePrefix(const std::string &typeName)
Applies RNTuple specific type name normalization rules (see specs) that help the string parsing in RF...
void CallFlushColumnsOnField(RFieldBase &)
std::shared_ptr< RStringPool > GetStringPoolOfField(const ROOT::RFieldBase &)
void CallSetArtificialOnField(RFieldBase &)
std::unique_ptr< RFieldBase > CreateEmulatedEnumField(std::string_view fieldName, std::string_view emulatedFromType, std::string_view underlyingIntType)
bool IsCustomEnumFieldDesc(const RNTupleDescriptor &desc, const RFieldDescriptor &fieldDesc)
Tells if the field describes a user-defined enum type.
std::string GetNormalizedUnresolvedTypeName(const std::string &origName)
Applies all RNTuple type normalization rules except typedef resolution.
ERNTupleSerializationMode GetRNTupleSerializationMode(const TClass *cl)
bool IsStdAtomicFieldDesc(const RFieldDescriptor &fieldDesc)
Tells if the field describes a std::atomic<T> type.
void CallConnectPageSinkOnField(RFieldBase &, ROOT::Internal::RPageSink &, ROOT::NTupleSize_t firstEntry=0)
std::uint64_t DescriptorId_t
Distriniguishes elements of the same type within a descriptor, e.g. different fields.
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...
std::string ResolveTypedef(const char *tname, bool resolveAll=false)
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.
bool * fMaskAvail
A bool array of size fCount, indicating the valid values in fValues.
const bool * fMaskReq
A bool array of size fCount, indicating the required values in the requested range.
Used in the return value of the Check() method.