-
Notifications
You must be signed in to change notification settings - Fork 33
/
ONElib.c
3925 lines (3361 loc) · 115 KB
/
ONElib.c
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
/*****************************************************************************************
*
* file: ONElib.c
* implementation for ONElib.h
*
* Author: Richard Durbin (rd109@cam.ac.uk)
* Copyright (C) Richard Durbin, Cambridge University and Eugene Myers 2019-
*
* HISTORY:
* Last edited: Dec 4 23:57 2022 (rd109)
* * Apr 23 00:31 2020 (rd109): global rename of VGP to ONE, Vgp to One, vgp to one
* * Apr 20 11:27 2020 (rd109): added VgpSchema to make schema dynamic
* * Dec 27 09:46 2019 (gene): style edits + compactify code
* * Jul 8 04:28 2019 (rd109): refactored to use info[]
* * Created: Thu Feb 21 22:40:28 2019 (rd109)
*
****************************************************************************************/
#include <sys/errno.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <sys/resource.h>
#include <stdarg.h>
#include <time.h>
#include <ctype.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/uio.h>
#include <math.h>
#ifdef DEBUG
#include <assert.h>
#else
#define assert(x)
#endif
#include "ONElib.h"
// set major and minor code versions
#define MAJOR 1
#define MINOR 1
// utilities with implementation at the end of the file
static void die(char *format, ...); // print message to stderr and exit -1
static void *myalloc(size_t size); // allocate block, die if malloc fails
static void *mycalloc(size_t number, size_t size); // allocate & zero # objects of size
#define new(n,type) (type *) myalloc((n)*sizeof(type)) // actually use these not myalloc
#define new0(n,type) (type *) mycalloc((n),sizeof(type))
// global required for parallelisation
static pthread_mutex_t mutexInit = PTHREAD_MUTEX_INITIALIZER;
// forward declarations of serialisation functions lower in the file
// RD 220818: I think that many of int below should be I64, e.g. for len, ilen etc.
OneCodec *vcCreate();
void vcAddToTable(OneCodec *vc, int len, char *bytes);
void vcAddHistogram(OneCodec *vc, OneCodec *vh);
void vcCreateCodec(OneCodec *vc, int partial);
void vcDestroy(OneCodec *vc);
int vcMaxSerialSize();
int vcSerialize(OneCodec *vc, void *out);
OneCodec *vcDeserialize(void *in);
int vcEncode(OneCodec *vc, int ilen, char *ibytes, char *obytes);
int vcDecode(OneCodec *vc, int ilen, char *ibytes, char *obytes);
// forward declarations of 64-bit integer encoding/decoding
static inline int ltfWrite (I64 x, FILE *f) ;
static inline I64 ltfRead (FILE *f) ;
/***********************************************************************************
*
* ONE_FILE CREATION & DESTRUCTION
*
**********************************************************************************/
char* oneTypeString[] = { 0, "INT", "REAL", "CHAR", "STRING",
"INT_LIST", "REAL_LIST", "STRING_LIST", "DNA" } ;
/******************* OneInfo ********************/
static OneInfo *infoCreate (int nField)
{ OneInfo *vi = new0 (1, OneInfo) ;
vi->nField = nField ;
if (nField) vi->fieldType = new (nField, OneType) ;
return vi;
}
static OneInfo *infoDeepCopy (OneInfo *vi0)
{ OneInfo *vi = new (1, OneInfo) ;
*vi = *vi0 ;
if (vi->nField)
{ vi->fieldType = new (vi->nField, OneType) ;
memcpy (vi->fieldType, vi0->fieldType, vi->nField*sizeof(OneType)) ;
}
if (vi->listCodec && vi->listCodec != DNAcodec) vi->listCodec = vcCreate() ;
if (vi->comment) vi->comment = strdup (vi0->comment) ;
return vi ;
}
static bool infoCheckFields (OneInfo *vi, OneFile *vf)
{ // check field types against the STRING_LIST in vf
char *s = oneString(vf) ;
int i ;
if (vi->nField != oneLen(vf)) return false ;
for (i = 0 ; i < vi->nField ; ++i, s = oneNextString(vf,s))
if (strcmp (oneTypeString[vi->fieldType[i]], s)) return false ;
return true ;
}
static void infoDestroy (OneInfo *vi)
{ if (vi->buffer && ! vi->isUserBuf) free (vi->buffer) ;
if (vi->listCodec) vcDestroy (vi->listCodec) ;
if (vi->fieldType) free (vi->fieldType) ;
if (vi->comment) free (vi->comment) ;
free (vi);
}
/******************* OneSchema ********************/
// a utility to set the OneInfo list information
static int listEltSize[9] = { 0, 0, 0, 0, 1, sizeof(I64), sizeof(double), 1, 1 } ;
static void schemaAddInfoFromArray (OneSchema *vs, int n, OneType *a, char t, char type)
{
// use during the bootstrap, while parsing .def files, and while parsing ~ lines in other files
if (vs->info[(int) t])
die ("duplicate schema specification for linetype %c in filetype %s", t, vs->primary) ;
if (isalpha(t) && type == 'G')
{ if (vs->groupType) die ("second group type in schema for filetype %s", vs->primary) ;
vs->groupType = t ;
}
else if (isalpha(t) && type == 'O')
{ if (vs->objectType) die ("second object type in schema for filetype %s", vs->primary) ;
vs->objectType = t ;
}
else if (vs->primary && (type != 'D' || !isalpha(t))) // allow non-alphabetic lines in header
die ("non-alphabetic linetype %c (ascii %d) in schema for filetype %s",t,t,vs->primary) ;
if (n > vs->nFieldMax) vs->nFieldMax = n ;
OneInfo *vi = infoCreate (n) ;
memcpy (vi->fieldType, a, n*sizeof(OneType)) ;
int i ;
for (i = 0 ; i < n ; ++i)
if (a[i] >= oneSTRING)
{ if (vi->listEltSize)
die ("OneFile schema error; multiple list types for linetype definition %c", t) ;
vi->listEltSize = listEltSize[vi->fieldType[i]] ;
vi->listField = i ;
if (a[i] == oneDNA)
{ vi->listCodec = DNAcodec ; vi->isUseListCodec = true ; }
else
vi->listCodec = vcCreate () ; // always make a listCodec for any list type
}
if (t >= 'A' && t <= 'Z') vi->binaryTypePack = ((t-'A') << 1) | (char) 0x80 ;
else if (t >= 'a' && t <= 'z') vi->binaryTypePack = ((26+t-'a') << 1) | (char) 0x80 ;
else if (t == ';') vi->binaryTypePack = (52 << 2) | (char) 0x80 ;
else if (t == '&') vi->binaryTypePack = (53 << 2) | (char) 0x80 ;
else if (t == '*') vi->binaryTypePack = (54 << 2) | (char) 0x80 ;
else if (t == '/') vi->binaryTypePack = (55 << 2) | (char) 0x80 ;
else if (t == '.') vi->binaryTypePack = (56 << 2) | (char) 0x80 ;
vs->info[(int)t] = vi ;
}
static void schemaAddInfoFromLine (OneSchema *vs, OneFile *vf, char t, char type)
{ // assumes field specification is in the STRING_LIST of the current vf line
// need to set vi->comment separately
static OneType a[32] ;
int i ;
OneType j ;
char *s = oneString(vf) ;
int n = oneLen(vf) ;
if (n > 32)
die ("line specification %d fields too long - need to recompile", n) ;
for (i = 0 ; i < n ; ++i, s = oneNextString(vf,s))
{ a[i] = 0 ;
for (j = oneINT ; j <= oneDNA ; ++j)
if (!strcmp (s, oneTypeString[j])) a[i] = j ;
if (!a[i])
die ("ONE schema error: bad field %d of %d type %s in line %d type %c",
i, n, s, vf->line, t) ;
}
schemaAddInfoFromArray (vs, n, a, t, type) ;
if (oneReadComment (vf))
vs->info[(int)t]->comment = strdup (oneReadComment(vf)) ;
}
static OneSchema *schemaLoadRecord (OneSchema *vs, OneFile *vf)
{ char *s;
// parse a schema specfication line from vf and add into vs
// return value is vs unless a new primary type is declared, in which case vs->nxt
switch (vf->lineType)
{
case '.': // ignore - blank or comment line in schema file
break ;
case 'P':
if (vs->primary && !vs->objectType)
die ("schema: file type %s has no object type", vs->primary) ;
if (oneLen(vf) == 0) die ("schema: primary name must have at least one letter") ;
OneSchema *vsNxt = new0 (1, OneSchema) ;
vs->nxt = vsNxt ;
vs = vsNxt ;
s = oneString(vf);
vs->primary = new (oneLen(vf)+1, char) ;
strcpy (vs->primary, s) ;
vs->nFieldMax = 4 ; // needed for header
break ;
case 'S':
if (oneLen(vf) == 0) die ("schema: secondary name must have at least one letter") ;
if (vs->nSecondary)
{ char **temp = vs->secondary ;
vs->secondary = new (vs->nSecondary+1, char*) ;
memcpy (vs->secondary, temp, vs->nSecondary*sizeof(char*)) ;
free (temp) ;
}
else
vs->secondary = new (1, char*) ;
s = oneString(vf);
vs->secondary[vs->nSecondary] = new0 (oneLen(vf)+1, char) ;
strcpy (vs->secondary[vs->nSecondary++], s) ;
break ;
case 'G': // group type
case 'O': // object type
case 'D': // standard record type
schemaAddInfoFromLine (vs, vf, oneChar(vf,0), vf->lineType) ;
break ;
default:
die ("unrecognized schema line %d starting with %c", vf->line, vf->lineType) ;
}
return vs ;
}
static void oneFileDestroy (OneFile *vf) ; // need a forward declaration here
OneSchema *oneSchemaCreateFromFile (char *filename)
{
FILE *fs = fopen (filename, "r") ;
if (!fs) return 0 ;
fclose(fs);
OneSchema *vs = new0 (1, OneSchema) ;
OneFile *vf = new0 (1, OneFile) ; // shell object to support bootstrap
// bootstrap specification of linetypes to read schemas
{ OneInfo *vi ;
vi = vf->info['P'] = infoCreate (1) ; // to define the schema for parsing a .def file
vi->fieldType[0] = oneSTRING ; vi->listEltSize = 1 ; vi->listField = 0 ;
vi = vf->info['O'] = infoCreate (2) ; // object type specification
vi->fieldType[0] = oneCHAR ;
vi->fieldType[1] = oneSTRING_LIST ; vi->listEltSize = 1 ; vi->listField = 1 ;
vi = vf->info['D'] = infoCreate (2) ; // line type specification
vi->fieldType[0] = oneCHAR ;
vi->fieldType[1] = oneSTRING_LIST ; vi->listEltSize = 1 ; vi->listField = 1 ;
vf->info['/'] = infoCreate (0) ; // to store comments
vf->field = new (2, OneField) ;
}
// first load the universal header and footer (non-alphabetic) line types
// do this by writing their schema into a temporary file and parsing it into the base schema
{ errno = 0 ;
static char template[64] ;
#define VALGRIND_MACOS
#ifdef VALGRIND_MACOS // MacOS valgrind is missing functions to make temp files it seems
sprintf (template, "/tmp/OneSchema.%d", getpid()) ;
vf->f = fopen (template, "w+") ;
if (errno) die ("failed to open temporary file %s errno %d\n", template, errno) ;
#else
strcpy (template, "/tmp/OneSchema.XXXXXX") ;
int fd = mkstemp (template) ;
if (errno) die ("failed to open temporary file %s errno %d\n", template, errno) ;
vf->f = fdopen (fd, "w+") ;
if (errno) die ("failed to assign temporary file to stream: errno %d\n", errno) ;
#endif
unlink (template) ; // this ensures that the file is removed on closure
if (errno) die ("failed to remove temporary file %s errno %d\n", template, errno) ;
}
// NB if you change the header spec and add a record with more than 4 fields,
// change the assignment of ->nFieldMax in the 'P' section of schemaLoadRecord() above
fprintf (vf->f, "D 1 3 6 STRING 3 INT 3 INT first line: 3-letter type, major, minor version\n") ;
fprintf (vf->f, "D 2 1 6 STRING subtype: 3-letter subtype\n") ;
fprintf (vf->f, "D # 2 4 CHAR 3 INT linetype, count\n") ;
fprintf (vf->f, "D @ 2 4 CHAR 3 INT linetype, list max\n") ;
fprintf (vf->f, "D + 2 4 CHAR 3 INT linetype, list total\n") ;
fprintf (vf->f, "D %% 4 4 CHAR 4 CHAR 4 CHAR 3 INT group, #/+, linetype, value\n") ;
fprintf (vf->f, "D ! 1 11 STRING_LIST provenance: program, version, command, date\n") ;
fprintf (vf->f, "D < 2 6 STRING 3 INT reference: filename, object count\n") ;
fprintf (vf->f, "D > 1 6 STRING deferred: filename\n") ;
fprintf (vf->f, "D ~ 3 4 CHAR 4 CHAR 11 STRING_LIST embedded schema linetype definition\n") ;
fprintf (vf->f, "D . 0 blank line, anywhere in file\n") ;
fprintf (vf->f, "D $ 1 3 INT binary file - goto footer: isBigEndian\n") ;
fprintf (vf->f, "D ^ 0 binary file: end of footer designation\n") ;
fprintf (vf->f, "D - 1 3 INT binary file: offset of start of footer\n") ;
fprintf (vf->f, "D & 1 8 INT_LIST binary file: object index\n") ;
fprintf (vf->f, "D * 1 8 INT_LIST binary file: group index\n") ;
fprintf (vf->f, "D ; 2 4 CHAR 6 STRING binary file: list codec\n") ;
fprintf (vf->f, "D / 1 6 STRING binary file: comment\n") ;
if (fseek (vf->f, 0, SEEK_SET)) die ("ONE schema failure: cannot rewind tmp file") ;
while (oneReadLine (vf))
schemaLoadRecord (vs, vf) ;
// next reuse the temp file to load the schema for reading schemas
if (fseek (vf->f, 0, SEEK_SET)) die ("ONE schema failure: cannot rewind tmp file") ;
fprintf (vf->f, "P 3 def this is the primary file type for schemas\n") ;
fprintf (vf->f, "O P 1 6 STRING primary type name\n") ;
fprintf (vf->f, "D S 1 6 STRING secondary type name\n") ;
fprintf (vf->f, "D G 2 4 CHAR 11 STRING_LIST define linetype for groupType\n") ;
fprintf (vf->f, "D O 2 4 CHAR 11 STRING_LIST define linetype for objectType\n") ;
fprintf (vf->f, "D D 2 4 CHAR 11 STRING_LIST define linetype for other records\n") ;
fprintf (vf->f, "\n") ; // terminator
if (fseek (vf->f, 0, SEEK_SET)) die ("ONE schema failure: cannot rewind tmp file") ;
OneSchema *vs0 = vs ; // need this because loadInfo() updates vs on reading P lines
vf->line = 0 ;
while (oneReadLine (vf))
vs = schemaLoadRecord (vs, vf) ;
OneSchema *vsDef = vs ; // will need this to destroy it once the true schema is read
oneFileDestroy (vf) ; // this will also effectively remove the temp file on closing
// finally read the schema itself
if (!(vf = oneFileOpenRead (filename, vs0, "def", 1)))
return 0 ;
vs = vs0 ; // set back to vs0, so next filetype spec will replace vsDef
vs->nxt = 0 ;
oneSchemaDestroy (vsDef) ; // no longer need this, and can destroy because unlinked from vs0
while (oneReadLine (vf))
vs = schemaLoadRecord (vs, vf) ;
oneFileDestroy (vf) ;
return vs0 ;
}
static char *schemaFixNewlines (const char *text)
{ // replace literal "\n" by '\n' chars in text
char *newText = strdup (text) ;
char *s = newText, *t = s ;
while (*s)
if (*s == '\\' && s[1] == 'n')
{ *t++ = '\n' ; s += 2 ; }
else
*t++ = *s++ ;
*t = 0 ;
return newText ;
}
OneSchema *oneSchemaCreateFromText (char *text) // write to temp file and call CreateFromFile()
{
static char template[64] ;
sprintf (template, "/tmp/OneTextSchema-%d.def", getpid()) ;
errno = 0 ;
FILE *f = fopen (template, "w") ;
char *fixedText = schemaFixNewlines (text) ;
fprintf (f, "%s\n", fixedText) ;
free (fixedText) ;
fclose (f) ;
if (errno) die ("failed to write temporary file %s errno %d\n", template, errno) ;
OneSchema *vs = oneSchemaCreateFromFile (template) ;
errno = 0 ;
unlink (template) ; // delete temporary file - not ideal: will remain if schemaCreate crashes
if (errno) die ("failed to remove temporary file %s errno %d\n", template, errno) ;
return vs ;
}
static OneSchema *oneSchemaCreateDynamic (char *fileType, char *subType)
{ // this is clean, but it seems a bit wasteful to create a temp file
char text[32] ;
assert (fileType && strlen(fileType) > 0) ;
assert (!subType || strlen(subType) > 0) ;
if (subType)
sprintf (text, "P %d %s\nS %d %s\n", (int) strlen(fileType),fileType,
(int) strlen(subType), subType) ;
else
sprintf (text, "P %d %s\n", (int) strlen(fileType), fileType) ;
OneSchema *vs = oneSchemaCreateFromText (text) ;
return vs ;
}
void oneSchemaDestroy (OneSchema *vs)
{ int i ;
while (vs)
{ for (i = 0 ; i < 128 ; ++i) if (vs->info[i]) infoDestroy (vs->info[i]) ;
if (vs->nSecondary)
{ for (i = 0 ; i < vs->nSecondary ; ++i) free (vs->secondary[i]) ;
free (vs->secondary) ;
}
free(vs->primary);
OneSchema *t = vs->nxt ;
free (vs) ;
vs = t ;
}
}
/*************************************/
static inline void setCodecBuffer (OneInfo *vi)
{
vi->bufSize = vcMaxSerialSize() + 1; // +1 for added but unused 0-terminator
vi->buffer = new (vi->bufSize, void);
}
static OneFile *oneFileCreate (OneSchema **vsp, char *type)
{ // searches through the linked list of vs to find type, either as primary or a secondary
// if found fills and returns vf, else returns 0
int i, j ;
OneFile *vf = new0 (1, OneFile) ;
char *secondary = 0 ;
OneSchema *vs = *vsp ;
// fprintf (stderr, "oneFileCreate vs %lx type %s\n", (unsigned long)vs, type) ;
// transfer header info
for (i = 0 ; i < 128 ; ++i)
if (vs->info[i]) vf->info[i] = infoDeepCopy (vs->info[i]) ;
// find type in schema
while ((vs = vs->nxt))
if (!strcmp (type, vs->primary))
break ;
else if (vs->nSecondary)
{ for (j = 0 ; j < vs->nSecondary ; ++j)
if (!strcmp (type, vs->secondary[j])) break ;
if (j < vs->nSecondary) { secondary = vs->secondary[j] ; break ; }
}
if (!vs)
{ oneFileDestroy (vf) ;
return 0 ; // failed to find a match
}
// transfer info from matched schema
for (i = 0 ; i < 128 ; ++i)
if (vs->info[i]) vf->info[i] = infoDeepCopy (vs->info[i]) ;
// build binaryTypeUnpack[]
for (i = 0 ; i < 128 ; ++i)
if (vf->info[i] && vf->info[i]->binaryTypePack)
{ U8 x = vf->info[i]->binaryTypePack ;
vf->binaryTypeUnpack[x] = i ;
vf->binaryTypeUnpack[x+1] = i ;
}
// set other information
vf->objectType = vs->objectType ;
vf->groupType = vs->groupType ;
vf->fileType = new (strlen(vs->primary)+1, char);
strcpy (vf->fileType, vs->primary) ;
if (secondary)
{ vf->subType = new (strlen(secondary)+1, char);
strcpy (vf->subType, secondary) ;
}
vf->nFieldMax = vs->nFieldMax ;
vf->field = new (vf->nFieldMax, OneField) ;
// setup for compression
vf->codecTrainingSize = 100000;
setCodecBuffer (vf->info[';']) ;
// determine endian of machine
{ int t = 1;
char *b = (char *) (&t);
vf->isBig = (*b == 0);
}
*vsp = vs ;
return vf ;
}
static void provRefDefCleanup (OneFile *vf)
{ int n ;
if (vf->provenance)
{ OneProvenance *p = vf->provenance ;
for (n = vf->info['!']->accum.count ; n-- ; p++)
{ free (p->program) ;
free (p->version) ;
free (p->command) ;
free (p->date) ;
}
free (vf->provenance) ;
}
if (vf->reference)
{ OneReference *r = vf->reference ;
for (n = vf->info['<']->accum.count ; n-- ; r++)
free (r->filename) ;
free (vf->reference) ;
}
if (vf->deferred)
{ OneReference *r = vf->deferred ;
for (n = vf->info['>']->accum.count ; n-- ; r++)
free (r->filename) ;
free (vf->deferred) ;
}
}
static void oneFileDestroy (OneFile *vf)
{ int i, j;
OneInfo *li, *lx;
if (vf->share)
{ for (i = 0; i < 128 ; i++)
{ lx = vf->info[i];
if (lx != NULL)
{ for (j = 1; j < vf->share; j++)
{ li = vf[j].info[i];
if (li != lx) // the index OneInfos are shared
{ if (li->listCodec == lx->listCodec) li->listCodec = NULL;
infoDestroy(li);
}
}
}
}
for (j = 1; j < vf->share; j++)
{ provRefDefCleanup (&vf[j]) ;
if (vf[j].codecBuf != NULL) free (vf[j].codecBuf);
if (vf[j].f != NULL) fclose (vf[j].f);
}
}
provRefDefCleanup (vf) ;
if (vf->codecBuf != NULL) free (vf->codecBuf);
if (vf->f != NULL && vf->f != stdout) fclose (vf->f);
for (i = 0; i < 128 ; i++)
if (vf->info[i] != NULL)
infoDestroy (vf->info[i]);
if (vf->field) free (vf->field) ;
if (vf->headerText)
{ OneHeaderText *t = vf->headerText ;
while (t)
{ free (t->text) ;
{ OneHeaderText *nxt = t->nxt ; free (t) ; t = nxt ; }
}
}
free(vf->fileType);
free(vf->subType);
free (vf) ;
}
/***********************************************************************************
*
* ASCII PARSING UTILITIES: error reporting, lexical level
*
**********************************************************************************/
void parseError (OneFile *vf, char *format, ...)
{ va_list args;
fprintf (stderr, "ONE PARSE ERROR ");
va_start (args, format);
vfprintf (stderr, format, args);
va_end (args);
vf->lineBuf[vf->linePos] = '\0';
fprintf (stderr, ", line %" PRId64 ": %s\n", vf->line, vf->lineBuf);
exit (1);
}
static inline char vfGetc(OneFile *vf)
{ char c = getc(vf->f);
if (vf->linePos < 127)
vf->lineBuf[vf->linePos++] = c;
return c;
}
static inline void eatWhite (OneFile *vf)
{ char x = vfGetc(vf);
if (x == ' ') // 200414: removed option to have tab instead of space
return;
parseError (vf, "failed to find expected space separation character");
}
static inline char readChar(OneFile *vf)
{ eatWhite(vf);
return vfGetc(vf);
}
static inline char *readBuf(OneFile *vf)
{ char x, *cp, *endBuf;
eatWhite (vf);
endBuf = vf->numberBuf + 32;
for (cp = vf->numberBuf; cp < endBuf ; cp++)
{ x = vfGetc(vf);
if (isspace(x) || x == '\0' || x == EOF)
break;
*cp = x;
}
if (cp >= endBuf)
{ cp[-1] = 0;
parseError (vf, "overlong item %s", vf->numberBuf);
}
else
{ ungetc (x, vf->f);
vf->linePos -= 1;
*cp = 0;
}
return vf->numberBuf;
}
static inline I64 readInt(OneFile *vf)
{ char *e, *b;
I64 x;
b = readBuf(vf);
x = strtoll(b, &e, 10);
if (e == b)
parseError (vf, "empty int field");
if (*e != '\0')
parseError (vf, "bad int");
return x;
}
static inline double readReal(OneFile *vf)
{ char *e, *b;
double x;
b = readBuf(vf);
x = strtod (b, &e);
if (e == b)
parseError (vf, "empty real field");
if (*e != '\0')
parseError (vf, "bad real");
return (x);
}
static inline void readString(OneFile *vf, char *buf, I64 n)
{ eatWhite (vf);
if (vf->isCheckString)
{ char *cp = buf;
--cp;
while (n-- && (*++cp = vfGetc (vf)))
if (*cp == '\n' || *cp == EOF)
break;
if (++n)
parseError (vf, "line too short %d", buf);
*++cp = 0;
}
else
{ if ((I64) fread (buf, 1, n, vf->f) != n)
die ("ONE parse error: failed to read %d byte string", n);
buf[n] = 0 ;
}
}
static inline void readFlush (OneFile *vf) // reads to the end of the line and stores as comment
{ char x;
int n = 0;
OneInfo *li = vf->info['/'] ;
// check the first character - if it is newline then done
x = getc (vf->f) ;
if (x == '\n')
return ;
else if (x != ' ')
parseError (vf, "comment not separated by a space") ;
// else the remainder of the line is a comment
if (!li->bufSize)
{ li->bufSize = 1024 ;
li->buffer = new (li->bufSize, char) ;
}
while ((x = getc (vf->f)) && x != '\n')
if (x == EOF)
parseError (vf, "premature end of file");
else
{ if ((n+1) >= li->bufSize)
{ char *s = new (2*li->bufSize, char) ;
memcpy (s, li->buffer, li->bufSize) ;
free (li->buffer) ;
li->buffer = s ;
li->bufSize *= 2 ;
}
((char*)li->buffer)[n] = x ;
++n ;
}
((char*)li->buffer)[n] = 0 ; // string terminator
}
/***********************************************************************************
*
* LIST BUFFER & COUNT MANAGEMENT: error reporting, lexical level
*
**********************************************************************************/
// Ensure line type t buffer can handles size+nStrings, and accumulate counts
static inline void updateCountsAndBuffer (OneFile *vf, char t, I64 size, I64 nStrings)
{ OneInfo *li;
li = vf->info[(int) t];
li->accum.total += size;
if (size > li->accum.max)
li->accum.max = size;
size += nStrings; // need to allocate space for terminal 0s
if ( ! li->isUserBuf && size > li->bufSize) // expand buffer
{ if (li->buffer != NULL) free (li->buffer);
li->bufSize = size;
li->buffer = new (size*li->listEltSize, void);
}
}
// Called when a new group starts or eof, accumulate group counts since last group start
static inline void updateGroupCount(OneFile *vf, bool isGroupLine)
{ int i;
OneInfo *li;
OneCounts *ci;
for (i = 'A'; i <= 'Z' ; i++)
{ li = vf->info[i];
if (li != NULL)
{ ci = &(li->accum);
if (vf->inGroup)
{ if (ci->groupCount < ci->count - li->gCount)
ci->groupCount = ci->count - li->gCount;
if (ci->groupTotal < ci->total - li->gTotal)
ci->groupTotal = ci->total - li->gTotal;
}
else
{ li->oCount = ci->count;
li->oTotal = ci->total;
}
li->gCount = ci->count;
li->gTotal = ci->total;
}
}
if (isGroupLine)
{ vf->group += 1;
vf->inGroup = true;
}
}
/***********************************************************************************
*
* BINARY INT LIST COMPACTION & UNCOMPACTION
*
**********************************************************************************/
static char *compactIntList (OneFile *vf, OneInfo *li, I64 len, char *buf, int *usedBytes)
{ char *y;
int d, k;
I64 z, i, mask, *ibuf;
ibuf = (I64 *) buf;
for (i = len-1; i > 0; i--) // convert to differences - often a big win, else harmless
ibuf[i] -= ibuf[i-1];
mask = 0; // find how many top bytes can be skipped
for (i = 1; i < len; i++)
if (ibuf[i] >= 0)
mask |= ibuf[i];
else
mask |= -(ibuf[i]+1);
k = sizeof(I64) ;
mask >>= 7;
for (d = 1; d < k; d++)
{ if (mask == 0)
break;
mask >>= 8;
}
*usedBytes = d ;
z = k - d; // number of 0 bytes
if (z == 0) return (char*)&ibuf[1] ;
if (buf != li->buffer && !li->isUserBuf && (I64) (li->bufSize*sizeof(I64)) < d*len)
{ if (li->buffer != NULL)
free (li->buffer);
li->bufSize = ((d*len) / sizeof(I64)) + 1;
li->buffer = new (li->bufSize * sizeof(I64), void);
}
y = li->buffer ;
buf += sizeof(I64) ; --len ; // don't record the first element of buf, which is not a diff
if (vf->isBig) // copy d bytes per I64, ignoring z before or after depending on isBig
while (len--)
{ buf += z;
for (k = 0; k < d; k++)
*y++ = *buf++;
}
else
while (len--)
{ for (k = 0; k < d; k++)
*y++ = *buf++;
buf += z;
}
return li->buffer ;
}
static void decompactIntList (OneFile *vf, I64 len, char *buf, int usedBytes)
{ int d, z, k;
char *s, *t;
z = sizeof(I64) - usedBytes ;
if (z > 0) // decompacts in place
{ buf += sizeof(I64) ; --len ; // don't decompact 0th element
d = usedBytes;
s = buf + d*len;
t = s + z*len;
if (vf->isBig)
while (s > buf)
{ for (k = 0; k < d; k++)
*--t = *--s;
if (*s & 0x80)
for (k = 0; k < z; k++)
*--t = 0xff;
else
for (k = 0; k < z; k++)
*--t = 0x0;
}
else
while (s > buf)
{ if (s[-1] & 0x80)
for (k = 0; k < z; k++)
*--t = 0xff;
else
for (k = 0; k < z; k++)
*--t = 0;
for (k = 0; k < d; k++)
*--t = *--s;
}
buf -= sizeof(I64) ; ++len ;
}
{ I64 i, *x = (I64 *) buf; // revert differencing
for (i = 1; i < len; i++)
x[i] += x[i-1];
}
}
// read and write compressed fields
static inline int writeCompressedFields (FILE *f, OneField *field, OneInfo *li)
{
int i, n = 0 ;
for (i = 0 ; i < li->nField ; ++i)
switch (li->fieldType[i])
{
case oneREAL: fwrite (&field[i].r, 8, 1, f) ; n += 8 ; break ;
case oneCHAR: putc (field[i].c, f) ; ++n ; break ;
default: // includes INT and all the LISTs, which store their length in field as an INT
n += ltfWrite (field[i].i, f) ;
}
return n ;
}
static inline void readCompressedFields (FILE *f, OneField *field, OneInfo *li)
{
int i ;
for (i = 0 ; i < li->nField ; ++i)
switch (li->fieldType[i])
{
case oneREAL: fread (&field[i].r, 8, 1, f) ; break ;
case oneCHAR: field[i].c = fgetc (f) ; break ;
default: // includes INT and all the LISTs, which store their length in field as an INT
field[i].i = ltfRead (f) ;
}
}
/***********************************************************************************
*
* ONE_READ_LINE:
* Reads the next line and returns false at end of file or on error. The line is
* parsed according to its linetype and contents accessed by macros that follow.
* The top bit of the first character determines whether the line is binary or ascii
*
**********************************************************************************/
// Read a string list, first into new allocs, then into sized line buffer.
// Annoyingly inefficient, but we don't use it very much.
static void readStringList(OneFile *vf, char t, I64 len)
{ int j;
I64 totLen, sLen;
char **string, *buf;
totLen = 0;
string = new (len, char *);
for (j = 0; j < len ; ++j)
{ sLen = readInt (vf);
totLen += sLen;
string[j] = new (sLen+1, char);
readString (vf, string[j], sLen);
}
updateCountsAndBuffer (vf, t, totLen, len);
buf = (char *) vf->info[(int) t]->buffer;
for (j = 0; j < len ; ++j)
{ strcpy (buf, string[j]);
buf += strlen(buf) + 1;
free (string[j]);
}
free (string);
}
static bool addProvenance(OneFile *vf, OneProvenance *from, int n) ; // need forward declaration
char oneReadLine (OneFile *vf)
{ bool isAscii;
U8 x;
char t;
OneInfo *li;
assert (!vf->isWrite) ;
assert (!vf->isFinal) ;
vf->linePos = 0; // must come before first vfGetc()
x = vfGetc (vf); // read first char
if (feof (vf->f) || x == '\n') // blank line (x=='\n') is end of records marker before footer
{ vf->lineType = 0 ; // additional marker of end of file
return 0;
}
vf->line += 1; // otherwise assume this is a good line, and die if not
if (x & 0x80)
{ isAscii = false;
t = vf->binaryTypeUnpack[x];
}
else
{ isAscii = true;
t = x;
}
vf->lineType = t;
li = vf->info[(int) t];
if (li == NULL)
parseError (vf, "unknown line type %c(%d was %d) line %d", t, t, x, (int)vf->line);
li->accum.count += 1;
if (t == vf->objectType)
vf->object += 1;
if (t == vf->groupType)
updateGroupCount (vf, true);
// fprintf (stderr, "reading line %" PRId64 " type %c nField %d listElt %d\n", vf->line, t, li->nField, li->listEltSize) ;
if (vf->info['/']->bufSize) // clear the comment buffer
*(char*)(vf->info['/']->buffer) = 0 ;
vf->nBits = 0 ; // will use for any compressed data read in
if (isAscii) // read field by field according to ascii spec
{ int i, j;
I64 *ilst, len;
double *rlst;
for (i = 0; i < li->nField; i++)
switch (li->fieldType[i])
{
case oneINT:
vf->field[i].i = readInt (vf);
// printf (" field %d int %d\n", i, (int)oneInt(vf,i)) ;
break;
case oneREAL:
vf->field[i].r = readReal (vf);
break;
case oneCHAR:
vf->field[i].c = readChar (vf);
// printf (" field %d char %c\n", i, (int)oneChar(vf,i)) ;
break;
case oneSTRING: