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