Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RMiniFile.cxx
Go to the documentation of this file.
1/// \file RMiniFile.cxx
2/// \author Jakob Blomer <jblomer@cern.ch>
3/// \date 2019-12-22
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#include "Rtypes.h"
14#include <ROOT/RConfig.hxx>
15#include <ROOT/RError.hxx>
16#include <ROOT/RMiniFile.hxx>
17#include <ROOT/RRawFile.hxx>
18#include <ROOT/RNTupleUtils.hxx>
19#include <ROOT/RNTupleZip.hxx>
22#include <ROOT/RFile.hxx>
23
24#include <Byteswap.h>
25#include <TBufferFile.h>
26#include <TDirectory.h>
27#include <TError.h>
28#include <TFile.h>
29#include <TKey.h>
30#include <TObjString.h>
31#include <TUUID.h>
32#include <TStreamerInfo.h>
33
34#include <xxhash.h>
35
36#include <algorithm>
37#include <cassert>
38#include <cerrno>
39#include <cstdio>
40#include <cstring>
41#include <memory>
42#include <string>
43#include <chrono>
44
45#ifdef R__LINUX
46#include <fcntl.h>
47#endif
48
49#ifndef R__LITTLE_ENDIAN
50#ifdef R__BYTESWAP
51// `R__BYTESWAP` is defined in RConfig.hxx for little-endian architectures; undefined otherwise
52#define R__LITTLE_ENDIAN 1
53#else
54#define R__LITTLE_ENDIAN 0
55#endif
56#endif /* R__LITTLE_ENDIAN */
57
58namespace {
59
60// The following types are used to read and write the TFile binary format
61
62/// Big-endian 16-bit unsigned integer
63class RUInt16BE {
64private:
65 std::uint16_t fValBE = 0;
66 static std::uint16_t Swap(std::uint16_t val)
67 {
68#if R__LITTLE_ENDIAN == 1
69 return RByteSwap<sizeof(val)>::bswap(val);
70#else
71 return val;
72#endif
73 }
74
75public:
76 RUInt16BE() = default;
77 explicit RUInt16BE(const std::uint16_t val) : fValBE(Swap(val)) {}
78 operator std::uint16_t() const { return Swap(fValBE); }
79 RUInt16BE &operator=(const std::uint16_t val)
80 {
81 fValBE = Swap(val);
82 return *this;
83 }
84};
85
86/// Big-endian 32-bit unsigned integer
87class RUInt32BE {
88private:
89 std::uint32_t fValBE = 0;
90 static std::uint32_t Swap(std::uint32_t val)
91 {
92#if R__LITTLE_ENDIAN == 1
93 return RByteSwap<sizeof(val)>::bswap(val);
94#else
95 return val;
96#endif
97 }
98
99public:
100 RUInt32BE() = default;
101 explicit RUInt32BE(const std::uint32_t val) : fValBE(Swap(val)) {}
102 operator std::uint32_t() const { return Swap(fValBE); }
103 RUInt32BE &operator=(const std::uint32_t val)
104 {
105 fValBE = Swap(val);
106 return *this;
107 }
108};
109
110/// Big-endian 32-bit signed integer
111class RInt32BE {
112private:
113 std::int32_t fValBE = 0;
114 static std::int32_t Swap(std::int32_t val)
115 {
116#if R__LITTLE_ENDIAN == 1
117 return RByteSwap<sizeof(val)>::bswap(val);
118#else
119 return val;
120#endif
121 }
122
123public:
124 RInt32BE() = default;
125 explicit RInt32BE(const std::int32_t val) : fValBE(Swap(val)) {}
126 operator std::int32_t() const { return Swap(fValBE); }
127 RInt32BE &operator=(const std::int32_t val)
128 {
129 fValBE = Swap(val);
130 return *this;
131 }
132};
133
134/// Big-endian 64-bit unsigned integer
135class RUInt64BE {
136private:
137 std::uint64_t fValBE = 0;
138 static std::uint64_t Swap(std::uint64_t val)
139 {
140#if R__LITTLE_ENDIAN == 1
141 return RByteSwap<sizeof(val)>::bswap(val);
142#else
143 return val;
144#endif
145 }
146
147public:
148 RUInt64BE() = default;
149 explicit RUInt64BE(const std::uint64_t val) : fValBE(Swap(val)) {}
150 operator std::uint64_t() const { return Swap(fValBE); }
151 RUInt64BE &operator=(const std::uint64_t val)
152 {
153 fValBE = Swap(val);
154 return *this;
155 }
156};
157
158/// A name (type, identifier, ...) in the TFile binary format, serialized as by TBufferFile::WriteTString():
159/// strings with up to 254 characters are prefixed by a one byte length. Longer strings are prefixed by the byte 255
160/// followed by the length as a 32-bit big-endian integer.
161/// In contrast to other "RTF..." classes, this class itself does not correspond to the on-disk byte layout but
162/// its string member fSerialized does.
163class RTFString {
164 std::string fSerialized;
165
166public:
167 static constexpr unsigned char kLongStringMarker = 255;
168
169 RTFString() : fSerialized(1, '\0') {}
170 RTFString(std::string_view str)
171 {
172 if (str.length() < kLongStringMarker) {
173 fSerialized.push_back(static_cast<char>(str.length()));
174 } else {
175 if (str.length() > static_cast<std::size_t>(std::numeric_limits<std::int32_t>::max()))
176 throw ROOT::RException(R__FAIL("string too long for the TFile format"));
177 RInt32BE length{static_cast<std::int32_t>(str.length())};
178 fSerialized.push_back(static_cast<char>(kLongStringMarker));
179 fSerialized.append(reinterpret_cast<const char *>(&length), sizeof(length));
180 }
181 fSerialized.append(str);
182 }
183 /// The size of the serialized string, including the length prefix
184 std::size_t GetSize() const { return fSerialized.size(); }
185 const char *GetData() const { return fSerialized.data(); }
186};
187
188#pragma pack(push, 1)
189/// The timestamp format used in TFile; the default constructor initializes with the current time
190struct RTFDatetime {
191 RUInt32BE fDatetime;
192 RTFDatetime()
193 {
194 auto now = std::chrono::system_clock::now();
195 auto tt = std::chrono::system_clock::to_time_t(now);
196 auto tm = *localtime(&tt);
197 fDatetime = (tm.tm_year + 1900 - 1995) << 26 | (tm.tm_mon + 1) << 22 | tm.tm_mday << 17 | tm.tm_hour << 12 |
198 tm.tm_min << 6 | tm.tm_sec;
199 }
200 explicit RTFDatetime(RUInt32BE val) : fDatetime(val) {}
201};
202
203/// The key part of a TFile record excluding the class, object, and title names
204struct RTFKey {
205 static constexpr unsigned kBigKeyVersion = 1000;
206
207 RInt32BE fNbytes{0};
208 RUInt16BE fVersion{4};
209 RUInt32BE fObjLen{0};
210 RTFDatetime fDatetime;
211 RUInt16BE fKeyLen{0};
212 RUInt16BE fCycle{1};
213 union {
214 struct {
215 RUInt32BE fSeekKey{0};
216 RUInt32BE fSeekPdir{0};
217 } fInfoShort;
218 struct {
219 RUInt64BE fSeekKey{0};
220 RUInt64BE fSeekPdir{0};
221 } fInfoLong;
222 };
223
224 RTFKey() : fInfoLong() {}
225 RTFKey(std::uint64_t seekKey, std::uint64_t seekPdir, const RTFString &clName, const RTFString &objName,
226 const RTFString &titleName, std::size_t szObjInMem, std::size_t szObjOnDisk = 0)
227 {
228 R__ASSERT(szObjInMem <= std::numeric_limits<std::uint32_t>::max());
229 R__ASSERT(szObjOnDisk <= std::numeric_limits<std::uint32_t>::max());
230 // For writing, we always produce "big" keys with 64-bit SeekKey and SeekPdir.
231 fVersion = fVersion + kBigKeyVersion;
232 fObjLen = szObjInMem;
233 const auto keyLen = GetHeaderSize() + clName.GetSize() + objName.GetSize() + titleName.GetSize();
234 // TKey stores the key length as a signed 16-bit integer
235 if (keyLen > static_cast<std::size_t>(std::numeric_limits<std::int16_t>::max()))
236 throw ROOT::RException(R__FAIL("TFile key header too long: " + std::to_string(keyLen) + " bytes"));
237 fKeyLen = static_cast<std::uint16_t>(keyLen);
238 fInfoLong.fSeekKey = seekKey;
239 fInfoLong.fSeekPdir = seekPdir;
240 // Depends on fKeyLen being set
241 fNbytes = fKeyLen + ((szObjOnDisk == 0) ? szObjInMem : szObjOnDisk);
242 }
243
244 std::uint32_t GetSize() const
245 {
246 // Negative size indicates a gap in the file
247 if (fNbytes < 0)
248 return -fNbytes;
249 return fNbytes;
250 }
251
252 std::uint32_t GetHeaderSize() const
253 {
254 if (fVersion >= kBigKeyVersion)
255 return 18 + sizeof(fInfoLong);
256 return 18 + sizeof(fInfoShort);
257 }
258
259 std::uint64_t GetSeekKey() const
260 {
261 if (fVersion >= kBigKeyVersion)
262 return fInfoLong.fSeekKey;
263 return fInfoShort.fSeekKey;
264 }
265};
266
267/// The TFile global header
268struct RTFHeader {
269 static constexpr unsigned kBEGIN = 100;
270 static constexpr unsigned kBigHeaderVersion = 1000000;
271
272 char fMagic[4]{'r', 'o', 'o', 't'};
273 RUInt32BE fVersion{(ROOT_VERSION_CODE >> 16) * 10000 + ((ROOT_VERSION_CODE & 0xFF00) >> 8) * 100 +
274 (ROOT_VERSION_CODE & 0xFF)};
275 RUInt32BE fBEGIN{kBEGIN};
276 union {
277 struct {
278 RUInt32BE fEND{0};
279 RUInt32BE fSeekFree{0};
280 RUInt32BE fNbytesFree{0};
281 RUInt32BE fNfree{1};
282 RUInt32BE fNbytesName{0};
283 unsigned char fUnits{4};
284 RUInt32BE fCompress{0};
285 RUInt32BE fSeekInfo{0};
286 RUInt32BE fNbytesInfo{0};
287 } fInfoShort;
288 struct {
289 RUInt64BE fEND{0};
290 RUInt64BE fSeekFree{0};
291 RUInt32BE fNbytesFree{0};
292 RUInt32BE fNfree{1};
293 RUInt32BE fNbytesName{0};
294 unsigned char fUnits{8};
295 RUInt32BE fCompress{0};
296 RUInt64BE fSeekInfo{0};
297 RUInt32BE fNbytesInfo{0};
298 } fInfoLong;
299 };
300
301 RTFHeader() : fInfoShort() {}
302 RTFHeader(int compression) : fInfoShort() { fInfoShort.fCompress = compression; }
303
304 void SetBigFile()
305 {
306 if (fVersion >= kBigHeaderVersion)
307 return;
308
309 // clang-format off
310 std::uint32_t end = fInfoShort.fEND;
311 std::uint32_t seekFree = fInfoShort.fSeekFree;
312 std::uint32_t nbytesFree = fInfoShort.fNbytesFree;
313 std::uint32_t nFree = fInfoShort.fNfree;
314 std::uint32_t nbytesName = fInfoShort.fNbytesName;
315 std::uint32_t compress = fInfoShort.fCompress;
316 std::uint32_t seekInfo = fInfoShort.fSeekInfo;
317 std::uint32_t nbytesInfo = fInfoShort.fNbytesInfo;
318 fInfoLong.fEND = end;
319 fInfoLong.fSeekFree = seekFree;
320 fInfoLong.fNbytesFree = nbytesFree;
321 fInfoLong.fNfree = nFree;
322 fInfoLong.fNbytesName = nbytesName;
323 fInfoLong.fUnits = 8;
324 fInfoLong.fCompress = compress;
325 fInfoLong.fSeekInfo = seekInfo;
326 fInfoLong.fNbytesInfo = nbytesInfo;
327 fVersion = fVersion + kBigHeaderVersion;
328 // clang-format on
329 }
330
331 bool IsBigFile(std::uint64_t offset = 0) const
332 {
333 return (fVersion >= kBigHeaderVersion) ||
334 (offset > static_cast<unsigned int>(std::numeric_limits<std::int32_t>::max()));
335 }
336
337 std::uint32_t GetSize() const
338 {
339 std::uint32_t sizeHead = sizeof(fMagic) + sizeof(fVersion) + sizeof(fBEGIN);
340 if (IsBigFile())
341 return sizeHead + sizeof(fInfoLong);
342 return sizeHead + sizeof(fInfoShort);
343 }
344
345 std::uint64_t GetEnd() const
346 {
347 if (IsBigFile())
348 return fInfoLong.fEND;
349 return fInfoShort.fEND;
350 }
351
352 void SetEnd(std::uint64_t value)
353 {
354 if (IsBigFile(value)) {
355 SetBigFile();
356 fInfoLong.fEND = value;
357 } else {
358 fInfoShort.fEND = value;
359 }
360 }
361
362 std::uint64_t GetSeekFree() const
363 {
364 if (IsBigFile())
365 return fInfoLong.fSeekFree;
366 return fInfoShort.fSeekFree;
367 }
368
369 void SetSeekFree(std::uint64_t value)
370 {
371 if (IsBigFile(value)) {
372 SetBigFile();
373 fInfoLong.fSeekFree = value;
374 } else {
375 fInfoShort.fSeekFree = value;
376 }
377 }
378
379 void SetNbytesFree(std::uint32_t value)
380 {
381 if (IsBigFile()) {
382 fInfoLong.fNbytesFree = value;
383 } else {
384 fInfoShort.fNbytesFree = value;
385 }
386 }
387
388 void SetNbytesName(std::uint32_t value)
389 {
390 if (IsBigFile()) {
391 fInfoLong.fNbytesName = value;
392 } else {
393 fInfoShort.fNbytesName = value;
394 }
395 }
396
397 std::uint64_t GetSeekInfo() const
398 {
399 if (IsBigFile())
400 return fInfoLong.fSeekInfo;
401 return fInfoShort.fSeekInfo;
402 }
403
404 void SetSeekInfo(std::uint64_t value)
405 {
406 if (IsBigFile(value)) {
407 SetBigFile();
408 fInfoLong.fSeekInfo = value;
409 } else {
410 fInfoShort.fSeekInfo = value;
411 }
412 }
413
414 std::uint64_t GetNbytesInfo() const
415 {
416 if (IsBigFile())
417 return fInfoLong.fNbytesInfo;
418 return fInfoShort.fNbytesInfo;
419 }
420
421 void SetNbytesInfo(std::uint32_t value)
422 {
423 if (IsBigFile()) {
424 fInfoLong.fNbytesInfo = value;
425 } else {
426 fInfoShort.fNbytesInfo = value;
427 }
428 }
429
430 void SetCompression(std::uint32_t value)
431 {
432 if (IsBigFile()) {
433 fInfoLong.fCompress = value;
434 } else {
435 fInfoShort.fCompress = value;
436 }
437 }
438};
439
440/// A reference to an unused byte-range in a TFile
441struct RTFFreeEntry {
442 static constexpr unsigned kBigFreeEntryVersion = 1000;
443
444 RUInt16BE fVersion{1};
445 union {
446 struct {
447 RUInt32BE fFirst{0};
448 RUInt32BE fLast{0};
449 } fInfoShort;
450 struct {
451 RUInt64BE fFirst{0};
452 RUInt64BE fLast{0};
453 } fInfoLong;
454 };
455
456 RTFFreeEntry() : fInfoShort() {}
457 void Set(std::uint64_t first, std::uint64_t last)
458 {
459 if (last > static_cast<unsigned int>(std::numeric_limits<std::int32_t>::max())) {
460 fVersion = fVersion + kBigFreeEntryVersion;
461 fInfoLong.fFirst = first;
462 fInfoLong.fLast = last;
463 } else {
464 fInfoShort.fFirst = first;
465 fInfoShort.fLast = last;
466 }
467 }
468 std::uint32_t GetSize() { return (fVersion >= kBigFreeEntryVersion) ? 18 : 10; }
469};
470
471/// The header of the directory key index
472struct RTFKeyList {
473 RUInt32BE fNKeys;
474 std::uint32_t GetSize() const { return sizeof(RTFKeyList); }
475 explicit RTFKeyList(std::uint32_t nKeys) : fNKeys(nKeys) {}
476};
477
478/// A streamed TDirectory (TFile) object
479struct RTFDirectory {
480 static constexpr unsigned kBigFileVersion = 1000;
481
482 RUInt16BE fClassVersion{5};
483 RTFDatetime fDateC;
484 RTFDatetime fDateM;
485 RUInt32BE fNBytesKeys{0};
486 RUInt32BE fNBytesName{0};
487 // The version of the key has to tell whether offsets are 32bit or 64bit long
488 union {
489 struct {
490 RUInt32BE fSeekDir{RTFHeader::kBEGIN};
491 RUInt32BE fSeekParent{0};
492 RUInt32BE fSeekKeys{0};
493 } fInfoShort;
494 struct {
495 RUInt64BE fSeekDir{RTFHeader::kBEGIN};
496 RUInt64BE fSeekParent{0};
497 RUInt64BE fSeekKeys{0};
498 } fInfoLong;
499 };
500
501 RTFDirectory() : fInfoShort() {}
502
503 // In case of a short TFile record (<2G), 3 padding ints are written after the UUID
504 std::uint32_t GetSize() const
505 {
506 if (fClassVersion >= kBigFileVersion)
507 return sizeof(RTFDirectory);
508 return 18 + sizeof(fInfoShort);
509 }
510
511 std::uint64_t GetSeekKeys() const
512 {
513 if (fClassVersion >= kBigFileVersion)
514 return fInfoLong.fSeekKeys;
515 return fInfoShort.fSeekKeys;
516 }
517
518 void SetSeekKeys(std::uint64_t seekKeys)
519 {
520 if (seekKeys > static_cast<unsigned int>(std::numeric_limits<std::int32_t>::max())) {
521 std::uint32_t seekDir = fInfoShort.fSeekDir;
522 std::uint32_t seekParent = fInfoShort.fSeekParent;
523 fInfoLong.fSeekDir = seekDir;
524 fInfoLong.fSeekParent = seekParent;
525 fInfoLong.fSeekKeys = seekKeys;
526 fClassVersion = fClassVersion + kBigFileVersion;
527 } else {
528 fInfoShort.fSeekKeys = seekKeys;
529 }
530 }
531};
532
533/// A zero UUID stored at the end of the TFile record
534struct RTFUUID {
535 RUInt16BE fVersionClass{1};
536 unsigned char fUUID[16];
537
538 RTFUUID()
539 {
540 TUUID uuid{TUUID::UUIDv4()};
541 char *buffer = reinterpret_cast<char *>(this);
542 uuid.FillBuffer(buffer);
543 assert(reinterpret_cast<RTFUUID *>(buffer) <= (this + 1));
544 }
545 std::uint32_t GetSize() const { return sizeof(RTFUUID); }
546};
547
548/// A streamed RNTuple class
549///
550/// NOTE: this must be kept in sync with RNTuple.hxx.
551/// Aside ensuring consistency between the two classes' members, you need to make sure
552/// that fVersionClass matches the class version of RNTuple.
553struct RTFNTuple {
554 RUInt32BE fByteCount{0x40000000 | (sizeof(RTFNTuple) - sizeof(fByteCount))};
555 RUInt16BE fVersionClass{2};
556 RUInt16BE fVersionEpoch{0};
557 RUInt16BE fVersionMajor{0};
558 RUInt16BE fVersionMinor{0};
559 RUInt16BE fVersionPatch{0};
560 RUInt64BE fSeekHeader{0};
561 RUInt64BE fNBytesHeader{0};
562 RUInt64BE fLenHeader{0};
563 RUInt64BE fSeekFooter{0};
564 RUInt64BE fNBytesFooter{0};
565 RUInt64BE fLenFooter{0};
566 RUInt64BE fMaxKeySize{0};
567
568 static constexpr std::uint32_t GetSizePlusChecksum() { return sizeof(RTFNTuple) + sizeof(std::uint64_t); }
569
570 RTFNTuple() = default;
571 explicit RTFNTuple(const ROOT::RNTuple &inMemoryAnchor)
572 {
573 fVersionEpoch = inMemoryAnchor.GetVersionEpoch();
574 fVersionMajor = inMemoryAnchor.GetVersionMajor();
575 fVersionMinor = inMemoryAnchor.GetVersionMinor();
576 fVersionPatch = inMemoryAnchor.GetVersionPatch();
577 fSeekHeader = inMemoryAnchor.GetSeekHeader();
578 fNBytesHeader = inMemoryAnchor.GetNBytesHeader();
579 fLenHeader = inMemoryAnchor.GetLenHeader();
580 fSeekFooter = inMemoryAnchor.GetSeekFooter();
581 fNBytesFooter = inMemoryAnchor.GetNBytesFooter();
582 fLenFooter = inMemoryAnchor.GetLenFooter();
583 fMaxKeySize = inMemoryAnchor.GetMaxKeySize();
584 }
585 std::uint32_t GetSize() const { return sizeof(RTFNTuple); }
586 // The byte count and class version members are not checksummed
587 std::uint32_t GetOffsetCkData() { return sizeof(fByteCount) + sizeof(fVersionClass); }
588 std::uint32_t GetSizeCkData() { return GetSize() - GetOffsetCkData(); }
589 unsigned char *GetPtrCkData() { return reinterpret_cast<unsigned char *>(this) + GetOffsetCkData(); }
590};
591
592/// The bare file global header
593struct RBareFileHeader {
594 char fMagic[7]{'r', 'n', 't', 'u', 'p', 'l', 'e'};
595 RUInt32BE fRootVersion{(ROOT_VERSION_CODE >> 16) * 10000 + ((ROOT_VERSION_CODE & 0xFF00) >> 8) * 100 +
596 (ROOT_VERSION_CODE & 0xFF)};
597 RUInt32BE fFormatVersion{1};
598 RUInt32BE fCompress{0};
599 RTFNTuple fNTuple;
600 // followed by the ntuple name
601};
602#pragma pack(pop)
603
604/// The artificial class name shown for opaque RNTuple keys (see TBasket)
605constexpr char const *kBlobClassName = "RBlob";
606/// The class name of the RNTuple anchor
607constexpr char const *kNTupleClassName = "ROOT::RNTuple";
608
609} // anonymous namespace
610
611namespace ROOT {
612namespace Internal {
613/// If a TFile container is written by a C stream (simple file), on dataset commit, the file header
614/// and the TFile record need to be updated
616 RTFHeader fHeader;
617 RTFDirectory fFileRecord;
618 std::uint64_t fSeekNTuple{0}; // Remember the offset for the keys list
619 std::uint64_t fSeekFileRecord{0};
620};
621
622/// The RKeyBlob writes an invisible key into a TFile. That is, a key that is not indexed in the list of keys,
623/// like a TBasket.
624/// NOTE: out of anonymous namespace because otherwise ClassDefInline fails to compile
625/// on some platforms.
626class RKeyBlob : public TKey { // NOLINT(misc-use-internal-linkage)
627public:
628 RKeyBlob() = default;
629
630 explicit RKeyBlob(TFile *file) : TKey(file)
631 {
632 fClassName = kBlobClassName;
633 fVersion += RTFKey::kBigKeyVersion;
634 fKeylen = Sizeof();
635 }
636
637 /// Register a new key for a data record of size nbytes
638 void Reserve(size_t nbytes, std::uint64_t *seekKey)
639 {
640 Create(nbytes);
641 *seekKey = fSeekKey;
642 }
643
644 bool WasAllocatedInAFreeSlot() const { return fLeft > 0; }
645
647};
648
649} // namespace Internal
650} // namespace ROOT
651
652// Computes how many chunks do we need to fit `nbytes` of payload, considering that the
653// first chunk also needs to house the offsets of the other chunks and no chunk can
654// be bigger than `maxChunkSize`. When saved to a TFile, each chunk is part of a separate TKey.
655static size_t ComputeNumChunks(size_t nbytes, size_t maxChunkSize)
656{
657 constexpr size_t kChunkOffsetSize = sizeof(std::uint64_t);
658
659 assert(nbytes > maxChunkSize);
660 size_t nChunks = (nbytes + maxChunkSize - 1) / maxChunkSize;
661 assert(nChunks > 1);
662 size_t nbytesTail = nbytes % maxChunkSize;
663 size_t nbytesExtra = (nbytesTail > 0) * (maxChunkSize - nbytesTail);
664 size_t nbytesChunkOffsets = (nChunks - 1) * kChunkOffsetSize;
665 if (nbytesChunkOffsets > nbytesExtra) {
666 ++nChunks;
667 nbytesChunkOffsets += kChunkOffsetSize;
668 }
669
670 // We don't support having more chunkOffsets than what fits in one chunk.
671 // For a reasonable-sized maxKeySize it looks very unlikely that we can have more chunks
672 // than we can fit in the first `maxKeySize` bytes. E.g. for maxKeySize = 1GiB we can fit
673 // 134217728 chunk offsets, making our multi-key blob's capacity exactly 128 PiB.
674 R__ASSERT(nbytesChunkOffsets <= maxChunkSize);
675
676 return nChunks;
677}
678
679/// Reads the TFile string at the given offset. Returns the number of bytes read. Writes the string content into str,
680/// if it is not null.
681static std::uint64_t ReadTFString(std::uint64_t offset, ROOT::Internal::RMiniFileReader &reader, std::string *str)
682{
683 std::size_t headerLength = 1;
684 std::size_t strLength = 0;
685 unsigned char shortLength = 0;
686 reader.ReadBuffer(&shortLength, 1, offset);
687 if (shortLength == RTFString::kLongStringMarker) {
688 RUInt32BE longLength;
689 reader.ReadBuffer(&longLength, sizeof(longLength), offset + headerLength);
690 strLength = longLength;
691 headerLength += sizeof(longLength);
692 } else {
693 strLength = shortLength;
694 }
695 if (str) {
696 str->resize(strLength);
697 if (strLength > 0)
698 reader.ReadBuffer(str->data(), strLength, offset + headerLength);
699 }
700 return headerLength + strLength;
701}
702
704
706{
707 char ident[4];
708 ReadBuffer(ident, 4, 0);
709 if (std::string(ident, 4) == "root")
710 return GetNTupleProper(ntupleName);
711 fIsBare = true;
712 return GetNTupleBare(ntupleName);
713}
714
715/// Searches for a key with the given name and type in the key index of the given directory.
716/// Return 0 if the key was not found.
717std::uint64_t ROOT::Internal::RMiniFileReader::SearchInDirectory(std::uint64_t &offsetDir, std::string_view keyName,
718 std::string_view typeName)
719{
720 RTFDirectory directory;
721 ReadBuffer(&directory, sizeof(directory), offsetDir);
722
723 RTFKey key;
724 RUInt32BE nKeys;
725 std::uint64_t offset = directory.GetSeekKeys();
726 ReadBuffer(&key, sizeof(key), offset);
727 offset += key.fKeyLen;
728 ReadBuffer(&nKeys, sizeof(nKeys), offset);
729 offset += sizeof(nKeys);
730
731 for (unsigned int i = 0; i < nKeys; ++i) {
732 ReadBuffer(&key, sizeof(key), offset);
733 auto offsetNextKey = offset + key.fKeyLen;
734
735 offset += key.GetHeaderSize();
736 std::string foundClassName;
737 offset += ReadTFString(offset, *this, &foundClassName);
738 if (foundClassName != typeName) {
739 offset = offsetNextKey;
740 continue;
741 }
742 std::string foundKeyName;
743 ReadTFString(offset, *this, &foundKeyName);
744 if (foundKeyName == keyName) {
745 return key.GetSeekKey();
746 }
747 offset = offsetNextKey;
748 }
749
750 // Not found
751 return 0;
752}
753
755{
756 if (fIsBare)
757 return;
758
759 RTFKey key;
760 ReadBuffer(&key, sizeof(key), fSeekKeyInfo);
761
762 R__ASSERT(fNbytesKeyAndInfo >= key.fKeyLen);
763 const std::uint64_t nbytesInfo = fNbytesKeyAndInfo - key.fKeyLen;
764 const std::uint64_t seekInfo = fSeekKeyInfo + key.fKeyLen;
765 const std::uint32_t uncompLenInfo = key.fObjLen;
766 auto streamerInfo = MakeUninitArray<char>(uncompLenInfo);
767 if (nbytesInfo == uncompLenInfo) {
768 // Uncompressed
769 ReadBuffer(streamerInfo.get(), nbytesInfo, seekInfo);
770 } else {
771 auto buffer = MakeUninitArray<std::byte>(nbytesInfo);
772 ReadBuffer(buffer.get(), nbytesInfo, seekInfo);
773 RNTupleDecompressor::Unzip(buffer.get(), nbytesInfo, uncompLenInfo, streamerInfo.get());
774 }
775
776 TBufferFile buffer(TBuffer::kRead, uncompLenInfo, streamerInfo.release());
777 // This is necessary to allow the "class tags" inside the StreamerInfo list to refer to the proper offset into
778 // the buffer. Normally TFile loads the StreamerInfo via TKey::ReadObjWithBuffer, whose buffer also includes the
779 // key itself. Since we dealt with the key above already, we are only passing the payload to TBufferFile so offsets
780 // need to be patched up.
781 buffer.SetBufferDisplacement(key.fKeyLen);
782 TList streamerInfoList;
783 streamerInfoList.Streamer(buffer);
784 TObjLink *lnk = streamerInfoList.FirstLink();
785 while (lnk) {
786 auto obj = lnk->GetObject();
787 // NOTE: the last element of the streamer info list may be a TList with the IO customization rules, so we need
788 // to check before static casting.
789 if (obj->IsA() == TStreamerInfo::Class()) {
790 auto info = static_cast<TStreamerInfo *>(obj);
791 info->BuildCheck();
792 }
793 lnk = lnk->Next();
794 }
795}
796
798{
799 RTFHeader fileHeader;
800 ReadBuffer(&fileHeader, sizeof(fileHeader), 0);
801
802 fSeekKeyInfo = fileHeader.GetSeekInfo();
803 fNbytesKeyAndInfo = fileHeader.GetNbytesInfo();
804
805 RTFKey key;
806 ReadBuffer(&key, sizeof(key), fileHeader.fBEGIN);
807 // Skip over the entire key length, including the class name, object name, and title stored in it.
808 std::uint64_t offset = fileHeader.fBEGIN + key.fKeyLen;
809 // Skip over the name and title of the TNamed preceding the TFile (root TDirectory) entry.
810 offset += ReadTFString(offset, *this, nullptr);
811 offset += ReadTFString(offset, *this, nullptr);
812
813 // split ntupleName by '/' character to open datasets in subdirectories.
814 std::string ntuplePathTail(ntuplePath);
815 if (!ntuplePathTail.empty() && ntuplePathTail[0] == '/')
816 ntuplePathTail = ntuplePathTail.substr(1);
817 auto pos = std::string::npos;
818 while ((pos = ntuplePathTail.find('/')) != std::string::npos) {
819 auto directoryName = ntuplePathTail.substr(0, pos);
820 ntuplePathTail.erase(0, pos + 1);
821
822 offset = SearchInDirectory(offset, directoryName, "TDirectory");
823 if (offset == 0) {
824 return R__FAIL("no directory named '" + std::string(directoryName) + "' in file '" + fRawFile->GetUrl() + "'");
825 }
826 ReadBuffer(&key, sizeof(key), offset);
827 offset = key.GetSeekKey() + key.fKeyLen;
828 }
829 // no more '/' delimiter in ntuplePath
830 auto ntupleName = ntuplePathTail;
831
832 offset = SearchInDirectory(offset, ntupleName, kNTupleClassName);
833 if (offset == 0) {
834 return R__FAIL("no RNTuple named '" + std::string(ntupleName) + "' in file '" + fRawFile->GetUrl() + "'");
835 }
836
837 ReadBuffer(&key, sizeof(key), offset);
838 offset = key.GetSeekKey() + key.fKeyLen;
839
840 // size of a RTFNTuple version 2 (min supported version); future anchor versions can grow.
841 constexpr size_t kMinNTupleSize = 78;
842 static_assert(kMinNTupleSize == RTFNTuple::GetSizePlusChecksum());
843 if (key.fObjLen < kMinNTupleSize) {
844 return R__FAIL("invalid anchor size: " + std::to_string(key.fObjLen) + " < " + std::to_string(sizeof(RTFNTuple)));
845 }
846
847 const auto objNbytes = key.GetSize() - key.fKeyLen;
848 auto res = GetNTupleProperAtOffset(offset, objNbytes, key.fObjLen);
849
850 return res;
851}
852
854 std::uint64_t compSize,
855 std::uint64_t uncompLen)
856{
857 if (compSize > uncompLen) {
858 return R__FAIL("Invalid size and length combination of anchor at offset " + std::to_string(payloadOffset) +
859 " (length: " + std::to_string(uncompLen) + ", bytes on disk: " + std::to_string(compSize) + ")");
860 }
861
862 // The object length can be smaller than the size of RTFNTuple if it comes from a past RNTuple class version,
863 // or larger than it if it comes from a future RNTuple class version.
864 auto bufAnchor = MakeUninitArray<unsigned char>(std::max<size_t>(uncompLen, sizeof(RTFNTuple)));
865 RTFNTuple *ntuple = new (bufAnchor.get()) RTFNTuple;
866
867 if (compSize < uncompLen) {
868 // Read into a temporary buffer
869 auto zipBuf = MakeUninitArray<unsigned char>(compSize);
870 ReadBuffer(zipBuf.get(), compSize, payloadOffset);
871 // Unzip into the final buffer
872 RNTupleDecompressor::Unzip(zipBuf.get(), compSize, uncompLen, ntuple);
873 } else {
874 // We can directly decompress into ntuple because this RTFNTuple object has been constructed in a memory area
875 // of (max(uncompLen, sizeof(RTFNTuple))) bytes.
876 ReadBuffer(ntuple, uncompLen, payloadOffset);
877 }
878
879 // We require that future class versions only append members and store the checksum in the last 8 bytes
880 // Checksum calculation: strip byte count, class version, fChecksum member
881 const auto lenCkData = uncompLen - ntuple->GetOffsetCkData() - sizeof(uint64_t);
882 const auto ckCalc = XXH3_64bits(ntuple->GetPtrCkData(), lenCkData);
883 uint64_t ckOnDisk;
884
885 RUInt64BE *ckOnDiskPtr = reinterpret_cast<RUInt64BE *>(bufAnchor.get() + uncompLen - sizeof(uint64_t));
886 ckOnDisk = static_cast<uint64_t>(*ckOnDiskPtr);
887 if (ckCalc != ckOnDisk) {
888 return R__FAIL("RNTuple anchor checksum mismatch");
889 }
890
891 return CreateAnchor(ntuple->fVersionEpoch, ntuple->fVersionMajor, ntuple->fVersionMinor, ntuple->fVersionPatch,
892 ntuple->fSeekHeader, ntuple->fNBytesHeader, ntuple->fLenHeader, ntuple->fSeekFooter,
893 ntuple->fNBytesFooter, ntuple->fLenFooter, ntuple->fMaxKeySize);
894}
895
897{
898 RBareFileHeader fileHeader;
899 ReadBuffer(&fileHeader, sizeof(fileHeader), 0);
900 auto offset = sizeof(fileHeader);
901 std::string foundName;
902 offset += ReadTFString(offset, *this, &foundName);
903 if (foundName != ntupleName) {
904 return R__FAIL("expected RNTuple named '" + std::string(ntupleName) + "' but instead found '" + foundName +
905 "' in file '" + fRawFile->GetUrl() + "'");
906 }
907
908 RTFNTuple ntuple;
909 ReadBuffer(&ntuple, sizeof(ntuple), offset);
910 std::uint64_t onDiskChecksum;
911 ReadBuffer(&onDiskChecksum, sizeof(onDiskChecksum), offset + sizeof(ntuple));
912 auto checksum = XXH3_64bits(ntuple.GetPtrCkData(), ntuple.GetSizeCkData());
913 if (checksum != static_cast<uint64_t>(onDiskChecksum))
914 return R__FAIL("RNTuple bare file: anchor checksum mismatch");
915
916 return CreateAnchor(ntuple.fVersionEpoch, ntuple.fVersionMajor, ntuple.fVersionMinor, ntuple.fVersionPatch,
917 ntuple.fSeekHeader, ntuple.fNBytesHeader, ntuple.fLenHeader, ntuple.fSeekFooter,
918 ntuple.fNBytesFooter, ntuple.fLenFooter, ntuple.fMaxKeySize);
919}
920
921void ROOT::Internal::RMiniFileReader::ReadBuffer(void *buffer, size_t nbytes, std::uint64_t offset)
922{
923 TryReadBuffer(buffer, nbytes, offset).ThrowOnError();
924}
925
927{
928 const auto ByteReadErr = [](std::size_t expected, std::size_t nread) {
929 return R__FAIL("invalid read (expected bytes: " + std::to_string(expected) + ", read: " + std::to_string(nread) +
930 ")");
931 };
932
933 size_t nread;
934 if (fMaxKeySize == 0 || nbytes <= fMaxKeySize) {
935 // Fast path: read single blob
936 nread = fRawFile->ReadAt(buffer, nbytes, offset);
937 } else {
938 // Read chunked blob. See RNTupleFileWriter::WriteBlob() for details.
939 const size_t nChunks = ComputeNumChunks(nbytes, fMaxKeySize);
940 const size_t nbytesChunkOffsets = (nChunks - 1) * sizeof(std::uint64_t);
941 const size_t nbytesFirstChunk = fMaxKeySize - nbytesChunkOffsets;
942 uint8_t *bufCur = reinterpret_cast<uint8_t *>(buffer);
943
944 // Read first chunk
945 nread = fRawFile->ReadAt(bufCur, fMaxKeySize, offset);
946 if (nread != fMaxKeySize)
947 return ByteReadErr(fMaxKeySize, nread);
948
949 // NOTE: we read the entire chunk in `bufCur`, but we only advance the pointer by `nbytesFirstChunk`,
950 // since the last part of `bufCur` will later be overwritten by the next chunk's payload.
951 // We do this to avoid a second ReadAt to read in the chunk offsets.
952 bufCur += nbytesFirstChunk;
953 nread -= nbytesChunkOffsets;
954
955 const auto chunkOffsets = MakeUninitArray<std::uint64_t>(nChunks - 1);
956 memcpy(chunkOffsets.get(), bufCur, nbytesChunkOffsets);
957
958 size_t remainingBytes = nbytes - nbytesFirstChunk;
959 std::uint64_t *curChunkOffset = &chunkOffsets[0];
960
961 do {
962 std::uint64_t chunkOffset;
963 RNTupleSerializer::DeserializeUInt64(curChunkOffset, chunkOffset);
964 ++curChunkOffset;
965
966 const size_t bytesToRead = std::min<size_t>(fMaxKeySize, remainingBytes);
967 // Ensure we don't read outside of the buffer
968 R__ASSERT(static_cast<size_t>(bufCur - reinterpret_cast<uint8_t *>(buffer)) <= nbytes - bytesToRead);
969
970 auto nbytesRead = fRawFile->ReadAt(bufCur, bytesToRead, chunkOffset);
971 if (nbytesRead != bytesToRead)
972 return ByteReadErr(bytesToRead, nbytesRead);
973
974 nread += bytesToRead;
975 bufCur += bytesToRead;
976 remainingBytes -= bytesToRead;
977 } while (remainingBytes > 0);
978 }
979
980 if (nread != nbytes)
981 return ByteReadErr(nbytes, nread);
982
983 return RResult<void>::Success();
984}
985
986////////////////////////////////////////////////////////////////////////////////
987
988/// Prepare a blob key in the provided buffer, which must provide space for kBlobKeyLen bytes. Note that the array type
989/// is purely documentation, the argument is actually just a pointer.
990void ROOT::Internal::RNTupleFileWriter::PrepareBlobKey(std::int64_t offset, size_t nbytes, size_t len,
991 unsigned char buffer[kBlobKeyLen])
992{
993 RTFString strClass{kBlobClassName};
994 RTFString strObject;
995 RTFString strTitle;
996 RTFKey keyHeader(offset, RTFHeader::kBEGIN, strClass, strObject, strTitle, len, nbytes);
997 R__ASSERT(keyHeader.fKeyLen == kBlobKeyLen);
998
999 // Copy structures into the buffer.
1000 unsigned char *writeBuffer = buffer;
1001 memcpy(writeBuffer, &keyHeader, keyHeader.GetHeaderSize());
1002 writeBuffer += keyHeader.GetHeaderSize();
1003 memcpy(writeBuffer, strClass.GetData(), strClass.GetSize());
1004 writeBuffer += strClass.GetSize();
1005 memcpy(writeBuffer, strObject.GetData(), strObject.GetSize());
1006 writeBuffer += strObject.GetSize();
1007 memcpy(writeBuffer, strTitle.GetData(), strTitle.GetSize());
1008 writeBuffer += strTitle.GetSize();
1009 R__ASSERT(writeBuffer == buffer + kBlobKeyLen);
1010}
1011
1012////////////////////////////////////////////////////////////////////////////////
1013
1015
1017{
1018 static_assert(kHeaderBlockSize % kBlockAlign == 0, "invalid header block size");
1019 if (bufferSize % kBlockAlign != 0)
1020 throw RException(R__FAIL("Buffer size not a multiple of alignment: " + std::to_string(bufferSize)));
1021
1022 assert(!fShared);
1023
1024 fShared = std::make_shared<RSharedData>(nullptr);
1025
1026 fShared->fBlockSize = bufferSize;
1027 fShared->fControlBlock = std::make_unique<ROOT::Internal::RTFileControlBlock>();
1028
1029 std::align_val_t blockAlign{kBlockAlign};
1030 fShared->fHeaderBlock = static_cast<unsigned char *>(::operator new[](kHeaderBlockSize, blockAlign));
1031 memset(fShared->fHeaderBlock, 0, kHeaderBlockSize);
1032 fShared->fBlock = static_cast<unsigned char *>(::operator new[](fShared->fBlockSize, blockAlign));
1033 memset(fShared->fBlock, 0, fShared->fBlockSize);
1034}
1035
1037
1039{
1040 if (fFile)
1041 fclose(fFile);
1042
1043 std::align_val_t blockAlign{kBlockAlign};
1044 if (fHeaderBlock)
1045 ::operator delete[](fHeaderBlock, blockAlign);
1046 if (fBlock)
1047 ::operator delete[](fBlock, blockAlign);
1048}
1049
1050namespace {
1051int FSeek64(FILE *stream, std::int64_t offset, int origin)
1052{
1053#ifdef R__SEEK64
1054 return fseeko64(stream, offset, origin);
1055#else
1056 return fseek(stream, offset, origin);
1057#endif
1058}
1059} // namespace
1060
1062{
1063 auto &shared = *fShared;
1064
1065 // Write the last partially filled block, which may still need appropriate alignment for Direct I/O.
1066 // If it is the first block, get the updated header block.
1067 if (shared.fBlockOffset == 0) {
1068 std::size_t headerBlockSize = kHeaderBlockSize;
1069 if (headerBlockSize > shared.fFilePos) {
1070 headerBlockSize = shared.fFilePos;
1071 }
1072 memcpy(shared.fBlock, shared.fHeaderBlock, headerBlockSize);
1073 }
1074
1075 std::size_t retval = FSeek64(shared.fFile, shared.fBlockOffset, SEEK_SET);
1076 if (retval)
1077 throw RException(R__FAIL(std::string("Seek failed: ") + strerror(errno)));
1078
1079 std::size_t lastBlockSize = shared.fFilePos - shared.fBlockOffset;
1080 R__ASSERT(lastBlockSize <= shared.fBlockSize);
1081 if (shared.fDirectIO) {
1082 // Round up to a multiple of kBlockAlign.
1083 lastBlockSize += kBlockAlign - 1;
1084 lastBlockSize = (lastBlockSize / kBlockAlign) * kBlockAlign;
1085 R__ASSERT(lastBlockSize <= shared.fBlockSize);
1086 }
1087 retval = fwrite(shared.fBlock, 1, lastBlockSize, shared.fFile);
1088 if (retval != lastBlockSize)
1089 throw RException(R__FAIL(std::string("write failed: ") + strerror(errno)));
1090
1091 // Write the (updated) header block, unless it was part of the write above.
1092 if (shared.fBlockOffset > 0) {
1093 retval = FSeek64(shared.fFile, 0, SEEK_SET);
1094 if (retval)
1095 throw RException(R__FAIL(std::string("Seek failed: ") + strerror(errno)));
1096
1097 retval = fwrite(shared.fHeaderBlock, 1, kHeaderBlockSize, shared.fFile);
1098 if (retval != RImplSimple::kHeaderBlockSize)
1099 throw RException(R__FAIL(std::string("write failed: ") + strerror(errno)));
1100 }
1101
1102 retval = fflush(shared.fFile);
1103 if (retval)
1104 throw RException(R__FAIL(std::string("Flush failed: ") + strerror(errno)));
1105}
1106
1107void ROOT::Internal::RNTupleFileWriter::RImplSimple::Write(const void *buffer, size_t nbytes, std::int64_t offset)
1108{
1109 auto &shared = *fShared;
1110
1111 R__ASSERT(shared.fFile);
1112 size_t retval;
1113 if ((offset >= 0) && (static_cast<std::uint64_t>(offset) != shared.fFilePos)) {
1114 shared.fFilePos = offset;
1115 }
1116
1117 // Keep header block to overwrite on commit.
1118 if (shared.fFilePos < kHeaderBlockSize) {
1119 std::size_t headerBytes = nbytes;
1120 if (shared.fFilePos + headerBytes > kHeaderBlockSize) {
1121 headerBytes = kHeaderBlockSize - shared.fFilePos;
1122 }
1123 memcpy(shared.fHeaderBlock + shared.fFilePos, buffer, headerBytes);
1124 }
1125
1126 R__ASSERT(shared.fFilePos >= shared.fBlockOffset);
1127
1128 while (nbytes > 0) {
1129 std::uint64_t posInBlock = shared.fFilePos % shared.fBlockSize;
1130 std::uint64_t blockOffset = shared.fFilePos - posInBlock;
1131 if (blockOffset != shared.fBlockOffset) {
1132 // Write the block.
1133 retval = FSeek64(shared.fFile, shared.fBlockOffset, SEEK_SET);
1134 if (retval)
1135 throw RException(R__FAIL(std::string("Seek failed: ") + strerror(errno)));
1136
1137 retval = fwrite(shared.fBlock, 1, shared.fBlockSize, shared.fFile);
1138 if (retval != shared.fBlockSize)
1139 throw RException(R__FAIL(std::string("write failed: ") + strerror(errno)));
1140
1141 // Null the buffer contents for good measure.
1142 memset(shared.fBlock, 0, shared.fBlockSize);
1143 }
1144
1145 shared.fBlockOffset = blockOffset;
1146 std::size_t blockSize = nbytes;
1147 if (blockSize > shared.fBlockSize - posInBlock) {
1148 blockSize = shared.fBlockSize - posInBlock;
1149 }
1150 memcpy(shared.fBlock + posInBlock, buffer, blockSize);
1151 buffer = static_cast<const unsigned char *>(buffer) + blockSize;
1152 nbytes -= blockSize;
1153 shared.fFilePos += blockSize;
1154 }
1155}
1156
1157std::uint64_t
1158ROOT::Internal::RNTupleFileWriter::RImplSimple::WriteKey(const void *buffer, std::size_t nbytes, std::size_t len,
1159 std::int64_t offset, std::uint64_t directoryOffset,
1160 const std::string &className, const std::string &objectName,
1161 const std::string &title)
1162{
1163 auto &shared = *fShared;
1164
1165 if (offset > 0)
1166 shared.fKeyOffset = offset;
1167 RTFString strClass{className};
1168 RTFString strObject{objectName};
1169 RTFString strTitle{title};
1170
1171 RTFKey key(shared.fKeyOffset, directoryOffset, strClass, strObject, strTitle, len, nbytes);
1172 Write(&key, key.GetHeaderSize(), shared.fKeyOffset);
1173 Write(strClass.GetData(), strClass.GetSize());
1174 Write(strObject.GetData(), strObject.GetSize());
1175 Write(strTitle.GetData(), strTitle.GetSize());
1176 auto offsetData = shared.fFilePos;
1177 // The next key starts after the data.
1178 shared.fKeyOffset = offsetData + nbytes;
1179 if (buffer)
1180 Write(buffer, nbytes);
1181
1182 return offsetData;
1183}
1184
1185std::uint64_t ROOT::Internal::RNTupleFileWriter::RImplSimple::ReserveBlobKey(std::size_t nbytes, std::size_t len,
1186 unsigned char keyBuffer[kBlobKeyLen])
1187{
1188 auto &shared = *fShared;
1189
1190 if (keyBuffer) {
1191 PrepareBlobKey(shared.fKeyOffset, nbytes, len, keyBuffer);
1192 } else {
1193 unsigned char localKeyBuffer[kBlobKeyLen];
1194 PrepareBlobKey(shared.fKeyOffset, nbytes, len, localKeyBuffer);
1195 Write(localKeyBuffer, kBlobKeyLen, shared.fKeyOffset);
1196 }
1197
1198 auto offsetData = shared.fKeyOffset + kBlobKeyLen;
1199 // The next key starts after the data.
1200 shared.fKeyOffset = offsetData + nbytes;
1201
1202 return offsetData;
1203}
1204
1205////////////////////////////////////////////////////////////////////////////////
1206
1207template <typename T>
1208std::uint64_t ROOT::Internal::RNTupleFileWriter::ReserveBlobKey(T &caller, TFile &file, std::size_t nbytes,
1209 std::size_t len, unsigned char keyBuffer[kBlobKeyLen])
1210{
1211 std::uint64_t offsetKey;
1212 ROOT::Internal::RKeyBlob keyBlob(&file);
1213 // Since it is unknown beforehand if offsetKey is beyond the 2GB limit or not,
1214 // RKeyBlob will always reserve space for a big key (version >= 1000)
1215 keyBlob.Reserve(nbytes, &offsetKey);
1216
1217 if (keyBuffer) {
1218 PrepareBlobKey(offsetKey, nbytes, len, keyBuffer);
1219 } else {
1220 unsigned char localKeyBuffer[kBlobKeyLen];
1221 PrepareBlobKey(offsetKey, nbytes, len, localKeyBuffer);
1222 caller.Write(localKeyBuffer, kBlobKeyLen, offsetKey);
1223 }
1224
1225 if (keyBlob.WasAllocatedInAFreeSlot()) {
1226 // If the key was allocated in a free slot, the last 4 bytes of its buffer contain the new size
1227 // of the remaining free slot and we need to write it to disk before the key gets destroyed at the end of the
1228 // function.
1229 caller.Write(keyBlob.GetBuffer() + nbytes, sizeof(Int_t), offsetKey + kBlobKeyLen + nbytes);
1230 }
1231
1232 auto offsetData = offsetKey + kBlobKeyLen;
1233
1234 return offsetData;
1235}
1236
1237void ROOT::Internal::RNTupleFileWriter::RImplTFile::Write(const void *buffer, size_t nbytes, std::int64_t offset)
1238{
1239 fDirectory->GetFile()->Seek(offset);
1240 bool rv = fDirectory->GetFile()->WriteBuffer((char *)(buffer), nbytes);
1241 if (rv)
1242 throw RException(R__FAIL("WriteBuffer failed."));
1243}
1244
1246 unsigned char keyBuffer[kBlobKeyLen])
1247{
1248 auto offsetData = RNTupleFileWriter::ReserveBlobKey(*this, *fDirectory->GetFile(), nbytes, len, keyBuffer);
1249 return offsetData;
1250}
1251
1252////////////////////////////////////////////////////////////////////////////////
1253
1254void ROOT::Internal::RNTupleFileWriter::RImplRFile::Write(const void *buffer, size_t nbytes, std::int64_t offset)
1255{
1256 auto *file = ROOT::Internal::GetRFileTFile(*fFile);
1257 file->Seek(offset);
1258 bool rv = file->WriteBuffer((char *)(buffer), nbytes);
1259 if (rv)
1260 throw RException(R__FAIL("WriteBuffer failed."));
1261}
1262
1264 unsigned char keyBuffer[kBlobKeyLen])
1265{
1266 auto *file = ROOT::Internal::GetRFileTFile(*fFile);
1267 auto offsetData = RNTupleFileWriter::ReserveBlobKey(*this, *file, nbytes, len, keyBuffer);
1268 return offsetData;
1269}
1270
1271////////////////////////////////////////////////////////////////////////////////
1272
1273ROOT::Internal::RNTupleFileWriter::RNTupleFileWriter(std::string_view name, std::uint64_t maxKeySize, bool isHidden)
1274 : fIsHidden(isHidden), fNTupleName(name)
1275{
1276 fFile.emplace<RImplSimple>();
1277 fNTupleAnchor.fMaxKeySize = maxKeySize;
1278 auto infoRNTuple = RNTuple::Class()->GetStreamerInfo();
1279 fStreamerInfoMap[infoRNTuple->GetNumber()] = infoRNTuple;
1280}
1281
1283
1284std::unique_ptr<ROOT::Internal::RNTupleFileWriter>
1285ROOT::Internal::RNTupleFileWriter::Recreate(std::string_view ntupleName, std::string_view path,
1286 EContainerFormat containerFormat, const ROOT::RNTupleWriteOptions &options)
1287{
1288 std::string fileName(path);
1289 size_t idxDirSep = fileName.find_last_of("\\/");
1290 if (idxDirSep != std::string::npos) {
1291 fileName.erase(0, idxDirSep + 1);
1292 }
1293#ifdef R__LINUX
1294 int flags = O_WRONLY | O_CREAT | O_TRUNC;
1295#ifdef O_LARGEFILE
1296 // Add the equivalent flag that is passed by fopen64.
1297 flags |= O_LARGEFILE;
1298#endif
1299 if (options.GetUseDirectIO()) {
1300 flags |= O_DIRECT;
1301 }
1302 int fd = open(std::string(path).c_str(), flags, 0666);
1303 if (fd == -1) {
1304 throw RException(R__FAIL(std::string("open failed for file \"") + std::string(path) + "\": " + strerror(errno)));
1305 }
1306 FILE *fileStream = fdopen(fd, "wb");
1307#else
1308#ifdef R__SEEK64
1309 FILE *fileStream = fopen64(std::string(path.data(), path.size()).c_str(), "wb");
1310#else
1311 FILE *fileStream = fopen(std::string(path.data(), path.size()).c_str(), "wb");
1312#endif
1313#endif
1314 if (!fileStream) {
1315 throw RException(R__FAIL(std::string("open failed for file \"") + std::string(path) + "\": " + strerror(errno)));
1316 }
1317 // RNTupleFileWriter::RImplSimple does its own buffering, turn off additional buffering from C stdio.
1318 std::setvbuf(fileStream, nullptr, _IONBF, 0);
1319
1320 auto writer = std::unique_ptr<RNTupleFileWriter>(
1321 new RNTupleFileWriter(ntupleName, options.GetMaxKeySize(), /*isHidden=*/false));
1322 RImplSimple &fileSimple = std::get<RImplSimple>(writer->fFile);
1323 fileSimple.AllocateBuffers(options.GetWriteBufferSize());
1324 fileSimple.fShared->fFile = fileStream;
1325 fileSimple.fShared->fDirectIO = options.GetUseDirectIO();
1326 writer->fFileName = fileName;
1327
1328 int defaultCompression = options.GetCompression();
1329 switch (containerFormat) {
1330 case EContainerFormat::kTFile: writer->WriteTFileSkeleton(defaultCompression); break;
1331 case EContainerFormat::kBare:
1332 writer->fIsBare = true;
1333 writer->WriteBareFileSkeleton(defaultCompression);
1334 break;
1335 default: R__ASSERT(false && "Internal error: unhandled container format");
1336 }
1337
1338 return writer;
1339}
1340
1341std::unique_ptr<ROOT::Internal::RNTupleFileWriter>
1342ROOT::Internal::RNTupleFileWriter::Append(std::string_view ntupleName, TDirectory &fileOrDirectory,
1343 std::uint64_t maxKeySize, bool hidden)
1344{
1345 TFile *file = fileOrDirectory.GetFile();
1346 if (!file)
1347 throw RException(R__FAIL("invalid attempt to add an RNTuple to a directory that is not backed by a file"));
1348 assert(file->IsBinary());
1349
1350 auto writer = std::unique_ptr<RNTupleFileWriter>(new RNTupleFileWriter(ntupleName, maxKeySize, hidden));
1351 auto &fileProper = writer->fFile.emplace<RImplTFile>();
1352 fileProper.fDirectory = &fileOrDirectory;
1353 return writer;
1354}
1355
1356std::unique_ptr<ROOT::Internal::RNTupleFileWriter>
1357ROOT::Internal::RNTupleFileWriter::Append(std::string_view ntupleName, ROOT::RFile &file, std::string_view ntupleDir,
1358 std::uint64_t maxKeySize)
1359{
1360 auto writer = std::unique_ptr<RNTupleFileWriter>(new RNTupleFileWriter(ntupleName, maxKeySize, /*isHidden=*/false));
1361 auto &rfile = writer->fFile.emplace<RImplRFile>();
1362 rfile.fFile = &file;
1363 R__ASSERT(ntupleDir.empty() || ntupleDir[ntupleDir.size() - 1] == '/');
1364 rfile.fDir = ntupleDir;
1365 return writer;
1366}
1367
1368std::unique_ptr<ROOT::Internal::RNTupleFileWriter>
1370{
1371 if (auto *tfile = std::get_if<RImplTFile>(&fFile)) {
1372 return Append(ntupleName, *tfile->fDirectory, fNTupleAnchor.fMaxKeySize, /* isHidden= */ true);
1373 } else if (auto *file = std::get_if<RImplSimple>(&fFile)) {
1374 if (fIsBare)
1375 throw ROOT::RException(R__FAIL("cloning a bare file is currently unsupported"));
1376
1377 auto writer = std::unique_ptr<RNTupleFileWriter>(
1378 new RNTupleFileWriter(ntupleName, fNTupleAnchor.GetMaxKeySize(), /* isHidden= */ true));
1379 auto &clonedFile = std::get<RImplSimple>(writer->fFile);
1380 clonedFile.fShared = file->fShared;
1381 return writer;
1382 }
1383 // TODO: support also RFile-based writers
1384 throw ROOT::RException(R__FAIL("cannot clone an RFile-based RNTupleFileWriter."));
1385}
1386
1388{
1389 RImplSimple *fileSimple = std::get_if<RImplSimple>(&fFile);
1390 if (!fileSimple)
1391 throw RException(R__FAIL("invalid attempt to seek non-simple writer"));
1392
1393 fileSimple->fShared->fFilePos = offset;
1394 fileSimple->fShared->fKeyOffset = offset;
1395 // The next Write() will Flush() if necessary.
1396}
1397
1399{
1400 fStreamerInfoMap.insert(streamerInfos.cbegin(), streamerInfos.cend());
1401}
1402
1404{
1405 const auto WriteStreamerInfoToFile = [&](TFile *file) {
1406 // Make sure the streamer info records used in the RNTuple are written to the file
1408 buf.SetParent(file);
1409 for (auto [_, info] : fStreamerInfoMap)
1410 buf.TagStreamerInfo(info);
1411 };
1412
1413 ROOT::Internal::RNTupleLink anchorInfo;
1414 // NOTE: checksum length is included in the uncompressed len
1415 anchorInfo.fLength = RTFNTuple{}.GetSize() + sizeof(std::uint64_t);
1417
1418 if (auto fileProper = std::get_if<RImplTFile>(&fFile)) {
1419 // Easy case, the ROOT file header and the RNTuple streaming is taken care of by TFile
1420 fileProper->fDirectory->WriteObject(&fNTupleAnchor, fNTupleName.c_str());
1421 WriteStreamerInfoToFile(fileProper->fDirectory->GetFile());
1422 auto key = static_cast<TKey *>(fileProper->fDirectory->GetListOfKeys()->FindObject(fNTupleName.c_str()));
1423 R__ASSERT(key);
1424 anchorInfo.fLocator.SetPosition(key->GetSeekKey() + key->GetKeylen());
1425 anchorInfo.fLocator.SetNBytesOnStorage(key->GetNbytes() - key->GetKeylen());
1426 // NOTE: this must happen after FindObject(), otherwise some TFile implementations, such as TBufferMergerFile,
1427 // may reset the keys list upon write.
1428 fileProper->fDirectory->GetFile()->Write();
1429
1430 if (fIsHidden) {
1431 // Remove the anchor's key from the directory's KeysList to disallow retrieving directly the
1432 // attribute RNTuple from the TFile.
1433 fileProper->fDirectory->GetListOfKeys()->Remove(key);
1434 }
1435 } else if (auto fileRFile = std::get_if<RImplRFile>(&fFile)) {
1436 // Same as the case above but handled via RFile
1437 fileRFile->fFile->Put(fileRFile->fDir + fNTupleName, fNTupleAnchor);
1438 WriteStreamerInfoToFile(ROOT::Internal::GetRFileTFile(*fileRFile->fFile));
1439 auto key = fileRFile->fFile->GetKeyInfo(fNTupleName);
1440 R__ASSERT(key);
1441 anchorInfo.fLocator.SetPosition(key->GetSeekKey() + key->GetNBytesKey());
1442 anchorInfo.fLocator.SetNBytesOnStorage(key->GetNBytesObj());
1443 fileRFile->fFile->Flush();
1444 } else {
1445 // Writing by C file stream: prepare the container format header and stream the RNTuple anchor object
1446 auto &fileSimple = std::get<RImplSimple>(fFile);
1447 auto &shared = *fileSimple.fShared;
1448
1449 if (fIsBare) {
1450 RTFNTuple ntupleOnDisk(fNTupleAnchor);
1451
1452 // Compute the checksum
1453 std::uint64_t checksum = XXH3_64bits(ntupleOnDisk.GetPtrCkData(), ntupleOnDisk.GetSizeCkData());
1454 memcpy(shared.fHeaderBlock + shared.fControlBlock->fSeekNTuple, &ntupleOnDisk, ntupleOnDisk.GetSize());
1455 memcpy(shared.fHeaderBlock + shared.fControlBlock->fSeekNTuple + ntupleOnDisk.GetSize(), &checksum,
1456 sizeof(checksum));
1457 fileSimple.Flush();
1458
1459 anchorInfo.fLocator.SetPosition(shared.fControlBlock->fSeekNTuple);
1460 anchorInfo.fLocator.SetNBytesOnStorage(ntupleOnDisk.GetSize());
1461 } else {
1462 anchorInfo = WriteTFileNTupleKey(compression);
1463 if (!fIsHidden) {
1464 WriteTFileKeysList(anchorInfo.fLocator.GetNBytesOnStorage()); // NOTE: this is written uncompressed
1465 WriteTFileStreamerInfo(compression);
1466 WriteTFileFreeList(); // NOTE: this is written uncompressed
1467
1468 // Update header and TFile record
1469 memcpy(shared.fHeaderBlock, &shared.fControlBlock->fHeader, shared.fControlBlock->fHeader.GetSize());
1470 R__ASSERT(shared.fControlBlock->fSeekFileRecord + shared.fControlBlock->fFileRecord.GetSize() <
1471 RImplSimple::kHeaderBlockSize);
1472 memcpy(shared.fHeaderBlock + shared.fControlBlock->fSeekFileRecord, &shared.fControlBlock->fFileRecord,
1473 shared.fControlBlock->fFileRecord.GetSize());
1474 }
1475
1476 fileSimple.Flush();
1477 }
1478 }
1479
1480 return anchorInfo;
1481}
1482
1483std::uint64_t ROOT::Internal::RNTupleFileWriter::WriteBlob(const void *data, size_t nbytes, size_t len)
1484{
1485 auto writeKey = [this](const void *payload, size_t nBytes, size_t length) {
1486 std::uint64_t offset = ReserveBlob(nBytes, length);
1487 WriteIntoReservedBlob(payload, nBytes, offset);
1488 return offset;
1489 };
1490
1491 const std::uint64_t maxKeySize = fNTupleAnchor.fMaxKeySize;
1492 R__ASSERT(maxKeySize > 0);
1493 // We don't need the object length except for seeing compression ratios in TFile::Map()
1494 // Make sure that the on-disk object length fits into the TKey header.
1495 if (static_cast<std::uint64_t>(len) > static_cast<std::uint64_t>(std::numeric_limits<std::uint32_t>::max()))
1496 len = nbytes;
1497
1498 if (nbytes <= maxKeySize) {
1499 // Fast path: only write 1 key.
1500 return writeKey(data, nbytes, len);
1501 }
1502
1503 /**
1504 * Writing a key bigger than the max allowed size. In this case we split the payload
1505 * into multiple keys, reserving the end of the first key payload for pointers to the
1506 * next ones. E.g. if a key needs to be split into 3 chunks, the first chunk will have
1507 * the format:
1508 * +--------------------+
1509 * | |
1510 * | Data |
1511 * |--------------------|
1512 * | pointer to chunk 2 |
1513 * | pointer to chunk 3 |
1514 * +--------------------+
1515 */
1516 const size_t nChunks = ComputeNumChunks(nbytes, maxKeySize);
1517 const size_t nbytesChunkOffsets = (nChunks - 1) * sizeof(std::uint64_t);
1518 const size_t nbytesFirstChunk = maxKeySize - nbytesChunkOffsets;
1519 // Skip writing the first chunk, it will be written last (in the file) below.
1520
1521 const uint8_t *chunkData = reinterpret_cast<const uint8_t *>(data) + nbytesFirstChunk;
1522 size_t remainingBytes = nbytes - nbytesFirstChunk;
1523
1524 const auto chunkOffsetsToWrite = MakeUninitArray<std::uint64_t>(nChunks - 1);
1525 std::uint64_t chunkOffsetIdx = 0;
1526
1527 do {
1528 const size_t bytesNextChunk = std::min<size_t>(remainingBytes, maxKeySize);
1529 const std::uint64_t offset = writeKey(chunkData, bytesNextChunk, bytesNextChunk);
1530
1531 RNTupleSerializer::SerializeUInt64(offset, &chunkOffsetsToWrite[chunkOffsetIdx]);
1532 ++chunkOffsetIdx;
1533
1534 remainingBytes -= bytesNextChunk;
1535 chunkData += bytesNextChunk;
1536
1537 } while (remainingBytes > 0);
1538
1539 // Write the first key, with part of the data and the pointers to (logically) following keys appended.
1540 const std::uint64_t firstOffset = ReserveBlob(maxKeySize, maxKeySize);
1541 WriteIntoReservedBlob(data, nbytesFirstChunk, firstOffset);
1542 const std::uint64_t chunkOffsetsOffset = firstOffset + nbytesFirstChunk;
1543 WriteIntoReservedBlob(chunkOffsetsToWrite.get(), nbytesChunkOffsets, chunkOffsetsOffset);
1544
1545 return firstOffset;
1546}
1547
1548std::uint64_t
1549ROOT::Internal::RNTupleFileWriter::ReserveBlob(size_t nbytes, size_t len, unsigned char keyBuffer[kBlobKeyLen])
1550{
1551 // ReserveBlob cannot be used to reserve a multi-key blob
1552 R__ASSERT(nbytes <= fNTupleAnchor.GetMaxKeySize());
1553
1554 std::uint64_t offset;
1555 if (auto *fileSimple = std::get_if<RImplSimple>(&fFile)) {
1556 if (fIsBare) {
1557 offset = fileSimple->fShared->fKeyOffset;
1558 fileSimple->fShared->fKeyOffset += nbytes;
1559 } else {
1560 offset = fileSimple->ReserveBlobKey(nbytes, len, keyBuffer);
1561 }
1562 } else if (auto *fileProper = std::get_if<RImplTFile>(&fFile)) {
1563 offset = fileProper->ReserveBlobKey(nbytes, len, keyBuffer);
1564 } else {
1565 auto &fileRFile = std::get<RImplRFile>(fFile);
1566 offset = fileRFile.ReserveBlobKey(nbytes, len, keyBuffer);
1567 }
1568 return offset;
1569}
1570
1571void ROOT::Internal::RNTupleFileWriter::WriteIntoReservedBlob(const void *buffer, size_t nbytes, std::int64_t offset)
1572{
1573 if (auto *fileSimple = std::get_if<RImplSimple>(&fFile)) {
1574 fileSimple->Write(buffer, nbytes, offset);
1575 } else if (auto *fileProper = std::get_if<RImplTFile>(&fFile)) {
1576 fileProper->Write(buffer, nbytes, offset);
1577 } else {
1578 auto &fileRFile = std::get<RImplRFile>(fFile);
1579 fileRFile.Write(buffer, nbytes, offset);
1580 }
1581}
1582
1583std::uint64_t ROOT::Internal::RNTupleFileWriter::WriteNTupleHeader(const void *data, size_t nbytes, size_t lenHeader)
1584{
1585 auto offset = WriteBlob(data, nbytes, lenHeader);
1586 fNTupleAnchor.fLenHeader = lenHeader;
1587 fNTupleAnchor.fNBytesHeader = nbytes;
1588 fNTupleAnchor.fSeekHeader = offset;
1589 return offset;
1590}
1591
1592std::uint64_t ROOT::Internal::RNTupleFileWriter::WriteNTupleFooter(const void *data, size_t nbytes, size_t lenFooter)
1593{
1594 auto offset = WriteBlob(data, nbytes, lenFooter);
1595 fNTupleAnchor.fLenFooter = lenFooter;
1596 fNTupleAnchor.fNBytesFooter = nbytes;
1597 fNTupleAnchor.fSeekFooter = offset;
1598 return offset;
1599}
1600
1602{
1603 RBareFileHeader bareHeader;
1604 bareHeader.fCompress = defaultCompression;
1605 auto &fileSimple = std::get<RImplSimple>(fFile);
1606 fileSimple.Write(&bareHeader, sizeof(bareHeader), 0);
1607 RTFString ntupleName{fNTupleName};
1608 fileSimple.Write(ntupleName.GetData(), ntupleName.GetSize());
1609
1610 // Write zero-initialized ntuple to reserve the space; will be overwritten on commit
1611 RTFNTuple ntupleOnDisk;
1612 fileSimple.fShared->fControlBlock->fSeekNTuple = fileSimple.fShared->fFilePos;
1613 fileSimple.Write(&ntupleOnDisk, ntupleOnDisk.GetSize());
1614 std::uint64_t checksum = 0;
1615 fileSimple.Write(&checksum, sizeof(checksum));
1616 fileSimple.fShared->fKeyOffset = fileSimple.fShared->fFilePos;
1617}
1618
1620{
1621 // The streamer info record is a TList of TStreamerInfo object. We cannot use
1622 // RNTupleSerializer::SerializeStreamerInfos because that uses TBufferIO::WriteObject.
1623 // This would prepend the streamed TList with self-decription information.
1624 // The streamer info record is just the streamed TList.
1625
1626 TList streamerInfoList;
1627 for (auto [_, info] : fStreamerInfoMap) {
1628 streamerInfoList.Add(info);
1629 }
1630
1631 // We will stream the list with a TBufferFile. When reading the streamer info records back,
1632 // the read buffer includes the key and the streamed list. Therefore, we need to start streaming
1633 // with an offset of the key length. Otherwise, the offset for referencing duplicate objects in the
1634 // buffer will point to the wrong places.
1635
1636 // Figure out key length
1637 RTFString strTList{"TList"};
1638 RTFString strStreamerInfo{"StreamerInfo"};
1639 RTFString strStreamerTitle{"Doubly linked list"};
1640 auto &fileSimple = std::get<RImplSimple>(fFile);
1641 fileSimple.fShared->fControlBlock->fHeader.SetSeekInfo(fileSimple.fShared->fKeyOffset);
1642 auto keyLen = RTFKey(fileSimple.fShared->fControlBlock->fHeader.GetSeekInfo(), RTFHeader::kBEGIN, strTList,
1643 strStreamerInfo, strStreamerTitle, 0)
1644 .fKeyLen;
1645
1646 TBufferFile buffer(TBuffer::kWrite, keyLen + 1);
1647 buffer.SetBufferOffset(keyLen);
1648 streamerInfoList.Streamer(buffer);
1649 assert(buffer.Length() > keyLen);
1650 const auto bufPayload = buffer.Buffer() + keyLen;
1651 const auto lenPayload = buffer.Length() - keyLen;
1652
1653 auto zipStreamerInfos = MakeUninitArray<unsigned char>(lenPayload);
1654 auto szZipStreamerInfos = RNTupleCompressor::Zip(bufPayload, lenPayload, compression, zipStreamerInfos.get());
1655
1656 fileSimple.WriteKey(zipStreamerInfos.get(), szZipStreamerInfos, lenPayload,
1657 fileSimple.fShared->fControlBlock->fHeader.GetSeekInfo(), RTFHeader::kBEGIN, "TList",
1658 "StreamerInfo", "Doubly linked list");
1659 fileSimple.fShared->fControlBlock->fHeader.SetNbytesInfo(fileSimple.fShared->fFilePos -
1660 fileSimple.fShared->fControlBlock->fHeader.GetSeekInfo());
1661}
1662
1664{
1665 RTFString strEmpty;
1666 RTFString strRNTupleClass{"ROOT::RNTuple"};
1667 RTFString strRNTupleName{fNTupleName};
1668 RTFString strFileName{fFileName};
1669
1670 auto &fileSimple = std::get<RImplSimple>(fFile);
1671 RTFKey keyRNTuple(fileSimple.fShared->fControlBlock->fSeekNTuple, RTFHeader::kBEGIN, strRNTupleClass, strRNTupleName,
1672 strEmpty, RTFNTuple::GetSizePlusChecksum(), anchorSize);
1673
1674 auto &fileShared = *fileSimple.fShared;
1675 fileSimple.fShared->fControlBlock->fFileRecord.SetSeekKeys(fileShared.fKeyOffset);
1676 RTFKeyList keyList{1};
1677 RTFKey keyKeyList(fileSimple.fShared->fControlBlock->fFileRecord.GetSeekKeys(), RTFHeader::kBEGIN, strEmpty,
1678 strFileName, strEmpty, keyList.GetSize() + keyRNTuple.fKeyLen);
1679 fileSimple.Write(&keyKeyList, keyKeyList.GetHeaderSize(),
1680 fileSimple.fShared->fControlBlock->fFileRecord.GetSeekKeys());
1681 fileSimple.Write(strEmpty.GetData(), strEmpty.GetSize());
1682 fileSimple.Write(strFileName.GetData(), strFileName.GetSize());
1683 fileSimple.Write(strEmpty.GetData(), strEmpty.GetSize());
1684 fileSimple.Write(&keyList, keyList.GetSize());
1685 fileSimple.Write(&keyRNTuple, keyRNTuple.GetHeaderSize());
1686 // Write class name, object name, and title for this key.
1687 fileSimple.Write(strRNTupleClass.GetData(), strRNTupleClass.GetSize());
1688 fileSimple.Write(strRNTupleName.GetData(), strRNTupleName.GetSize());
1689 fileSimple.Write(strEmpty.GetData(), strEmpty.GetSize());
1690 fileSimple.fShared->fControlBlock->fFileRecord.fNBytesKeys =
1691 fileShared.fFilePos - fileSimple.fShared->fControlBlock->fFileRecord.GetSeekKeys();
1692 fileShared.fKeyOffset = fileShared.fFilePos;
1693}
1694
1696{
1697 auto &fileSimple = std::get<RImplSimple>(fFile);
1698 auto &fileShared = *fileSimple.fShared;
1699 fileSimple.fShared->fControlBlock->fHeader.SetSeekFree(fileShared.fKeyOffset);
1700 RTFString strEmpty;
1701 RTFString strFileName{fFileName};
1702 RTFFreeEntry freeEntry;
1703 RTFKey keyFreeList(fileSimple.fShared->fControlBlock->fHeader.GetSeekFree(), RTFHeader::kBEGIN, strEmpty,
1704 strFileName, strEmpty, freeEntry.GetSize());
1705 std::uint64_t firstFree = fileSimple.fShared->fControlBlock->fHeader.GetSeekFree() + keyFreeList.GetSize();
1706 freeEntry.Set(firstFree, std::max(2000000000ULL, ((firstFree / 1000000000ULL) + 1) * 1000000000ULL));
1707 fileSimple.WriteKey(&freeEntry, freeEntry.GetSize(), freeEntry.GetSize(),
1708 fileSimple.fShared->fControlBlock->fHeader.GetSeekFree(), RTFHeader::kBEGIN, "", fFileName, "");
1709 fileSimple.fShared->fControlBlock->fHeader.SetNbytesFree(fileShared.fFilePos -
1710 fileSimple.fShared->fControlBlock->fHeader.GetSeekFree());
1711 fileSimple.fShared->fControlBlock->fHeader.SetEnd(fileShared.fFilePos);
1712}
1713
1715{
1716 RTFString strRNTupleClass{"ROOT::RNTuple"};
1717 RTFString strRNTupleName{fNTupleName};
1718 RTFString strEmpty;
1719
1720 RTFNTuple ntupleOnDisk(fNTupleAnchor);
1721 RUInt64BE checksum{XXH3_64bits(ntupleOnDisk.GetPtrCkData(), ntupleOnDisk.GetSizeCkData())};
1722 auto &fileSimple = std::get<RImplSimple>(fFile);
1723 fileSimple.fShared->fControlBlock->fSeekNTuple = fileSimple.fShared->fKeyOffset;
1724
1725 char keyBuf[RTFNTuple::GetSizePlusChecksum()];
1726
1727 // concatenate the RNTuple anchor with its checksum
1728 memcpy(keyBuf, &ntupleOnDisk, sizeof(RTFNTuple));
1729 memcpy(keyBuf + sizeof(RTFNTuple), &checksum, sizeof(checksum));
1730
1731 const auto sizeAnchor = sizeof(RTFNTuple) + sizeof(checksum);
1732 char zipAnchor[RTFNTuple::GetSizePlusChecksum()];
1733 auto szZipAnchor = RNTupleCompressor::Zip(keyBuf, sizeAnchor, compression, zipAnchor);
1734
1735 ROOT::Internal::RNTupleLink anchorLink;
1736 auto anchorOffset =
1737 fileSimple.WriteKey(zipAnchor, szZipAnchor, sizeof(keyBuf), fileSimple.fShared->fControlBlock->fSeekNTuple,
1738 RTFHeader::kBEGIN, "ROOT::RNTuple", fNTupleName, "");
1739
1740 assert(szZipAnchor < std::numeric_limits<decltype(anchorLink.fLength)>::max());
1741 anchorLink.fLength = sizeof(keyBuf);
1742 anchorLink.fLocator.SetPosition(anchorOffset);
1743 anchorLink.fLocator.SetNBytesOnStorage(szZipAnchor);
1744 return anchorLink;
1745}
1746
1748{
1749 RTFString strTFile{"TFile"};
1750 RTFString strFileName{fFileName};
1751 RTFString strEmpty;
1752
1753 auto &fileSimple = std::get<RImplSimple>(fFile);
1754 fileSimple.fShared->fControlBlock->fHeader = RTFHeader(defaultCompression);
1755
1756 RTFUUID uuid;
1757
1758 // First record of the file: the TFile object at offset kBEGIN (= 100)
1759 RTFKey keyRoot(RTFHeader::kBEGIN, 0, strTFile, strFileName, strEmpty,
1760 sizeof(RTFDirectory) + strFileName.GetSize() + strEmpty.GetSize() + uuid.GetSize());
1761 std::uint32_t nbytesName = keyRoot.fKeyLen + strFileName.GetSize() + 1;
1762 fileSimple.fShared->fControlBlock->fFileRecord.fNBytesName = nbytesName;
1763 fileSimple.fShared->fControlBlock->fHeader.SetNbytesName(nbytesName);
1764
1765 fileSimple.Write(&keyRoot, keyRoot.GetHeaderSize(), RTFHeader::kBEGIN);
1766 // Write class name, object name, and title for the TFile key.
1767 fileSimple.Write(strTFile.GetData(), strTFile.GetSize());
1768 fileSimple.Write(strFileName.GetData(), strFileName.GetSize());
1769 fileSimple.Write(strEmpty.GetData(), strEmpty.GetSize());
1770 // Write the name and title of the TNamed preceding the TFile entry.
1771 fileSimple.Write(strFileName.GetData(), strFileName.GetSize());
1772 fileSimple.Write(strEmpty.GetData(), strEmpty.GetSize());
1773 // Will be overwritten on commit
1774 fileSimple.fShared->fControlBlock->fSeekFileRecord = fileSimple.fShared->fFilePos;
1775 fileSimple.Write(&fileSimple.fShared->fControlBlock->fFileRecord,
1776 fileSimple.fShared->fControlBlock->fFileRecord.GetSize());
1777 fileSimple.Write(&uuid, uuid.GetSize());
1778
1779 // Padding bytes to allow the TFile record to grow for a big file
1780 RUInt32BE padding{0};
1781 for (int i = 0; i < 3; ++i)
1782 fileSimple.Write(&padding, sizeof(padding));
1783 fileSimple.fShared->fKeyOffset = fileSimple.fShared->fFilePos;
1784}
std::string className
Definition JSONIO.cxx:31
T ReadBuffer(TBufferFile *buf)
One of the template functions used to read objects from messages.
Definition MPSendRecv.h:158
#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
static size_t ComputeNumChunks(size_t nbytes, size_t maxChunkSize)
static std::uint64_t ReadTFString(std::uint64_t offset, ROOT::Internal::RMiniFileReader &reader, std::string *str)
Reads the TFile string at the given offset.
#define ROOT_VERSION_CODE
Definition RVersion.hxx:27
#define ClassDefInlineOverride(name, id)
Definition Rtypes.h:359
#define R__ASSERT(e)
Checks condition e and reports a fatal error if it's false.
Definition TError.h:139
const Int_t kBEGIN
Definition TFile.cxx:207
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
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 length
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 UChar_t len
char name[80]
Definition TGX11.cxx:142
T1 fFirst
Definition X11Events.mm:86
#define _(A, B)
Definition cfortran.h:112
The RKeyBlob writes an invisible key into a TFile.
bool WasAllocatedInAFreeSlot() const
void Reserve(size_t nbytes, std::uint64_t *seekKey)
Register a new key for a data record of size nbytes.
Read RNTuple data blocks from a TFile container, provided by a RRawFile.
Definition RMiniFile.hxx:55
void ReadBuffer(void *buffer, size_t nbytes, std::uint64_t offset)
Reads a given byte range from the file into the provided memory buffer.
void LoadStreamerInfo()
Load the streamer info from the file into the global list of streamer infos.
RResult< RNTuple > GetNTupleProperAtOffset(std::uint64_t payloadOffset, std::uint64_t compSize, std::uint64_t uncompLen)
Loads an RNTuple anchor from a TFile at the given file offset (unzipping it if necessary).
RResult< RNTuple > GetNTupleBare(std::string_view ntupleName)
Used when the file container turns out to be a bare file.
ROOT::RResult< void > TryReadBuffer(void *buffer, size_t nbytes, std::uint64_t offset)
Like ReadBuffer but returns a RResult instead of throwing.
std::uint64_t SearchInDirectory(std::uint64_t &offsetDir, std::string_view keyName, std::string_view typeName)
Searches for a key with the given name and type in the key index of the directory starting at offsetD...
RResult< RNTuple > GetNTuple(std::string_view ntupleName)
Extracts header and footer location for the RNTuple identified by ntupleName.
RResult< RNTuple > GetNTupleProper(std::string_view ntuplePath)
Used when the file turns out to be a TFile container.
static std::size_t Zip(const void *from, std::size_t nbytes, int compression, void *to)
Returns the size of the compressed data, written into the provided output buffer.
static void Unzip(const void *from, size_t nbytes, size_t dataLen, void *to)
The nbytes parameter provides the size ls of the from buffer.
Write RNTuple data blocks in a TFile or a bare file container.
std::uint64_t ReserveBlob(size_t nbytes, size_t len, unsigned char keyBuffer[kBlobKeyLen]=nullptr)
Reserves a new record as an RBlob key in the file.
ROOT::Internal::RNTupleLink WriteTFileNTupleKey(int compression)
The only key that will be visible in file->ls() Returns the link to the RNTuple anchor.
void WriteTFileStreamerInfo(int compression)
Write the compressed streamer info record with the description of the RNTuple class.
std::string fNTupleName
The identifier of the RNTuple; A single writer object can only write a single RNTuple but multiple wr...
void WriteTFileKeysList(std::uint64_t anchorSize)
Write the TList with the RNTuple key.
void WriteBareFileSkeleton(int defaultCompression)
For a bare file, which is necessarily written by a C file stream, write file header.
std::uint64_t WriteNTupleHeader(const void *data, size_t nbytes, size_t lenHeader)
Writes the compressed header and registeres its location; lenHeader is the size of the uncompressed h...
static std::uint64_t ReserveBlobKey(T &caller, TFile &file, std::size_t nbytes, std::size_t len, unsigned char keyBuffer[kBlobKeyLen])
static std::unique_ptr< RNTupleFileWriter > Append(std::string_view ntupleName, TDirectory &fileOrDirectory, std::uint64_t maxKeySize, bool isHidden)
The directory parameter can also be a TFile object (TFile inherits from TDirectory).
void WriteTFileFreeList()
Last record in the file.
std::unique_ptr< RNTupleFileWriter > CloneAsHidden(std::string_view ntupleName) const
Creates a new RNTupleFileWriter with the same underlying TDirectory as this but writing to a differen...
void WriteTFileSkeleton(int defaultCompression)
For a TFile container written by a C file stream, write the header and TFile object.
RNTupleFileWriter(std::string_view name, std::uint64_t maxKeySize, bool isHidden)
Private constructor used by all factory methods.
void Seek(std::uint64_t offset)
Seek a simple writer to offset.
ROOT::Internal::RNTupleSerializer::StreamerInfoMap_t fStreamerInfoMap
Set of streamer info records that should be written to the file.
std::uint64_t WriteBlob(const void *data, size_t nbytes, size_t len)
Writes a new record as an RBlob key into the file.
static std::unique_ptr< RNTupleFileWriter > Recreate(std::string_view ntupleName, std::string_view path, EContainerFormat containerFormat, const ROOT::RNTupleWriteOptions &options)
Create or truncate the local file given by path with the new empty RNTuple identified by ntupleName.
void WriteIntoReservedBlob(const void *buffer, size_t nbytes, std::int64_t offset)
Write into a reserved record; the caller is responsible for making sure that the written byte range i...
static constexpr std::size_t kBlobKeyLen
The key length of a blob. It is always a big key (version > 1000) with class name RBlob.
RNTupleLink Commit(int compression=RCompressionSetting::EDefaults::kUseGeneralPurpose)
Writes the RNTuple key to the file so that the header and footer keys can be found.
static void PrepareBlobKey(std::int64_t offset, size_t nbytes, size_t len, unsigned char buffer[kBlobKeyLen])
Prepares buffer for a new record as an RBlob key at offset.
std::uint64_t WriteNTupleFooter(const void *data, size_t nbytes, size_t lenFooter)
Writes the compressed footer and registeres its location; lenFooter is the size of the uncompressed f...
bool fIsHidden
True if this RNTuple's anchor must be stored as a hidden key (this is the case e.g....
void UpdateStreamerInfos(const ROOT::Internal::RNTupleSerializer::StreamerInfoMap_t &streamerInfos)
Ensures that the streamer info records passed as argument are written to the file.
RNTuple fNTupleAnchor
Header and footer location of the ntuple, written on Commit()
EContainerFormat
For testing purposes, RNTuple data can be written into a bare file container instead of a ROOT file.
std::map< Int_t, TVirtualStreamerInfo * > StreamerInfoMap_t
static std::uint32_t DeserializeUInt64(const void *buffer, std::uint64_t &val)
static std::uint32_t SerializeUInt64(std::uint64_t val, void *buffer)
The RRawFile provides read-only access to local and remote files.
Definition RRawFile.hxx:43
Base class for all ROOT issued exceptions.
Definition RError.hxx:78
An interface to read from, or write to, a ROOT file, as well as performing other common operations.
Definition RFile.hxx:289
std::uint64_t GetNBytesOnStorage() const
void SetType(ELocatorType type)
void SetPosition(std::uint64_t position)
void SetNBytesOnStorage(std::uint64_t nBytesOnStorage)
Common user-tunable settings for storing RNTuples.
std::size_t GetWriteBufferSize() const
std::uint64_t GetMaxKeySize() const
std::uint32_t GetCompression() const
Representation of an RNTuple data set in a ROOT file.
Definition RNTuple.hxx:67
std::uint64_t GetLenFooter() const
Definition RNTuple.hxx:140
std::uint64_t GetSeekHeader() const
Definition RNTuple.hxx:134
std::uint16_t GetVersionMajor() const
Definition RNTuple.hxx:130
std::uint64_t GetNBytesFooter() const
Definition RNTuple.hxx:139
std::uint64_t GetNBytesHeader() const
Definition RNTuple.hxx:135
std::uint64_t fMaxKeySize
The maximum size for a TKey payload. Payloads bigger than this size will be written as multiple blobs...
Definition RNTuple.hxx:121
std::uint16_t GetVersionMinor() const
Definition RNTuple.hxx:131
std::uint16_t GetVersionPatch() const
Definition RNTuple.hxx:132
std::uint64_t GetMaxKeySize() const
Definition RNTuple.hxx:141
std::uint64_t GetLenHeader() const
Definition RNTuple.hxx:136
static TClass * Class()
std::uint64_t GetSeekFooter() const
Definition RNTuple.hxx:138
std::uint16_t GetVersionEpoch() const
Definition RNTuple.hxx:129
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
The concrete implementation of TBuffer for writing/reading to/from a ROOT file or socket.
Definition TBufferFile.h:47
void TagStreamerInfo(TVirtualStreamerInfo *info) override
Mark the classindex of the current file as using this TStreamerInfo.
void SetBufferDisplacement() override
Definition TBufferIO.h:82
void SetParent(TObject *parent)
Set parent owning this buffer.
Definition TBuffer.cxx:269
@ kWrite
Definition TBuffer.h:73
@ kRead
Definition TBuffer.h:73
void SetBufferOffset(Int_t offset=0)
Definition TBuffer.h:93
Int_t Length() const
Definition TBuffer.h:100
char * Buffer() const
Definition TBuffer.h:96
TVirtualStreamerInfo * GetStreamerInfo(Int_t version=0, Bool_t isTransient=kFALSE) const
returns a pointer to the TVirtualStreamerInfo object for version If the object does not exist,...
Definition TClass.cxx:4716
Describe directory structure in memory.
Definition TDirectory.h:45
virtual TFile * GetFile() const
Definition TDirectory.h:221
A file, usually with extension .root, that stores data and code in the form of serialized objects in ...
Definition TFile.h:130
Bool_t IsBinary() const
Definition TFile.h:349
Book space in a file, create I/O buffers, to fill them, (un)compress them.
Definition TKey.h:28
Int_t Sizeof() const override
Return the size in bytes of the key header structure.
Definition TKey.cxx:1504
Int_t fVersion
Key version identifier.
Definition TKey.h:41
Int_t fLeft
Number of bytes left in current segment.
Definition TKey.h:50
Short_t fKeylen
Number of bytes for the key itself.
Definition TKey.h:45
Long64_t fSeekKey
Location of object on file.
Definition TKey.h:47
virtual void Create(Int_t nbytes, TFile *f=nullptr)
Create a TKey object of specified size.
Definition TKey.cxx:513
virtual char * GetBuffer() const
Definition TKey.h:80
TString fClassName
Object Class name.
Definition TKey.h:49
A doubly linked list.
Definition TList.h:38
void Streamer(TBuffer &) override
Stream all objects in the collection to or from the I/O buffer.
Definition TList.cxx:1323
void Add(TObject *obj) override
Definition TList.h:81
virtual TObjLink * FirstLink() const
Definition TList.h:107
Describes a persistent version of a class.
void BuildCheck(TFile *file=nullptr, Bool_t load=kTRUE) override
Check if built and consistent with the class dictionary.
static TClass * Class()
This class defines a UUID (Universally Unique IDentifier), also known as GUIDs (Globally Unique IDent...
Definition TUUID.h:42
static TUUID UUIDv4()
Create a UUID version 4 (variant 1) UUID according to RFC 4122.
Definition TUUID.cxx:157
void FillBuffer(char *&buffer)
Stream UUID into output buffer.
Definition TUUID.cxx:306
RNTuple CreateAnchor(std::uint16_t versionEpoch, std::uint16_t versionMajor, std::uint16_t versionMinor, std::uint16_t versionPatch, std::uint64_t seekHeader, std::uint64_t nbytesHeader, std::uint64_t lenHeader, std::uint64_t seekFooter, std::uint64_t nbytesFooter, std::uint64_t lenFooter, std::uint64_t maxKeySize)
Definition RNTuple.cxx:51
TFile * GetRFileTFile(RFile &rfile)
Definition RFile.cxx:618
Helper templated class for swapping bytes; specializations for N={2,4,8} are provided below.
Definition Byteswap.h:124
void Write(const void *buffer, size_t nbytes, std::int64_t offset)
Low-level writing using a TFile.
std::uint64_t ReserveBlobKey(size_t nbytes, size_t len, unsigned char keyBuffer[kBlobKeyLen]=nullptr)
Reserves an RBlob opaque key as data record and returns the offset of the record.
void AllocateBuffers(std::size_t bufferSize)
std::uint64_t WriteKey(const void *buffer, std::size_t nbytes, std::size_t len, std::int64_t offset=-1, std::uint64_t directoryOffset=100, const std::string &className="", const std::string &objectName="", const std::string &title="")
Writes a TKey including the data record, given by buffer, into fFile; returns the file offset to the ...
static constexpr int kBlockAlign
Direct I/O requires that all buffers and write lengths are aligned.
void Write(const void *buffer, size_t nbytes, std::int64_t offset=-1)
Writes bytes in the open stream, either at fFilePos or at the given offset.
static constexpr std::size_t kHeaderBlockSize
During commit, WriteTFileKeysList() updates fNBytesKeys and fSeekKeys of the RTFFile located at fSeek...
std::shared_ptr< RSharedData > fShared
std::uint64_t ReserveBlobKey(std::size_t nbytes, std::size_t len, unsigned char keyBuffer[kBlobKeyLen]=nullptr)
Reserves an RBlob opaque key as data record and returns the offset of the record.
TDirectory * fDirectory
A sub directory in fFile or nullptr if the data is stored in the root directory of the file.
void Write(const void *buffer, size_t nbytes, std::int64_t offset)
Low-level writing using a TFile.
std::uint64_t ReserveBlobKey(size_t nbytes, size_t len, unsigned char keyBuffer[kBlobKeyLen]=nullptr)
Reserves an RBlob opaque key as data record and returns the offset of the record.
If a TFile container is written by a C stream (simple file), on dataset commit, the file header and t...
auto * tt
Definition textangle.C:16