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