-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathrntuple.mjs
More file actions
1545 lines (1303 loc) · 50 KB
/
rntuple.mjs
File metadata and controls
1545 lines (1303 loc) · 50 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { isStr, isObject } from './core.mjs';
import { R__unzip } from './io.mjs';
import { TDrawSelector, treeDraw } from './tree.mjs';
// ENTupleColumnType - supported column types
const kBit = 0x00,
kByte = 0x01,
kChar = 0x02,
kInt8 = 0x03,
kUInt8 = 0x04,
kInt16 = 0x05,
kUInt16 = 0x06,
kInt32 = 0x07,
kUInt32 = 0x08,
kInt64 = 0x09,
kUInt64 = 0x0A,
kReal16 = 0x0B,
kReal32 = 0x0C,
kReal64 = 0x0D,
kIndex32 = 0x0E,
kIndex64 = 0x0F,
kSwitch = 0x10,
kSplitInt16 = 0x11,
kSplitUInt16 = 0x12,
kSplitInt32 = 0x13,
kSplitUInt32 = 0x14,
kSplitInt64 = 0x15,
kSplitUInt64 = 0x16,
kSplitReal16 = 0x17,
kSplitReal32 = 0x18,
kSplitReal64 = 0x19,
kSplitIndex32 = 0x1A,
kSplitIndex64 = 0x1B,
kReal32Trunc = 0x1C,
kReal32Quant = 0x1D,
LITTLE_ENDIAN = true;
class RBufferReader {
constructor(buffer) {
if (buffer instanceof ArrayBuffer) {
this.buffer = buffer;
this.byteOffset = 0;
this.byteLength = buffer.byteLength;
} else if (ArrayBuffer.isView(buffer)) {
this.buffer = buffer.buffer;
this.byteOffset = buffer.byteOffset;
this.byteLength = buffer.byteLength;
} else
throw new TypeError('Invalid buffer type');
this.view = new DataView(this.buffer);
// important - offset should start from actual place in the buffer
this.offset = this.byteOffset;
}
// Move to a specific position in the buffer
seek(position) {
if (typeof position === 'bigint') {
if (position > BigInt(Number.MAX_SAFE_INTEGER))
throw new Error(`Offset too large to seek safely: ${position}`);
this.offset = Number(position);
} else
this.offset = position;
}
// Read unsigned 8-bit integer (1 BYTE)
readU8() {
const val = this.view.getUint8(this.offset);
this.offset += 1;
return val;
}
// Read unsigned 16-bit integer (2 BYTES)
readU16() {
const val = this.view.getUint16(this.offset, LITTLE_ENDIAN);
this.offset += 2;
return val;
}
// Read unsigned 32-bit integer (4 BYTES)
readU32() {
const val = this.view.getUint32(this.offset, LITTLE_ENDIAN);
this.offset += 4;
return val;
}
// Read signed 8-bit integer (1 BYTE)
readS8() {
const val = this.view.getInt8(this.offset);
this.offset += 1;
return val;
}
// Read signed 16-bit integer (2 BYTES)
readS16() {
const val = this.view.getInt16(this.offset, LITTLE_ENDIAN);
this.offset += 2;
return val;
}
// Read signed 32-bit integer (4 BYTES)
readS32() {
const val = this.view.getInt32(this.offset, LITTLE_ENDIAN);
this.offset += 4;
return val;
}
// Read 32-bit float (4 BYTES)
readF32() {
const val = this.view.getFloat32(this.offset, LITTLE_ENDIAN);
this.offset += 4;
return val;
}
// Read 64-bit float (8 BYTES)
readF64() {
const val = this.view.getFloat64(this.offset, LITTLE_ENDIAN);
this.offset += 8;
return val;
}
// Read a string with 32-bit length prefix
readString() {
const length = this.readU32();
let str = '';
for (let i = 0; i < length; i++)
str += String.fromCharCode(this.readU8());
return str;
}
// Read unsigned 64-bit integer (8 BYTES)
readU64() {
const val = this.view.getBigUint64(this.offset, LITTLE_ENDIAN);
this.offset += 8;
return val;
}
// Read signed 64-bit integer (8 BYTES)
readS64() {
const val = this.view.getBigInt64(this.offset, LITTLE_ENDIAN);
this.offset += 8;
return val;
}
}
/** @summary Rearrange bytes from split format to normal format (row-wise) for decoding
* @private */
function recontructUnsplitBuffer(view, coltype) {
// Determine byte size based on column type
let byteSize;
switch (coltype) {
case kSplitReal64:
case kSplitInt64:
case kSplitUInt64:
case kSplitIndex64:
byteSize = 8;
break;
case kSplitReal32:
case kSplitInt32:
case kSplitIndex32:
case kSplitUInt32:
byteSize = 4;
break;
case kSplitInt16:
case kSplitUInt16:
case kSplitReal16:
byteSize = 2;
break;
default:
return view;
}
const count = view.byteLength / byteSize,
outBuffer = new ArrayBuffer(view.byteLength),
outView = new DataView(outBuffer);
for (let i = 0; i < count; ++i) {
for (let b = 0; b < byteSize; ++b) {
const splitIndex = b * count + i,
byte = view.getUint8(splitIndex),
writeIndex = i * byteSize + b;
outView.setUint8(writeIndex, byte);
}
}
return outView;
}
/** @summary Decode a 32 bit intex buffer
* @private */
function decodeIndex32(view) {
for (let o = 0, prev = 0; o < view.byteLength; o += 4) {
const v = prev + view.getInt32(o, LITTLE_ENDIAN);
view.setInt32(o, v, LITTLE_ENDIAN);
prev = v;
}
}
/** @summary Decode a 64 bit intex buffer
* @private */
function decodeIndex64(view, shift) {
for (let o = 0, prev = 0n; o < view.byteLength; o += (8 + shift)) {
const v = prev + view.getBigInt64(o, LITTLE_ENDIAN);
view.setBigInt64(o, v, LITTLE_ENDIAN);
prev = v;
}
}
/** @summary Decode a reconstructed 16bit signed integer buffer using ZigZag encoding
* @private */
function decodeZigzag16(view) {
for (let o = 0; o < view.byteLength; o += 2) {
const x = view.getUint16(o, LITTLE_ENDIAN);
view.setInt16(o, (x >>> 1) ^ (-(x & 1)), LITTLE_ENDIAN);
}
}
/** @summary Decode a reconstructed 32bit signed integer buffer using ZigZag encoding
* @private */
function decodeZigzag32(view) {
for (let o = 0; o < view.byteLength; o += 4) {
const x = view.getUint32(o, LITTLE_ENDIAN);
view.setInt32(o, (x >>> 1) ^ (-(x & 1)), LITTLE_ENDIAN);
}
}
/** @summary Decode a reconstructed 64bit signed integer buffer using ZigZag encoding
* @private */
function decodeZigzag64(view) {
for (let o = 0; o < view.byteLength; o += 8) {
const x = view.getUint64(o, LITTLE_ENDIAN);
view.setInt64(o, (x >>> 1) ^ (-(x & 1)), LITTLE_ENDIAN);
}
}
// Envelope Types
// TODO: Define usage logic for envelope types in future
// const kEnvelopeTypeHeader = 0x01,
// kEnvelopeTypeFooter = 0x02,
// kEnvelopeTypePageList = 0x03,
// Field Flags
const kFlagRepetitiveField = 0x01,
kFlagProjectedField = 0x02,
kFlagHasTypeChecksum = 0x04,
// Column Flags
kFlagDeferredColumn = 0x01,
kFlagHasValueRange = 0x02;
class RNTupleDescriptorBuilder {
deserializeHeader(header_blob) {
if (!header_blob)
return;
const reader = new RBufferReader(header_blob),
payloadStart = reader.offset,
// Read the envelope metadata
{ envelopeLength } = this._readEnvelopeMetadata(reader),
// Seek to end of envelope to get checksum
checksumPos = payloadStart + envelopeLength - 8,
currentPos = reader.offset;
reader.seek(checksumPos);
this.headerEnvelopeChecksum = reader.readU64();
reader.seek(currentPos);
// Read feature flags list (may span multiple 64-bit words)
this._readFeatureFlags(reader);
// Read metadata strings
this.name = reader.readString();
this.description = reader.readString();
this.writer = reader.readString();
// 4 list frames inside the header envelope
this._readSchemaDescription(reader);
}
deserializeFooter(footer_blob) {
if (!footer_blob)
return;
const reader = new RBufferReader(footer_blob);
// Read the envelope metadata
this._readEnvelopeMetadata(reader);
// Feature flag(32 bits)
this._readFeatureFlags(reader);
// Header checksum (64-bit xxhash3)
const headerChecksumFromFooter = reader.readU64();
if (headerChecksumFromFooter !== this.headerEnvelopeChecksum)
throw new Error('RNTuple corrupted: header checksum does not match footer checksum.');
const schemaExtensionSize = reader.readS64();
if (schemaExtensionSize < 0)
throw new Error('Schema extension frame is not a record frame, which is unexpected.');
// Schema extension record frame (4 list frames inside)
this._readSchemaDescription(reader);
// Cluster Group record frame
this._readClusterGroups(reader);
}
_readEnvelopeMetadata(reader) {
const typeAndLength = reader.readU64(),
// Envelope metadata
// The 16 bits are the envelope type ID, and the 48 bits are the envelope length
envelopeType = Number(typeAndLength & 0xFFFFn),
envelopeLength = Number((typeAndLength >> 16n) & 0xFFFFFFFFFFFFn);
return {
envelopeType,
envelopeLength
};
}
_readSchemaDescription(reader) {
// Reading new descriptor arrays from the input
const newFields = this._readFieldDescriptors(reader),
newColumns = this._readColumnDescriptors(reader),
newAliases = this._readAliasColumn(reader),
newExtra = this._readExtraTypeInformation(reader);
// Merging these new arrays into existing arrays
this.fieldDescriptors = (this.fieldDescriptors || []).concat(newFields);
this.columnDescriptors = (this.columnDescriptors || []).concat(newColumns);
this.aliasColumns = (this.aliasColumns || []).concat(newAliases);
this.extraTypeInfo = (this.extraTypeInfo || []).concat(newExtra);
}
_readFeatureFlags(reader) {
this.featureFlags = [];
while (true) {
const val = reader.readU64();
this.featureFlags.push(val);
if ((val & 0x8000000000000000n) === 0n)
break; // MSB not set: end of list
}
// verify all feature flags are zero
if (this.featureFlags.some(v => v !== 0n))
throw new Error('Unexpected non-zero feature flags: ' + this.featureFlags);
}
_readFieldDescriptors(reader) {
const startOffset = BigInt(reader.offset),
fieldListSize = reader.readS64(), // signed 64-bit
fieldListIsList = fieldListSize < 0;
if (!fieldListIsList)
throw new Error('Field list frame is not a list frame, which is required.');
const fieldListCount = reader.readU32(), // number of field entries
// List frame: list of field record frames
fieldDescriptors = [];
for (let i = 0; i < fieldListCount; ++i) {
const recordStart = BigInt(reader.offset),
fieldRecordSize = reader.readS64(),
fieldVersion = reader.readU32(),
typeVersion = reader.readU32(),
parentFieldId = reader.readU32(),
structRole = reader.readU16(),
flags = reader.readU16(),
fieldName = reader.readString(),
typeName = reader.readString(),
typeAlias = reader.readString(),
description = reader.readString();
let arraySize = null,
sourceFieldId = null,
checksum = null;
if (flags & kFlagRepetitiveField)
arraySize = reader.readU64();
if (flags & kFlagProjectedField)
sourceFieldId = reader.readU32();
if (flags & kFlagHasTypeChecksum)
checksum = reader.readU32();
fieldDescriptors.push({
fieldVersion,
typeVersion,
parentFieldId,
structRole,
flags,
fieldName,
typeName,
typeAlias,
description,
arraySize,
sourceFieldId,
checksum
});
reader.seek(Number(recordStart + fieldRecordSize));
}
reader.seek(Number(startOffset - fieldListSize));
return fieldDescriptors;
}
_readColumnDescriptors(reader) {
const startOffset = BigInt(reader.offset),
columnListSize = reader.readS64(),
columnListIsList = columnListSize < 0;
if (!columnListIsList)
throw new Error('Column list frame is not a list frame, which is required.');
const columnListCount = reader.readU32(), // number of column entries
columnDescriptors = [];
for (let i = 0; i < columnListCount; ++i) {
const recordStart = BigInt(reader.offset),
columnRecordSize = reader.readS64(),
coltype = reader.readU16(),
bitsOnStorage = reader.readU16(),
fieldId = reader.readU32(),
flags = reader.readU16(),
representationIndex = reader.readU16();
let firstElementIndex = null,
minValue = null,
maxValue = null;
if (flags & kFlagDeferredColumn)
firstElementIndex = reader.readU64();
if (flags & kFlagHasValueRange) {
minValue = reader.readF64();
maxValue = reader.readF64();
}
const column = {
coltype,
bitsOnStorage,
fieldId,
flags,
representationIndex,
firstElementIndex,
minValue,
maxValue,
index: i
};
column.isDeferred = function() {
return (this.flags & RNTupleDescriptorBuilder.kFlagDeferredColumn) !== 0;
};
column.isSuppressed = function() {
return this.firstElementIndex !== null && this.firstElementIndex < 0;
};
columnDescriptors.push(column);
reader.seek(Number(recordStart + columnRecordSize));
}
reader.seek(Number(startOffset - columnListSize));
return columnDescriptors;
}
_readAliasColumn(reader) {
const startOffset = BigInt(reader.offset),
aliasColumnListSize = reader.readS64(),
aliasListisList = aliasColumnListSize < 0;
if (!aliasListisList)
throw new Error('Alias column list frame is not a list frame, which is required.');
const aliasColumnCount = reader.readU32(), // number of alias column entries
aliasColumns = [];
for (let i = 0; i < aliasColumnCount; ++i) {
const recordStart = BigInt(reader.offset),
aliasColumnRecordSize = reader.readS64(),
physicalColumnId = reader.readU32(),
fieldId = reader.readU32();
aliasColumns.push({
physicalColumnId,
fieldId
});
reader.seek(Number(recordStart + aliasColumnRecordSize));
}
reader.seek(Number(startOffset - aliasColumnListSize));
return aliasColumns;
}
_readExtraTypeInformation(reader) {
const startOffset = BigInt(reader.offset),
extraTypeInfoListSize = reader.readS64(),
isList = extraTypeInfoListSize < 0;
if (!isList)
throw new Error('Extra type info frame is not a list frame, which is required.');
const entryCount = reader.readU32(),
extraTypeInfo = [];
for (let i = 0; i < entryCount; ++i) {
const recordStart = BigInt(reader.offset),
extraTypeInfoRecordSize = reader.readS64(),
contentId = reader.readU32(),
typeVersion = reader.readU32();
extraTypeInfo.push({
contentId,
typeVersion
});
reader.seek(Number(recordStart + extraTypeInfoRecordSize));
}
reader.seek(Number(startOffset - extraTypeInfoListSize));
return extraTypeInfo;
}
_readClusterGroups(reader) {
const startOffset = BigInt(reader.offset),
clusterGroupListSize = reader.readS64(),
isList = clusterGroupListSize < 0;
if (!isList)
throw new Error('Cluster group frame is not a list frame');
const groupCount = reader.readU32();
this.clusterGroups = [];
for (let i = 0; i < groupCount; ++i) {
const recordStart = BigInt(reader.offset),
clusterRecordSize = reader.readS64(),
minEntry = reader.readU64(),
entrySpan = reader.readU64(),
numClusters = reader.readU32(),
pageListLength = reader.readU64(),
// Locator method to get the page list locator offset
pageListLocator = this._readLocator(reader);
this.clusterGroups.push({ minEntry, entrySpan, numClusters, pageListLocator, pageListLength });
reader.seek(Number(recordStart + clusterRecordSize));
}
reader.seek(Number(startOffset - clusterGroupListSize));
}
_readLocator(reader) {
const sizeAndType = reader.readU32(); // 4 bytes: size + T bit
if ((sizeAndType | 0) < 0) // | makes the sizeAndType as signed
throw new Error('Non-standard locators (T=1) not supported yet');
const size = sizeAndType,
offset = reader.readU64(); // 8 bytes: offset
return { size, offset };
}
deserializePageList(page_list_blob) {
if (!page_list_blob)
throw new Error('deserializePageList: received an invalid or empty page list blob');
const reader = new RBufferReader(page_list_blob);
this._readEnvelopeMetadata(reader);
// Page list checksum (64-bit xxhash3)
const pageListHeaderChecksum = reader.readU64();
if (pageListHeaderChecksum !== this.headerEnvelopeChecksum)
throw new Error('RNTuple corrupted: header checksum does not match Page List Header checksum.');
const listStartOffset = BigInt(reader.offset),
// Read cluster summaries list frame
clusterSummaryListSize = reader.readS64();
if (clusterSummaryListSize >= 0)
throw new Error('Expected a list frame for cluster summaries');
const clusterSummaryCount = reader.readU32();
this.clusterSummaries = [];
for (let i = 0; i < clusterSummaryCount; ++i) {
const recordStart = BigInt(reader.offset),
clusterSummaryRecordSize = reader.readS64(),
firstEntry = reader.readU64(),
combined = reader.readU64(),
flags = combined >> 56n,
numEntries = Number(combined & 0x00FFFFFFFFFFFFFFn);
if (flags & 0x01n)
throw new Error('Cluster summary uses unsupported sharded flag (0x01)');
this.clusterSummaries.push({ firstEntry, numEntries, flags });
reader.seek(Number(recordStart + clusterSummaryRecordSize));
}
reader.seek(Number(listStartOffset - clusterSummaryListSize));
this._readNestedFrames(reader);
reader.readU64(); // checksumPagelist
}
_readNestedFrames(reader) {
const numListClusters = reader.readS64(),
numRecordCluster = reader.readU32();
if (numListClusters >= 0)
throw new Error('Expected list frame for clusters');
this.pageLocations = [];
for (let i = 0; i < numRecordCluster; ++i) {
const outerListSize = reader.readS64();
if (outerListSize >= 0)
throw new Error('Expected outer list frame for columns');
const numColumns = reader.readU32(),
columns = [];
for (let c = 0; c < numColumns; ++c) {
const innerListSize = reader.readS64();
if (innerListSize >= 0)
throw new Error('Expected inner list frame for pages');
const numPages = reader.readU32(),
pages = [];
for (let p = 0; p < numPages; ++p) {
const numElementsWithBit = reader.readS32(),
hasChecksum = numElementsWithBit < 0,
numElements = BigInt(Math.abs(Number(numElementsWithBit))),
locator = this._readLocator(reader);
pages.push({
numElements,
hasChecksum,
locator
});
}
const elementOffset = reader.readS64(),
isSuppressed = elementOffset < 0,
compression = isSuppressed ? null : reader.readU32();
columns.push({
pages,
elementOffset,
isSuppressed,
compression
});
}
this.pageLocations.push(columns);
}
}
/** @summary Search field by name
* @private */
findField(name) {
for (let n = 0; n < this.fieldDescriptors.length; ++n) {
const field = this.fieldDescriptors[n];
if (field.fieldName === name)
return field;
}
}
/** @summary Return all childs of specified field
* @private */
findChildFields(field) {
const indx = this.fieldDescriptors.indexOf(field), res = [];
for (let n = 0; n < this.fieldDescriptors.length; ++n) {
const fld = this.fieldDescriptors[n];
if ((fld !== field) && (fld.parentFieldId === indx))
res.push(fld);
}
return res;
}
/** @summary Return array of columns for specified field
* @private */
findColumns(field) {
const res = [];
if (!field)
return res;
for (const colDesc of this.columnDescriptors) {
if (this.fieldDescriptors[colDesc.fieldId] === field)
res.push(colDesc);
}
return res;
}
} // class RNTupleDescriptorBuilder
/** @summary Very preliminary function to read header/footer from RNTuple
* @private */
async function readHeaderFooter(tuple) {
// if already read - return immediately, make possible to call several times
if (tuple?.builder)
return tuple.builder;
if (!tuple?.$file)
return null;
// request header and footer buffers from the file
return tuple.$file.readBuffer([tuple.fSeekHeader, tuple.fNBytesHeader, tuple.fSeekFooter, tuple.fNBytesFooter]).then(blobs => {
if (blobs?.length !== 2)
throw new Error('Failure reading header or footer blobs');
// Handle both compressed and uncompressed cases
const processBlob = (blob, uncompressedSize) => {
// If uncompressedSize matches blob size, it's uncompressed
if (blob.byteLength === uncompressedSize)
return Promise.resolve(blob);
return R__unzip(blob, uncompressedSize);
};
return Promise.all([
processBlob(blobs[0], tuple.fLenHeader),
processBlob(blobs[1], tuple.fLenFooter)
]);
}).then(unzip_blobs => {
const [header_blob, footer_blob] = unzip_blobs;
if (!header_blob || !footer_blob)
throw new Error('Failure when uncompress header and footer blobs');
tuple.builder = new RNTupleDescriptorBuilder;
tuple.builder.deserializeHeader(header_blob);
tuple.builder.deserializeFooter(footer_blob);
// Deserialize Page List
const group = tuple.builder.clusterGroups?.[0];
if (!group || !group.pageListLocator)
throw new Error('No valid cluster group or page list locator found');
const offset = Number(group.pageListLocator.offset),
size = Number(group.pageListLocator.size);
return tuple.$file.readBuffer([offset, size]);
}).then(page_list_blob => {
if (!(page_list_blob instanceof DataView))
throw new Error(`Expected DataView from readBuffer, got ${Object.prototype.toString.call(page_list_blob)}`);
const group = tuple.builder.clusterGroups?.[0],
uncompressedSize = Number(group.pageListLength);
// Check if page list data is uncompressed
if (page_list_blob.byteLength === uncompressedSize)
return page_list_blob;
// Attempt to decompress the page list
return R__unzip(page_list_blob, uncompressedSize);
}).then(unzipped_blob => {
if (!(unzipped_blob instanceof DataView))
throw new Error(`Unzipped page list is not a DataView, got ${Object.prototype.toString.call(unzipped_blob)}`);
tuple.builder.deserializePageList(unzipped_blob);
return tuple.builder;
}).catch(err => {
console.error('Error during readHeaderFooter execution:', err);
return null;
});
}
/** @class Base class to read columns/fields from RNtuple
* @private */
class ReaderItem {
constructor(column, name) {
this.column = null;
this.name = name;
this.id = -1;
this.coltype = 0;
this.sz = 0;
this.simple = true;
this.page = -1; // current page for the reading
if (column?.coltype !== undefined) {
this.column = column;
this.id = column.index;
this.coltype = column.coltype;
// special handling of split types
if ((this.coltype >= kSplitInt16) && (this.coltype <= kSplitIndex64)) {
this.coltype -= (kSplitInt16 - kInt16);
this.simple = false;
}
} else if (column?.length)
this.items = column;
}
cleanup() {
this.views = null;
this.view = null;
this.view_len = 0;
}
init_o() {
this.o = 0;
this.o2 = 0; // for bit count
if (this.column && this.views?.length) {
this.view = this.views.shift();
this.view_len = this.view.byteLength;
}
}
reset_extras() {}
shift_o(sz) {
this.o += sz;
while ((this.o >= this.view_len) && this.view_len) {
this.o -= this.view_len;
if (this.views.length) {
this.view = this.views.shift();
this.view_len = this.view.byteLength;
} else {
this.view = null;
this.view_len = 0;
}
}
}
shift(entries) {
if (this.sz && this.simple)
this.shift_o(this.sz * entries);
else {
while (entries-- > 0)
this.func({});
}
}
/** @summary Simple column with fixed element size - no vectors, no strings */
is_simple() { return this.sz && this.simple; }
set_not_simple() {
this.simple = false;
this.items?.forEach(item => item.set_not_simple());
}
assignReadFunc() {
switch (this.coltype) {
case kBit: {
this.func = function(obj) {
if (this.o2 === 0)
this.byte = this.view.getUint8(this.o);
obj[this.name] = ((this.byte >>> this.o2++) & 1) === 1;
if (this.o2 === 8) {
this.o2 = 0;
this.shift_o(1);
}
};
break;
}
case kReal64:
this.func = function(obj) {
obj[this.name] = this.view.getFloat64(this.o, LITTLE_ENDIAN);
this.shift_o(8);
};
this.sz = 8;
break;
case kReal32:
this.func = function(obj) {
obj[this.name] = this.view.getFloat32(this.o, LITTLE_ENDIAN);
this.shift_o(4);
};
this.sz = 4;
break;
case kReal16:
this.func = function(obj) {
const value = this.view.getUint16(this.o, LITTLE_ENDIAN);
this.shift_o(2);
// reimplementing of HalfToFloat
let fbits = (value & 0x8000) << 16,
abs = value & 0x7FFF;
if (abs) {
fbits |= 0x38000000 << (abs >= 0x7C00 ? 1 : 0);
for (; abs < 0x400; abs <<= 1, fbits -= 0x800000);
fbits += abs << 13;
}
this.buf.setUint32(0, fbits, true);
obj[this.name] = this.buf.getFloat32(0, true);
};
this.sz = 2;
this.buf = new DataView(new ArrayBuffer(4), 0);
break;
case kReal32Trunc:
case kReal32Quant:
this.nbits = this.column.bitsOnStorage;
if (this.coltype === kReal32Trunc)
this.buf = new DataView(new ArrayBuffer(4), 0);
else {
this.factor = (this.column.maxValue - this.column.minValue) / ((1 << this.nbits) - 1);
this.min = this.column.minValue;
}
this.func = function(obj) {
let res = 0, len = this.nbits;
// extract nbits from the
while (len > 0) {
if (this.o2 === 0) {
this.byte = this.view.getUint8(this.o);
this.o2 = 8; // number of bits in the value
}
const pos = this.nbits - len; // extracted bits
if (len >= this.o2) {
res |= (this.byte & ((1 << this.o2) - 1)) << pos; // get all remaining bits
len -= this.o2;
this.o2 = 0;
this.shift_o(1);
} else {
res |= (this.byte & ((1 << len) - 1)) << pos; // get only len bits from the value
this.o2 -= len;
this.byte >>= len;
len = 0;
}
}
if (this.buf) {
this.buf.setUint32(0, res << (32 - this.nbits), true);
obj[this.name] = this.buf.getFloat32(0, true);
} else
obj[this.name] = res * this.factor + this.min;
};
break;
case kInt64:
case kIndex64:
this.func = function(obj) {
// FIXME: let process BigInt in the TTree::Draw
obj[this.name] = Number(this.view.getBigInt64(this.o, LITTLE_ENDIAN));
this.shift_o(8);
};
this.sz = 8;
break;
case kUInt64:
this.func = function(obj) {
// FIXME: let process BigInt in the TTree::Draw
obj[this.name] = Number(this.view.getBigUint64(this.o, LITTLE_ENDIAN));
this.shift_o(8);
};
this.sz = 8;
break;
case kSwitch:
this.func = function(obj) {
// index not used in std::variant, may be in some other usecases
// obj[this.name] = Number(this.view.getBigInt64(this.o, LITTLE_ENDIAN));
this.shift_o(8); // skip value, not used yet
obj[this.name] = this.view.getInt32(this.o, LITTLE_ENDIAN);
this.shift_o(4);
};
this.sz = 12;
break;
case kInt32:
case kIndex32:
this.func = function(obj) {
obj[this.name] = this.view.getInt32(this.o, LITTLE_ENDIAN);
this.shift_o(4);
};
this.sz = 4;
break;
case kUInt32:
this.func = function(obj) {
obj[this.name] = this.view.getUint32(this.o, LITTLE_ENDIAN);
this.shift_o(4);
};
this.sz = 4;
break;
case kInt16:
this.func = function(obj) {
obj[this.name] = this.view.getInt16(this.o, LITTLE_ENDIAN);
this.shift_o(2);
};
this.sz = 2;
break;
case kUInt16:
this.func = function(obj) {
obj[this.name] = this.view.getUint16(this.o, LITTLE_ENDIAN);
this.shift_o(2);
};
this.sz = 2;
break;
case kInt8:
this.func = function(obj) {
obj[this.name] = this.view.getInt8(this.o);
this.shift_o(1);
};
this.sz = 1;
break;
case kUInt8:
case kByte:
this.func = function(obj) {
obj[this.name] = this.view.getUint8(this.o);
this.shift_o(1);
};
this.sz = 1;
break;
case kChar:
this.func = function(obj) {
obj[this.name] = String.fromCharCode(this.view.getInt8(this.o));
this.shift_o(1);
};
this.sz = 1;
break;
default:
throw new Error(`Unsupported column type: ${this.coltype}`);
}
}
readStr(len) {
let s = '';
while (len-- > 0) {
s += String.fromCharCode(this.view.getInt8(this.o));
this.shift_o(1);
}
return s;
}