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