Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RFieldBase.hxx
Go to the documentation of this file.
1/// \file ROOT/RFieldBase.hxx
2/// \author Jakob Blomer <jblomer@cern.ch>
3/// \date 2018-10-09
4
5/*************************************************************************
6 * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. *
7 * All rights reserved. *
8 * *
9 * For the licensing terms see $ROOTSYS/LICENSE. *
10 * For the list of contributors see $ROOTSYS/README/CREDITS. *
11 *************************************************************************/
12
13#ifndef ROOT_RFieldBase
14#define ROOT_RFieldBase
15
16#include <ROOT/BitUtils.hxx>
17#include <ROOT/RColumn.hxx>
19#include <ROOT/RError.hxx>
20#include <ROOT/RFieldUtils.hxx>
21#include <ROOT/RNTupleRange.hxx>
22#include <ROOT/RNTupleTypes.hxx>
23#include <ROOT/RNTupleUtils.hxx>
24
25#include <atomic>
26#include <cassert>
27#include <cstddef>
28#include <functional>
29#include <iterator>
30#include <memory>
31#include <new>
32#include <string>
33#include <string_view>
34#include <typeinfo>
35#include <type_traits>
36#include <vector>
37
38namespace ROOT {
39
40class REntry;
41class RFieldBase;
42class RClassField;
43
44namespace Detail {
45class RFieldVisitor;
46class RRawPtrWriteEntry;
47} // namespace Detail
48
49class RNTupleAttrSetReader;
50
51namespace Internal {
52
53class RPageSink;
54class RPageSource;
55struct RFieldRepresentationModifier;
56struct RNTupleAttrEntry;
57
58// TODO(jblomer): find a better way to not have these methods in the RFieldBase public API
59void CallFlushColumnsOnField(RFieldBase &);
60void CallCommitClusterOnField(RFieldBase &);
64CallFieldBaseCreate(const std::string &fieldName, const std::string &typeName, const ROOT::RCreateFieldOptions &options,
66void CallSetArtificialOnField(RFieldBase &);
67std::shared_ptr<RStringPool> CallSetSharedStringPoolOnField(const std::shared_ptr<Internal::RStringPool> &);
68std::shared_ptr<RStringPool> GetStringPoolOfField(const ROOT::RFieldBase &);
69
70/// Set a common string pool for all field (hierarchies) created in a block
72private:
73 std::shared_ptr<RStringPool> fOldPool;
74
75public:
77 {
78 fOldPool = CallSetSharedStringPoolOnField(std::make_shared<Internal::RStringPool>());
79 }
80 explicit RFieldSharedStringPoolRaii(const std::shared_ptr<Internal::RStringPool> &pool)
81 {
83 }
89};
90
91} // namespace Internal
92
93// clang-format off
94/**
95\class ROOT::RFieldBase
96\ingroup NTuple
97\brief A field translates read and write calls from/to underlying columns to/from tree values
98
99A field is a serializable C++ type or a container for a collection of subfields. The RFieldBase and its
100type-safe descendants provide the object to column mapper. They map C++ objects to primitive columns. The
101mapping is trivial for simple types such as 'double'. Complex types resolve to multiple primitive columns.
102The field knows based on its type and the field name the type(s) and name(s) of the columns.
103
104Note: the class hierarchy starting at RFieldBase is not meant to be extended by user-provided child classes.
105This is and can only be partially enforced through C++.
106*/
107// clang-format on
109 friend class RFieldZero; // to reset fParent pointer in ReleaseSubfields()
110 friend class ROOT::Detail::RRawPtrWriteEntry; // to call Append()
111 friend class ROOT::RNTupleAttrSetReader; // for field->Read() in LoadEntry()
112 friend struct ROOT::Internal::RFieldRepresentationModifier; // used for unit tests
118 Internal::CallFieldBaseCreate(const std::string &fieldName, const std::string &typeName,
119 const ROOT::RCreateFieldOptions &options, const ROOT::RNTupleDescriptor *desc,
120 ROOT::DescriptorId_t fieldId);
122 friend std::shared_ptr<Internal::RStringPool>
123 Internal::CallSetSharedStringPoolOnField(const std::shared_ptr<Internal::RStringPool> &);
124 friend std::shared_ptr<Internal::RStringPool> ROOT::Internal::GetStringPoolOfField(const ROOT::RFieldBase &);
125
126protected:
127 /// A functor to release the memory acquired by CreateValue() (memory and constructor).
128 /// This implementation works for types with a trivial destructor. More complex fields implement a derived deleter.
129 /// The deleter is operational without the field object and thus can be used to destruct/release a value after
130 /// the field has been destructed.
131 class RDeleter {
132 std::size_t fAlignment;
133 void DeleteAligned(void *objPtr) const; // outlined to make Windows happy
134
135 public:
136 explicit RDeleter(std::size_t align) : fAlignment(align) { assert(Internal::IsValidAlignment(align)); }
137 virtual ~RDeleter() = default;
138 virtual void operator()(void *objPtr, bool dtorOnly)
139 {
140 if (dtorOnly)
141 return;
142
143 // Match operator new in RFieldBase::CreateObjectRawPtr()
144 if (fAlignment <= sizeof(std::max_align_t)) {
145 operator delete(objPtr);
146 } else {
147 DeleteAligned(objPtr);
148 }
149 }
150 };
151
152 /// A deleter for templated RFieldBase descendents where the value type is known.
153 template <typename T>
154 class RTypedDeleter : public RDeleter {
155 public:
156 RTypedDeleter() : RDeleter(alignof(T)) {}
157 void operator()(void *objPtr, bool dtorOnly) final
158 {
159 std::destroy_at(static_cast<T *>(objPtr));
160 RDeleter::operator()(objPtr, dtorOnly);
161 }
162 };
163
164 // We cannot directly use RFieldBase::RDeleter as a shared pointer deleter due to splicing. We use this
165 // wrapper class to store a polymorphic pointer to the actual deleter.
167 std::unique_ptr<RFieldBase::RDeleter> fDeleter;
168 void operator()(void *objPtr) { fDeleter->operator()(objPtr, false /* dtorOnly*/); }
169 explicit RSharedPtrDeleter(std::unique_ptr<RFieldBase::RDeleter> deleter) : fDeleter(std::move(deleter)) {}
170 };
171
172public:
173 static constexpr std::uint32_t kInvalidTypeVersion = -1U;
174 enum {
175 /// No constructor needs to be called, i.e. any bit pattern in the allocated memory represents a valid type
176 /// A trivially constructible field has a no-op ConstructValue() implementation
178 /// The type is cleaned up just by freeing its memory. I.e. the destructor performs a no-op.
180 /// A field of a fundamental type that can be directly mapped via RField<T>::Map(), i.e. maps as-is to a single
181 /// column
183 /// The TClass checksum is set and valid
185 /// This field is an instance of RInvalidField and can be safely `static_cast` to it
187 /// This field is a user defined type that was missing dictionaries and was reconstructed from the on-disk
188 /// information
190 /// Can attach new item fields even when already connected
192 /// The field represents a collection in SoA layout
194
195 /// Shorthand for types that are both trivially constructible and destructible
197 };
198
199 using ColumnRepresentation_t = std::vector<ROOT::ENTupleColumnType>;
200
201 /// During its lifetime, a field undergoes the following possible state transitions:
202 ///
203 /// [*] --> Unconnected --> ConnectedToSink ----
204 /// | | |
205 /// | --> ConnectedToSource ---> [*]
206 /// | |
207 /// -------------------------------
208 enum class EState {
212 };
213
214 // clang-format off
215 /**
216 \class ROOT::RFieldBase::RColumnRepresentations
217 \ingroup NTuple
218 \brief The list of column representations a field can have.
219
220 Some fields have multiple possible column representations, e.g. with or without split encoding.
221 All column representations supported for writing also need to be supported for reading. In addition,
222 fields can support extra column representations for reading only, e.g. a 64bit integer reading from a
223 32bit column.
224 The defined column representations must be supported by corresponding column packing/unpacking implementations,
225 i.e. for the example above, the unpacking of 32bit ints to 64bit pages must be implemented in RColumnElement.hxx
226 */
227 // clang-format on
229 public:
230 /// A list of column representations
231 using Selection_t = std::vector<ColumnRepresentation_t>;
232
234 RColumnRepresentations(const Selection_t &serializationTypes, const Selection_t &deserializationExtraTypes);
235
236 /// The first column list from `fSerializationTypes` is the default for writing.
240
241 private:
243 /// The union of the serialization types and the deserialization extra types passed during construction.
244 /// Duplicates the serialization types list but the benefit is that GetDeserializationTypes() does not need to
245 /// compile the list.
247 }; // class RColumnRepresentations
248
249 class RValue;
250 class RBulkValues;
251
252private:
253 /// Set by the SharedStringPoolRaii object to a pre-existing string pool used during all field constructions.
254 /// A string pool must not be shared among threads.
255 static thread_local std::shared_ptr<Internal::RStringPool> fgSharedStringPool;
256 /// The string storage for name, type (alias), and description. The string pool is always shared with the subfields.
257 std::shared_ptr<Internal::RStringPool> fStringPool;
258 /// The field name relative to its parent field
259 const std::string *fFieldName = nullptr;
260 /// The C++ type captured by this field
261 const std::string *fTypeName = nullptr;
262 /// A typedef or using name that was used when creating the field
263 const std::string *fTypeAlias = nullptr;
264 /// Free text set by the user
265 const std::string *fDescription = nullptr;
266 /// The role of this field in the data model structure
268 /// For fixed sized arrays, the array length
269 std::size_t fNRepetitions;
270 /// A field qualifies as simple if it is mappable (which implies it has a single principal column),
271 /// and it is not an artificial field
273 /// A field that is not backed on disk but computed, e.g. a default-constructed missing field or
274 /// a field whose data is created by I/O customization rules. Subfields of artificial fields are
275 /// artificial, too.
276 bool fIsArtificial = false;
277 /// When the columns are connected to a page source or page sink, the field represents a field id in the
278 /// corresponding RNTuple descriptor. This on-disk ID is set in RPageSink::Create() for writing and by
279 /// RFieldDescriptor::CreateField() when recreating a field / model from the stored descriptor.
281 /// Changed by ConnectTo[Sink,Source], reset by Clone()
283
284 /// Used by the SharedStringPoolRaii
285 static std::shared_ptr<Internal::RStringPool> SetSharedStringPool(const std::shared_ptr<Internal::RStringPool> &);
286
287 /// Translate an entry index to a column element index of the principal column. This function
288 /// takes into account the role and number of repetitions on each level of the field hierarchy as follows:
289 /// - Top level fields: element index == entry index
290 /// - Record fields propagate their principal column index to the principal columns of direct descendant fields
291 /// - Collection and variant fields set the principal column index of their children to 0
292 ///
293 /// The column element index also depends on the number of repetitions of each field in the hierarchy, e.g., given a
294 /// field with type `std::array<std::array<float, 4>, 2>`, this function called with `globalIndex == 1`
295 /// returns 8 for the innermost field.
297
298 /// Flushes data from active columns
299 void FlushColumns();
300 /// Flushes data from active columns to disk and calls CommitClusterImpl()
301 void CommitCluster();
302 /// Fields and their columns live in the void until connected to a physical page storage. Only once connected, data
303 /// can be read or written. In order to find the field in the page storage, the field's on-disk ID has to be set.
304 /// \param firstEntry The global index of the first entry with on-disk data for the connected field
305 void ConnectPageSink(ROOT::Internal::RPageSink &pageSink, ROOT::NTupleSize_t firstEntry = 0);
306 /// Connects the field and its subfield tree to the given page source. Once connected, data can be read.
307 /// Only unconnected fields may be connected, i.e. the method is not idempotent. The field ID has to be set prior to
308 /// calling this function. For subfields, a field ID may or may not be set. If the field ID is unset, it will be
309 /// determined using the page source descriptor, based on the parent field ID and the subfield name.
311
313 {
314 fIsSimple = false;
315 fIsArtificial = true;
316 for (auto &field : fSubfields) {
317 field->SetArtificial();
318 }
319 }
320
321 void SetStringPool(const std::shared_ptr<Internal::RStringPool> &pool);
322
323protected:
324 struct RBulkSpec;
325
326 /// Bits used in CompareOnDisk()
327 enum {
328 /// The in-memory field and the on-disk field differ in the field version
330 /// The in-memory field and the on-disk field differ in the type version
332 /// The in-memory field and the on-disk field differ in their structural roles
334 /// The in-memory field and the on-disk field have different type names
336 /// The in-memory field and the on-disk field have different repetition counts
337 kDiffNRepetitions = 0x10
338 };
339
340 /// Collections and classes own subfields
341 std::vector<std::unique_ptr<RFieldBase>> fSubfields;
342 /// Subfields point to their mother field
344 /// All fields that have columns have a distinct main column. E.g., for simple fields (`float`, `int`, ...), the
345 /// principal column corresponds to the field type. For collection fields except fixed-sized arrays,
346 /// the main column is the offset field. Class fields have no column of their own.
347 /// When reading, points to any column of the column team of the active representation. Usually, this is just
348 /// the first column.
349 /// When writing, points to the first column index of the currently active (not suppressed) column representation.
351 /// Some fields have a second column in its column representation. In this case, `fAuxiliaryColumn` points into
352 /// `fAvailableColumns` to the column that immediately follows the column `fPrincipalColumn` points to.
354 /// The columns are connected either to a sink or to a source (not to both); they are owned by the field.
355 /// Contains all columns of all representations in order of representation and column index.
356 std::vector<std::unique_ptr<ROOT::Internal::RColumn>> fAvailableColumns;
357 /// Properties of the type that allow for optimizations of collections of that type
358 std::uint32_t fTraits = 0;
359 /// C++ type version cached from the descriptor after a call to ConnectPageSource()
361 /// TClass checksum cached from the descriptor after a call to ConnectPageSource(). Only set
362 /// for classes with dictionaries.
363 std::uint32_t fOnDiskTypeChecksum = 0;
364 /// Pointers into the static vector returned by RColumnRepresentations::GetSerializationTypes() when
365 /// SetColumnRepresentatives() is called. Otherwise (if empty) GetColumnRepresentatives() returns a vector
366 /// with a single element, the default representation. Always empty for artificial fields.
367 std::vector<std::reference_wrapper<const ColumnRepresentation_t>> fColumnRepresentatives;
368
369 /// Factory method for the field's type. The caller owns the returned pointer
370 void *CreateObjectRawPtr() const;
371
372 /// Helpers for generating columns. We use the fact that most fields have the same C++/memory types
373 /// for all their column representations.
374 /// Where possible, we call the helpers not from the header to reduce compilation time.
375 template <Internal::RColumn::EColumnType ColumnTypeT, std::uint32_t ColumnIndexT, typename HeadT, typename... TailTs>
376 void GenerateColumnsImpl(const ColumnRepresentation_t &representation, std::uint16_t representationIndex)
377 {
378 assert(ColumnIndexT < representation.size());
379 Internal::RColumn *column = nullptr;
380 static_assert(ColumnTypeT == Internal::RColumn::EColumnType::kRead ||
382 if constexpr (ColumnTypeT == Internal::RColumn::EColumnType::kRead) {
383 column = fAvailableColumns
384 .emplace_back(Internal::RReadColumn::Create<HeadT>(representation[ColumnIndexT], ColumnIndexT,
385 representationIndex))
386 .get();
387 } else {
388 column = fAvailableColumns
389 .emplace_back(Internal::RWriteColumn::Create<HeadT>(representation[ColumnIndexT], ColumnIndexT,
390 representationIndex))
391 .get();
392 }
393
394 // Initially, the first two columns become the active column representation
395 if (representationIndex == 0 && !fPrincipalColumn) {
396 fPrincipalColumn = column;
397 } else if (representationIndex == 0 && !fAuxiliaryColumn) {
398 fAuxiliaryColumn = column;
399 } else {
400 // We currently have no fields with more than 2 columns in its column representation
401 R__ASSERT(representationIndex > 0);
402 }
403
404 if constexpr (sizeof...(TailTs))
405 GenerateColumnsImpl<ColumnTypeT, ColumnIndexT + 1, TailTs...>(representation, representationIndex);
406 }
407
408 /// For writing, use the currently set column representative
409 template <typename... ColumnCppTs>
411 {
412 if (fColumnRepresentatives.empty()) {
413 fAvailableColumns.reserve(sizeof...(ColumnCppTs));
416 } else {
417 const auto N = fColumnRepresentatives.size();
418 fAvailableColumns.reserve(N * sizeof...(ColumnCppTs));
419 for (unsigned i = 0; i < N; ++i) {
421 fColumnRepresentatives[i].get(), i);
422 }
423 }
424 }
425
426 /// For reading, use the on-disk column list
427 template <typename... ColumnCppTs>
429 {
430 std::uint16_t representationIndex = 0;
431 do {
432 const auto &onDiskTypes = EnsureCompatibleColumnTypes(desc, representationIndex);
433 if (onDiskTypes.empty())
434 break;
435 GenerateColumnsImpl<Internal::RColumn::EColumnType::kRead, 0, ColumnCppTs...>(onDiskTypes,
436 representationIndex);
437 fColumnRepresentatives.emplace_back(onDiskTypes);
438 if (representationIndex > 0) {
439 for (std::size_t i = 0; i < sizeof...(ColumnCppTs); ++i) {
440 fAvailableColumns[i]->ForReading()->MergeTeams(
441 *(fAvailableColumns[representationIndex * sizeof...(ColumnCppTs) + i]->ForReading()));
442 }
443 }
444 representationIndex++;
445 } while (true);
446 }
447
448 /// Implementations in derived classes should return a static RColumnRepresentations object. The default
449 /// implementation does not attach any columns to the field.
450 virtual const RColumnRepresentations &GetColumnRepresentations() const;
451 /// Implementations in derived classes should create the backing columns corresponding to the field type for
452 /// writing. The default implementation does not attach any columns to the field.
453 virtual void GenerateColumns() {}
454 /// Implementations in derived classes should create the backing columns corresponding to the field type for reading.
455 /// The default implementation does not attach any columns to the field. The method should check, using the page
456 /// source and `fOnDiskId`, if the column types match and throw if they don't.
457 virtual void GenerateColumns(const ROOT::RNTupleDescriptor & /*desc*/) {}
458 /// Returns the on-disk column types found in the provided descriptor for `fOnDiskId` and the given
459 /// representation index. If there are no columns for the given representation index, return an empty
460 /// ColumnRepresentation_t list. Otherwise, the returned reference points into the static array returned by
461 /// GetColumnRepresentations().
462 /// Throws an exception if the types on disk don't match any of the deserialization types from
463 /// GetColumnRepresentations().
465 EnsureCompatibleColumnTypes(const ROOT::RNTupleDescriptor &desc, std::uint16_t representationIndex) const;
466 /// When connecting a field to a page sink, the field's default column representation is subject
467 /// to adjustment according to the write options. E.g., if compression is turned off, encoded columns
468 /// are changed to their unencoded counterparts.
470
471 /// Called by Clone(), which additionally copies the on-disk ID
472 virtual std::unique_ptr<RFieldBase> CloneImpl(std::string_view newName) const = 0;
473
474 /// Constructs value in a given location of size at least GetValueSize(). Called by the base class' CreateValue().
475 virtual void ConstructValue(void *where) const = 0;
476 virtual std::unique_ptr<RDeleter> GetDeleter() const { return std::make_unique<RDeleter>(GetAlignment()); }
477 /// Allow derived classes to call ConstructValue(void *) and GetDeleter() on other (sub)fields.
478 static void CallConstructValueOn(const RFieldBase &other, void *where) { other.ConstructValue(where); }
479 static std::unique_ptr<RDeleter> GetDeleterOf(const RFieldBase &other) { return other.GetDeleter(); }
480
481 /// Allow parents to mark their childs as artificial fields (used in class and record fields)
482 static void CallSetArtificialOn(RFieldBase &other) { other.SetArtificial(); }
483
484 /// Operations on values of complex types, e.g. ones that involve multiple columns or for which no direct
485 /// column type exists.
486 virtual std::size_t AppendImpl(const void *from);
487 virtual void ReadGlobalImpl(ROOT::NTupleSize_t globalIndex, void *to);
488 virtual void ReadInClusterImpl(RNTupleLocalIndex localIndex, void *to);
489
490 /// Write the given value into columns. The value object has to be of the same type as the field.
491 /// Returns the number of uncompressed bytes written.
492 std::size_t Append(const void *from);
493
494 /// Populate a single value with data from the field. The memory location pointed to by to needs to be of the
495 /// fitting type. The fast path is conditioned by the field qualifying as simple, i.e. maps as-is
496 /// to a single column and is not artifical.
497 void Read(ROOT::NTupleSize_t globalIndex, void *to)
498 {
499 if (fIsSimple) {
500 fPrincipalColumn->ForReading()->Read(globalIndex, to);
501 } else if (!fIsArtificial) {
502 ReadGlobalImpl(globalIndex, to);
503 }
504 }
505
506 /// Populate a single value with data from the field. The memory location pointed to by to needs to be of the
507 /// fitting type. The fast path is conditioned by the field qualifying as simple, i.e. maps as-is
508 /// to a single column and is not artificial.
509 void Read(RNTupleLocalIndex localIndex, void *to)
510 {
511 if (fIsSimple) {
512 fPrincipalColumn->ForReading()->Read(localIndex, to);
513 } else if (!fIsArtificial) {
514 ReadInClusterImpl(localIndex, to);
515 }
516 }
517
518 /// General implementation of bulk read. Loop over the required range and read values that are required
519 /// and not already present. Derived classes may implement more optimized versions of this method.
520 /// See ReadBulk() for the return value.
521 virtual std::size_t ReadBulkImpl(const RBulkSpec &bulkSpec);
522
523 /// Returns the number of newly available values, that is the number of bools in `bulkSpec.fMaskAvail` that
524 /// flipped from false to true. As a special return value, `kAllSet` can be used if all values are read
525 /// independent from the masks.
526 std::size_t ReadBulk(const RBulkSpec &bulkSpec);
527
528 /// Allow derived classes to call Append() and Read() on other (sub)fields.
529 static std::size_t CallAppendOn(RFieldBase &other, const void *from) { return other.Append(from); }
530 static void CallReadOn(RFieldBase &other, RNTupleLocalIndex localIndex, void *to) { other.Read(localIndex, to); }
531 static void CallReadOn(RFieldBase &other, ROOT::NTupleSize_t globalIndex, void *to) { other.Read(globalIndex, to); }
532 static void *CallCreateObjectRawPtrOn(RFieldBase &other) { return other.CreateObjectRawPtr(); }
533
534 /// Fields may need direct access to the principal column of their subfields, e.g. in RRVecField::ReadBulk()
536
537 // Perform housekeeping tasks for global to cluster-local index translation
538 virtual void CommitClusterImpl() {}
539 // The field can indicate that it needs to register extra type information in the on-disk schema.
540 // In this case, a callback from the page sink to the field will be registered on connect, so that the
541 // extra type information can be collected when the dataset gets committed.
542 virtual bool HasExtraTypeInfo() const { return false; }
543 // The page sink's callback when the data set gets committed will call this method to get the field's extra
544 // type information. This has to happen at the end of writing because the type information may change depending
545 // on the data that's written, e.g. for polymorphic types in the streamer field.
547
548 /// Can only be set on unconnected fields
549 void SetTypeAlias(std::string_view typeAlias);
550
551 /// Add a new subfield to the list of nested fields. Throws an exception if childName is non-empty and the passed
552 /// field has a different name.
553 void Attach(std::unique_ptr<RFieldBase> child, std::string_view expectedChildName = "");
554
555 /// Called by ConnectPageSource() before connecting; derived classes may override this as appropriate, e.g.
556 /// for the application of I/O rules. In the process, the field at hand or its subfields may be marked as
557 /// "artifical", i.e. introduced by schema evolution and not backed by on-disk information.
558 /// May return a field substitute that fits the on-disk schema as a replacement for the field at hand.
559 /// A field substitute must read into the same in-memory layout than the original field and field substitutions
560 /// must not be cyclic.
561 virtual std::unique_ptr<RFieldBase> BeforeConnectPageSource(ROOT::Internal::RPageSource & /* source */)
562 {
563 return nullptr;
564 }
565
566 /// For non-artificial fields, check compatibility of the in-memory field and the on-disk field. In the process,
567 /// the field at hand may change its on-disk ID or perform other tasks related to automatic schema evolution.
568 /// If the on-disk field is incompatible with the in-memory field at hand, an exception is thrown.
569 virtual void ReconcileOnDiskField(const RNTupleDescriptor &desc);
570
571 /// Returns a combination of kDiff... flags, indicating peroperties that are different between the field at hand
572 /// and the given on-disk field
573 std::uint32_t CompareOnDiskField(const RFieldDescriptor &fieldDesc, std::uint32_t ignoreBits) const;
574 /// Compares the field to the corresponding on-disk field information in the provided descriptor.
575 /// Throws an exception if the fields don't match.
576 /// Optionally, a set of bits can be provided that should be ignored in the comparison.
577 RResult<void> EnsureMatchingOnDiskField(const RNTupleDescriptor &desc, std::uint32_t ignoreBits = 0) const;
578 /// Convenience wrapper for the common case of calling EnsureMatchinOnDiskField() for collections. Collections
579 /// may differ in type name (most collections schema evolve into each other). An on-disk SoA collection may also
580 /// have any type version whereas all other collections need to have type version 0.
582 /// Many fields accept a range of type prefixes for schema evolution,
583 /// e.g. std::unique_ptr< and std::optional< for nullable fields
585 EnsureMatchingTypePrefix(const RNTupleDescriptor &desc, const std::vector<std::string> &prefixes) const;
586
587 /// Factory method to resurrect a field from the stored on-disk type information. This overload takes an already
588 /// normalized type name and type alias.
589 /// `desc` and `fieldId` must be passed if `options.fEmulateUnknownTypes` is true, otherwise they can be left blank.
591 Create(const std::string &fieldName, const std::string &typeName, const ROOT::RCreateFieldOptions &options,
592 const ROOT::RNTupleDescriptor *desc, ROOT::DescriptorId_t fieldId);
593
594public:
595 template <bool IsConstT>
596 class RSchemaIteratorTemplate;
599
600 // This is used in CreateObject() and is specialized for void
601 template <typename T>
603 using deleter = std::default_delete<T>;
604 };
605
606 /// Used in the return value of the Check() method
608 std::string fFieldName; ///< Qualified field name causing the error
609 std::string fTypeName; ///< Type name corresponding to the (sub)field
610 std::string fErrMsg; ///< Cause of the failure, e.g. unsupported type
611 };
612
613 /// The constructor creates the underlying column objects and connects them to either a sink or a source.
614 /// If `isSimple` is `true`, the trait `kTraitMappable` is automatically set on construction.
615 RFieldBase(std::string_view name, std::string_view type, ROOT::ENTupleStructure structure, bool isSimple,
616 std::size_t nRepetitions = 0);
617 RFieldBase(const RFieldBase &) = delete;
618 RFieldBase(RFieldBase &&) = default;
619 RFieldBase &operator=(const RFieldBase &) = delete;
621 virtual ~RFieldBase() = default;
622
623 /// Copies the field and its subfields using a possibly new name and a new, unconnected set of columns
624 std::unique_ptr<RFieldBase> Clone(std::string_view newName) const;
625
626 /// Factory method to create a field from a certain type given as string.
627 /// Note that the provided type name must be a valid C++ type name. Template arguments of templated types
628 /// must be type names or integers (e.g., no expressions).
630 Create(const std::string &fieldName, const std::string &typeName);
631
632 /// Checks if the given type is supported by RNTuple. In case of success, the result vector is empty.
633 /// Otherwise there is an error record for each failing subfield (subtype).
634 static std::vector<RCheckResult> Check(const std::string &fieldName, const std::string &typeName);
635
636 /// Generates an object of the field type and allocates new initialized memory according to the type.
637 /// Implemented at the end of this header because the implementation is using RField<T>::TypeName()
638 /// The returned object can be released with `delete`, i.e. it is valid to call:
639 /// ~~~{.cpp}
640 /// auto ptr = field->CreateObject();
641 /// delete ptr.release();
642 /// ~~~
643 /// Over-aligned types need to delete the returned pointer using the delete operator overload that specifies the
644 /// type's alignment.
645 ///
646 /// Note that CreateObject<void>() is supported. The returned `unique_ptr` has a custom deleter that reports an error
647 /// if it is called. The intended use of the returned `unique_ptr<void>` is to call `release()`. In this way, the
648 /// transfer of pointer ownership is explicit.
649 template <typename T>
650 std::unique_ptr<T, typename RCreateObjectDeleter<T>::deleter> CreateObject() const;
651 /// Generates an object of the field's type, wraps it in a shared pointer and returns it as an RValue connected to
652 /// the field.
654 /// Creates a new, initially empty bulk.
655 /// RBulkValues::ReadBulk() will construct the array of values. The memory of the value array is managed by the
656 /// RBulkValues class.
658 /// Creates a value from a memory location with an already constructed object
659 RValue BindValue(std::shared_ptr<void> objPtr);
660 /// Creates the list of direct child values given an existing value for this field. E.g. a single value for the
661 /// correct `std::variant` or all the elements of a collection. The default implementation assumes no subvalues
662 /// and returns an empty vector.
663 virtual std::vector<RValue> SplitValue(const RValue &value) const;
664 /// What sizeof(T) for this type returns
665 virtual size_t GetValueSize() const = 0;
666 /// What alignof(T) for this type returns
667 virtual size_t GetAlignment() const = 0;
668 std::uint32_t GetTraits() const { return fTraits; }
669 virtual bool R__DEPRECATED(6, 46, "This queries internal state that should not be required in user code")
670 HasReadCallbacks() const
671 {
672 return false;
673 }
674
675 const std::string &GetFieldName() const { return *fFieldName; }
676 /// Returns the field name and parent field names separated by dots (`grandparent.parent.child`)
677 std::string GetQualifiedFieldName() const;
678 const std::string &GetTypeName() const { return *fTypeName; }
679 const std::string &GetTypeAlias() const { return *fTypeAlias; }
681 std::size_t GetNRepetitions() const { return fNRepetitions; }
682 const RFieldBase *GetParent() const { return fParent; }
683 std::vector<RFieldBase *> GetMutableSubfields();
684 std::vector<const RFieldBase *> GetConstSubfields() const;
685 bool IsSimple() const { return fIsSimple; }
686 bool IsArtificial() const { return fIsArtificial; }
687 /// Get the field's description
688 const std::string &GetDescription() const { return *fDescription; }
689 void SetDescription(std::string_view description);
690 EState GetState() const { return fState; }
691
694
695 /// Returns the `fColumnRepresentative` pointee or, if unset (always the case for artificial fields), the field's
696 /// default representative
698 /// Fixes a column representative. This can only be done _before_ connecting the field to a page sink.
699 /// Otherwise, or if the provided representation is not in the list of GetColumnRepresentations(),
700 /// an exception is thrown
702 /// Whether or not an explicit column representative was set
704
705 /// Indicates an evolution of the mapping scheme from C++ type to columns
706 virtual std::uint32_t GetFieldVersion() const { return 0; }
707 /// Indicates an evolution of the C++ type itself
708 virtual std::uint32_t GetTypeVersion() const { return 0; }
709 /// Return the current TClass reported checksum of this class. Only valid if `kTraitTypeChecksum` is set.
710 virtual std::uint32_t GetTypeChecksum() const { return 0; }
711 /// Return the C++ type version stored in the field descriptor; only valid after a call to ConnectPageSource()
712 std::uint32_t GetOnDiskTypeVersion() const { return fOnDiskTypeVersion; }
713 /// Return checksum stored in the field descriptor; only valid after a call to ConnectPageSource(),
714 /// if the field stored a type checksum
715 std::uint32_t GetOnDiskTypeChecksum() const { return fOnDiskTypeChecksum; }
716
723
724 virtual void AcceptVisitor(ROOT::Detail::RFieldVisitor &visitor) const;
725}; // class RFieldBase
726
727/// Iterates over the subtree of fields in depth-first search order
728template <bool IsConstT>
730private:
731 struct Position {
732 using FieldPtr_t = std::conditional_t<IsConstT, const RFieldBase *, RFieldBase *>;
733 Position() : fFieldPtr(nullptr), fIdxInParent(-1) {}
734 Position(FieldPtr_t fieldPtr, int idxInParent) : fFieldPtr(fieldPtr), fIdxInParent(idxInParent) {}
737 };
738 /// The stack of nodes visited when walking down the tree of fields
739 std::vector<Position> fStack;
740
741public:
743 using iterator_category = std::forward_iterator_tag;
744 using difference_type = std::ptrdiff_t;
745 using value_type = std::conditional_t<IsConstT, const RFieldBase, RFieldBase>;
746 using pointer = std::conditional_t<IsConstT, const RFieldBase *, RFieldBase *>;
747 using reference = std::conditional_t<IsConstT, const RFieldBase &, RFieldBase &>;
748
750 RSchemaIteratorTemplate(pointer val, int idxInParent) { fStack.emplace_back(Position(val, idxInParent)); }
752 /// Given that the iterator points to a valid field which is not the end iterator, go to the next field
753 /// in depth-first search order
754 void Advance()
755 {
756 auto itr = fStack.rbegin();
757 if (!itr->fFieldPtr->fSubfields.empty()) {
758 fStack.emplace_back(Position(itr->fFieldPtr->fSubfields[0].get(), 0));
759 return;
760 }
761
762 unsigned int nextIdxInParent = ++(itr->fIdxInParent);
763 while (nextIdxInParent >= itr->fFieldPtr->fParent->fSubfields.size()) {
764 if (fStack.size() == 1) {
765 itr->fFieldPtr = itr->fFieldPtr->fParent;
766 itr->fIdxInParent = -1;
767 return;
768 }
769 fStack.pop_back();
770 itr = fStack.rbegin();
771 nextIdxInParent = ++(itr->fIdxInParent);
772 }
773 itr->fFieldPtr = itr->fFieldPtr->fParent->fSubfields[nextIdxInParent].get();
774 }
775
776 iterator operator++(int) /* postfix */
777 {
778 auto r = *this;
779 Advance();
780 return r;
781 }
782 iterator &operator++() /* prefix */
783 {
784 Advance();
785 return *this;
786 }
787 reference operator*() const { return *fStack.back().fFieldPtr; }
788 pointer operator->() const { return fStack.back().fFieldPtr; }
789 bool operator==(const iterator &rh) const { return fStack.back().fFieldPtr == rh.fStack.back().fFieldPtr; }
790 bool operator!=(const iterator &rh) const { return fStack.back().fFieldPtr != rh.fStack.back().fFieldPtr; }
791};
792
793/// Points to an object with RNTuple I/O support and keeps a pointer to the corresponding field.
794/// Fields can create RValue objects through RFieldBase::CreateValue(), RFieldBase::BindValue()) or
795/// RFieldBase::SplitValue().
797 friend class RFieldBase;
798 friend class ROOT::REntry;
800
801private:
802 RFieldBase *fField = nullptr; ///< The field that created the RValue
803 /// Set by Bind() or by RFieldBase::CreateValue(), RFieldBase::SplitValue() or RFieldBase::BindValue()
804 std::shared_ptr<void> fObjPtr;
805 mutable std::atomic<const std::type_info *> fTypeInfo = nullptr;
806
807 RValue(RFieldBase *field, std::shared_ptr<void> objPtr) : fField(field), fObjPtr(std::move(objPtr)) {}
808
809public:
810 RValue(const RValue &other) : fField(other.fField), fObjPtr(other.fObjPtr) {}
811 RValue &operator=(const RValue &other)
812 {
813 fField = other.fField;
814 fObjPtr = other.fObjPtr;
815 // We could copy over the cached type info, or just start with a fresh state...
816 fTypeInfo = nullptr;
817 return *this;
818 }
819 RValue(RValue &&other) : fField(other.fField), fObjPtr(std::move(other.fObjPtr)) {}
821 {
822 fField = other.fField;
823 fObjPtr = other.fObjPtr;
824 // We could copy over the cached type info, or just start with a fresh state...
825 fTypeInfo = nullptr;
826 return *this;
827 }
828 ~RValue() = default;
829
830private:
831 template <typename T>
833 {
834 if constexpr (!std::is_void_v<T>) {
835 const std::type_info &ti = typeid(T);
836 // Fast path: if we had a matching type before, try comparing the type_info's. This may still fail in case the
837 // type has a suppressed template argument that may change the typeid.
838 auto *cachedTypeInfo = fTypeInfo.load();
839 if (cachedTypeInfo != nullptr && *cachedTypeInfo == ti) {
840 return;
841 }
842 std::string renormalizedTypeName = Internal::GetRenormalizedTypeName(ti);
843 if (Internal::IsMatchingFieldType(fField->GetTypeName(), renormalizedTypeName, ti)) {
844 fTypeInfo.store(&ti);
845 return;
846 }
847 throw RException(R__FAIL("type mismatch for field \"" + fField->GetFieldName() + "\": expected " +
848 fField->GetTypeName() + ", got " + renormalizedTypeName));
849 }
850 }
851
852 std::size_t Append() { return fField->Append(fObjPtr.get()); }
853
854public:
855 void Read(ROOT::NTupleSize_t globalIndex) { fField->Read(globalIndex, fObjPtr.get()); }
856 void Read(RNTupleLocalIndex localIndex) { fField->Read(localIndex, fObjPtr.get()); }
857
858 void Bind(std::shared_ptr<void> objPtr) { fObjPtr = std::move(objPtr); }
859 void BindRawPtr(void *rawPtr);
860 /// Replace the current object pointer by a pointer to a new object constructed by the field
861 void EmplaceNew() { fObjPtr = fField->CreateValue().GetPtr<void>(); }
862
863 template <typename T>
864 std::shared_ptr<T> GetPtr() const
865 {
866 EnsureMatchingType<T>();
867 return std::static_pointer_cast<T>(fObjPtr);
868 }
869
870 template <typename T>
871 const T &GetRef() const
872 {
873 EnsureMatchingType<T>();
874 return *static_cast<T *>(fObjPtr.get());
875 }
876
877 const RFieldBase &GetField() const { return *fField; }
878};
879
880/// Input parameter to RFieldBase::ReadBulk() and RFieldBase::ReadBulkImpl().
881// See the RBulkValues class documentation for more information.
883 /// Possible return value of ReadBulk() and ReadBulkImpl(), which indicates that the full bulk range was read
884 /// independently of the provided masks.
885 static const std::size_t kAllSet = std::size_t(-1);
886
887 RNTupleLocalIndex fFirstIndex; ///< Start of the bulk range
888 std::size_t fCount = 0; ///< Size of the bulk range
889 /// A bool array of size fCount, indicating the required values in the requested range
890 const bool *fMaskReq = nullptr;
891 bool *fMaskAvail = nullptr; ///< A bool array of size `fCount`, indicating the valid values in fValues
892 /// The destination area, which has to be an array of valid objects of the correct type large enough to hold the bulk
893 /// range.
894 void *fValues = nullptr;
895 /// Reference to memory owned by the RBulkValues class. The field implementing BulkReadImpl() may use `fAuxData` as
896 /// memory that stays persistent between calls.
897 std::vector<unsigned char> *fAuxData = nullptr;
898};
899
900// clang-format off
901/**
902\class ROOT::RFieldBase::RBulkValues
903\ingroup NTuple
904\brief Points to an array of objects with RNTuple I/O support, used for bulk reading.
905
906Similar to RValue, but manages an array of consecutive values. Bulks have to come from the same cluster.
907Bulk I/O works with two bit masks: the mask of all the available entries in the current bulk and the mask
908of the required entries in a bulk read. The idea is that a single bulk may serve multiple read operations
909on the same range, where in each read operation a different subset of values is required.
910The memory of the value array is managed by the RBulkValues class.
911*/
912// clang-format on
914private:
915 friend class RFieldBase;
916
917 RFieldBase *fField = nullptr; ///< The field that created the array of values
918 std::unique_ptr<RFieldBase::RDeleter> fDeleter; /// Cached deleter of fField
919 void *fValues = nullptr; ///< Pointer to the start of the array
920 std::size_t fValueSize = 0; ///< Cached copy of RFieldBase::GetValueSize()
921 std::size_t fCapacity = 0; ///< The size of the array memory block in number of values
922 std::size_t fSize = 0; ///< The number of available values in the array (provided their mask is set)
923 bool fIsAdopted = false; ///< True if the user provides the memory buffer for fValues
924 std::unique_ptr<bool[]> fMaskAvail; ///< Masks invalid values in the array
925 std::size_t fNValidValues = 0; ///< The sum of non-zero elements in the fMask
926 RNTupleLocalIndex fFirstIndex; ///< Index of the first value of the array
927 /// Reading arrays of complex values may require additional memory, for instance for the elements of
928 /// arrays of vectors. A pointer to the `fAuxData` array is passed to the field's BulkRead method.
929 /// The RBulkValues class does not modify the array in-between calls to the field's BulkRead method.
930 std::vector<unsigned char> fAuxData;
931
932 void ReleaseValues();
933 /// Sets a new range for the bulk. If there is enough capacity, the `fValues` array will be reused.
934 /// Otherwise a new array is allocated. After reset, fMaskAvail is false for all values.
935 void Reset(RNTupleLocalIndex firstIndex, std::size_t size);
936
937 bool ContainsRange(RNTupleLocalIndex firstIndex, std::size_t size) const
938 {
939 if (firstIndex.GetClusterId() != fFirstIndex.GetClusterId())
940 return false;
941 return (firstIndex.GetIndexInCluster() >= fFirstIndex.GetIndexInCluster()) &&
942 ((firstIndex.GetIndexInCluster() + size) <= (fFirstIndex.GetIndexInCluster() + fSize));
943 }
944
945 void *GetValuePtrAt(std::size_t idx) const { return reinterpret_cast<unsigned char *>(fValues) + idx * fValueSize; }
946
947 explicit RBulkValues(RFieldBase *field)
948 : fField(field), fDeleter(field->GetDeleter()), fValueSize(field->GetValueSize())
949 {
950 }
951
952public:
953 ~RBulkValues();
954 RBulkValues(const RBulkValues &) = delete;
956 RBulkValues(RBulkValues &&other);
958
959 // Sets `fValues` and `fSize`/`fCapacity` to the given values. The capacity is specified in number of values.
960 // Once a buffer is adopted, an attempt to read more values then available throws an exception.
961 void AdoptBuffer(void *buf, std::size_t capacity);
962
963 /// Reads `size` values from the associated field, starting from `firstIndex`. Note that the index is given
964 /// relative to a certain cluster. The return value points to the array of read objects.
965 /// The `maskReq` parameter is a bool array of at least `size` elements. Only objects for which the mask is
966 /// true are guaranteed to be read in the returned value array. A `nullptr` means to read all elements.
967 void *ReadBulk(RNTupleLocalIndex firstIndex, const bool *maskReq, std::size_t size)
968 {
969 if (!ContainsRange(firstIndex, size))
970 Reset(firstIndex, size);
971
972 // We may read a subrange of the currently available range
974
975 if (fNValidValues == fSize)
976 return GetValuePtrAt(offset);
977
978 RBulkSpec bulkSpec;
979 bulkSpec.fFirstIndex = firstIndex;
980 bulkSpec.fCount = size;
981 bulkSpec.fMaskReq = maskReq;
982 bulkSpec.fMaskAvail = &fMaskAvail[offset];
983 bulkSpec.fValues = GetValuePtrAt(offset);
984 bulkSpec.fAuxData = &fAuxData;
985 auto nRead = fField->ReadBulk(bulkSpec);
986 if (nRead == RBulkSpec::kAllSet) {
987 // We expect that field implementations consistently return kAllSet either in all cases or never. This avoids
988 // the following case where we would have to manually count how many valid values we actually have:
989 // 1. A partial ReadBulk, according to maskReq, with values potentially missing in the middle.
990 // 2. A second ReadBulk that reads a complete subrange. If this returned kAllSet, we don't know how to update
991 // fNValidValues, other than counting. The field should return a concrete number of how many new values it read
992 // in addition to those already present.
993 R__ASSERT((offset == 0) && (size == fSize));
995 } else {
996 fNValidValues += nRead;
997 }
998 return GetValuePtrAt(offset);
999 }
1000
1001 /// Overload to read all elements in the given cluster range.
1002 void *ReadBulk(ROOT::RNTupleLocalRange range) { return ReadBulk(*range.begin(), nullptr, range.size()); }
1003};
1004
1005namespace Internal {
1006// At some point, RFieldBase::OnClusterCommit() may allow for a user-defined callback to change the
1007// column representation. For now, we inject this for testing and internal use only.
1009 static void SetPrimaryColumnRepresentation(RFieldBase &field, std::uint16_t newRepresentationIdx)
1010 {
1011 R__ASSERT(newRepresentationIdx < field.fColumnRepresentatives.size());
1012 const auto N = field.fColumnRepresentatives[0].get().size();
1013 R__ASSERT(N >= 1 && N <= 2);
1015 field.fPrincipalColumn = field.fAvailableColumns[newRepresentationIdx * N].get();
1016 if (field.fAuxiliaryColumn) {
1017 R__ASSERT(N == 2);
1018 field.fAuxiliaryColumn = field.fAvailableColumns[newRepresentationIdx * N + 1].get();
1019 }
1020 }
1021};
1022} // namespace Internal
1023} // namespace ROOT
1024
1025#endif
#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
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
#define N
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 offset
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 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.
A container of const raw pointers, corresponding to a row in the data set.
A column is a storage-backed array of a simple, fixed-size type, from which pages can be mapped into ...
Definition RColumn.hxx:40
RReadColumn * ForReading()
Definition RColumn.hxx:411
Set a common string pool for all field (hierarchies) created in a block.
RFieldSharedStringPoolRaii(const std::shared_ptr< Internal::RStringPool > &pool)
std::shared_ptr< RStringPool > fOldPool
RFieldSharedStringPoolRaii(RFieldSharedStringPoolRaii &&other)=delete
RFieldSharedStringPoolRaii(const RFieldSharedStringPoolRaii &other)=delete
RFieldSharedStringPoolRaii & operator=(RFieldSharedStringPoolRaii &&other)=delete
RFieldSharedStringPoolRaii & operator=(const RFieldSharedStringPoolRaii &other)=delete
Abstract interface to write data into an ntuple.
Abstract interface to read data from an ntuple.
void Read(const ROOT::NTupleSize_t globalIndex, void *to)
Definition RColumn.hxx:131
The REntry is a collection of values in an RNTuple corresponding to a complete row in the data set.
Definition REntry.hxx:55
Base class for all ROOT issued exceptions.
Definition RError.hxx:78
Field specific extra type information from the header / extenstion header.
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 * ReadBulk(RNTupleLocalIndex firstIndex, const bool *maskReq, std::size_t size)
Reads size values from the associated field, starting from firstIndex.
void * GetValuePtrAt(std::size_t idx) const
bool ContainsRange(RNTupleLocalIndex firstIndex, std::size_t size) const
std::size_t fNValidValues
The sum of non-zero elements in the fMask.
bool fIsAdopted
True if the user provides the memory buffer for fValues.
void Reset(RNTupleLocalIndex firstIndex, std::size_t size)
Sets a new range for the bulk.
void * fValues
Cached deleter of fField.
std::size_t fCapacity
The size of the array memory block in number of values.
void * ReadBulk(ROOT::RNTupleLocalRange range)
Overload to read all elements in the given cluster range.
std::size_t fValueSize
Cached copy of RFieldBase::GetValueSize()
RFieldBase * fField
The field that created the array of values.
RBulkValues & operator=(const RBulkValues &)=delete
RBulkValues(RFieldBase *field)
std::size_t fSize
The number of available values in the array (provided their mask is set)
void AdoptBuffer(void *buf, std::size_t capacity)
std::vector< unsigned char > fAuxData
Reading arrays of complex values may require additional memory, for instance for the elements of arra...
RNTupleLocalIndex fFirstIndex
Index of the first value of the array.
RBulkValues(const RBulkValues &)=delete
The list of column representations a field can have.
const Selection_t & GetSerializationTypes() const
const Selection_t & GetDeserializationTypes() const
const ColumnRepresentation_t & GetSerializationDefault() const
The first column list from fSerializationTypes is the default for writing.
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.
A functor to release the memory acquired by CreateValue() (memory and constructor).
RDeleter(std::size_t align)
virtual void operator()(void *objPtr, bool dtorOnly)
virtual ~RDeleter()=default
void DeleteAligned(void *objPtr) const
Iterates over the subtree of fields in depth-first search order.
std::vector< Position > fStack
The stack of nodes visited when walking down the tree of fields.
bool operator==(const iterator &rh) const
std::conditional_t< IsConstT, const RFieldBase &, RFieldBase & > reference
std::conditional_t< IsConstT, const RFieldBase *, RFieldBase * > pointer
std::conditional_t< IsConstT, const RFieldBase, RFieldBase > value_type
std::forward_iterator_tag iterator_category
void Advance()
Given that the iterator points to a valid field which is not the end iterator, go to the next field i...
bool operator!=(const iterator &rh) const
RSchemaIteratorTemplate(pointer val, int idxInParent)
A deleter for templated RFieldBase descendents where the value type is known.
void operator()(void *objPtr, bool dtorOnly) final
Points to an object with RNTuple I/O support and keeps a pointer to the corresponding field.
std::shared_ptr< void > fObjPtr
Set by Bind() or by RFieldBase::CreateValue(), RFieldBase::SplitValue() or RFieldBase::BindValue()
RValue & operator=(const RValue &other)
void Read(ROOT::NTupleSize_t globalIndex)
void EmplaceNew()
Replace the current object pointer by a pointer to a new object constructed by the field.
void EnsureMatchingType() const
void Bind(std::shared_ptr< void > objPtr)
void Read(RNTupleLocalIndex localIndex)
RValue(const RValue &other)
RValue & operator=(RValue &&other)
const RFieldBase & GetField() const
std::atomic< const std::type_info * > fTypeInfo
std::shared_ptr< T > GetPtr() const
RFieldBase * fField
The field that created the RValue.
RValue(RFieldBase *field, std::shared_ptr< void > objPtr)
void BindRawPtr(void *rawPtr)
const T & GetRef() const
A field translates read and write calls from/to underlying columns to/from tree values.
ROOT::DescriptorId_t fOnDiskId
When the columns are connected to a page source or page sink, the field represents a field id in the ...
ROOT::ENTupleStructure GetStructure() const
virtual size_t GetValueSize() const =0
What sizeof(T) for this type returns.
static constexpr std::uint32_t kInvalidTypeVersion
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 size_t GetAlignment() const =0
What alignof(T) for this type returns.
virtual std::unique_ptr< RDeleter > GetDeleter() const
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)
void GenerateColumnsImpl(const ColumnRepresentation_t &representation, std::uint16_t representationIndex)
Helpers for generating columns.
std::vector< std::unique_ptr< RFieldBase > > fSubfields
Collections and classes own subfields.
std::uint32_t GetOnDiskTypeVersion() const
Return the C++ type version stored in the field descriptor; only valid after a call to ConnectPageSou...
virtual const RColumnRepresentations & GetColumnRepresentations() const
Implementations in derived classes should return a static RColumnRepresentations object.
EState
During its lifetime, a field undergoes the following possible state transitions:
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
std::unique_ptr< T, typename RCreateObjectDeleter< T >::deleter > CreateObject() const
Generates an object of the field type and allocates new initialized memory according to the type.
Definition RField.hxx:599
RFieldBase & operator=(const RFieldBase &)=delete
virtual void GenerateColumns(const ROOT::RNTupleDescriptor &)
Implementations in derived classes should create the backing columns corresponding to the field type ...
void AutoAdjustColumnTypes(const ROOT::RNTupleWriteOptions &options)
When connecting a field to a page sink, the field's default column representation is subject to adjus...
virtual void ConstructValue(void *where) const =0
Constructs value in a given location of size at least GetValueSize(). Called by the base class' Creat...
std::vector< const RFieldBase * > GetConstSubfields() const
void SetOnDiskId(ROOT::DescriptorId_t id)
void GenerateColumnsImpl(const ROOT::RNTupleDescriptor &desc)
For reading, use the on-disk column list.
virtual void GenerateColumns()
Implementations in derived classes should create the backing columns corresponding to the field type ...
void SetTypeAlias(std::string_view typeAlias)
Can only be set on unconnected fields.
void Read(RNTupleLocalIndex localIndex, void *to)
Populate a single value with data from the field.
const RFieldBase * GetParent() const
std::vector< RFieldBase * > GetMutableSubfields()
static std::unique_ptr< RDeleter > GetDeleterOf(const RFieldBase &other)
static ROOT::Internal::RColumn * GetPrincipalColumnOf(const RFieldBase &other)
Fields may need direct access to the principal column of their subfields, e.g. in RRVecField::ReadBul...
static std::vector< RCheckResult > Check(const std::string &fieldName, const std::string &typeName)
Checks if the given type is supported by RNTuple.
RSchemaIterator begin()
ROOT::Internal::RColumn * fAuxiliaryColumn
Some fields have a second column in its column representation.
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...
RSchemaIteratorTemplate< false > RSchemaIterator
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...
RFieldBase(RFieldBase &&)=default
virtual std::vector< RValue > SplitValue(const RValue &value) const
Creates the list of direct child values given an existing value for this field.
virtual std::unique_ptr< RFieldBase > CloneImpl(std::string_view newName) const =0
Called by Clone(), which additionally copies the on-disk ID.
static void CallSetArtificialOn(RFieldBase &other)
Allow parents to mark their childs as artificial fields (used in class and record fields)
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.
const std::string & GetFieldName() const
@ kTraitEmulatedField
This field is a user defined type that was missing dictionaries and was reconstructed from the on-dis...
@ kTraitTrivialType
Shorthand for types that are both trivially constructible and destructible.
@ kTraitTriviallyDestructible
The type is cleaned up just by freeing its memory. I.e. the destructor performs a no-op.
@ kTraitExtensible
Can attach new item fields even when already connected.
@ kTraitTriviallyConstructible
No constructor needs to be called, i.e.
@ kTraitSoACollection
The field represents a collection in SoA layout.
@ 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.
@ kTraitTypeChecksum
The TClass checksum is set and valid.
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....
virtual bool R__DEPRECATED(6, 46, "This queries internal state that should not be required in user code") HasReadCallbacks() const
std::vector< ROOT::ENTupleColumnType > ColumnRepresentation_t
const std::string * fTypeName
The C++ type captured by this field.
RFieldBase & operator=(RFieldBase &&)=default
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.
const std::string & GetTypeAlias() const
static void CallReadOn(RFieldBase &other, ROOT::NTupleSize_t globalIndex, void *to)
virtual ~RFieldBase()=default
static std::size_t CallAppendOn(RFieldBase &other, const void *from)
Allow derived classes to call Append() and Read() on other (sub)fields.
virtual void ReadInClusterImpl(RNTupleLocalIndex localIndex, void *to)
static std::shared_ptr< Internal::RStringPool > SetSharedStringPool(const std::shared_ptr< Internal::RStringPool > &)
Used by the SharedStringPoolRaii.
virtual void CommitClusterImpl()
std::vector< std::reference_wrapper< const ColumnRepresentation_t > > fColumnRepresentatives
Pointers into the static vector returned by RColumnRepresentations::GetSerializationTypes() when SetC...
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.
std::vector< std::unique_ptr< ROOT::Internal::RColumn > > fAvailableColumns
The columns are connected either to a sink or to a source (not to both); they are owned by the 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.
EState fState
Changed by ConnectTo[Sink,Source], reset by Clone()
static void * CallCreateObjectRawPtrOn(RFieldBase &other)
bool IsArtificial() const
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.
const std::string & GetDescription() const
Get the field's description.
virtual std::uint32_t GetFieldVersion() const
Indicates an evolution of the mapping scheme from C++ type to columns.
virtual std::unique_ptr< RFieldBase > BeforeConnectPageSource(ROOT::Internal::RPageSource &)
Called by ConnectPageSource() before connecting; derived classes may override this as appropriate,...
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),...
RSchemaIteratorTemplate< true > RConstSchemaIterator
virtual std::uint32_t GetTypeChecksum() const
Return the current TClass reported checksum of this class. Only valid if kTraitTypeChecksum is set.
bool IsSimple() const
std::uint32_t GetTraits() const
std::size_t GetNRepetitions() const
std::uint32_t fOnDiskTypeChecksum
TClass checksum cached from the descriptor after a call to ConnectPageSource().
const std::string & GetTypeName() const
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)
static void CallReadOn(RFieldBase &other, RNTupleLocalIndex localIndex, void *to)
ROOT::DescriptorId_t GetOnDiskId() const
std::uint32_t fOnDiskTypeVersion
C++ type version cached from the descriptor after a call to ConnectPageSource()
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.
static void CallConstructValueOn(const RFieldBase &other, void *where)
Allow derived classes to call ConstructValue(void *) and GetDeleter() on other (sub)fields.
EState GetState() const
void GenerateColumnsImpl()
For writing, use the currently set column representative.
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.
virtual ROOT::RExtraTypeInfoDescriptor GetExtraTypeInfo() const
virtual std::uint32_t GetTypeVersion() const
Indicates an evolution of the C++ type itself.
void * CreateObjectRawPtr() const
Factory method for the field's type. The caller owns the returned pointer.
void Read(ROOT::NTupleSize_t globalIndex, void *to)
Populate a single value with data from the field.
@ kDiffStructure
The in-memory field and the on-disk field differ in their structural roles.
@ kDiffTypeName
The in-memory field and the on-disk field have different type names.
@ kDiffTypeVersion
The in-memory field and the on-disk field differ in the type version.
@ kDiffFieldVersion
The in-memory field and the on-disk field differ in the field version.
@ kDiffNRepetitions
The in-memory field and the on-disk field have different repetition counts.
std::uint32_t GetOnDiskTypeChecksum() const
Return checksum stored in the field descriptor; only valid after a call to ConnectPageSource(),...
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...
RFieldBase(const RFieldBase &)=delete
virtual bool HasExtraTypeInfo() const
bool fIsArtificial
A field that is not backed on disk but computed, e.g.
virtual std::size_t ReadBulkImpl(const RBulkSpec &bulkSpec)
General implementation of bulk read.
bool HasDefaultColumnRepresentative() const
Whether or not an explicit column representative was set.
Metadata stored for every field of an RNTuple.
The container field for an ntuple model, which itself has no physical representation.
Definition RField.hxx:58
Class used to read a RNTupleAttrSet in the context of a RNTupleReader.
The on-storage metadata of an RNTuple.
Addresses a column element or field item relative to a particular cluster, instead of a global NTuple...
ROOT::NTupleSize_t GetIndexInCluster() const
ROOT::DescriptorId_t GetClusterId() const
Used to loop over entries of collections in a single cluster.
ROOT::NTupleSize_t size() const
RIterator begin() const
Common user-tunable settings for storing RNTuples.
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
std::shared_ptr< RStringPool > CallSetSharedStringPoolOnField(const std::shared_ptr< Internal::RStringPool > &)
void CallCommitClusterOnField(RFieldBase &)
void CallConnectPageSourceOnField(RFieldBase &, ROOT::Internal::RPageSource &)
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)
void CallFlushColumnsOnField(RFieldBase &)
std::shared_ptr< RStringPool > GetStringPoolOfField(const ROOT::RFieldBase &)
void CallSetArtificialOnField(RFieldBase &)
bool IsMatchingFieldType(const std::string &actualTypeName)
Helper to check if a given type name is the one expected of Field<T>.
Definition RField.hxx:591
std::string GetRenormalizedTypeName(const std::string &metaNormalizedName)
Given a type name normalized by ROOT meta, renormalize it for RNTuple. E.g., insert std::prefix.
constexpr bool IsValidAlignment(std::size_t align) noexcept
Return true if align is a valid C++ alignment value: strictly positive and a power of two.
Definition BitUtils.hxx:36
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...
static void SetPrimaryColumnRepresentation(RFieldBase &field, std::uint16_t newRepresentationIdx)
A pair of scoped + meta entry used by the RNTupleAttrSetWriter.
Input parameter to RFieldBase::ReadBulk() and RFieldBase::ReadBulkImpl().
static const std::size_t kAllSet
Possible return value of ReadBulk() and ReadBulkImpl(), which indicates that the full bulk range was ...
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.
std::vector< unsigned char > * fAuxData
Reference to memory owned by the RBulkValues class.
Used in the return value of the Check() method.
std::string fFieldName
Qualified field name causing the error.
std::string fTypeName
Type name corresponding to the (sub)field.
std::string fErrMsg
Cause of the failure, e.g. unsupported type.
Position(FieldPtr_t fieldPtr, int idxInParent)
std::conditional_t< IsConstT, const RFieldBase *, RFieldBase * > FieldPtr_t
RSharedPtrDeleter(std::unique_ptr< RFieldBase::RDeleter > deleter)
std::unique_ptr< RFieldBase::RDeleter > fDeleter