Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RFile.hxx
Go to the documentation of this file.
1/// \file ROOT/RFile.hxx
2/// \author Giacomo Parolini <giacomo.parolini@cern.ch>
3/// \date 2025-03-19
4/// \warning This is part of the ROOT 7 prototype! It will change without notice. Feedback
5/// is welcome!
6
7#ifndef ROOT7_RFile
8#define ROOT7_RFile
9
10#include <Compression.h>
11#include <ROOT/RError.hxx>
12
13#include <deque>
14#include <functional>
15#include <iostream>
16#include <memory>
17#include <string_view>
18#include <typeinfo>
19#include <type_traits>
20#include <variant>
21
22class TFile;
23class TIterator;
24class TKey;
25class TTree;
26
27namespace ROOT {
28namespace Experimental {
29
30class RKeyInfo;
31class RFile;
32
33namespace Internal {
34
36
37/// Returns an **owning** pointer to the object referenced by `key`. The caller must delete this pointer.
38/// This method is meant to only be used by the pythonization.
39[[nodiscard]] void *RFile_GetObjectFromKey(RFile &file, const RKeyInfo &key);
40
42
43} // namespace Internal
44
45namespace Detail {
46
47/// Given a "path-like" string (like foo/bar/baz), returns a pair `{ dirName, baseName }`.
48/// `baseName` will be empty if the string ends with '/'.
49/// `dirName` will be empty if the string contains no '/'.
50/// `dirName`, if not empty, always ends with a '/'.
51/// NOTE: this function does no semantic checking or path expansion, nor does it interact with the
52/// filesystem in any way (so it won't follow symlink or anything like that).
53/// Moreover it doesn't trim the path in any way, so any leading or trailing whitespaces will be preserved.
54/// This function does not perform any copy: the returned string_views have the same lifetime as `path`.
55std::pair<std::string_view, std::string_view> DecomposePath(std::string_view path);
56
57}
58
59class RFileKeyIterable;
60
61/**
62\class ROOT::Experimental::RKeyInfo
63\ingroup io_files
64\brief Information about an RFile object's Key.
65
66Every object inside a ROOT file has an associated "Key" which contains metadata on the object, such as its name, type
67etc.
68Querying this information can be done via RFile::ListKeys(). Reading an object's Key
69doesn't deserialize the full object, so it's a relatively lightweight operation.
70*/
71class RKeyInfo final {
74
75public:
76 enum class ECategory : std::uint16_t {
78 kObject,
80 };
81
82private:
83 std::string fPath;
84 std::string fTitle;
85 std::string fClassName;
86 std::uint16_t fCycle = 0;
88 std::uint64_t fLenObj = 0;
89 std::uint64_t fNBytesObj = 0;
90 std::uint64_t fNBytesKey = 0;
91 std::uint64_t fSeekKey = 0;
92 std::uint64_t fSeekParentDir = 0;
93
94 explicit RKeyInfo(const TKey &key);
95
96public:
97 RKeyInfo() = default;
98
99 /// Returns the absolute path of this key, i.e. the directory part plus the object name.
100 const std::string &GetPath() const { return fPath; }
101 /// Returns the base name of this key, i.e. the name of the object without the directory part.
102 std::string GetBaseName() const { return std::string(Detail::DecomposePath(fPath).second); }
103 const std::string &GetTitle() const { return fTitle; }
104 const std::string &GetClassName() const { return fClassName; }
105 std::uint16_t GetCycle() const { return fCycle; }
106 ECategory GetCategory() const { return fCategory; }
107 /// Returns the in-memory size of the uncompressed object.
108
109 std::uint64_t GetLenObj() const { return fLenObj; }
110 /// Returns the on-disk size of the (potentially compressed) object, excluding its key.
111 std::uint64_t GetNBytesObj() const { return fNBytesObj; }
112
113 /// Returns the on-disk size of this object's key.
114 std::uint64_t GetNBytesKey() const { return fNBytesKey; }
115 /// Returns the on-disk offset of this object's key.
116 std::uint64_t GetSeekKey() const { return fSeekKey; }
117
118 /// Returns the on-disk offset of this object's parent directory key.
119 std::uint64_t GetSeekParentDir() const { return fSeekParentDir; }
120};
121
122/// The iterable returned by RFile::ListKeys()
123class RFileKeyIterable final {
124 using Pattern_t = std::string;
125
126 TFile *fFile = nullptr;
128 std::uint32_t fFlags = 0;
129
130public:
131 class RIterator {
132 friend class RFileKeyIterable;
133
135 // This is ugly, but TList returns an (owning) pointer to a polymorphic TIterator...and we need this class
136 // to be copy-constructible.
137 std::shared_ptr<TIterator> fIter;
138 std::string fDirPath;
139
140 // Outlined to avoid including TIterator.h
141 RIterStackElem(TIterator *it, const std::string &path = "");
142 // Outlined to avoid including TIterator.h
144
145 // fDirPath doesn't need to be compared because it's implied by fIter.
146 bool operator==(const RIterStackElem &other) const { return fIter == other.fIter; }
147 };
148
149 // Using a deque to have pointer stability
150 std::deque<RIterStackElem> fIterStack;
152 const TKey *fCurKey = nullptr;
153 std::uint16_t fRootDirNesting = 0;
154 std::uint32_t fFlags = 0;
155
156 void Advance();
157
158 // NOTE: `iter` here is an owning pointer (or null)
159 RIterator(TIterator *iter, Pattern_t pattern, std::uint32_t flags);
160
161 public:
163 using iterator_category = std::input_iterator_tag;
164 using difference_type = std::ptrdiff_t;
166 using pointer = const value_type *;
167 using reference = const value_type &;
168
170 {
171 Advance();
172 return *this;
173 }
174 value_type operator*();
175 bool operator!=(const iterator &rh) const { return !(*this == rh); }
176 bool operator==(const iterator &rh) const { return fIterStack == rh.fIterStack; }
177 };
178
179 RFileKeyIterable(TFile *file, std::string_view rootDir, std::uint32_t flags)
180 : fFile(file), fPattern(std::string(rootDir)), fFlags(flags)
181 {
182 }
183
184 RIterator begin() const;
185 RIterator end() const;
186};
187
188/**
189\class ROOT::Experimental::RFile
190\ingroup io_files
191\brief An interface to read from, or write to, a ROOT file, as well as performing other common operations.
192
193Please refer to the documentation of TFile for the details related to how data and executable code can be stored
194in ROOT files.
195
196## When and why should you use RFile
197
198RFile is a modern and minimalistic interface to ROOT files, both local and remote, that can be used instead of TFile
199when you only need basic Put/Get operations and don't need the more advanced TFile/TDirectory functionalities.
200It provides:
201- a simple interface that makes it easy to do things right and hard to do things wrong;
202- more robustness and better error reporting for those operations;
203- clearer ownership semantics expressed through the type system.
204
205RFile doesn't cover the entirety of use cases covered by TFile/TDirectory/TDirectoryFile and is not
206a 1:1 replacement for them. It is meant to simplify the most common use cases by following newer standard C++
207practices.
208
209## Ownership model
210
211RFile handles ownership via smart pointers, typically std::unique_ptr.
212
213When getting an object from the file (via RFile::Get) you get back a unique copy of the object. Calling `Get` on the
214same object twice produces two independent clones of the object. The ownership over that object is solely on the caller
215and not shared with the RFile. Therefore, the object will remain valid after closing or destroying the RFile that
216generated it. This also means that any modification done to the object are **not** reflected to the file automatically:
217to update the object in the file you need to write it again (via RFile::Overwrite).
218
219RFile::Put and RFile::Overwrite are the way to write objects to the file. Both methods take a const reference to the
220object to write and don't change the ownership of the object in any way. Calling Put or Overwrite doesn't guarantee that
221the object is immediately written to the underlying storage: to ensure that, you need to call RFile::Flush (or close the
222file).
223
224## Directories
225
226Even though there is no equivalent of TDirectory in the RFile API, directories are still an existing concept in RFile
227(since they are a concept in the ROOT binary format). However they are for now only interacted with indirectly, via the
228use of filesystem-like string-based paths. If you Put an object in an RFile under the path "path/to/object", "object"
229will be stored under directory "to" which is in turn stored under directory "path". This hierarchy is encoded in the
230ROOT file itself and it can provide some optimization and/or conveniences when querying objects.
231
232For the most part, it is convenient to think about RFile in terms of a key-value storage where string-based paths are
233used to refer to arbitrary objects. However, given the hierarchical nature of ROOT files, certain filesystem-like
234properties are applied to paths, for ease of use: the '/' character is treated specially as the directory separator;
235multiple '/' in a row are collapsed into one (since RFile doesn't allow directories with empty names).
236
237At the moment, RFile doesn't allow getting directories via Get, nor writing ones via Put (this may change in the
238future).
239
240## Sample usage
241Opening an RFile (for writing) and writing an object to it:
242~~~{.cpp}
243auto rfile = ROOT::RFile::Recreate("my_file.root");
244auto myObj = TH1D("h", "h", 10, 0, 1);
245rfile->Put(myObj.GetName(), myObj);
246~~~
247
248Opening an RFile (for reading) and reading an object from it:
249~~~{.cpp}
250auto rfile = ROOT::RFile::Open("my_file.root");
251auto myObj = file->Get<TH1D>("h");
252~~~
253*/
254class RFile final {
255 friend void *Internal::RFile_GetObjectFromKey(RFile &file, const RKeyInfo &key);
257
258 /// Flags used in PutInternal()
259 enum PutFlags {
260 /// When encountering an object at the specified path, overwrite it with the new one instead of erroring out.
262 /// When overwriting an object, preserve the existing one and create a new cycle, rather than removing it.
264 };
265
266 std::unique_ptr<TFile> fFile;
267
268 // Outlined to avoid including TFile.h
269 explicit RFile(std::unique_ptr<TFile> file);
270
271 /// Gets object `path` from the file and returns an **owning** pointer to it.
272 /// The caller should immediately wrap it into a unique_ptr of the type described by `type`.
273 [[nodiscard]] void *GetUntyped(std::string_view path,
274 std::variant<const char *, std::reference_wrapper<const std::type_info>> type) const;
275
276 /// Writes `obj` to file, without taking its ownership.
277 void PutUntyped(std::string_view path, const std::type_info &type, const void *obj, std::uint32_t flags);
278
279 /// \see Put
280 template <typename T>
281 void PutInternal(std::string_view path, const T &obj, std::uint32_t flags)
282 {
283 PutUntyped(path, typeid(T), &obj, flags);
284 }
285
286 /// Given `path`, returns the TKey corresponding to the object at that path (assuming the path is fully split, i.e.
287 /// "a/b/c" always means "object 'c' inside directory 'b' inside directory 'a'").
288 /// IMPORTANT: `path` must have been validated/normalized via ValidateAndNormalizePath() (see RFile.cxx).
289 TKey *GetTKey(std::string_view path) const;
290
291public:
293 kListObjects = 1 << 0,
294 kListDirs = 1 << 1,
296 };
297
299 /// See core/zip/inc/Compression.h for the meaning of the `compression` argument.
300 /// Default compression is 505 (ZSTD level 10).
302 /// If true the RFile will show up in the TBrowser window. This causes the file to also be added
303 /// to the list of global files. Set to false to prevent this global registration.
305
307 };
308
310 /// If true the RFile will show up in the TBrowser window. This causes the file to also be added
311 /// to the list of global files. Set to false to prevent this global registration.
313
315 };
316
318 /// If true the RFile will show up in the TBrowser window. This causes the file to also be added
319 /// to the list of global files. Set to false to prevent this global registration.
321
323 };
324
325 // This is arbitrary, but it's useful to avoid pathological cases
326 static constexpr int kMaxPathNesting = 1000;
327
328 ///// Factory methods /////
329
330 /// Opens the file for reading. `path` may be a regular file path or a remote URL.
331 /// \throw ROOT::RException if the file at `path` could not be opened.
332 static std::unique_ptr<RFile> Open(std::string_view path, const ROpenOptions &opts = ROpenOptions());
333
334 /// Opens the file for reading/writing, overwriting it if it already exists.
335 /// \throw ROOT::RException if a file could not be created at `path` (e.g. if the specified
336 /// directory tree does not exist).
337 static std::unique_ptr<RFile> Recreate(std::string_view path, const RRecreateOptions &opts = RRecreateOptions());
338
339 /// Opens the file for updating, creating a new one if it doesn't exist.
340 /// \throw ROOT::RException if the file at `path` could neither be read nor created
341 /// (e.g. if the specified directory tree does not exist).
342 static std::unique_ptr<RFile> Update(std::string_view path, const RUpdateOptions &opts = RUpdateOptions());
343
344 ///// Instance methods /////
345
346 // Outlined to avoid including TFile.h
348
349 /// Retrieves an object from the file.
350 /// `path` should be a string such that `IsValidPath(path) == true`, otherwise an exception will be thrown.
351 /// See \ref ValidateAndNormalizePath() for info about valid path names.
352 /// If the object is not there returns a null pointer.
353 template <typename T>
354 std::unique_ptr<T> Get(std::string_view path) const
355 {
356 void *obj = GetUntyped(path, typeid(T));
357 return std::unique_ptr<T>(static_cast<T *>(obj));
358 }
359
360 /// Puts an object into the file.
361 /// The application retains ownership of the object.
362 /// `path` should be a string such that `IsValidPath(path) == true`, otherwise an exception will be thrown.
363 /// See \ref ValidateAndNormalizePath() for info about valid path names.
364 ///
365 /// Throws a RException if `path` already identifies a valid object or directory.
366 /// Throws a RException if the file was opened in read-only mode.
367 template <typename T>
368 void Put(std::string_view path, const T &obj)
369 {
370 static_assert(!std::is_base_of_v<TTree, T>, "Writing TTree with RFile is unsupported.");
371 PutInternal(path, obj, /* flags = */ 0);
372 }
373
374 /// Puts an object into the file, overwriting any previously-existing object at that path.
375 /// The application retains ownership of the object.
376 ///
377 /// If an object already exists at that path, it is kept as a backup cycle unless `backupPrevious` is false.
378 /// Note that even if `backupPrevious` is false, any existing cycle except the latest will be preserved.
379 ///
380 /// Throws a RException if `path` is already the path of a directory.
381 /// Throws a RException if the file was opened in read-only mode.
382 template <typename T>
383 void Overwrite(std::string_view path, const T &obj, bool backupPrevious = true)
384 {
385 static_assert(!std::is_base_of_v<TTree, T>, "Writing TTree with RFile is unsupported.");
386 std::uint32_t flags = kPutAllowOverwrite;
387 flags |= backupPrevious * kPutOverwriteKeepCycle;
388 PutInternal(path, obj, flags);
389 }
390
391 /// Writes all objects and the file structure to disk.
392 /// Returns the number of bytes written.
393 size_t Flush();
394
395 /// Flushes the RFile if needed and closes it, disallowing any further reading or writing.
396 void Close();
397
398 /// Returns an iterable over all keys of objects and/or directories written into this RFile starting at path
399 /// `basePath` (defaulting to include the content of all subdirectories).
400 /// By default, keys referring to directories are not returned: only those referring to leaf objects are.
401 /// If `basePath` is the path of a leaf object, only `basePath` itself will be returned.
402 /// If `basePath` is the path of a directory, it won't appear in the listing.
403 /// `flags` is a bitmask specifying the listing mode.
404 /// If `(flags & kListObjects) != 0`, the listing will include keys of non-directory objects (default);
405 /// If `(flags & kListDirs) != 0`, the listing will include keys of directory objects;
406 /// If `(flags & kListRecursive) != 0`, the listing will recurse on all subdirectories of `basePath` (default),
407 /// otherwise it will only list immediate children of `basePath`.
408 ///
409 /// Example usage:
410 /// ~~~{.cpp}
411 /// for (RKeyInfo key : file->ListKeys()) {
412 /// /* iterate over all objects in the RFile */
413 /// cout << key.GetPath() << ";" << key.GetCycle() << " of type " << key.GetClassName() << "\n";
414 /// }
415 /// for (RKeyInfo key : file->ListKeys("", kListDirs|kListObjects|kListRecursive)) {
416 /// /* iterate over all objects and directories in the RFile */
417 /// }
418 /// for (RKeyInfo key : file->ListKeys("a/b", kListObjects)) {
419 /// /* iterate over all objects that are immediate children of directory "a/b" */
420 /// }
421 /// for (RKeyInfo key : file->ListKeys("foo", kListDirs|kListRecursive)) {
422 /// /* iterate over all directories under directory "foo", recursively */
423 /// }
424 /// ~~~
425 RFileKeyIterable ListKeys(std::string_view basePath = "", std::uint32_t flags = kListObjects | kListRecursive) const
426 {
427 return RFileKeyIterable(fFile.get(), basePath, flags);
428 }
429
430 /// Retrieves information about the key of object at `path`, if one exists.
431 std::optional<RKeyInfo> GetKeyInfo(std::string_view path) const;
432
433 /// Prints the internal structure of this RFile to the given stream.
434 void Print(std::ostream &out = std::cout) const;
435};
436
437} // namespace Experimental
438} // namespace ROOT
439
440#endif
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
bool operator==(const iterator &rh) const
Definition RFile.hxx:176
bool operator!=(const iterator &rh) const
Definition RFile.hxx:175
std::deque< RIterStackElem > fIterStack
Definition RFile.hxx:150
RIterator(TIterator *iter, Pattern_t pattern, std::uint32_t flags)
Definition RFile.cxx:409
The iterable returned by RFile::ListKeys()
Definition RFile.hxx:123
RFileKeyIterable(TFile *file, std::string_view rootDir, std::uint32_t flags)
Definition RFile.hxx:179
An interface to read from, or write to, a ROOT file, as well as performing other common operations.
Definition RFile.hxx:254
void Close()
Flushes the RFile if needed and closes it, disallowing any further reading or writing.
Definition RFile.cxx:544
static std::unique_ptr< RFile > Open(std::string_view path, const ROpenOptions &opts=ROpenOptions())
Opens the file for reading.
Definition RFile.cxx:204
static constexpr int kMaxPathNesting
Definition RFile.hxx:326
std::unique_ptr< TFile > fFile
Definition RFile.hxx:266
size_t Flush()
Writes all objects and the file structure to disk.
Definition RFile.cxx:539
void Print(std::ostream &out=std::cout) const
Prints the internal structure of this RFile to the given stream.
Definition RFile.cxx:525
void PutInternal(std::string_view path, const T &obj, std::uint32_t flags)
Definition RFile.hxx:281
TKey * GetTKey(std::string_view path) const
Given path, returns the TKey corresponding to the object at that path (assuming the path is fully spl...
Definition RFile.cxx:241
std::optional< RKeyInfo > GetKeyInfo(std::string_view path) const
Retrieves information about the key of object at path, if one exists.
Definition RFile.cxx:563
std::unique_ptr< T > Get(std::string_view path) const
Retrieves an object from the file.
Definition RFile.hxx:354
void * GetUntyped(std::string_view path, std::variant< const char *, std::reference_wrapper< const std::type_info > > type) const
Gets object path from the file and returns an owning pointer to it.
Definition RFile.cxx:286
static std::unique_ptr< RFile > Recreate(std::string_view path, const RRecreateOptions &opts=RRecreateOptions())
Opens the file for reading/writing, overwriting it if it already exists.
Definition RFile.cxx:226
void Overwrite(std::string_view path, const T &obj, bool backupPrevious=true)
Puts an object into the file, overwriting any previously-existing object at that path.
Definition RFile.hxx:383
void PutUntyped(std::string_view path, const std::type_info &type, const void *obj, std::uint32_t flags)
Writes obj to file, without taking its ownership.
Definition RFile.cxx:331
PutFlags
Flags used in PutInternal()
Definition RFile.hxx:259
@ kPutOverwriteKeepCycle
When overwriting an object, preserve the existing one and create a new cycle, rather than removing it...
Definition RFile.hxx:263
@ kPutAllowOverwrite
When encountering an object at the specified path, overwrite it with the new one instead of erroring ...
Definition RFile.hxx:261
RFileKeyIterable ListKeys(std::string_view basePath="", std::uint32_t flags=kListObjects|kListRecursive) const
Returns an iterable over all keys of objects and/or directories written into this RFile starting at p...
Definition RFile.hxx:425
void Put(std::string_view path, const T &obj)
Puts an object into the file.
Definition RFile.hxx:368
RFile(std::unique_ptr< TFile > file)
Definition RFile.cxx:237
static std::unique_ptr< RFile > Update(std::string_view path, const RUpdateOptions &opts=RUpdateOptions())
Opens the file for updating, creating a new one if it doesn't exist.
Definition RFile.cxx:215
Information about an RFile object's Key.
Definition RFile.hxx:71
const std::string & GetClassName() const
Definition RFile.hxx:104
std::uint64_t GetNBytesKey() const
Returns the on-disk size of this object's key.
Definition RFile.hxx:114
std::uint64_t fNBytesObj
Definition RFile.hxx:89
std::uint64_t fNBytesKey
Definition RFile.hxx:90
const std::string & GetTitle() const
Definition RFile.hxx:103
std::uint64_t fSeekParentDir
Definition RFile.hxx:92
ECategory GetCategory() const
Definition RFile.hxx:106
std::uint64_t GetSeekParentDir() const
Returns the on-disk offset of this object's parent directory key.
Definition RFile.hxx:119
std::string GetBaseName() const
Returns the base name of this key, i.e. the name of the object without the directory part.
Definition RFile.hxx:102
std::uint16_t GetCycle() const
Definition RFile.hxx:105
const std::string & GetPath() const
Returns the absolute path of this key, i.e. the directory part plus the object name.
Definition RFile.hxx:100
std::uint64_t GetSeekKey() const
Returns the on-disk offset of this object's key.
Definition RFile.hxx:116
std::uint64_t GetLenObj() const
Returns the in-memory size of the uncompressed object.
Definition RFile.hxx:109
std::uint64_t GetNBytesObj() const
Returns the on-disk size of the (potentially compressed) object, excluding its key.
Definition RFile.hxx:111
A log configuration for a channel, e.g.
Definition RLogger.hxx:97
A file, usually with extension .root, that stores data and code in the form of serialized objects in ...
Definition TFile.h:130
Iterator abstract base class.
Definition TIterator.h:30
Book space in a file, create I/O buffers, to fill them, (un)compress them.
Definition TKey.h:28
A TTree represents a columnar dataset.
Definition TTree.h:95
std::pair< std::string_view, std::string_view > DecomposePath(std::string_view path)
Given a "path-like" string (like foo/bar/baz), returns a pair { dirName, baseName }.
Definition RFile.cxx:193
ROOT::RLogChannel & RFileLog()
Definition RFile.cxx:24
void * RFile_GetObjectFromKey(RFile &file, const RKeyInfo &key)
Returns an owning pointer to the object referenced by key.
Definition RFile.cxx:573
TFile * GetRFileTFile(RFile &rfile)
Definition RFile.cxx:579
bool operator==(const RIterStackElem &other) const
Definition RFile.hxx:146
RIterStackElem(TIterator *it, const std::string &path="")
Definition RFile.cxx:402
bool fEnableBrowsability
If true the RFile will show up in the TBrowser window.
Definition RFile.hxx:312
bool fEnableBrowsability
If true the RFile will show up in the TBrowser window.
Definition RFile.hxx:304
int fCompressionSettings
See core/zip/inc/Compression.h for the meaning of the compression argument.
Definition RFile.hxx:301
bool fEnableBrowsability
If true the RFile will show up in the TBrowser window.
Definition RFile.hxx:320
@ kUseGeneralPurpose
Use the new recommended general-purpose setting; it is a best trade-off between compression ratio/dec...
Definition Compression.h:58