Debian Codegraph @

include/plink2_text.cc

raw
1 // This library is part of PLINK 2.0, copyright (C) 2005-2025 Shaun Purcell,
2 // Christopher Chang.
3 //
4 // This library is free software: you can redistribute it and/or modify it
5 // under the terms of the GNU Lesser General Public License as published by the
6 // Free Software Foundation, either version 3 of the License, or (at your
7 // option) any later version.
8 //
9 // This library is distributed in the hope that it will be useful, but WITHOUT
10 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
12 // for more details.
13 //
14 // You should have received a copy of the GNU Lesser General Public License
15 // along with this library. If not, see <http://www.gnu.org/licenses/>.
16
17 #include <errno.h>
18 #include "plink2_text.h"
19
20 #ifdef __cplusplus
21 namespace plink2 {
22 #endif
23
24 static inline textFILEMain* GetTxfp(textFILE* txf_ptr) {
25 return &GET_PRIVATE(*txf_ptr, m);
26 }
27
28 static inline TextStreamMain* GetTxsp(TextStream* txs_ptr) {
29 return &GET_PRIVATE(*txs_ptr, m);
30 }
31
32 static inline const TextStreamMain* GetTxspK(const TextStream* txs_ptr) {
33 return &GET_PRIVATE(*txs_ptr, m);
34 }
35
36 PglErr GetFileType(const char* fname, FileCompressionType* ftype_ptr) {
37 FILE* infile = fopen(fname, FOPEN_RB);
38 if (unlikely(!infile)) {
39 // Note that this does not print an error message (since it may be called
40 // by a worker thread).
41 return kPglRetOpenFail;
42 }
43 unsigned char buf[16];
44 const uint32_t nbytes = fread_unlocked(buf, 1, 16, infile);
45 if (unlikely(ferror_unlocked(infile) || fclose(infile))) {
46 return kPglRetReadFail;
47 }
48 if (nbytes < 4) {
49 *ftype_ptr = kFileUncompressed;
50 return kPglRetSuccess;
51 }
52 uint32_t magic4;
53 memcpy(&magic4, buf, 4);
54
55 if (IsZstdFrame(magic4)) {
56 *ftype_ptr = kFileZstd;
57 return kPglRetSuccess;
58 }
59 if (S_CAST(uint16_t, magic4) != 0x8b1f) { // gzip ID1/ID2 bytes
60 *ftype_ptr = kFileUncompressed;
61 return kPglRetSuccess;
62 }
63 if ((nbytes == 16) && IsBgzfHeader(buf)) {
64 *ftype_ptr = kFileBgzf;
65 } else {
66 *ftype_ptr = kFileGzip;
67 }
68 return kPglRetSuccess;
69 }
70
71 void EraseTextFileBase(TextFileBase* trbp) {
72 trbp->consume_iter = nullptr;
73 trbp->consume_stop = nullptr;
74 trbp->errmsg = nullptr;
75 trbp->reterr = kPglRetEof;
76 trbp->ff = nullptr;
77 trbp->dst = nullptr;
78 }
79
80 void PreinitTextFile(textFILE* txf_ptr) {
81 EraseTextFileBase(&GetTxfp(txf_ptr)->base);
82 }
83
84 BoolErr GzRawInit(const void* buf, uint32_t nbytes, GzRawDecompressStream* gzp) {
85 gzp->ds_initialized = 0;
86 gzp->in = S_CAST(unsigned char*, malloc(kDecompressChunkSize));
87 if (!gzp->in) {
88 return 1;
89 }
90 z_stream* dsp = &gzp->ds;
91 memcpy(gzp->in, buf, nbytes);
92 dsp->next_in = gzp->in;
93 dsp->avail_in = nbytes;
94 dsp->zalloc = nullptr;
95 dsp->zfree = nullptr;
96 dsp->opaque = nullptr;
97 #if defined(__clang__) || (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 6))
98 # pragma GCC diagnostic push
99 # pragma GCC diagnostic ignored "-Wold-style-cast"
100 #endif
101 if (unlikely(inflateInit2(dsp, MAX_WBITS | 16) != Z_OK)) {
102 return 1;
103 }
104 #if defined(__clang__) || (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 6))
105 # pragma GCC diagnostic pop
106 #endif
107 gzp->ds_initialized = 1;
108 gzp->eof = 0;
109 return 0;
110 }
111
112 BoolErr ZstRawInit(const void* buf, uint32_t nbytes, ZstRawDecompressStream* zstp) {
113 zstp->ib.src = malloc(kDecompressChunkSize);
114 if (unlikely(!zstp->ib.src)) {
115 zstp->ds = nullptr;
116 return 1;
117 }
118 zstp->ds = ZSTD_createDStream();
119 if (unlikely(!zstp->ds)) {
120 return 1;
121 }
122 memcpy(K_CAST(void*, zstp->ib.src), buf, nbytes);
123 zstp->ib.size = nbytes;
124 zstp->ib.pos = 0;
125 return 0;
126 }
127
128 const char kShortErrRfileAlreadyOpen[] = "TextFileOpenInternal can't be called on an already-open file";
129 const char kShortErrRfileEnforcedMaxBlenTooSmall[] = "TextFileOpenInternal: enforced_max_line_blen too small (must be at least max(1 MiB, dst_capacity - 1 MiB))";
130 const char kShortErrRfileDstCapacityTooSmall[] = "TextFileOpenInternal: dst_capacity too small (2 MiB minimum)";
131
132 PglErr TextFileOpenInternal(const char* fname, uint32_t enforced_max_line_blen, uint32_t dst_capacity, char* dst, textFILEMain* txfp, TextStreamMain* txsp) {
133 PglErr reterr = kPglRetSuccess;
134 TextFileBase* trbp;
135 if (txfp) {
136 trbp = &txfp->base;
137 } else {
138 trbp = &txsp->base;
139 }
140 {
141 // 1. Open file, get type.
142 if (unlikely(trbp->ff)) {
143 reterr = kPglRetImproperFunctionCall;
144 trbp->errmsg = kShortErrRfileAlreadyOpen;
145 goto TextFileOpenInternal_ret_1;
146 }
147 if (enforced_max_line_blen || txfp) {
148 if (unlikely(enforced_max_line_blen < kDecompressMinBlen)) {
149 reterr = kPglRetImproperFunctionCall;
150 trbp->errmsg = kShortErrRfileEnforcedMaxBlenTooSmall;
151 goto TextFileOpenInternal_ret_1;
152 }
153 if (dst) {
154 if (unlikely(dst_capacity < kDecompressMinCapacity)) {
155 reterr = kPglRetImproperFunctionCall;
156 trbp->errmsg = kShortErrRfileDstCapacityTooSmall;
157 goto TextFileOpenInternal_ret_1;
158 }
159 if (unlikely(enforced_max_line_blen + kDecompressChunkSize < dst_capacity)) {
160 reterr = kPglRetImproperFunctionCall;
161 trbp->errmsg = kShortErrRfileEnforcedMaxBlenTooSmall;
162 goto TextFileOpenInternal_ret_1;
163 }
164 }
165 } else {
166 // token-reading mode. dst == nullptr not currently supported.
167 assert(dst && (dst_capacity == kTokenStreamBlen));
168 }
169 trbp->ff = fopen(fname, FOPEN_RB);
170 if (unlikely(!trbp->ff)) {
171 goto TextFileOpenInternal_ret_OPEN_FAIL;
172 }
173 trbp->file_type = kFileUncompressed;
174 if (dst) {
175 trbp->dst_owned_by_consumer = 1;
176 trbp->dst_capacity = dst_capacity;
177 } else {
178 dst = S_CAST(char*, malloc(kDecompressMinCapacity));
179 if (unlikely(dst == nullptr)) {
180 goto TextFileOpenInternal_ret_NOMEM;
181 }
182 trbp->dst_owned_by_consumer = 0;
183 trbp->dst_capacity = kDecompressMinCapacity;
184 }
185 trbp->dst = dst;
186 uint32_t nbytes = fread_unlocked(dst, 1, 16, trbp->ff);
187 trbp->dst_len = nbytes;
188 trbp->enforced_max_line_blen = enforced_max_line_blen;
189 trbp->consume_iter = dst;
190 trbp->consume_stop = dst;
191 if (nbytes >= 4) {
192 // assumes aligned dst; this should be safe?
193 uint32_t magic4;
194 CopyFromUnalignedU32(&magic4, CToUc(dst));
195 if (IsZstdFrame(magic4)) {
196 trbp->dst_len = 0;
197 trbp->file_type = kFileZstd;
198 ZstRawDecompressStream* zstp;
199 if (txfp) {
200 zstp = &txfp->rds.zst;
201 } else {
202 zstp = &txsp->rds.zst;
203 }
204 if (unlikely(ZstRawInit(dst, nbytes, zstp))) {
205 goto TextFileOpenInternal_ret_NOMEM;
206 }
207 } else if ((magic4 << 8) == 0x088b1f00) {
208 // gzip ID1/ID2 bytes, deflate compression method
209 trbp->dst_len = 0;
210 if ((nbytes == 16) && IsBgzfHeader(dst)) {
211 trbp->file_type = kFileBgzf;
212 if (txfp) {
213 BgzfRawDecompressStream* bgzfp = &txfp->rds.bgzf;
214 bgzfp->in = S_CAST(unsigned char*, malloc(kDecompressChunkSize));
215 if (unlikely(!bgzfp->in)) {
216 bgzfp->ldc = nullptr;
217 goto TextFileOpenInternal_ret_NOMEM;
218 }
219 bgzfp->ldc = libdeflate_alloc_decompressor();
220 if (!bgzfp->ldc) {
221 goto TextFileOpenInternal_ret_NOMEM;
222 }
223 memcpy(bgzfp->in, dst, nbytes);
224 bgzfp->in_size = nbytes;
225 bgzfp->in_pos = 0;
226 } else {
227 reterr = BgzfRawMtStreamInit(dst, txsp->decompress_thread_ct, trbp->ff, nullptr, &txsp->rds.bgzf, &trbp->errmsg);
228 if (unlikely(reterr)) {
229 goto TextFileOpenInternal_ret_1;
230 }
231 }
232 } else {
233 trbp->file_type = kFileGzip;
234 GzRawDecompressStream* gzp;
235 if (txfp) {
236 gzp = &txfp->rds.gz;
237 } else {
238 gzp = &txsp->rds.gz;
239 }
240 if (unlikely(GzRawInit(dst, nbytes, gzp))) {
241 goto TextFileOpenInternal_ret_NOMEM;
242 }
243 }
244 }
245 } else if (!nbytes) {
246 if (unlikely(!feof_unlocked(trbp->ff))) {
247 goto TextFileOpenInternal_ret_READ_FAIL;
248 }
249 // May as well accept this.
250 // Don't jump to ret_1 since we're setting txfp->reterr to a different
251 // value than we're returning.
252 trbp->reterr = kPglRetEof;
253 return kPglRetSuccess;
254 }
255 }
256 while (0) {
257 TextFileOpenInternal_ret_NOMEM:
258 reterr = kPglRetNomem;
259 break;
260 TextFileOpenInternal_ret_OPEN_FAIL:
261 reterr = kPglRetOpenFail;
262 trbp->errmsg = strerror(errno);
263 break;
264 TextFileOpenInternal_ret_READ_FAIL:
265 reterr = kPglRetReadFail;
266 trbp->errmsg = strerror(errno);
267 break;
268 }
269 TextFileOpenInternal_ret_1:
270 trbp->reterr = reterr;
271 return reterr;
272 }
273
274 PglErr TextFileOpenEx(const char* fname, uint32_t enforced_max_line_blen, uint32_t dst_capacity, char* dst, textFILE* txf_ptr) {
275 return TextFileOpenInternal(fname, enforced_max_line_blen, dst_capacity, dst, GetTxfp(txf_ptr), nullptr);
276 }
277
278 // Set enforced_max_line_blen == 0 in the token-reading case.
279 BoolErr IsPathologicallyLongLineOrToken(const char* line_start, const char* load_start, const char* known_line_end, uint32_t enforced_max_line_blen) {
280 if (enforced_max_line_blen) {
281 // Preconditions:
282 // * No \n in [line_start, load_start).
283 // * (known_line_end - load_start) is usually <= enforced_max_line_blen,
284 // and never much larger. Not a hard requirement, but it's better to
285 // enforce the line-length limit during line iteration outside this
286 // regime to avoid duplicating work.
287 if (S_CAST(uintptr_t, known_line_end - line_start) <= enforced_max_line_blen) {
288 return 0;
289 }
290 const uint32_t already_scanned_byte_ct = load_start - line_start;
291 if (unlikely(already_scanned_byte_ct >= enforced_max_line_blen)) {
292 return 1;
293 }
294 const char* memchr_result = S_CAST(const char*, memchr(load_start, '\n', enforced_max_line_blen - already_scanned_byte_ct));
295 if (unlikely(!memchr_result)) {
296 return 1;
297 }
298 // If we've found a line with terminal \n at or after this address, there
299 // are <= enforced_max_line_blen bytes left, so no remaining line can be
300 // longer.
301 const char* memchr_result_thresh = known_line_end - (enforced_max_line_blen + 1);
302 while (1) {
303 if (memchr_result >= memchr_result_thresh) {
304 return 0;
305 }
306 memchr_result = S_CAST(const char*, memchr(&(memchr_result[1]), '\n', enforced_max_line_blen));
307 if (unlikely(!memchr_result)) {
308 return 1;
309 }
310 }
311 }
312 if (S_CAST(uintptr_t, known_line_end - line_start) <= kMaxTokenBlen) {
313 return 0;
314 }
315 const uint32_t already_scanned_byte_ct = load_start - line_start;
316 if (unlikely(already_scanned_byte_ct >= kMaxTokenBlen)) {
317 return 1;
318 }
319 // No loop needed for now, since token-scanning buffer sizes are hardcoded.
320 //
321 // Replace with a forward-scanning version of this functionality when
322 // available ("FirstPostspaceBoundedFar"?)
323 return (LastSpaceOrEoln(load_start, kMaxTokenBlen - already_scanned_byte_ct) == nullptr);
324 }
325
326 const char kShortErrRfileTruncatedGz[] = "GzRawStreamRead: gzipped file appears to be truncated";
327
328 PglErr GzRawStreamRead(char* dst_end, FILE* ff, GzRawDecompressStream* gzp, char** dst_iterp, const char** errmsgp) {
329 if (gzp->eof) {
330 // (!dsp->avail_in) && feof_unlocked(ff)) {
331 return kPglRetSuccess;
332 }
333 z_stream* dsp = &gzp->ds;
334 char* dst_iter = *dst_iterp;
335 do {
336 if (dsp->avail_in) { // can be zero after TextRewind()
337 while (1) {
338 dsp->next_out = CToUc(dst_iter);
339 dsp->avail_out = dst_end - dst_iter;
340 int zerr = inflate(dsp, Z_SYNC_FLUSH);
341 if (unlikely((zerr < 0) || (zerr == Z_NEED_DICT))) {
342 if (dsp->msg) {
343 *errmsgp = dsp->msg;
344 } else {
345 *errmsgp = zError(zerr);
346 }
347 return kPglRetDecompressFail;
348 }
349 dst_iter = DowncastToC(dsp->next_out);
350 if (zerr != Z_STREAM_END) {
351 break;
352 }
353 // bugfix (25 May 2021): may need to open a new stream, or skip
354 // trailing garbage
355 const uint32_t trailing_byte_ct = dsp->avail_in;
356 if (trailing_byte_ct < 2) {
357 if (trailing_byte_ct) {
358 gzp->in[0] = dsp->next_in[0];
359 }
360 const uint32_t nbytes = fread_unlocked(&(gzp->in[trailing_byte_ct]), 1, kDecompressChunkSize - trailing_byte_ct, ff);
361 dsp->next_in = gzp->in;
362 dsp->avail_in = trailing_byte_ct + nbytes;
363 }
364 if ((dsp->avail_in < 2) || (dsp->next_in[0] != 31) || (dsp->next_in[1] != 139)) {
365 // EOF or trailing garbage
366 gzp->eof = 1;
367 *dst_iterp = dst_iter;
368 return kPglRetSuccess;
369 }
370 #ifdef NDEBUG
371 inflateReset(dsp);
372 #else
373 const int errcode = inflateReset(dsp);
374 assert(errcode == Z_OK);
375 #endif
376 }
377 if (dsp->avail_in) {
378 break;
379 }
380 }
381 const uint32_t nbytes = fread_unlocked(gzp->in, 1, kDecompressChunkSize, ff);
382 dsp->next_in = gzp->in;
383 dsp->avail_in = nbytes;
384 if (unlikely(!nbytes)) {
385 if (unlikely(!feof_unlocked(ff))) {
386 *errmsgp = strerror(errno);
387 return kPglRetReadFail;
388 }
389 *errmsgp = kShortErrRfileTruncatedGz;
390 return kPglRetDecompressFail;
391 }
392 } while (dst_iter != dst_end);
393 *dst_iterp = dst_iter;
394 return kPglRetSuccess;
395 }
396
397 PglErr ZstRawStreamRead(char* dst_end, FILE* ff, ZstRawDecompressStream* zstp, char** dst_iterp, const char** errmsgp) {
398 if ((!zstp->ib.size) && feof_unlocked(ff)) {
399 return kPglRetSuccess;
400 }
401 // Sequentially dependent blocks limited to ~128 KiB.
402 char* dst_iter = *dst_iterp;
403 while (1) {
404 ZSTD_outBuffer zob = {CToUc(dst_iter), S_CAST(size_t, dst_end - dst_iter), 0};
405 // ib.size == 0 ok, no need to special-case rewind.
406 const uintptr_t read_size_hint = ZSTD_decompressStream(zstp->ds, &zob, &zstp->ib);
407 if (unlikely(ZSTD_isError(read_size_hint))) {
408 *errmsgp = ZSTD_getErrorName(read_size_hint);
409 return kPglRetDecompressFail;
410 }
411 dst_iter = &(dst_iter[zob.pos]);
412 if (dst_iter == dst_end) {
413 break;
414 }
415 // Decoder has flushed everything it could. Either we're at EOF, or we
416 // must load more.
417 unsigned char* in = S_CAST(unsigned char*, K_CAST(void*, zstp->ib.src));
418 const uint32_t n_inbytes = zstp->ib.size - zstp->ib.pos;
419 memmove(in, &(in[zstp->ib.pos]), n_inbytes);
420 unsigned char* load_start = &(in[n_inbytes]);
421 const uint32_t nbytes = fread_unlocked(load_start, 1, kDecompressChunkSize - n_inbytes, ff);
422 if (unlikely(ferror_unlocked(ff))) {
423 *errmsgp = strerror(errno);
424 return kPglRetReadFail;
425 }
426 zstp->ib.pos = 0;
427 const uint32_t new_size = nbytes + n_inbytes;
428 zstp->ib.size = new_size;
429 // bugfix (28 Feb 2021): Possible for nbytes to be zero at the same time
430 // n_inbytes is positive when e.g. the input .zst file is the concatenation
431 // of multiple ordinary .zst files, which is permitted by the spec.
432 if (!new_size) {
433 break;
434 }
435 }
436 *dst_iterp = dst_iter;
437 return kPglRetSuccess;
438 }
439
440 const char kShortErrLongLine[] = "Pathologically long line";
441 const char kShortErrInteriorEmptyLine[] = "Unexpected interior empty line";
442
443 PglErr TextFileAdvance(textFILE* txf_ptr) {
444 textFILEMain* txfp = GetTxfp(txf_ptr);
445 TextFileBase* basep = &txfp->base;
446 if (basep->reterr) {
447 return basep->reterr;
448 }
449 PglErr reterr = kPglRetSuccess;
450 {
451 char* line_start = basep->consume_stop;
452 assert(basep->consume_iter == line_start);
453 char* dst = basep->dst;
454 char* dst_load_start;
455 while (1) {
456 const uint32_t dst_offset = line_start - dst;
457 const uint32_t dst_rem = basep->dst_len - dst_offset;
458 // (dst_rem guaranteed to be < basep->enforced_max_line_blen here, since
459 // otherwise we error out earlier.)
460 // Two cases:
461 // 1. Move (possibly empty) unfinished line to the beginning of the
462 // buffer.
463 // 2. Resize the buffer/report out-of-memory.
464 if (dst_rem < basep->dst_capacity - kDecompressChunkSize) {
465 if (dst_offset) {
466 memmove(dst, line_start, dst_rem);
467 }
468 } else {
469 if (unlikely(basep->dst_owned_by_consumer)) {
470 goto TextFileAdvance_ret_NOMEM;
471 }
472 uint32_t next_dst_capacity = basep->enforced_max_line_blen + kDecompressChunkSize;
473 if ((next_dst_capacity / 2) > basep->dst_capacity) {
474 next_dst_capacity = basep->dst_capacity * 2;
475 }
476 #ifndef __LP64__
477 if (next_dst_capacity >= 0x80000000U) {
478 goto TextFileAdvance_ret_NOMEM;
479 }
480 #endif
481 char* dst_next;
482 if (!dst_offset) {
483 dst_next = S_CAST(char*, realloc(dst, next_dst_capacity));
484 if (unlikely(!dst_next)) {
485 goto TextFileAdvance_ret_NOMEM;
486 }
487 } else {
488 dst_next = S_CAST(char*, malloc(next_dst_capacity));
489 if (unlikely(!dst_next)) {
490 goto TextFileAdvance_ret_NOMEM;
491 }
492 memcpy(dst_next, line_start, dst_rem);
493 }
494 basep->dst = dst_next;
495 dst = dst_next;
496 }
497 line_start = dst;
498 dst_load_start = &(dst[dst_rem]);
499 FILE* ff = basep->ff;
500 char* dst_iter = dst_load_start;
501 // We don't want to always fill the entire buffer here. The main plink2
502 // use case of textFILE is to just peek at an unknown-length header line
503 // with a maximal-length line-load buffer, compute a
504 // legitimate-line-length bound, and then (move-)construct a TextStream
505 // with the shorter buffer size.
506 // Instead, we load up to the smallest power of 2 >= (dst_rem + 1 MiB).
507 uintptr_t stop_offset = (2 * k1LU) << bsru32(dst_rem + kDecompressChunkSize - 1);
508 if (stop_offset > basep->dst_capacity) {
509 stop_offset = basep->dst_capacity;
510 }
511 char* dst_stop = &(dst[stop_offset]);
512 basep->consume_iter = dst;
513 switch (basep->file_type) {
514 case kFileUncompressed:
515 {
516 uint32_t rlen = dst_stop - dst_iter;
517 if (rlen > kMaxBytesPerIO) {
518 // We need to know how many bytes were read, so fread_checked()
519 // doesn't work.
520 // This is an if-statement instead of a while loop since rlen can
521 // never be larger than 2 * kMaxBytesPerIO.
522 const uint32_t nbytes = fread_unlocked(dst_iter, 1, kMaxBytesPerIO, ff);
523 if (nbytes < kMaxBytesPerIO) {
524 if (unlikely(ferror_unlocked(ff))) {
525 goto TextFileAdvance_ret_READ_FAIL;
526 }
527 basep->dst_len = nbytes + dst_rem;
528 break;
529 }
530 rlen -= kMaxBytesPerIO;
531 dst_iter = &(dst_iter[kMaxBytesPerIO]);
532 }
533 const uint32_t nbytes = fread_unlocked(dst_iter, 1, rlen, ff);
534 if (unlikely(ferror_unlocked(ff))) {
535 goto TextFileAdvance_ret_READ_FAIL;
536 }
537 dst_iter = &(dst_iter[nbytes]);
538 break;
539 }
540 case kFileGzip:
541 {
542 reterr = GzRawStreamRead(dst_stop, ff, &txfp->rds.gz, &dst_iter, &basep->errmsg);
543 if (unlikely(reterr)) {
544 goto TextFileAdvance_ret_1;
545 }
546 break;
547 }
548 case kFileBgzf:
549 {
550 // Fully independent blocks limited to 64 KiB.
551 // probable todo: move this to a BgzfRawStreamRead() function in
552 // plink2_bgzf (and move ZstRawStreamRead() to plink2_zstfile).
553 BgzfRawDecompressStream* bgzfp = &txfp->rds.bgzf;
554 if ((!bgzfp->in_size) && feof_unlocked(ff)) {
555 break;
556 }
557 struct libdeflate_decompressor* ldc = bgzfp->ldc;
558 unsigned char* in = bgzfp->in;
559 unsigned char* in_iter = &(in[bgzfp->in_pos]);
560 unsigned char* in_end = &(in[bgzfp->in_size]);
561 while (1) {
562 uint32_t n_inbytes = in_end - in_iter;
563 if (n_inbytes > 25) {
564 if (unlikely(!IsBgzfHeader(in_iter))) {
565 goto TextFileAdvance_ret_INVALID_BGZF;
566 }
567 uint16_t bsize_minus1_u16;
568 memcpy(&bsize_minus1_u16, &(in_iter[16]), 2);
569 const uint32_t bsize_minus1 = bsize_minus1_u16;
570 if (unlikely(bsize_minus1 < 25)) {
571 goto TextFileAdvance_ret_INVALID_BGZF;
572 }
573 if (bsize_minus1 < n_inbytes) {
574 // We have at least one fully-loaded compressed block.
575 // Decompress it if we have enough space.
576 const uint32_t in_size = bsize_minus1 - 25;
577 uint32_t out_size;
578 memcpy(&out_size, &(in_iter[in_size + 22]), 4);
579 if (unlikely(out_size > 65536)) {
580 goto TextFileAdvance_ret_INVALID_BGZF;
581 }
582 if (out_size > S_CAST(uintptr_t, dst_stop - dst_iter)) {
583 break;
584 }
585 if (unlikely(libdeflate_deflate_decompress(ldc, &(in_iter[18]), in_size, dst_iter, out_size, nullptr))) {
586 goto TextFileAdvance_ret_INVALID_BGZF;
587 }
588 in_iter = &(in_iter[bsize_minus1 + 1]);
589 dst_iter = &(dst_iter[out_size]);
590 continue;
591 }
592 }
593 // Either we're at EOF, or we must load more.
594 memmove(in, in_iter, n_inbytes);
595 unsigned char* load_start = &(in[n_inbytes]);
596 const uint32_t nbytes = fread_unlocked(load_start, 1, kDecompressChunkSize - n_inbytes, ff);
597 if (unlikely(ferror_unlocked(ff))) {
598 goto TextFileAdvance_ret_READ_FAIL;
599 }
600 in_iter = in;
601 in_end = &(load_start[nbytes]);
602 bgzfp->in_size = in_end - in;
603 if (!nbytes) {
604 if (unlikely(n_inbytes)) {
605 goto TextFileAdvance_ret_INVALID_BGZF;
606 }
607 break;
608 }
609 }
610 bgzfp->in_pos = in_iter - in;
611 dst_stop = dst_iter;
612 break;
613 }
614 case kFileZstd:
615 {
616 reterr = ZstRawStreamRead(dst_stop, ff, &txfp->rds.zst, &dst_iter, &basep->errmsg);
617 if (unlikely(reterr)) {
618 goto TextFileAdvance_ret_1;
619 }
620 break;
621 }
622 }
623 basep->dst_len = dst_iter - dst;
624 if (!basep->dst_len) {
625 goto TextFileAdvance_ret_EOF;
626 }
627 if (dst_iter != dst_stop) {
628 // If last character of file isn't a newline, append one to simplify
629 // downstream code.
630 if (dst_iter[-1] != '\n') {
631 *dst_iter++ = '\n';
632 basep->dst_len += 1;
633 }
634 basep->consume_stop = dst_iter;
635 break;
636 }
637 char* last_byte_ptr = Memrchr(dst_load_start, '\n', dst_iter - dst_load_start);
638 if (last_byte_ptr) {
639 basep->consume_stop = &(last_byte_ptr[1]);
640 break;
641 }
642 // Buffer is full, and no '\n' is present. Restart the loop and try to
643 // load more data (extending the buffer if necessary), if we aren't
644 // already at/past the line-length limit.
645 if (basep->dst_len >= basep->enforced_max_line_blen) {
646 goto TextFileAdvance_ret_LONG_LINE;
647 }
648 }
649 if (unlikely(IsPathologicallyLongLineOrToken(dst, dst_load_start, basep->consume_stop, basep->enforced_max_line_blen))) {
650 goto TextFileAdvance_ret_LONG_LINE;
651 }
652 }
653 while (0) {
654 TextFileAdvance_ret_NOMEM:
655 reterr = kPglRetNomem;
656 break;
657 TextFileAdvance_ret_READ_FAIL:
658 reterr = kPglRetReadFail;
659 basep->errmsg = strerror(errno);
660 break;
661 TextFileAdvance_ret_LONG_LINE:
662 basep->errmsg = kShortErrLongLine;
663 reterr = kPglRetMalformedInput;
664 break;
665 TextFileAdvance_ret_INVALID_BGZF:
666 basep->errmsg = kShortErrInvalidBgzf;
667 reterr = kPglRetDecompressFail;
668 break;
669 TextFileAdvance_ret_EOF:
670 reterr = kPglRetEof;
671 break;
672 }
673 TextFileAdvance_ret_1:
674 basep->reterr = reterr;
675 return reterr;
676 }
677
678 PglErr TextFileOnlyEmptyLinesLeft(textFILE* txf_ptr) {
679 TextFileBase* basep = &GetTxfp(txf_ptr)->base;
680 char* line_start = basep->consume_iter;
681 while (1) {
682 if (line_start == basep->consume_stop) {
683 basep->consume_iter = line_start;
684 PglErr reterr = TextFileAdvance(txf_ptr);
685 if (reterr) {
686 return reterr;
687 }
688 line_start = basep->consume_iter;
689 }
690 line_start = FirstNonTspace(line_start);
691 if (unlikely(!IsEolnKns(*line_start))) {
692 basep->reterr = kPglRetMalformedInput;
693 basep->errmsg = kShortErrInteriorEmptyLine;
694 return kPglRetMalformedInput;
695 }
696 line_start = AdvPastDelim(line_start, '\n');
697 }
698 }
699
700 void TextFileRewind(textFILE* txf_ptr) {
701 textFILEMain* txfp = GetTxfp(txf_ptr);
702 TextFileBase* basep = &txfp->base;
703 if ((!basep->ff) || ((basep->reterr) && (basep->reterr != kPglRetEof))) {
704 return;
705 }
706 rewind(basep->ff);
707 basep->reterr = kPglRetSuccess;
708 basep->dst_len = 0;
709 basep->consume_iter = basep->dst;
710 basep->consume_stop = basep->dst;
711 if (basep->file_type != kFileUncompressed) {
712 if (basep->file_type == kFileGzip) {
713 txfp->rds.gz.ds.avail_in = 0;
714 txfp->rds.gz.eof = 0;
715 #ifdef NDEBUG
716 inflateReset(&txfp->rds.gz.ds);
717 #else
718 const int errcode = inflateReset(&txfp->rds.gz.ds);
719 assert(errcode == Z_OK);
720 #endif
721 } else if (basep->file_type == kFileBgzf) {
722 txfp->rds.bgzf.in_size = 0;
723 txfp->rds.bgzf.in_pos = 0;
724 } else {
725 // kFileZstd
726 txfp->rds.zst.ib.size = 0;
727 txfp->rds.zst.ib.pos = 0;
728 ZSTD_DCtx_reset(txfp->rds.zst.ds, ZSTD_reset_session_only);
729 }
730 }
731 }
732
733 BoolErr CleanupTextFile(textFILE* txf_ptr, PglErr* reterrp) {
734 textFILEMain* txfp = GetTxfp(txf_ptr);
735 TextFileBase* basep = &txfp->base;
736 basep->consume_iter = nullptr;
737 basep->consume_stop = nullptr;
738 basep->reterr = kPglRetEof;
739 basep->errmsg = nullptr;
740 if (basep->dst && (!basep->dst_owned_by_consumer)) {
741 free(basep->dst);
742 basep->dst = nullptr;
743 }
744 if (basep->ff) {
745 if (basep->file_type != kFileUncompressed) {
746 if (basep->file_type == kFileZstd) {
747 if (txfp->rds.zst.ib.src) {
748 free_const(txfp->rds.zst.ib.src);
749 txfp->rds.zst.ib.src = nullptr;
750 }
751 if (txfp->rds.zst.ds) {
752 ZSTD_freeDStream(txfp->rds.zst.ds);
753 txfp->rds.zst.ds = nullptr;
754 }
755 } else if (basep->file_type == kFileBgzf) {
756 if (txfp->rds.bgzf.in) {
757 free(txfp->rds.bgzf.in);
758 txfp->rds.bgzf.in = nullptr;
759 }
760 if (txfp->rds.bgzf.ldc) {
761 libdeflate_free_decompressor(txfp->rds.bgzf.ldc);
762 txfp->rds.bgzf.ldc = nullptr;
763 }
764 } else {
765 // plain gzip
766 if (txfp->rds.gz.in) {
767 free(txfp->rds.gz.in);
768 txfp->rds.gz.in = nullptr;
769 }
770 if (txfp->rds.gz.ds_initialized) {
771 inflateEnd(&txfp->rds.gz.ds);
772 }
773 }
774 }
775 if (unlikely(fclose_null(&basep->ff))) {
776 if (!reterrp) {
777 return 1;
778 }
779 if (*reterrp == kPglRetSuccess) {
780 *reterrp = kPglRetReadFail;
781 return 1;
782 }
783 }
784 }
785 return 0;
786 }
787
788
789 void PreinitTextStream(TextStream* txs_ptr) {
790 TextStreamMain* txsp = GetTxsp(txs_ptr);
791 EraseTextFileBase(&txsp->base);
792 txsp->syncp = nullptr;
793 }
794
795 // This type of code is especially bug-prone (ESR would call it a "defect
796 // attractor"). Goal is to get it right, and fast enough to be a major win
797 // over gzgets()... and then not worry about it again for years.
798 THREAD_FUNC_DECL TextStreamThread(void* raw_arg) {
799 TextStreamMain* context = S_CAST(TextStreamMain*, raw_arg);
800 TextFileBase* basep = &context->base;
801 TextStreamSync* syncp = context->syncp;
802 FileCompressionType file_type = basep->file_type;
803 RawMtDecompressStream* rdsp = &context->rds;
804 FILE* ff = basep->ff;
805 char* buf = basep->dst;
806 char* buf_end = &(buf[basep->dst_capacity]);
807 char* cur_block_start = basep->consume_stop;
808 char* read_head = &(buf[basep->dst_len]);
809
810 // We can either be reading/decompressing into memory past the bytes passed
811 // to the consumer, or we can be doing it before those bytes.
812 // In the first case, read_stop is buf_end, but it gets changed to the
813 // latest value of consume_tail when we return to the front of the buffer.
814 // In the second case, read_stop is the position of the first passed byte.
815 char* read_stop = buf_end;
816 #ifdef _WIN32
817 CRITICAL_SECTION* critical_sectionp = &syncp->critical_section;
818 HANDLE reader_progress_event = syncp->reader_progress_event;
819 HANDLE consumer_progress_event = syncp->consumer_progress_event;
820 #else
821 pthread_mutex_t* sync_mutexp = &syncp->sync_mutex;
822 pthread_cond_t* reader_progress_condvarp = &syncp->reader_progress_condvar;
823 pthread_cond_t* consumer_progress_condvarp = &syncp->consumer_progress_condvar;
824 #endif
825 const uint32_t enforced_max_line_blen = basep->enforced_max_line_blen;
826 const char* new_fname = nullptr;
827 const uint32_t is_token_stream = (enforced_max_line_blen == 0);
828 while (1) {
829 TxsInterrupt interrupt = kTxsInterruptNone;
830 PglErr reterr;
831 TxsInterrupt min_interrupt;
832 while (1) {
833 uintptr_t read_attempt_size = read_stop - read_head;
834 if (!read_attempt_size) {
835 const uint32_t memmove_required = (read_stop == buf_end);
836 if (unlikely((cur_block_start == buf) && memmove_required)) {
837 // May need to modify this predicate if we ever allow is_token_stream
838 // && !dst_owned_by_consumer.
839 const uint32_t prev_capacity = buf_end - buf;
840 if (basep->dst_owned_by_consumer || (prev_capacity >= enforced_max_line_blen)) {
841 goto TextStreamThread_LONG_LINE;
842 }
843 // Try to expand buffer.
844 uint32_t next_dst_capacity = enforced_max_line_blen + kDecompressChunkSize;
845 if ((next_dst_capacity / 2) > basep->dst_capacity) {
846 next_dst_capacity = basep->dst_capacity * 2;
847 }
848 #ifndef __LP64__
849 if (next_dst_capacity >= 0x80000000U) {
850 goto TextStreamThread_NOMEM;
851 }
852 #endif
853 char* dst_next = S_CAST(char*, realloc(buf, next_dst_capacity));
854 if (unlikely(!dst_next)) {
855 goto TextStreamThread_NOMEM;
856 }
857 #ifdef _WIN32
858 EnterCriticalSection(critical_sectionp);
859 #else
860 pthread_mutex_lock(sync_mutexp);
861 #endif
862 basep->dst = dst_next;
863 basep->dst_capacity = next_dst_capacity;
864 syncp->consume_tail = dst_next;
865 syncp->available_end = dst_next;
866 syncp->dst_reallocated = 1;
867 #ifdef _WIN32
868 LeaveCriticalSection(critical_sectionp);
869 #else
870 pthread_mutex_unlock(sync_mutexp);
871 #endif
872 buf = dst_next;
873 buf_end = &(buf[next_dst_capacity]);
874 cur_block_start = buf;
875 read_head = &(buf[prev_capacity]);
876 read_stop = &(buf[next_dst_capacity]);
877 continue;
878 }
879 // We cannot continue reading forward. Cases:
880 // 1. read_stop == buf_end, cur_block_start != buf. This means we're
881 // in the middle of reading/decompressing a long line, and want to
882 // wait for consume_tail == cur_block_start, so we can memmove all
883 // the bytes back and continue reading forward. (Tried
884 // relaxing this to
885 // consume_tail >= (buf_end - cur_block_start) + margin
886 // for various values of margin, but that didn't make a meaningful
887 // difference.)
888 // 2. read_stop == buf_end, cur_block_start == buf. We failed with a
889 // long-line error here.
890 // 3. read_stop < buf_end (usual case). This means the consumer may
891 // not be done handling some bytes-in-front we handed off earlier.
892 // We are waiting for consume_tail <= cur_block_start, which means
893 // all bytes in front have been consumed and we're free to continue
894 // reading forward.
895 char* latest_consume_tail;
896 #ifdef _WIN32
897 // bugfix (7 May 2018): when consumer thread is waiting with
898 // syncp->consume_tail == cur_block_start, read_stop is near but not at
899 // buf_end, and there's no '\n' in the subsequent read, we can reach
900 // here a second time without releasing the consumer, so we'd enter
901 // deadlock if we unconditionally wait on consumer_progress_event (and
902 // in the Linux/OS X case, we'd be waiting for a spurious wakeup to
903 // save us).
904 // However, if memmove_required isn't true, we have to wait first; see
905 // the 21 Mar bugfix.
906 if (!memmove_required) {
907 goto TextStreamThread_wait_first;
908 }
909 while (1) {
910 EnterCriticalSection(critical_sectionp);
911 interrupt = syncp->interrupt;
912 if (interrupt != kTxsInterruptNone) {
913 goto TextStreamThread_INTERRUPT;
914 }
915 latest_consume_tail = syncp->consume_tail;
916 if (memmove_required) {
917 if (latest_consume_tail == cur_block_start) {
918 syncp->consume_tail = buf;
919 syncp->available_end = buf;
920 break;
921 }
922 } else if (latest_consume_tail <= cur_block_start) {
923 break;
924 }
925 LeaveCriticalSection(critical_sectionp);
926 TextStreamThread_wait_first:
927 WaitForSingleObject(consumer_progress_event, INFINITE);
928 }
929 // bugfix (23 Mar 2018): didn't always leave the critical section
930 LeaveCriticalSection(critical_sectionp);
931 #else
932 pthread_mutex_lock(sync_mutexp);
933 if (!memmove_required) {
934 // Wait for all bytes in front of read_stop to be consumed.
935 goto TextStreamThread_wait_first;
936 }
937 while (1) {
938 interrupt = syncp->interrupt;
939 if (interrupt != kTxsInterruptNone) {
940 goto TextStreamThread_INTERRUPT;
941 }
942 latest_consume_tail = syncp->consume_tail;
943 if (memmove_required) {
944 if (latest_consume_tail == cur_block_start) {
945 // All bytes have been consumed; memmove is now safe.
946 // bugfix (2 Oct 2018): Previously, this just set
947 // syncp->cur_circular_end = cur_block_start, but that created
948 // TWO consume_iter == available_end == cur_circular_end cases,
949 // one of which was handled incorrectly.
950 syncp->consume_tail = buf;
951 syncp->available_end = buf;
952 break;
953 }
954 // There are bytes behind cur_block_start that haven't been
955 // consumed yet. This is possible on the first iteration through
956 // the loop, since consumer_progress_state may have been set for a
957 // reason we aren't interested in.
958
959 } else if (latest_consume_tail <= cur_block_start) {
960 // All bytes in front of read_stop have been consumed.
961 break;
962 }
963 TextStreamThread_wait_first:
964 while (!syncp->consumer_progress_state) {
965 pthread_cond_wait(consumer_progress_condvarp, sync_mutexp);
966 }
967 syncp->consumer_progress_state = 0;
968 }
969 pthread_mutex_unlock(sync_mutexp);
970 #endif
971 if (read_stop == buf_end) {
972 const uint32_t cur_memmove_len = buf_end - cur_block_start;
973 memmove(buf, cur_block_start, cur_memmove_len);
974 cur_block_start = buf;
975 read_head = &(buf[cur_memmove_len]);
976 } else {
977 read_stop = buf_end;
978 }
979 continue;
980 }
981 if (read_attempt_size > kDecompressChunkSize) {
982 read_attempt_size = kDecompressChunkSize;
983 }
984 char* cur_read_end = read_head;
985 char* cur_read_stop = &(read_head[read_attempt_size]);
986 switch (file_type) {
987 case kFileUncompressed:
988 {
989 cur_read_end += fread_unlocked(read_head, 1, read_attempt_size, ff);
990 if (unlikely(ferror_unlocked(ff))) {
991 goto TextStreamThread_READ_FAIL;
992 }
993 break;
994 }
995 case kFileGzip:
996 {
997 reterr = GzRawStreamRead(cur_read_stop, ff, &rdsp->gz, &cur_read_end, &syncp->errmsg);
998 if (unlikely(reterr)) {
999 goto TextStreamThread_MISC_FAIL;
1000 }
1001 break;
1002 }
1003 case kFileBgzf:
1004 {
1005 reterr = BgzfRawMtStreamRead(CToUc(cur_read_stop), &rdsp->bgzf, R_CAST(unsigned char**, &cur_read_end), &syncp->errmsg);
1006 if (unlikely(reterr)) {
1007 goto TextStreamThread_MISC_FAIL;
1008 }
1009 break;
1010 }
1011 case kFileZstd:
1012 {
1013 reterr = ZstRawStreamRead(cur_read_stop, ff, &rdsp->zst, &cur_read_end, &syncp->errmsg);
1014 if (unlikely(reterr)) {
1015 goto TextStreamThread_MISC_FAIL;
1016 }
1017 break;
1018 }
1019 }
1020 if (cur_read_end < cur_read_stop) {
1021 char* final_read_head = cur_read_end;
1022 if (cur_block_start != final_read_head) {
1023 if (final_read_head[-1] != '\n') {
1024 // Append '\n' so consumer can always use rawmemchr(., '\n') to
1025 // find the end of the current line.
1026 *final_read_head++ = '\n';
1027 }
1028 }
1029 // Still want to consistently enforce max line/token length.
1030 if (unlikely(IsPathologicallyLongLineOrToken(cur_block_start, read_head, final_read_head, enforced_max_line_blen))) {
1031 goto TextStreamThread_LONG_LINE;
1032 }
1033 read_head = final_read_head;
1034 goto TextStreamThread_EOF;
1035 }
1036 char* last_byte_ptr;
1037 if (!is_token_stream) {
1038 last_byte_ptr = Memrchr(read_head, '\n', read_attempt_size);
1039 } else {
1040 last_byte_ptr = LastSpaceOrEoln(read_head, read_attempt_size);
1041 }
1042 if (last_byte_ptr) {
1043 char* next_available_end = &(last_byte_ptr[1]);
1044 if (unlikely(IsPathologicallyLongLineOrToken(cur_block_start, read_head, next_available_end, enforced_max_line_blen))) {
1045 goto TextStreamThread_LONG_LINE;
1046 }
1047 #ifdef _WIN32
1048 EnterCriticalSection(critical_sectionp);
1049 #else
1050 pthread_mutex_lock(sync_mutexp);
1051 #endif
1052 interrupt = syncp->interrupt;
1053 if (interrupt != kTxsInterruptNone) {
1054 goto TextStreamThread_INTERRUPT;
1055 }
1056 char* latest_consume_tail = syncp->consume_tail;
1057 const uint32_t all_later_bytes_consumed = (latest_consume_tail <= cur_block_start);
1058 const uint32_t return_to_start = all_later_bytes_consumed && (latest_consume_tail >= &(buf[kDecompressChunkSize]));
1059 if (return_to_start) {
1060 // bugfix (2 Oct 2018): This was previously setting
1061 // syncp->available_end = next_available_end too, and that was being
1062 // handled as a special case which conflicted with a rare legitimate
1063 // case.
1064 syncp->cur_circular_end = next_available_end;
1065 syncp->available_end = buf;
1066 } else {
1067 syncp->available_end = next_available_end;
1068 }
1069 #ifdef _WIN32
1070 // bugfix (23 Mar 2018): this needs to be in the critical section,
1071 // otherwise there's a danger of this resetting legitimate progress
1072 ResetEvent(consumer_progress_event);
1073 SetEvent(reader_progress_event);
1074 LeaveCriticalSection(critical_sectionp);
1075 #else
1076 // bugfix (21 Mar 2018): must force consumer_progress_state to 0 (or
1077 // ResetEvent(consumer_progress_event); otherwise the other wait loop's
1078 // read_stop = buf_end assignment may occur before all later bytes are
1079 // actually consumed, in the next_available_end == latest_consume_tail
1080 // edge case.
1081 syncp->consumer_progress_state = 0;
1082 pthread_cond_signal(reader_progress_condvarp);
1083 pthread_mutex_unlock(sync_mutexp);
1084 #endif
1085 if (return_to_start) {
1086 // Best to return to the beginning of the buffer.
1087 // (Note that read_attempt_size is guaranteed to be
1088 // <= kDecompressChunkSize.)
1089 const uintptr_t trailing_byte_ct = cur_read_end - next_available_end;
1090 memcpy(buf, next_available_end, trailing_byte_ct);
1091 cur_block_start = buf;
1092 read_head = &(buf[trailing_byte_ct]);
1093 // May as well reduce false sharing risk.
1094 read_stop = R_CAST(char*, RoundDownPow2(R_CAST(uintptr_t, latest_consume_tail), kCacheline));
1095 continue;
1096 }
1097 if (all_later_bytes_consumed) {
1098 read_stop = buf_end;
1099 } else {
1100 read_stop = R_CAST(char*, RoundDownPow2(R_CAST(uintptr_t, latest_consume_tail), kCacheline));
1101 }
1102 cur_block_start = next_available_end;
1103 }
1104 read_head = cur_read_end;
1105 }
1106 while (0) {
1107 TextStreamThread_NOMEM:
1108 min_interrupt = kTxsInterruptShutdown;
1109 reterr = kPglRetNomem;
1110 break;
1111 TextStreamThread_OPEN_FAIL:
1112 min_interrupt = kTxsInterruptShutdown;
1113 syncp->errmsg = strerror(errno);
1114 reterr = kPglRetOpenFail;
1115 break;
1116 TextStreamThread_READ_FAIL:
1117 min_interrupt = kTxsInterruptShutdown;
1118 syncp->errmsg = strerror(errno);
1119 reterr = kPglRetReadFail;
1120 break;
1121 TextStreamThread_LONG_LINE:
1122 min_interrupt = kTxsInterruptShutdown;
1123 syncp->errmsg = kShortErrLongLine;
1124 reterr = kPglRetMalformedInput;
1125 break;
1126 TextStreamThread_EOF:
1127 min_interrupt = kTxsInterruptRetarget;
1128 reterr = kPglRetEof;
1129 break;
1130 TextStreamThread_MISC_FAIL:
1131 min_interrupt = kTxsInterruptShutdown;
1132 break;
1133 }
1134 // We need to wait for a message from the consumer before we can usefully
1135 // proceed.
1136 // More precisely:
1137 // * In the eof subcase, we're waiting for either a rewind or shutdown
1138 // request.
1139 // * In the error subcase, we're just waiting for the shutdown request.
1140
1141 // Pass the error code back.
1142 #ifdef _WIN32
1143 EnterCriticalSection(critical_sectionp);
1144 #else
1145 pthread_mutex_lock(sync_mutexp);
1146 #endif
1147 syncp->reterr = reterr;
1148 interrupt = syncp->interrupt;
1149 if (interrupt >= min_interrupt) {
1150 // It's our lucky day: we don't need to wait again.
1151 goto TextStreamThread_INTERRUPT;
1152 }
1153 if (reterr == kPglRetEof) {
1154 syncp->available_end = read_head;
1155 }
1156 #ifdef _WIN32
1157 SetEvent(reader_progress_event);
1158 LeaveCriticalSection(critical_sectionp);
1159 while (1) {
1160 WaitForSingleObject(consumer_progress_event, INFINITE);
1161 EnterCriticalSection(critical_sectionp);
1162 interrupt = syncp->interrupt;
1163 if (interrupt >= min_interrupt) {
1164 break;
1165 }
1166 LeaveCriticalSection(critical_sectionp);
1167 }
1168 #else
1169 pthread_cond_signal(reader_progress_condvarp);
1170 do {
1171 while (!syncp->consumer_progress_state) {
1172 pthread_cond_wait(consumer_progress_condvarp, sync_mutexp);
1173 }
1174 syncp->consumer_progress_state = 0;
1175 interrupt = syncp->interrupt;
1176 } while (interrupt < min_interrupt);
1177 #endif
1178 TextStreamThread_INTERRUPT:
1179 // must be in critical section here, or be holding the mutex.
1180 if (interrupt == kTxsInterruptRetarget) {
1181 new_fname = syncp->new_fname;
1182 syncp->interrupt = kTxsInterruptNone;
1183 syncp->reterr = kPglRetSuccess;
1184 }
1185 #ifdef _WIN32
1186 LeaveCriticalSection(critical_sectionp);
1187 #else
1188 pthread_mutex_unlock(sync_mutexp);
1189 #endif
1190 if (interrupt == kTxsInterruptShutdown) {
1191 // possible todo: close the file here
1192 THREAD_RETURN;
1193 }
1194 assert(interrupt == kTxsInterruptRetarget);
1195 read_head = buf;
1196 if (!new_fname) {
1197 if (file_type == kFileBgzf) {
1198 reterr = BgzfRawMtStreamRewind(&rdsp->bgzf, &syncp->errmsg);
1199 if (unlikely(reterr)) {
1200 goto TextStreamThread_MISC_FAIL;
1201 }
1202 } else {
1203 // See TextFileRewind().
1204 rewind(ff);
1205 if (file_type != kFileUncompressed) {
1206 if (file_type == kFileGzip) {
1207 rdsp->gz.ds.avail_in = 0;
1208 rdsp->gz.eof = 0;
1209 #ifdef NDEBUG
1210 inflateReset(&rdsp->gz.ds);
1211 #else
1212 const int errcode = inflateReset(&rdsp->gz.ds);
1213 assert(errcode == Z_OK);
1214 #endif
1215 } else {
1216 // kFileZstd
1217 rdsp->zst.ib.size = 0;
1218 rdsp->zst.ib.pos = 0;
1219 ZSTD_DCtx_reset(rdsp->zst.ds, ZSTD_reset_session_only);
1220 }
1221 }
1222 }
1223 } else {
1224 // Switch to another file, with less creation/destruction of resources.
1225 FILE* next_ff = fopen(new_fname, FOPEN_RB);
1226 if (unlikely(!next_ff)) {
1227 goto TextStreamThread_OPEN_FAIL;
1228 }
1229 // See TextFileOpenInternal().
1230 uint32_t nbytes = fread_unlocked(buf, 1, 16, next_ff);
1231 FileCompressionType next_file_type = kFileUncompressed;
1232 if (nbytes >= 4) {
1233 uint32_t magic4;
1234 CopyFromUnalignedU32(&magic4, CToUc(buf));
1235 if (IsZstdFrame(magic4)) {
1236 next_file_type = kFileZstd;
1237 } else if ((magic4 << 8) == 0x088b1f00) {
1238 if ((nbytes == 16) && IsBgzfHeader(buf)) {
1239 next_file_type = kFileBgzf;
1240 } else {
1241 next_file_type = kFileGzip;
1242 }
1243 }
1244 }
1245 if (file_type != next_file_type) {
1246 // Destroy old type-specific resources, and allocate new ones.
1247 if (file_type == kFileGzip) {
1248 free(rdsp->gz.in);
1249 inflateEnd(&rdsp->gz.ds);
1250 } else if (file_type == kFileBgzf) {
1251 CleanupBgzfRawMtStream(&rdsp->bgzf);
1252 } else if (file_type == kFileZstd) {
1253 free_const(rdsp->zst.ib.src);
1254 ZSTD_freeDStream(rdsp->zst.ds);
1255 }
1256
1257 if (unlikely(fclose(ff))) {
1258 fclose(next_ff);
1259 goto TextStreamThread_READ_FAIL;
1260 }
1261 ff = next_ff;
1262 basep->ff = ff;
1263 file_type = next_file_type;
1264 basep->file_type = file_type;
1265 switch (file_type) {
1266 case kFileUncompressed:
1267 read_head = &(read_head[nbytes]);
1268 break;
1269 case kFileGzip:
1270 if (unlikely(GzRawInit(buf, nbytes, &rdsp->gz))) {
1271 goto TextStreamThread_NOMEM;
1272 }
1273 break;
1274 case kFileBgzf:
1275 reterr = BgzfRawMtStreamInit(buf, context->decompress_thread_ct, ff, nullptr, &rdsp->bgzf, &syncp->errmsg);
1276 if (unlikely(reterr)) {
1277 goto TextStreamThread_MISC_FAIL;
1278 }
1279 // bugfix (5 Oct 2019): forgot this break
1280 break;
1281 case kFileZstd:
1282 if (unlikely(ZstRawInit(buf, nbytes, &rdsp->zst))) {
1283 goto TextStreamThread_NOMEM;
1284 }
1285 break;
1286 }
1287 } else {
1288 switch (file_type) {
1289 case kFileUncompressed:
1290 read_head = &(read_head[nbytes]);
1291 break;
1292 // Rest of this is similar to rewind.
1293 case kFileGzip:
1294 {
1295 GzRawDecompressStream* gzp = &rdsp->gz;
1296 gzp->eof = 0;
1297 z_stream* dsp = &gzp->ds;
1298 #ifdef NDEBUG
1299 inflateReset(dsp);
1300 #else
1301 const int errcode = inflateReset(dsp);
1302 assert(errcode == Z_OK);
1303 #endif
1304 memcpy(gzp->in, buf, nbytes);
1305 dsp->next_in = gzp->in;
1306 dsp->avail_in = nbytes;
1307 break;
1308 }
1309 case kFileBgzf:
1310 {
1311 reterr = BgzfRawMtStreamRetarget(buf, &rdsp->bgzf, next_ff, &syncp->errmsg);
1312 if (unlikely(reterr)) {
1313 fclose(next_ff);
1314 goto TextStreamThread_MISC_FAIL;
1315 }
1316 break;
1317 }
1318 case kFileZstd:
1319 {
1320 ZstRawDecompressStream* zstp = &rdsp->zst;
1321 ZSTD_DCtx_reset(zstp->ds, ZSTD_reset_session_only);
1322 memcpy(K_CAST(void*, zstp->ib.src), buf, nbytes);
1323 zstp->ib.size = nbytes;
1324 zstp->ib.pos = 0;
1325 break;
1326 }
1327 }
1328 if (unlikely(fclose(ff))) {
1329 fclose(next_ff);
1330 goto TextStreamThread_READ_FAIL;
1331 }
1332 ff = next_ff;
1333 basep->ff = ff;
1334 }
1335 }
1336 cur_block_start = buf;
1337 read_stop = buf_end;
1338 }
1339 }
1340
1341 const char kShortErrRfileInvalid[] = "TextStreamOpenEx can't be called with a closed or error-state textFILE";
1342
1343 PglErr TextStreamOpenEx(const char* fname, uint32_t enforced_max_line_blen, uint32_t dst_capacity, uint32_t decompress_thread_ct, textFILE* txf_ptr, char* dst, TextStream* txs_ptr) {
1344 TextStreamMain* txsp = GetTxsp(txs_ptr);
1345 TextFileBase* txs_basep = &txsp->base;
1346 PglErr reterr = kPglRetSuccess;
1347 {
1348 txsp->decompress_thread_ct = decompress_thread_ct;
1349 if (txf_ptr) {
1350 // Move-construct (unless there was an error, or file is not opened)
1351 if (unlikely((!TextFileIsOpen(txf_ptr)) || TextFileErrcode(txf_ptr))) {
1352 reterr = kPglRetImproperFunctionCall;
1353 txs_basep->errmsg = kShortErrRfileInvalid;
1354 goto TextStreamOpenEx_ret_1;
1355 }
1356 if (unlikely(TextIsOpen(txs_ptr))) {
1357 reterr = kPglRetImproperFunctionCall;
1358 txs_basep->errmsg = kShortErrRfileAlreadyOpen;
1359 goto TextStreamOpenEx_ret_1;
1360 }
1361 textFILEMain* txfp = GetTxfp(txf_ptr);
1362 *txs_basep = txfp->base; // struct copy
1363 // Simplify TextStreamThread() initialization.
1364 const uint32_t backfill_ct = txs_basep->consume_iter - txs_basep->dst;
1365 if (backfill_ct) {
1366 txs_basep->dst_len -= backfill_ct;
1367 memmove(txs_basep->dst, txs_basep->consume_iter, txs_basep->dst_len);
1368 txs_basep->consume_iter = txs_basep->dst;
1369 txs_basep->consume_stop -= backfill_ct;
1370 }
1371 txs_basep->enforced_max_line_blen = enforced_max_line_blen;
1372 assert(txs_basep->dst_len <= dst_capacity);
1373 txs_basep->dst_capacity = dst_capacity;
1374 reterr = txfp->base.reterr;
1375 const FileCompressionType file_type = txfp->base.file_type;
1376 if (file_type != kFileUncompressed) {
1377 if (file_type == kFileGzip) {
1378 txsp->rds.gz = txfp->rds.gz;
1379 } else if (file_type == kFileZstd) {
1380 txsp->rds.zst = txfp->rds.zst;
1381 } else {
1382 reterr = BgzfRawMtStreamInit(nullptr, decompress_thread_ct, txs_basep->ff, &txfp->rds.bgzf, &txsp->rds.bgzf, &txs_basep->errmsg);
1383 if (unlikely(reterr)) {
1384 EraseTextFileBase(&txfp->base);
1385 goto TextStreamOpenEx_ret_1;
1386 }
1387 }
1388 }
1389 EraseTextFileBase(&txfp->base);
1390 } else {
1391 reterr = TextFileOpenInternal(fname, enforced_max_line_blen, dst_capacity, dst, nullptr, txsp);
1392 }
1393 if (reterr) {
1394 if (reterr == kPglRetEof) {
1395 txs_basep->reterr = kPglRetEof;
1396 return kPglRetSuccess;
1397 }
1398 goto TextStreamOpenEx_ret_1;
1399 }
1400 assert(!txsp->syncp);
1401 TextStreamSync* syncp;
1402 if (unlikely(cachealigned_malloc(RoundUpPow2(sizeof(TextStreamSync), kCacheline), &syncp))) {
1403 goto TextStreamOpenEx_ret_NOMEM;
1404 }
1405 txsp->syncp = syncp;
1406 dst = txs_basep->dst;
1407 syncp->consume_tail = dst;
1408 syncp->cur_circular_end = nullptr;
1409 syncp->available_end = txs_basep->consume_stop;
1410 syncp->errmsg = nullptr;
1411 syncp->reterr = kPglRetSuccess;
1412 syncp->dst_reallocated = 0;
1413 syncp->interrupt = kTxsInterruptNone;
1414 syncp->new_fname = nullptr;
1415 #ifdef _WIN32
1416 syncp->read_thread = nullptr;
1417 // apparently this can raise a low-memory exception in older Windows
1418 // versions, but that's not really our problem.
1419 InitializeCriticalSection(&syncp->critical_section);
1420
1421 syncp->reader_progress_event = CreateEvent(nullptr, FALSE, FALSE, nullptr);
1422 if (unlikely(!syncp->reader_progress_event)) {
1423 DeleteCriticalSection(&syncp->critical_section);
1424 goto TextStreamOpenEx_ret_THREAD_CREATE_FAIL;
1425 }
1426 syncp->consumer_progress_event = CreateEvent(nullptr, FALSE, FALSE, nullptr);
1427 if (unlikely(!syncp->consumer_progress_event)) {
1428 DeleteCriticalSection(&syncp->critical_section);
1429 CloseHandle(syncp->reader_progress_event);
1430 goto TextStreamOpenEx_ret_THREAD_CREATE_FAIL;
1431 }
1432 syncp->read_thread = R_CAST(HANDLE, _beginthreadex(nullptr, kDefaultThreadStack, TextStreamThread, txsp, 0, nullptr));
1433 if (unlikely(!syncp->read_thread)) {
1434 DeleteCriticalSection(&syncp->critical_section);
1435 CloseHandle(syncp->consumer_progress_event);
1436 CloseHandle(syncp->reader_progress_event);
1437 goto TextStreamOpenEx_ret_THREAD_CREATE_FAIL;
1438 }
1439 #else
1440 syncp->sync_init_state = 0;
1441 if (unlikely(pthread_mutex_init(&syncp->sync_mutex, nullptr))) {
1442 goto TextStreamOpenEx_ret_THREAD_CREATE_FAIL;
1443 }
1444 syncp->sync_init_state = 1;
1445 if (unlikely(pthread_cond_init(&syncp->reader_progress_condvar, nullptr))) {
1446 goto TextStreamOpenEx_ret_THREAD_CREATE_FAIL;
1447 }
1448 syncp->sync_init_state = 2;
1449 syncp->consumer_progress_state = 0;
1450 if (unlikely(pthread_cond_init(&syncp->consumer_progress_condvar, nullptr))) {
1451 goto TextStreamOpenEx_ret_THREAD_CREATE_FAIL;
1452 }
1453 syncp->sync_init_state = 3;
1454 # ifdef __cplusplus
1455 if (unlikely(pthread_create(&syncp->read_thread,
1456 &g_thread_startup.smallstack_thread_attr,
1457 TextStreamThread, txsp))) {
1458 goto TextStreamOpenEx_ret_THREAD_CREATE_FAIL;
1459 }
1460 # else
1461 pthread_attr_t smallstack_thread_attr;
1462 if (unlikely(pthread_attr_init(&smallstack_thread_attr))) {
1463 goto TextStreamOpenEx_ret_THREAD_CREATE_FAIL;
1464 }
1465 pthread_attr_setstacksize(&smallstack_thread_attr, kDefaultThreadStack);
1466 if (unlikely(pthread_create(&syncp->read_thread, &smallstack_thread_attr,
1467 TextStreamThread, txsp))) {
1468 pthread_attr_destroy(&smallstack_thread_attr);
1469 goto TextStreamOpenEx_ret_THREAD_CREATE_FAIL;
1470 }
1471 pthread_attr_destroy(&smallstack_thread_attr);
1472 # endif
1473 syncp->sync_init_state = 4;
1474 #endif
1475 }
1476 while (0) {
1477 TextStreamOpenEx_ret_NOMEM:
1478 reterr = kPglRetNomem;
1479 break;
1480 TextStreamOpenEx_ret_THREAD_CREATE_FAIL:
1481 reterr = kPglRetThreadCreateFail;
1482 break;
1483 }
1484 TextStreamOpenEx_ret_1:
1485 txs_basep->reterr = reterr;
1486 return reterr;
1487 }
1488
1489 uint32_t TextDecompressThreadCt(const TextStream* txs_ptr) {
1490 const TextStreamMain* txsp = GetTxspK(txs_ptr);
1491 FileCompressionType file_type = txsp->base.file_type;
1492 if (file_type == kFileUncompressed) {
1493 return 0;
1494 }
1495 if (file_type != kFileBgzf) {
1496 return 1;
1497 }
1498 return GetThreadCtTg(&txsp->rds.bgzf.tg);
1499 }
1500
1501 PglErr TextAdvance(TextStream* txs_ptr) {
1502 TextStreamMain* txsp = GetTxsp(txs_ptr);
1503 TextFileBase* basep = &txsp->base;
1504 char* consume_iter = basep->consume_iter;
1505 TextStreamSync* syncp = txsp->syncp;
1506 #ifdef _WIN32
1507 CRITICAL_SECTION* critical_sectionp = &syncp->critical_section;
1508 HANDLE consumer_progress_event = syncp->consumer_progress_event;
1509 while (1) {
1510 EnterCriticalSection(critical_sectionp);
1511 const PglErr reterr = syncp->reterr;
1512 if (unlikely((reterr != kPglRetSuccess) && (reterr != kPglRetEof))) {
1513 basep->errmsg = syncp->errmsg;
1514 LeaveCriticalSection(critical_sectionp);
1515 basep->reterr = reterr;
1516 // No need to set consumer_progress event here, just let the cleanup
1517 // routine take care of that.
1518 return reterr;
1519 }
1520 char* available_end = syncp->available_end;
1521 char* cur_circular_end = syncp->cur_circular_end;
1522 if (consume_iter == cur_circular_end) {
1523 char* buf = basep->dst;
1524 consume_iter = buf;
1525 basep->consume_iter = buf;
1526 cur_circular_end = nullptr;
1527 syncp->cur_circular_end = nullptr;
1528 if (consume_iter != available_end) {
1529 SetEvent(consumer_progress_event);
1530 }
1531 }
1532 if (syncp->dst_reallocated) {
1533 consume_iter = basep->dst;
1534 syncp->dst_reallocated = 0;
1535 }
1536 syncp->consume_tail = consume_iter;
1537 if ((consume_iter != available_end) || cur_circular_end) {
1538 if (cur_circular_end) {
1539 basep->consume_stop = cur_circular_end;
1540 } else {
1541 basep->consume_stop = available_end;
1542 }
1543 LeaveCriticalSection(critical_sectionp);
1544 // We could set the consumer_progress event here, but it's not really
1545 // necessary?
1546 // SetEvent(consumer_progress_event);
1547 return kPglRetSuccess;
1548 }
1549 SetEvent(consumer_progress_event);
1550 LeaveCriticalSection(critical_sectionp);
1551 // We've processed all the consume-ready bytes...
1552 if (reterr != kPglRetSuccess) {
1553 // ...and we're at eof. Don't set consumer_progress event here; let that
1554 // wait until cleanup or rewind/retarget.
1555 basep->reterr = kPglRetEof;
1556 return kPglRetEof;
1557 }
1558 // ...and there's probably more.
1559 WaitForSingleObject(syncp->reader_progress_event, INFINITE);
1560 // bugfix (2 Oct 2018)
1561 consume_iter = syncp->consume_tail;
1562 basep->consume_iter = consume_iter;
1563 }
1564 #else
1565 pthread_mutex_t* sync_mutexp = &syncp->sync_mutex;
1566 pthread_cond_t* consumer_progress_condvarp = &syncp->consumer_progress_condvar;
1567 pthread_cond_t* reader_progress_condvarp = &syncp->reader_progress_condvar;
1568 pthread_mutex_lock(sync_mutexp);
1569 while (1) {
1570 const PglErr reterr = syncp->reterr;
1571 if (unlikely((reterr != kPglRetSuccess) && (reterr != kPglRetEof))) {
1572 basep->errmsg = syncp->errmsg;
1573 pthread_mutex_unlock(sync_mutexp);
1574 basep->reterr = reterr;
1575 return reterr;
1576 }
1577 char* available_end = syncp->available_end;
1578 // bugfix (2 Oct 2018): There were TWO consume_iter == available_end ==
1579 // cur_circular_end cases.
1580 // printf("checking for more to consume: %lx %lx %lx\n", (uintptr_t)consume_iter, (uintptr_t)syncp->cur_circular_end, (uintptr_t)available_end);
1581 if (consume_iter == syncp->cur_circular_end) {
1582 char* buf = basep->dst;
1583 consume_iter = buf;
1584 basep->consume_iter = buf;
1585 syncp->cur_circular_end = nullptr;
1586 // File-reader could be waiting on either "all bytes in front have been
1587 // consumed, some bytes behind may remain" or "all bytes have been
1588 // consumed". Signal in case it's the first.
1589 if (consume_iter != available_end) {
1590 syncp->consumer_progress_state = 1;
1591 pthread_cond_signal(consumer_progress_condvarp);
1592 }
1593 }
1594 if (syncp->dst_reallocated) {
1595 consume_iter = basep->dst;
1596 syncp->dst_reallocated = 0;
1597 }
1598 syncp->consume_tail = consume_iter;
1599 // If cur_circular_end is still non-null here, there must be bytes
1600 // available even when consume_iter == available_end. (Is the latter
1601 // still possible? Check this.)
1602 if ((consume_iter != available_end) || syncp->cur_circular_end) {
1603 if (syncp->cur_circular_end) {
1604 basep->consume_stop = syncp->cur_circular_end;
1605 } else {
1606 basep->consume_stop = available_end;
1607 }
1608 // pthread_cond_signal(consumer_progress_condvarp);
1609 pthread_mutex_unlock(sync_mutexp);
1610 // printf("consuming %lx..%lx\n", (uintptr_t)(*consume_iterp), (uintptr_t)rlsp->consume_stop);
1611 return kPglRetSuccess;
1612 }
1613 // We've processed all the consume-ready bytes...
1614 if (reterr != kPglRetSuccess) {
1615 // ...and we're at eof.
1616 pthread_mutex_unlock(sync_mutexp);
1617 basep->reterr = kPglRetEof;
1618 return kPglRetEof;
1619 }
1620 // ...and there's probably more.
1621 syncp->consumer_progress_state = 1;
1622 pthread_cond_signal(consumer_progress_condvarp);
1623 // no need for an explicit spurious-wakeup check, we'll check the progress
1624 // condition (available_end has advanced, or we have a read error) anyway
1625 // and get back here if it isn't satisfied
1626 pthread_cond_wait(reader_progress_condvarp, sync_mutexp);
1627 // bugfix (2 Oct 2018)
1628 consume_iter = syncp->consume_tail;
1629 basep->consume_iter = syncp->consume_tail;
1630 }
1631 #endif
1632 }
1633
1634 PglErr TextOnlyEmptyLinesLeft(TextStream* txs_ptr) {
1635 TextFileBase* basep = &GetTxsp(txs_ptr)->base;
1636 char* line_start = basep->consume_iter;
1637 while (1) {
1638 if (line_start == basep->consume_stop) {
1639 basep->consume_iter = line_start;
1640 PglErr reterr = TextAdvance(txs_ptr);
1641 if (reterr) {
1642 return reterr;
1643 }
1644 line_start = basep->consume_iter;
1645 }
1646 line_start = FirstNonTspace(line_start);
1647 if (unlikely(!IsEolnKns(*line_start))) {
1648 basep->reterr = kPglRetMalformedInput;
1649 basep->errmsg = kShortErrInteriorEmptyLine;
1650 return kPglRetMalformedInput;
1651 }
1652 line_start = AdvPastDelim(line_start, '\n');
1653 }
1654 }
1655
1656 PglErr TextSkipNz(uintptr_t skip_ct, TextStream* txs_ptr) {
1657 TextFileBase* basep = &GetTxsp(txs_ptr)->base;
1658 #ifdef __LP64__
1659 char* consume_iter = basep->consume_iter;
1660 // Minor extension of AdvToNthDelimChecked().
1661 const VecUc vvec_all_lf = vecuc_set1('\n');
1662 while (1) {
1663 uintptr_t starting_addr = R_CAST(uintptr_t, consume_iter);
1664 VecUc* consume_viter = R_CAST(VecUc*, RoundDownPow2(starting_addr, kBytesPerVec));
1665 uintptr_t ending_addr = R_CAST(uintptr_t, basep->consume_stop);
1666 VecUc* consume_vstop = R_CAST(VecUc*, RoundDownPow2(ending_addr, kBytesPerVec));
1667 VecUc cur_vvec = *consume_viter;
1668 VecUc lf_vvec = (cur_vvec == vvec_all_lf);
1669 # ifndef SIMDE_ARM_NEON_A32V8_NATIVE
1670 uint32_t lf_bytes = vecuc_movemask(lf_vvec);
1671 const uint32_t leading_byte_ct = starting_addr - R_CAST(uintptr_t, consume_viter);
1672 const uint32_t leading_mask = UINT32_MAX << leading_byte_ct;
1673 lf_bytes &= leading_mask;
1674 uint32_t cur_lf_ct;
1675 for (; consume_viter != consume_vstop; ) {
1676 cur_lf_ct = PopcountVec8thUint(lf_bytes);
1677 if (cur_lf_ct >= skip_ct) {
1678 goto TextSkipNz_finish;
1679 }
1680 skip_ct -= cur_lf_ct;
1681 // bugfix (28 Sep 2019): forgot to update cur_vvec/lf_vvec/lf_bytes?!
1682 ++consume_viter;
1683 cur_vvec = *consume_viter;
1684 lf_vvec = (cur_vvec == vvec_all_lf);
1685 lf_bytes = vecuc_movemask(lf_vvec);
1686 }
1687 lf_bytes &= (1U << (ending_addr % kBytesPerVec)) - 1;
1688 cur_lf_ct = PopcountVec8thUint(lf_bytes);
1689 if (cur_lf_ct >= skip_ct) {
1690 TextSkipNz_finish:
1691 // todo: check if this is faster outside of vector-space
1692 lf_bytes = ClearBottomSetBits(skip_ct - 1, lf_bytes);
1693 const uint32_t byte_offset_in_vec = ctzu32(lf_bytes) + 1;
1694 const uintptr_t result_addr = R_CAST(uintptr_t, consume_viter) + byte_offset_in_vec;
1695 basep->consume_iter = R_CAST(char*, result_addr);
1696 return kPglRetSuccess;
1697 }
1698 # else
1699 uint64_t lf_nybbles = arm_shrn4_uc(lf_vvec);
1700 const uint32_t leading_byte_ct = starting_addr - R_CAST(uintptr_t, consume_viter);
1701 const uint64_t leading_mask = UINT64_MAX << (4 * leading_byte_ct);
1702 lf_nybbles &= leading_mask;
1703 uint32_t cur_lf_ct;
1704 for (; consume_viter != consume_vstop; ) {
1705 cur_lf_ct = count_set_nybbles(lf_nybbles);
1706 if (cur_lf_ct >= skip_ct) {
1707 goto TextSkipNz_finish;
1708 }
1709 skip_ct -= cur_lf_ct;
1710 // bugfix (28 Sep 2019): forgot to update cur_vvec/lf_vvec/lf_bytes?!
1711 ++consume_viter;
1712 cur_vvec = *consume_viter;
1713 lf_vvec = (cur_vvec == vvec_all_lf);
1714 lf_nybbles = arm_shrn4_uc(lf_vvec);
1715 }
1716 lf_nybbles &= (1LLU << (4 * (ending_addr % kBytesPerVec))) - 1;
1717 cur_lf_ct = count_set_nybbles(lf_nybbles);
1718 if (cur_lf_ct >= skip_ct) {
1719 TextSkipNz_finish:
1720 uint64_t lf_bits4 = lf_nybbles & kMask1111;
1721 lf_bits4 = ClearBottomSetBits(skip_ct - 1, lf_bits4);
1722 const uint32_t byte_offset_in_vec = (ctzw(lf_bits4) / 4) + 1;
1723 const uintptr_t result_addr = R_CAST(uintptr_t, consume_viter) + byte_offset_in_vec;
1724 basep->consume_iter = R_CAST(char*, result_addr);
1725 return kPglRetSuccess;
1726 }
1727 # endif
1728 skip_ct -= cur_lf_ct;
1729 // bugfix (30 Oct 2019)
1730 basep->consume_iter = basep->consume_stop;
1731 PglErr reterr = TextAdvance(txs_ptr);
1732 // not unlikely() due to eof
1733 if (reterr) {
1734 return reterr;
1735 }
1736 consume_iter = basep->consume_iter;
1737 }
1738 #else
1739 char* consume_iter = basep->consume_iter;
1740 char* consume_stop = basep->consume_stop;
1741 for (uintptr_t ulii = 0; ulii != skip_ct; ++ulii) {
1742 if (consume_iter == consume_stop) {
1743 basep->consume_iter = consume_iter;
1744 PglErr reterr = TextAdvance(txs_ptr);
1745 if (reterr) {
1746 return reterr;
1747 }
1748 consume_iter = basep->consume_iter;
1749 consume_stop = basep->consume_stop;
1750 }
1751 consume_iter = AdvPastDelim(consume_iter, '\n');
1752 }
1753 basep->consume_iter = consume_iter;
1754 return kPglRetSuccess;
1755 #endif
1756 }
1757
1758 PglErr TextRetarget(const char* new_fname, TextStream* txs_ptr) {
1759 TextStreamMain* txsp = GetTxsp(txs_ptr);
1760 TextFileBase* basep = &txsp->base;
1761 TextStreamSync* syncp = txsp->syncp;
1762 #ifdef _WIN32
1763 CRITICAL_SECTION* critical_sectionp = &syncp->critical_section;
1764 EnterCriticalSection(critical_sectionp);
1765 const PglErr reterr = syncp->reterr;
1766 if (reterr != kPglRetSuccess) {
1767 if (unlikely(reterr != kPglRetEof)) {
1768 basep->errmsg = syncp->errmsg;
1769 LeaveCriticalSection(critical_sectionp);
1770 basep->reterr = reterr;
1771 return reterr;
1772 }
1773 // clear eof
1774 syncp->reterr = kPglRetSuccess;
1775 }
1776 basep->reterr = kPglRetSuccess;
1777 // bugfix (5 Mar 2018): need to reset these here, can't wait for reader
1778 // thread to receive signal
1779 char* buf = basep->dst;
1780 syncp->consume_tail = buf;
1781 syncp->cur_circular_end = nullptr;
1782 syncp->available_end = buf;
1783 syncp->dst_reallocated = 0;
1784 syncp->interrupt = kTxsInterruptRetarget;
1785 // Could also just open the file in this function (before acquiring the
1786 // mutex) and pass a gzFile. Advantages: nothing bad happens if new_fname
1787 // is overwritten before it's read, RLstreamErrPrint() no longer has to deal
1788 // with OpenFail error. Disadvantage: peak resource usage is a bit higher if
1789 // we open the second file before closing the first one. Advantages probably
1790 // outweigh disadvantages, but I'll wait till --pmerge development to make a
1791 // decision since that's the main function that actually cares.
1792 syncp->new_fname = new_fname;
1793 SetEvent(syncp->consumer_progress_event);
1794 LeaveCriticalSection(critical_sectionp);
1795 #else
1796 pthread_mutex_t* sync_mutexp = &syncp->sync_mutex;
1797 pthread_cond_t* consumer_progress_condvarp = &syncp->consumer_progress_condvar;
1798 pthread_mutex_lock(sync_mutexp);
1799 const PglErr reterr = syncp->reterr;
1800 if (reterr != kPglRetSuccess) {
1801 if (unlikely(reterr != kPglRetEof)) {
1802 basep->errmsg = syncp->errmsg;
1803 pthread_mutex_unlock(sync_mutexp);
1804 basep->reterr = reterr;
1805 return reterr;
1806 }
1807 // clear eof
1808 syncp->reterr = kPglRetSuccess;
1809 }
1810 // bugfix (4 Oct 2019): also need to clear eof here
1811 basep->reterr = kPglRetSuccess;
1812 char* buf = basep->dst;
1813 syncp->consume_tail = buf;
1814 syncp->cur_circular_end = nullptr;
1815 syncp->available_end = buf;
1816 syncp->dst_reallocated = 0;
1817 syncp->interrupt = kTxsInterruptRetarget;
1818 syncp->new_fname = new_fname;
1819 syncp->consumer_progress_state = 1;
1820 pthread_cond_signal(consumer_progress_condvarp);
1821 pthread_mutex_unlock(sync_mutexp);
1822 #endif
1823 basep->consume_iter = buf;
1824 basep->consume_stop = buf;
1825 return kPglRetSuccess;
1826 }
1827
1828 BoolErr CleanupTextStream(TextStream* txs_ptr, PglErr* reterrp) {
1829 TextStreamMain* txsp = GetTxsp(txs_ptr);
1830 TextFileBase* basep = &txsp->base;
1831 TextStreamSync* syncp = txsp->syncp;
1832 if (syncp) {
1833 #ifdef _WIN32
1834 if (syncp->read_thread) {
1835 CRITICAL_SECTION* critical_sectionp = &syncp->critical_section;
1836 EnterCriticalSection(critical_sectionp);
1837 syncp->interrupt = kTxsInterruptShutdown;
1838 SetEvent(syncp->consumer_progress_event);
1839 LeaveCriticalSection(critical_sectionp);
1840 WaitForSingleObject(syncp->read_thread, INFINITE);
1841 DeleteCriticalSection(critical_sectionp);
1842 CloseHandle(syncp->consumer_progress_event);
1843 CloseHandle(syncp->reader_progress_event);
1844 }
1845 #else
1846 const uint32_t sync_init_state = syncp->sync_init_state;
1847 if (sync_init_state) {
1848 pthread_mutex_t* sync_mutexp = &syncp->sync_mutex;
1849 pthread_cond_t* consumer_progress_condvarp = &syncp->consumer_progress_condvar;
1850 if (sync_init_state == 4) {
1851 pthread_mutex_lock(sync_mutexp);
1852 syncp->interrupt = kTxsInterruptShutdown;
1853 syncp->consumer_progress_state = 1;
1854 pthread_cond_signal(consumer_progress_condvarp);
1855 pthread_mutex_unlock(sync_mutexp);
1856 pthread_join(syncp->read_thread, nullptr);
1857 }
1858 pthread_mutex_destroy(sync_mutexp);
1859 if (sync_init_state > 1) {
1860 pthread_cond_destroy(&syncp->reader_progress_condvar);
1861 if (sync_init_state > 2) {
1862 pthread_cond_destroy(consumer_progress_condvarp);
1863 }
1864 }
1865 }
1866 #endif
1867 aligned_free(txsp->syncp);
1868 txsp->syncp = nullptr;
1869 }
1870 basep->consume_iter = nullptr;
1871 basep->consume_stop = nullptr;
1872 basep->reterr = kPglRetEof;
1873 basep->errmsg = nullptr;
1874 if (basep->dst && (!basep->dst_owned_by_consumer)) {
1875 free(basep->dst);
1876 basep->dst = nullptr;
1877 }
1878 if (basep->ff) {
1879 if (basep->file_type != kFileUncompressed) {
1880 if (basep->file_type == kFileZstd) {
1881 if (txsp->rds.zst.ib.src) {
1882 free_const(txsp->rds.zst.ib.src);
1883 txsp->rds.zst.ib.src = nullptr;
1884 }
1885 if (txsp->rds.zst.ds) {
1886 ZSTD_freeDStream(txsp->rds.zst.ds);
1887 txsp->rds.zst.ds = nullptr;
1888 }
1889 } else if (basep->file_type == kFileBgzf) {
1890 CleanupBgzfRawMtStream(&txsp->rds.bgzf);
1891 } else {
1892 // plain gzip
1893 if (txsp->rds.gz.in) {
1894 free(txsp->rds.gz.in);
1895 txsp->rds.gz.in = nullptr;
1896 }
1897 if (txsp->rds.gz.ds_initialized) {
1898 inflateEnd(&txsp->rds.gz.ds);
1899 }
1900 }
1901 basep->file_type = kFileUncompressed;
1902 }
1903 if (unlikely(fclose_null(&basep->ff))) {
1904 if (!reterrp) {
1905 return 1;
1906 }
1907 if (*reterrp == kPglRetSuccess) {
1908 // Note that we don't set basep->reterr or ->errmsg here.
1909 *reterrp = kPglRetReadFail;
1910 return 1;
1911 }
1912 }
1913 }
1914 return 0;
1915 }
1916
1917
1918 PglErr TksNext(TokenStream* tksp, uint32_t shard_ct, char** shard_boundaries) {
1919 TextStreamMain* txsp = GetTxsp(&tksp->txs);
1920 txsp->base.consume_iter = txsp->base.consume_stop;
1921 PglErr reterr = TextAdvance(&(tksp->txs));
1922 if (reterr) { // not unlikely due to eof
1923 return reterr;
1924 }
1925 char* consume_iter = txsp->base.consume_iter;
1926 char* consume_stop = txsp->base.consume_stop;
1927 shard_boundaries[0] = consume_iter;
1928 shard_boundaries[shard_ct] = consume_stop;
1929 if (shard_ct > 1) {
1930 const uintptr_t shard_size_target = S_CAST(uintptr_t, consume_stop - consume_iter) / shard_ct;
1931 char* boundary_min = consume_iter;
1932 char* cur_boundary = consume_iter;
1933 for (uint32_t boundary_idx = 1; boundary_idx < shard_ct; ++boundary_idx) {
1934 boundary_min = &(boundary_min[shard_size_target]);
1935 if (boundary_min > cur_boundary) {
1936 // last character must be token separator
1937 cur_boundary = FirstSpaceOrEoln(boundary_min);
1938 ++cur_boundary;
1939 }
1940 shard_boundaries[boundary_idx] = cur_boundary;
1941 }
1942 }
1943 return kPglRetSuccess;
1944 }
1945
1946 #ifdef __cplusplus
1947 }
1948 #endif