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