forked from rcedgar/syncmer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmyutils.cpp
2746 lines (2443 loc) · 56.1 KB
/
myutils.cpp
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
#ifdef _MSC_VER
#define _SCL_SECURE_NO_WARNINGS
#define _HAS_ITERATOR_DEBUGGING 0
#define _ITERATOR_DEBUG_LEVEL 0
#define MYUTILS_CPP
#endif
#include <time.h>
#include <stdarg.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
#include <ctype.h>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <signal.h>
#include <float.h>
#include <algorithm>
#include <stdlib.h>
#ifdef _MSC_VER
#define WIN32_LEAN_AND_MEAN
#include <crtdbg.h>
#include <process.h>
#include <windows.h>
#include <psapi.h>
#include <io.h>
#else
#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <dirent.h>
#endif
#ifndef _MSC_VER
#include <dirent.h>
#include <sys/types.h>
#endif
#include "myutils.h"
unsigned g_AllocLine;
const char *g_AllocFile;
static map<FILE *, string> FileToFileName;
const unsigned MY_IO_BUFSIZ = 32000;
const unsigned MAX_FORMATTED_STRING_LENGTH = 64000;
static char *g_IOBuffers[256];
static time_t g_StartTime = time(0);
extern vector<string> g_Argv;
static double g_PeakMemUseBytes;
static char g_TmpStr[64];
unsigned g_AllocCount;
unsigned g_FreeCount;
#if ALLOC_TOTALS
uint64 g_AllocTotal;
uint64 g_FreeTotal;
#endif
const int VER =
#include "ver.h"
;
static const double LOG2 = log(2.0);
static const double LOG10 = log(10.0);
double mylog2(double x)
{
return log(x)/LOG2;
}
double mylog10(double x)
{
return log(x)/LOG10;
}
unsigned GetRequestedThreadCount()
{
static unsigned N = 1;
static bool Done = false;
if (Done)
return N;
unsigned MaxN = omp_get_max_threads();
unsigned CoreCount = GetCPUCoreCount();
if (optset_threads)
N = opt(threads);
else
{
if (CoreCount > 10)
{
Progress("CPU has %u cores, defaulting to 10 threads\n", CoreCount);
N = 10;
}
else
N = CoreCount;
}
if (N > MaxN)
{
Warning("Max OMP threads %u", MaxN);
N = MaxN;
}
if (N == 0)
N = 1;
Done = true;
return N;
}
const char *GetPlatform()
{
#if BITS==32
asserta(sizeof(void *) == 4);
#ifdef _MSC_VER
return "win32";
#elif defined(__APPLE__)
return "osx32";
#elif defined(__GNUC__)
return "linux32";
#else
#error "Unknown compiler"
#endif
#elif BITS==64
asserta(sizeof(void *) == 8);
#ifdef _MSC_VER
return "win64";
#elif defined(__APPLE__)
return "osx64";
#elif defined(__GNUC__)
return "linux64";
#else
#error "Unknown compiler"
#endif
#else
#error "Bad BITS"
#endif
}
const char *BaseName(const char *PathName)
{
const char *q = 0;
for (const char *p = PathName; *p; ++p)
{
if (*p == '/' || *p == '\\')
q = p + 1;
}
if (q != 0)
return q;
return PathName;
}
static void AllocBuffer(FILE *f)
{
#if DEBUG
setbuf(f, 0);
#else
int fd = fileno(f);
if (fd < 0 || fd >= 256)
return;
if (g_IOBuffers[fd] == 0)
g_IOBuffers[fd] = myalloc(char, MY_IO_BUFSIZ);
setvbuf(f, g_IOBuffers[fd], _IOFBF, MY_IO_BUFSIZ);
#endif
}
static void FreeBuffer(FILE *f)
{
#if 0
int fd = fileno(f);
if (fd < 0 || fd >= 256)
return;
if (g_IOBuffers[fd] == 0)
return;
myfree(g_IOBuffers[fd]);
g_IOBuffers[fd] = 0;
#endif
}
unsigned GetElapsedSecs()
{
return (unsigned) (time(0) - g_StartTime);
}
bool StdioFileExists(const string &FileName)
{
struct stat SD;
int i = stat(FileName.c_str(), &SD);
return i == 0;
}
void myassertfail(const char *Exp, const char *File, unsigned Line)
{
Die("%s(%u) assert failed: %s", File, Line, Exp);
}
bool myisatty(int fd)
{
return isatty(fd) != 0;
}
#ifdef _MSC_VER
#include <io.h>
int fseeko(FILE *stream, off_t offset, int whence)
{
off_t FilePos = _fseeki64(stream, offset, whence);
return (FilePos == -1L) ? -1 : 0;
}
#define ftello(fm) (off_t) _ftelli64(fm)
#endif
void LogStdioFileState(FILE *f)
{
unsigned long tellpos = (unsigned long) ftello(f);
long fseek_pos = fseek(f, 0, SEEK_CUR);
int fd = fileno(f);
Log("FILE * %p\n", f);
Log("fileno %d\n", fd);
Log("feof %d\n", feof(f));
Log("ferror %d\n", ferror(f));
Log("ftell %ld\n", tellpos);
Log("fseek %ld\n", fseek_pos);
#if !defined(_GNU_SOURCE) && !defined(__APPLE_CC__)
fpos_t fpos;
int fgetpos_retval = fgetpos(f, &fpos);
Log("fpos %ld (retval %d)\n", (long) fpos, fgetpos_retval);
// Log("eof %d\n", _eof(fd));
#endif
#ifdef _MSC_VER
__int64 pos64 = _ftelli64(f);
Log("_ftelli64 %lld\n", pos64);
#endif
if (FileToFileName.find(f) == FileToFileName.end())
Log("Not found in FileToFileName\n");
else
Log("Name %s\n", FileToFileName[f].c_str());
}
void ParseFileName(const string &FileName, string &Path, string &Name)
{
size_t n = string::npos;
size_t n1 = FileName.rfind('/');
if (n1 != string::npos)
n = n1;
#if _MSC_VER
size_t n2 = FileName.rfind('\\');
size_t n3 = FileName.rfind(':');
if (n2 != string::npos && n2 > n)
n = n2;
if (n3 != string::npos && n3 > n)
n = n3;
#endif
if (n == string::npos)
{
Path = ".";
Name = FileName;
return;
}
Path = FileName.substr(0, n);
Name = FileName.substr(n+1, string::npos);
}
#ifdef _MSC_VER
void ReadDir(const string &DirName, vector<string> &FileNames)
{
FileNames.clear();
if (DirName.find('?') != string::npos || DirName.find('*') != string::npos)
Die("Invalid directory name '%s'", DirName.c_str());
string DirNameSlashStar = DirName;
if (!EndsWith(DirName, "/") && !EndsWith(DirName, "\\"))
DirNameSlashStar += "/";
DirNameSlashStar += "*";
struct _finddata_t FileInfo;
intptr_t h = _findfirst(DirNameSlashStar.c_str(), &FileInfo);
if (h == -1)
Die("Directory not found '%s'", DirName.c_str());
for (;;)
{
string FileName = string(FileInfo.name);
FileNames.push_back(FileName);
int rc = _findnext(h, &FileInfo);
if (rc != 0)
break;
FileNames.push_back(FileInfo.name);
}
_findclose(h);
sort(FileNames.begin(), FileNames.end());
}
#else
void ReadDir(const string &DirName, vector<string> &FileNames)
{
FileNames.clear();
DIR *h = opendir(DirName.c_str());
if (h == 0)
Die("Directory not found '%s'", DirName.c_str());
for (;;)
{
struct dirent *d = readdir(h);
if (d == 0)
break;
string FileName = string(d->d_name);
FileNames.push_back(FileName);
}
closedir(h);
sort(FileNames.begin(), FileNames.end());
}
#endif
FILE *OpenStdioFile(const string &FileName)
{
if (FileName == "")
Die("Missing input file name");
const char *Mode = "rb";
FILE *f = fopen(FileName.c_str(), Mode);
if (f == 0)
{
if (errno == EFBIG)
{
if (sizeof(off_t) == 4)
Die("File too big for 32-bit version (sizeof(off_t)=%d): %s", sizeof(off_t), FileName.c_str());
else
Die("Cannot open '%s', file too big (off_t=%u bits)",
FileName.c_str(), sizeof(off_t)*8);
}
Die("Cannot open %s, errno=%d %s",
FileName.c_str(), errno, strerror(errno));
}
AllocBuffer(f);
FileToFileName[f] = FileName;
return f;
}
FILE *CreateStdioFile(const string &FileName)
{
if (FileName == "")
// Die("Missing output file name");
return 0;
FILE *f = fopen(FileName.c_str(), "wb+");
if (0 == f)
Die("Cannot create %s, errno=%d %s",
FileName.c_str(), errno, strerror(errno));
const unsigned MYBUFFSZ = 262144+8;
char *buf = (char *) malloc(MYBUFFSZ);
setvbuf(f, buf, _IOFBF, MYBUFFSZ);
AllocBuffer(f);
FileToFileName[f] = FileName;
return f;
}
void SetStdioFilePos(FILE *f, uint32 Pos)
{
if (0 == f)
Die("SetStdioFilePos failed, f=NULL");
int Ok = fseeko(f, Pos, SEEK_SET);
off_t NewPos = ftello(f);
if (Ok != 0 || Pos != NewPos)
{
LogStdioFileState(f);
Die("SetStdioFilePos(%d) failed, Ok=%d NewPos=%d",
(int) Pos, Ok, (int) NewPos);
}
}
void SetStdioFilePos64(FILE *f, uint64 Pos)
{
if (0 == f)
Die("SetStdioFilePos failed, f=NULL");
int Ok = fseeko(f, Pos, SEEK_SET);
off_t NewPos = ftello(f);
if (Ok != 0 || Pos != NewPos)
{
LogStdioFileState(f);
Die("SetStdioFilePos64(%ul) failed, Ok=%d NewPos=%ul",
(unsigned long) Pos, Ok, (unsigned long) NewPos);
}
}
uint32 ReadStdioFile_NoFail(FILE *f, void *Buffer, uint32 Bytes)
{
asserta(f != 0);
off_t PosBefore = ftello(f);
size_t ElementsRead = fread(Buffer, Bytes, 1, f);
off_t PosAfter = ftello(f);
if (ElementsRead == 1)
return Bytes;
uint32 BytesRead = uint32(PosAfter - PosBefore);
return BytesRead;
}
void ReadStdioFile(FILE *f, uint32 Pos, void *Buffer, uint32 Bytes)
{
asserta(f != 0);
SetStdioFilePos(f, Pos);
uint32 ElementsRead = (uint32) fread(Buffer, Bytes, 1, f);
if (ElementsRead != 1)
{
LogStdioFileState(f);
Die("ReadStdioFile failed, attempted %lu bytes, errno=%d",
(unsigned long) Bytes, errno);
}
}
void ReadStdioFile64(FILE *f, uint64 Pos, void *Buffer, uint64 Bytes)
{
asserta(f != 0);
uint32 Bytes32 = (uint32) Bytes;
asserta(Bytes32 == Bytes);
SetStdioFilePos64(f, Pos);
uint64 ElementsRead = (uint64) fread(Buffer, Bytes32, 1, f);
if (ElementsRead != Bytes)
{
LogStdioFileState(f);
Die("ReadStdioFile64 failed, attempted %lu bytes, errno=%d",
(unsigned long) Bytes, errno);
}
}
void ReadStdioFile(FILE *f, void *Buffer, uint32 Bytes)
{
asserta(f != 0);
size_t ElementsRead = fread(Buffer, Bytes, 1, f);
if (ElementsRead != 1)
{
LogStdioFileState(f);
Die("ReadStdioFile64 failed, attempted %u bytes, errno=%d",
Bytes, errno);
}
}
void ReadStdioFile64(FILE *f, void *Buffer, uint64 Bytes)
{
asserta(f != 0);
size_t ElementsRead = fread(Buffer, Bytes, 1, f);
if (ElementsRead != 1)
{
LogStdioFileState(f);
Die("ReadStdioFile64 failed, attempted %u bytes, errno=%d",
Bytes, errno);
}
}
byte *ReadAllStdioFile(FILE *f, uint32 &FileSize)
{
uint64 Pos = GetStdioFilePos64(f);
uint64 FileSize64 = GetStdioFileSize64(f);
#if BITS == 32
if (FileSize > UINT_MAX)
Die("ReadAllStdioFile (32-bit): file too big");
#endif
FileSize = uint32(FileSize64);
SetStdioFilePos(f, 0);
byte *Buffer = myalloc(byte, FileSize);
ReadStdioFile(f, Buffer, FileSize);
SetStdioFilePos64(f, Pos);
return Buffer;
}
byte *ReadAllStdioFile64(const string &FileName, uint64 &FileSize)
{
FILE *f = OpenStdioFile(FileName);
FileSize = GetStdioFileSize64(f);
#if BITS==32
if (FileSize > UINT32_MAX)
Die("File too big, requires 64-bit version: %s", FileName.c_str());
#endif
byte *Buffer = ReadAllStdioFile64(f, FileSize);
CloseStdioFile(f);
return Buffer;
}
byte *ReadAllStdioFile64(FILE *f, uint64 &FileSize)
{
uint64 SavedPos = GetStdioFilePos64(f);
FileSize = GetStdioFileSize64(f);
#if BITS==32
if (FileSize > UINT32_MAX)
Die("File too big, requires 64-bit version");
byte *Buffer = myalloc(byte, (uint32) FileSize);
#else
if (FileSize > UINT_MAX)
Die("ReadAllStdioFile64, file too big %s", MemBytesToStr((double) FileSize));
unsigned uFileSize = (unsigned) FileSize;
byte *Buffer = myalloc(byte, uFileSize);
#endif
uint64 Pos = 0;
uint64 BytesLeft = FileSize;
const uint64 ChunkSize = 0x40000000; // 1Gb
for (;;)
{
if (BytesLeft == 0)
break;
uint64 BytesToRead = BytesLeft;
if (BytesToRead > ChunkSize)
BytesToRead = ChunkSize;
ReadStdioFile64(f, Pos, Buffer + Pos, BytesToRead);
BytesLeft -= BytesToRead;
}
SetStdioFilePos64(f, SavedPos);
return Buffer;
}
byte *ReadAllStdioFile32(const std::string &FileName, uint32 &FileSize)
{
#if WIN32
FILE *f = OpenStdioFile(FileName);
FileSize = GetStdioFileSize32(f);
CloseStdioFile(f);
HANDLE h = CreateFile(FileName.c_str(), GENERIC_READ, FILE_SHARE_READ,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (h == INVALID_HANDLE_VALUE)
Die("ReadAllStdioFile:Open(%s) failed", FileName.c_str());
byte *Buffer = myalloc(byte, FileSize);
DWORD BytesRead;
ReadFile(h, Buffer, FileSize, &BytesRead, NULL);
if (FileSize != BytesRead)
Die("ReadAllStdioFile:Error reading %s, attempted %u got %u",
FileName.c_str(), FileSize, (unsigned) BytesRead);
CloseHandle(h);
return Buffer;
#else
int h = open(FileName.c_str(), O_RDONLY);
if (h < 0)
Die("ReadAllStdioFile:Cannot open %s", FileName.c_str());
FileSize = lseek(h, 0, SEEK_END);
#ifndef __APPLE__
if (FileSize == (off_t) (-1))
Die("ReadAllStdioFile:Error seeking %s", FileName.c_str());
#endif
// byte *Buffer = myalloc<byte>(FileSize);
size_t stBytes = (size_t) FileSize;
if ((off_t) stBytes != FileSize)
Die("ReadAllStdioFile: off_t overflow");
byte *Buffer = (byte *) myalloc(byte, stBytes);
if (Buffer == 0)
Die("ReadAllStdioFile: failed to allocate %s", MemBytesToStr((double) stBytes));
lseek(h, 0, SEEK_SET);
size_t n = read(h, Buffer, stBytes);
if (n != FileSize)
Die("ReadAllStdioFile, Error reading %s, attempted %g got %g",
FileName.c_str(), (double) FileSize, (double) n);
close(h);
return Buffer;
#endif
}
void WriteStdioFile(FILE *f, uint32 Pos, const void *Buffer, uint32 Bytes)
{
if (0 == f)
Die("WriteStdioFile failed, f=NULL");
SetStdioFilePos(f, Pos);
size_t BytesWritten = fwrite(Buffer, 1, Bytes, f);
if (BytesWritten != Bytes)
{
LogStdioFileState(f);
Die("WriteStdioFile failed, attempted %ul bytes, wrote %ul bytes, errno=%d",
(unsigned long) Bytes, (unsigned long) BytesWritten, errno);
}
}
void WriteStdioFileStr(FILE *f, const char *s)
{
uint32 Bytes = ustrlen(s);
WriteStdioFile(f, s, Bytes);
}
void WriteStdioFile(FILE *f, const void *Buffer, uint32 Bytes)
{
if (0 == f)
Die("WriteStdioFile failed, f=NULL");
size_t BytesWritten = fwrite(Buffer, 1, Bytes, f);
if (BytesWritten != Bytes)
{
LogStdioFileState(f);
Die("WriteStdioFile failed, attempted %ul bytes, wrote %ul bytes, errno=%d",
(unsigned long) Bytes, (unsigned long) BytesWritten, errno);
}
}
void WriteStdioFile64(FILE *f, const void *Buffer, uint64 Bytes)
{
if (0 == f)
Die("WriteStdioFile failed, f=NULL");
size_t BytesWritten = fwrite(Buffer, 1, Bytes, f);
if (BytesWritten != Bytes)
{
LogStdioFileState(f);
Die("WriteStdioFile failed, attempted %ul bytes, wrote %ul bytes, errno=%d",
(unsigned long) Bytes, (unsigned long) BytesWritten, errno);
}
}
// Return false on EOF, true if line successfully read.
bool ReadLineStdioFile(FILE *f, char *Line, uint32 Bytes)
{
if (feof(f))
return false;
if ((int) Bytes < 0)
Die("ReadLineStdioFile: Bytes < 0");
char *RetVal = fgets(Line, (int) Bytes, f);
if (NULL == RetVal)
{
if (feof(f))
return false;
if (ferror(f))
Die("ReadLineStdioFile: errno=%d", errno);
Die("ReadLineStdioFile: fgets=0, feof=0, ferror=0");
}
if (RetVal != Line)
Die("ReadLineStdioFile: fgets != Buffer");
size_t n = strlen(Line);
if (n < 1 || Line[n-1] != '\n')
Die("ReadLineStdioFile: line too long or missing end-of-line");
if (n > 0 && (Line[n-1] == '\r' || Line[n-1] == '\n'))
Line[n-1] = 0;
if (n > 1 && (Line[n-2] == '\r' || Line[n-2] == '\n'))
Line[n-2] = 0;
return true;
}
void ReadTabbedLineStdioFile(FILE *f, vector<string> &Fields, unsigned FieldCount)
{
string Line;
bool Ok = ReadLineStdioFile(f, Line);
if (!Ok)
Die("Unxpected end-of-file in tabbed text");
Split(Line, Fields, '\t');
unsigned n = SIZE(Fields);
if (FieldCount != UINT_MAX && n != FieldCount)
{
Log("\n");
Log("Line='%s'\n", Line.c_str());
Die("Expected %u tabbed fields, got %u", FieldCount, n);
}
}
// Return false on EOF, true if line successfully read.
bool ReadLineStdioFile(FILE *f, string &Line)
{
Line.clear();
for (;;)
{
int c = fgetc(f);
if (c == -1)
{
if (feof(f))
{
if (!Line.empty())
return true;
return false;
}
Die("ReadLineStdioFile, errno=%d", errno);
}
if (c == '\r')
continue;
if (c == '\n')
return true;
Line.push_back((char) c);
}
}
void RenameStdioFile(const string &FileNameFrom, const string &FileNameTo)
{
int Ok = rename(FileNameFrom.c_str(), FileNameTo.c_str());
if (Ok != 0)
Die("RenameStdioFile(%s,%s) failed, errno=%d %s",
FileNameFrom.c_str(), FileNameTo.c_str(), errno, strerror(errno));
}
void FlushStdioFile(FILE *f)
{
int Ok = fflush(f);
if (Ok != 0)
Die("fflush(%p)=%d,", f, Ok);
}
void CloseStdioFile(FILE *f)
{
if (f == 0)
return;
int Ok = fclose(f);
if (Ok != 0)
Die("fclose(%p)=%d", f, Ok);
FreeBuffer(f);
}
uint32 GetStdioFilePos32(FILE *f)
{
off_t FilePos = ftello(f);
if (FilePos < 0)
Die("ftello=%d", (int) FilePos);
if (FilePos > UINT32_MAX)
Die("File offset too big for 32-bit version (%s)", MemBytesToStr((double) FilePos));
return (uint32) FilePos;
}
uint64 GetStdioFilePos64(FILE *f)
{
off_t FilePos = ftello(f);
if (FilePos < 0)
Die("ftello=%d", (int) FilePos);
return (uint64) FilePos;
}
uint32 GetStdioFileSize32(FILE *f)
{
uint32 CurrentPos = GetStdioFilePos32(f);
int Ok = fseeko(f, 0, SEEK_END);
if (Ok < 0)
Die("fseek in GetFileSize");
off_t Length = ftello(f);
SetStdioFilePos(f, CurrentPos);
if (Length < 0)
Die("ftello in GetFileSize");
#if BITS == 32
if (Length > UINT32_MAX)
Die("File size too big for 32-bit version (%s)", MemBytesToStr((double) Length));
#endif
return (uint32) Length;
}
uint64 GetStdioFileSize64(FILE *f)
{
uint64 CurrentPos = GetStdioFilePos64(f);
int Ok = fseeko(f, 0, SEEK_END);
if (Ok < 0)
Die("fseek in GetFileSize64");
off_t Length = ftello(f);
SetStdioFilePos64(f, CurrentPos);
if (Length < 0)
Die("ftello in GetFileSize");
#if BITS == 32
if (Length > UINT32_MAX)
Die("File size too big for 32-bit version (%s)", MemBytesToStr((double) Length));
#endif
return (uint64) Length;
}
void MoveStdioFile(const string &FileName1, const string &FileName2)
{
if (StdioFileExists(FileName2))
DeleteStdioFile(FileName2);
RenameStdioFile(FileName1, FileName2);
}
void DeleteStdioFile(const string &FileName)
{
int Ok = remove(FileName.c_str());
if (Ok != 0)
Die("remove(%s) failed, errno=%d %s", FileName.c_str(), errno, strerror(errno));
}
double GetUsableMemBytes()
{
double RAM = GetPhysMemBytes();
#if BITS==32
#ifdef _MSC_VER
if (RAM > 2e9)
return 2e9;
#else
if (RAM > 4e9)
return 4e9;
#endif
#endif
return RAM;
}
static char **g_ThreadStrs;
static unsigned g_ThreadStrCount;
static char *GetThreadStr()
{
unsigned ThreadIndex = GetThreadIndex();
if (ThreadIndex >= g_ThreadStrCount)
{
unsigned NewThreadStrCount = ThreadIndex + 4;
char **NewThreadStrs = myalloc(char *, NewThreadStrCount);
zero(NewThreadStrs, NewThreadStrCount);
if (g_ThreadStrCount > 0)
memcpy(NewThreadStrs, g_ThreadStrs, g_ThreadStrCount*sizeof(char *));
g_ThreadStrs = NewThreadStrs;
g_ThreadStrCount = NewThreadStrCount;
}
if (g_ThreadStrs[ThreadIndex] == 0)
g_ThreadStrs[ThreadIndex] = myalloc(char, MAX_FORMATTED_STRING_LENGTH+1);
char *Str = g_ThreadStrs[ThreadIndex];
return Str;
}
void myvstrprintf(string &Str, const char *Format, va_list ArgList)
{
char *szStr = GetThreadStr();
vsnprintf(szStr, MAX_FORMATTED_STRING_LENGTH-1, Format, ArgList);
szStr[MAX_FORMATTED_STRING_LENGTH - 1] = '\0';
Str.assign(szStr);
}
void Pf(FILE *f, const char *Format, ...)
{
if (f == 0)
return;
va_list ArgList;
va_start(ArgList, Format);
vfprintf(f, Format, ArgList);
va_end(ArgList);
}
void Ps(string &Str, const char *Format, ...)
{
va_list ArgList;
va_start(ArgList, Format);
myvstrprintf(Str, Format, ArgList);
va_end(ArgList);
}
void Psa(string &Str, const char *Format, ...)
{
va_list ArgList;
va_start(ArgList, Format);
string Tmp;
myvstrprintf(Tmp, Format, ArgList);
va_end(ArgList);
Str += Tmp;
}
void Psasc(string &Str, const char *Format, ...)
{
unsigned n = SIZE(Str);
if (n > 0 && Str[n-1] != ';')
Str += ";";
va_list ArgList;
va_start(ArgList, Format);
string Tmp;
myvstrprintf(Tmp, Format, ArgList);
va_end(ArgList);
Str += Tmp;
n = SIZE(Str);
if (n > 0 && Str[n-1] != ';')
Str += ";";
}
FILE *g_fLog = 0;
void SetLogFileName(const string &FileName)
{
if (g_fLog != 0)
CloseStdioFile(g_fLog);
g_fLog = 0;
if (FileName.empty())
return;
g_fLog = CreateStdioFile(FileName);
setbuf(g_fLog, 0);
}
void Log(const char *Format, ...)
{
if (g_fLog == 0)
return;
va_list ArgList;
va_start(ArgList, Format);
vfprintf(g_fLog, Format, ArgList);
va_end(ArgList);
fflush(g_fLog);
}
void Die_(const char *Format, ...)
{
#pragma omp critical
{
static bool InDie = false;
if (InDie)
exit(1);
InDie = true;
string Msg;
if (g_fLog != 0)
setbuf(g_fLog, 0);
va_list ArgList;
va_start(ArgList, Format);
myvstrprintf(Msg, Format, ArgList);
va_end(ArgList);
fprintf(stderr, "\n\n");
Log("\n");
time_t t = time(0);
Log("%s", asctime(localtime(&t)));
for (unsigned i = 0; i < g_Argv.size(); i++)
{
fprintf(stderr, (i == 0) ? "%s" : " %s", g_Argv[i].c_str());
Log((i == 0) ? "%s" : " %s", g_Argv[i].c_str());
}
fprintf(stderr, "\n");
Log("\n");
time_t CurrentTime = time(0);
unsigned ElapsedSeconds = unsigned(CurrentTime - g_StartTime);
const char *sstr = SecsToStr(ElapsedSeconds);
Log("Elapsed time: %s\n", sstr);
const char *szStr = Msg.c_str();
fprintf(stderr, "Elapsed time %s\n", SecsToHHMMSS((int) ElapsedSeconds));
fprintf(stderr, "Max memory %s\n", MemBytesToStr(g_PeakMemUseBytes));
fprintf(stderr, "\n---Fatal error---\n%s\n", szStr);
Log("\n---Fatal error---\n%s\n", szStr);
#ifdef _MSC_VER
if (IsDebuggerPresent())
__debugbreak();
_CrtSetDbgFlag(0);
#endif
exit(1);
}
}
void Warning_(const char *Format, ...)
{
string Msg;
va_list ArgList;
va_start(ArgList, Format);
myvstrprintf(Msg, Format, ArgList);
va_end(ArgList);
const char *szStr = Msg.c_str();
fprintf(stderr, "\nWARNING: %s\n\n", szStr);
if (g_fLog != stdout)
{
Log("\nWARNING: %s\n", szStr);
fflush(g_fLog);
}
}
#ifdef _MSC_VER
void mysleep(unsigned ms)
{
Sleep(ms);
}
#else
void mysleep(unsigned ms)
{
usleep(ms);
}
#endif
#ifdef _MSC_VER
double GetMemUseBytes()
{
HANDLE hProc = GetCurrentProcess();
PROCESS_MEMORY_COUNTERS PMC;
BOOL bOk = GetProcessMemoryInfo(hProc, &PMC, sizeof(PMC));
if (!bOk)
return 1000000;
double Bytes = (double) PMC.WorkingSetSize;
if (Bytes > g_PeakMemUseBytes)
g_PeakMemUseBytes = Bytes;
return Bytes;
}
double GetPhysMemBytes()
{
MEMORYSTATUSEX MS;
MS.dwLength = sizeof(MS);
BOOL Ok = GlobalMemoryStatusEx(&MS);
if (!Ok)
return 0.0;
return double(MS.ullTotalPhys);
}
#elif linux || __linux__ || __CYGWIN__
double GetPhysMemBytes()