Basic.xs

filter: Statementstmt 100% 81 / 81 Branchbran 89.2% 91 / 102 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 93.9% 172 / 183 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« blib/lib/Bioinf/Basic.pm ↑ Summary
1 /*FASTA reading and writing for Bioinf::Basic.
2  
3 fasta2hash() and hash2fasta_file() used to be pure perl in ~/Scripts/bioinf.pm:
4 one readline, chomp and string append per line in, and one substr-sized SV per
5 80-column line out. Here a file is read in large blocks and every line of a
6 record is appended straight onto that record's SV, so no per-line SV is ever
7 made, and each finished sequence is shrunk to its length, which is the RAM a
8 proteome or genome actually needs rather than whatever the last buffer growth
9 left. On the file described at FASTA_BLOCK below, bioinf.pm read it in 3.83 s
10 with a peak RSS of 1,098 MB, and this in 0.80 s and 967 MB, 900 MB of which is
11 the sequences themselves; writing it back took 44.44 s and takes 0.97 s, and
12 the two files are byte-identical. The perl side (lib/Bioinf/Basic.pm) opens and
13 closes the files.
14  
15 Every croak() and warn() here starts with C99's __func__, so a message names
16 the C function that raised it (read_fasta or write_fasta) and stays right if
17 one is renamed.*/
18 #define PERL_NO_GET_CONTEXT
19 #include "EXTERN.h"
20 #include "perl.h"
21 #include "XSUB.h"
22 #include <string.h>
23 /*`restrict` is spelled bare, which is C99 syntax.
24  
25 It is carried only by read_fasta()'s block buffer, which this file allocates
26 itself and reaches through nothing but that pointer and the ones derived from
27 it. Every other pointer here is perl's: an SV, AV or HV, or the PV inside one,
28 which the perl API may alias behind the code's back -- in write_fasta() a
29 defline and its sequence can be COW copies of the one buffer -- so the
30 qualifier would be a false promise. perl is built with -fno-strict-aliasing,
31 where `restrict` is the only disambiguation there is, but it earns nothing even
32 on the buffer: the loop over it stores only through memchr() and sv_catpvn(),
33 which are opaque calls the compiler must assume write anywhere. The generated
34 code for this file was byte-identical with and without it (gcc -O2 -std=gnu99,
35 2026-09-30), so the one annotation records the contract rather than buying
36 speed.
37  
38 Makefile.PL probes for a C99 flag but cannot always find one. MSVC accepts the
39 keyword only under /std:c11 or later and otherwise spells it __restrict, older
40 gcc spells it __restrict__, and a strict C89 compiler has no equivalent. Map it
41 where a spelling exists and define it away where none does -- the same block as
42 ~/Scripts/stats/LikeR.xs. It sits below every #include so that it cannot
43 rewrite a parameter named `restrict` inside a system header.*/
44 #if !defined(__cplusplus) && !defined(restrict)
45 # if defined(_MSC_VER)
46 # define restrict __restrict
47 # elif !defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L
48 # if defined(__GNUC__)
49 # define restrict __restrict__
50 # else
51 # define restrict /*no spelling available; annotation only*/
52 # endif
53 # endif
54 #endif
55 /*PerlIO_read() request size. Reading a 928 MB FASTA of 400,000 records in
56 60-column lines, on this machine on 2026-09-29, took 0.84 s with 16 KiB blocks,
57 0.80 s with 64 KiB, 0.81 s with 256 KiB and 0.82 s with 1 MiB (best of three
58 each, file in the page cache), so nothing is gained past 64 KiB. Build with
59 DEFINE=-DFASTA_BLOCK=<bytes> to try another.*/
60 #ifndef FASTA_BLOCK
61 #define FASTA_BLOCK 65536
62 #endif
63  
64 /*Drop a trailing '\r' left by a CRLF file. It is chopped when the line ends
65 rather than when it is read, because a block can end between the '\r' and
66 its '\n'.*/
67 10033 static void chop_cr(SV *sv) {
68 10033 ▶ if (SvCUR(sv) && SvPVX(sv)[SvCUR(sv) - 1] == '\r') SvCUR_set(sv, SvCUR(sv) - 1);
Branch: 2 branches
BranchTrueFalseTotal
if (SvCUR(sv) && SvPVX(sv)[SvCUR(sv) - 1] == '\r') SvCUR_set(sv, SvCUR(sv) - 1); 10026 7 10033
if (SvCUR(sv) && SvPVX(sv)[SvCUR(sv) - 1] == '\r') SvCUR_set(sv, SvCUR(sv) - 1); 11 10015 10026
69 10033 }
70  
71 /*Every record of fh as a hash of defline => sequence, or with key given only
72 that record's sequence (undef if it is absent), reading no further than the
73 defline after it. name is the file's name, for messages. order, when not NULL,
74 gets each defline in file order.
75  
76 A repeated defline is warned about and its sequences concatenated, which is
77 what bioinf.pm did: it is the file that is wrong, and nothing here can say
78 which of the two records was meant. With key given, only a repeat of key is
79 looked for. Finding the others would mean keeping every defline read on the way
80 to key: a hash of 400,000 keys, for one record of a proteome.*/
81 30 static SV *read_fasta(pTHX_ PerlIO *fh, SV *key, const char *name, AV *order) {
82 30 HV *out = (HV*)sv_2mortal((SV*)newHV());
83 30 SV *hdr = sv_2mortal(newSVpvs(""));
84 30 SV *seq = NULL; // record being filled; NULL before the first defline and while skipping
85 30 bool have_def = FALSE, in_hdr = FALSE, bol = TRUE, done = FALSE, fed = FALSE; // fed: the '\n' that ends an unterminated last line has been supplied
86 30 UV line = 0; // 1-based, as $. would count it
87 char *restrict buf;
88 30 Newx(buf, FASTA_BLOCK, char);
89 30 SAVEFREEPV(buf); // freed at the caller's LEAVE, croak or not
90 82 ▶ while (!done) {
Branch: 1 branch
BranchTrueFalseTotal
while (!done) { 78 4 82
91 78 SSize_t n = PerlIO_read(fh, buf, FASTA_BLOCK);
92 78 ▶ if (n < 0 || PerlIO_error(fh)) croak("%s: error reading %s: %s", __func__, name, Strerror(errno));
Branch: 2 branches
BranchTrueFalseTotal
if (n < 0 || PerlIO_error(fh)) croak("%s: error reading %s: %s", __func__, name, Strerror(errno)); 78 0 78
if (n < 0 || PerlIO_error(fh)) croak("%s: error reading %s: %s", __func__, name, Strerror(errno)); 0 78 78
93 78 ▶ if (n == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n == 0) { 29 49 78
94 29 ▶ if (bol || fed) break;
Branch: 2 branches
BranchTrueFalseTotal
if (bol || fed) break; 5 24 29
if (bol || fed) break; 5 0 5
95 5 buf[0] = '\n';
96 5 n = 1;
97 5 fed = TRUE;
98 }
99 54 const char *p = buf, *end = buf + n;
100 20088 ▶ while (p < end) {
Branch: 1 branch
BranchTrueFalseTotal
while (p < end) { 20065 23 20088
101 20065 ▶ if (bol) {
Branch: 1 branch
BranchTrueFalseTotal
if (bol) { 19975 90 20065
102 19975 line++;
103 19975 bol = FALSE;
104 19975 ▶ if (*p == '>') {
Branch: 1 branch
BranchTrueFalseTotal
if (*p == '>') { 65 19910 19975
105 65 in_hdr = TRUE;
106 65 SvCUR_set(hdr, 0);
107 65 p++;
108 65 continue;
109 }
110 }
111 20000 const char *nl = (const char*)memchr(p, '\n', (size_t)(end - p));
112 20000 ▶ const char *e = nl ? nl : end;
Branch: 1 branch
BranchTrueFalseTotal
const char *e = nl ? nl : end; 19975 25 20000
113 20000 ▶ if (in_hdr) sv_catpvn(hdr, p, (STRLEN)(e - p));
Branch: 1 branch
BranchTrueFalseTotal
if (in_hdr) sv_catpvn(hdr, p, (STRLEN)(e - p)); 67 19933 20000
114 19933 ▶ else if (seq) sv_catpvn(seq, p, (STRLEN)(e - p));
Branch: 1 branch
BranchTrueFalseTotal
else if (seq) sv_catpvn(seq, p, (STRLEN)(e - p)); 9980 9953 19933
115 9953 ▶ else if (!have_def && e > p && !(e - p == 1 && *p == '\r'))
Branch: 4 branches
BranchTrueFalseTotal
else if (!have_def && e > p && !(e - p == 1 && *p == '\r')) 3 9950 9953
else if (!have_def && e > p && !(e - p == 1 && *p == '\r')) 2 1 3
else if (!have_def && e > p && !(e - p == 1 && *p == '\r')) 1 1 2
else if (!have_def && e > p && !(e - p == 1 && *p == '\r')) 0 1 1
116 1 croak("%s: %s line %" UVuf " is sequence, but no defline (\">...\") has come before it", __func__, name, line);
117 19999 ▶ if (!nl) break;
Branch: 1 branch
BranchTrueFalseTotal
if (!nl) break; 25 19974 19999
118 19974 p = nl + 1;
119 19974 bol = TRUE;
120 19974 ▶ if (!in_hdr) {
Branch: 1 branch
BranchTrueFalseTotal
if (!in_hdr) { 19909 65 19974
121 19909 ▶ if (seq) chop_cr(seq);
Branch: 1 branch
BranchTrueFalseTotal
if (seq) chop_cr(seq); 9968 9941 19909
122 19909 continue;
123 }
124 65 in_hdr = FALSE;
125 65 chop_cr(hdr);
126 65 ▶ if (!SvCUR(hdr)) croak("%s: %s line %" UVuf " is a defline with no name", __func__, name, line);
Branch: 1 branch
BranchTrueFalseTotal
if (!SvCUR(hdr)) croak("%s: %s line %" UVuf " is a defline with no name", __func__, name, line); 1 64 65
127 64 ▶ if (seq) SvPV_shrink_to_cur(seq);
Branch: 4 branches
BranchTrueFalseTotal
if (seq) SvPV_shrink_to_cur(seq); 23 41 64
if (seq) SvPV_shrink_to_cur(seq); 1 22 23
if (seq) SvPV_shrink_to_cur(seq); 0 1 1
if (seq) SvPV_shrink_to_cur(seq); 0 23 23
128 64 ▶ bool is_key = key && sv_eq(hdr, key);
Branch: 2 branches
BranchTrueFalseTotal
bool is_key = key && sv_eq(hdr, key); 30 34 64
bool is_key = key && sv_eq(hdr, key); 9 21 30
129 64 ▶ if (key && !is_key && hv_exists_ent(out, key, 0)) {
Branch: 3 branches
BranchTrueFalseTotal
if (key && !is_key && hv_exists_ent(out, key, 0)) { 30 34 64
if (key && !is_key && hv_exists_ent(out, key, 0)) { 21 9 30
if (key && !is_key && hv_exists_ent(out, key, 0)) { 4 17 21
130 4 done = TRUE; // the wanted record is complete
131 4 break;
132 }
133 60 have_def = TRUE;
134 60 ▶ if (key && !is_key) {
Branch: 2 branches
BranchTrueFalseTotal
if (key && !is_key) { 26 34 60
if (key && !is_key) { 17 9 26
135 17 seq = NULL;
136 17 continue;
137 }
138 43 ▶ if (hv_exists_ent(out, hdr, 0))
Branch: 1 branch
BranchTrueFalseTotal
if (hv_exists_ent(out, hdr, 0)) 2 41 43
139 2 warn("%s: \"%s\" appears more than once in %s (line %" UVuf "); its sequences will be concatenated", __func__, SvPV_nolen(hdr), name, line);
140 41 ▶ else if (order) av_push(order, newSVsv(hdr));
Branch: 1 branch
BranchTrueFalseTotal
else if (order) av_push(order, newSVsv(hdr)); 0 41 41
141 43 seq = HeVAL(hv_fetch_ent(out, hdr, 1, 0));
142 43 ▶ if (!SvOK(seq)) sv_setpvs(seq, "");
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(seq)) sv_setpvs(seq, ""); 41 2 43
143 }
144 }
145 28 ▶ if (seq) SvPV_shrink_to_cur(seq);
Branch: 4 branches
BranchTrueFalseTotal
if (seq) SvPV_shrink_to_cur(seq); 23 5 28
if (seq) SvPV_shrink_to_cur(seq); 2 21 23
if (seq) SvPV_shrink_to_cur(seq); 0 2 2
if (seq) SvPV_shrink_to_cur(seq); 1 22 23
146 28 ▶ if (!key) return newRV_inc((SV*)out);
Branch: 1 branch
BranchTrueFalseTotal
if (!key) return newRV_inc((SV*)out); 16 12 28
147 12 HE *he = hv_fetch_ent(out, key, 0, 0);
148 12 ▶ return he ? SvREFCNT_inc_simple_NN(HeVAL(he)) : newSV(0); // not a copy: out is mortal, so this becomes the only reference
Branch: 1 branch
BranchTrueFalseTotal
return he ? SvREFCNT_inc_simple_NN(HeVAL(he)) : newSV(0); // not a copy: out is mortal, so this becomes the only reference 8 4 12
149 }
150  
151 /*Each key of h named in order, as ">key" and then its sequence broken into
152 lines of width characters; width 0 puts each sequence on one line.*/
153 9 static void write_fasta(pTHX_ PerlIO *fh, HV *h, AV *order, STRLEN width) {
154 23 ▶ for (SSize_t i = 0; i <= av_len(order); i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (SSize_t i = 0; i <= av_len(order); i++) { 16 7 23
155 16 SV **k = av_fetch(order, i, 0);
156 16 ▶ if (!k || !SvOK(*k)) croak("%s: element %" IVdf " of the order is undefined", __func__, (IV)i);
Branch: 2 branches
BranchTrueFalseTotal
if (!k || !SvOK(*k)) croak("%s: element %" IVdf " of the order is undefined", __func__, (IV)i); 16 0 16
if (!k || !SvOK(*k)) croak("%s: element %" IVdf " of the order is undefined", __func__, (IV)i); 1 15 16
157 15 HE *he = hv_fetch_ent(h, *k, 0, 0);
158 STRLEN kl, sl;
159 // kp and sp not restrict: a defline and its sequence may share one COW buffer
160 15 const char *kp = SvPV_const(*k, kl);
161 15 ▶ if (!he || !SvOK(HeVAL(he))) croak("%s: \"%s\" has no sequence in the hash", __func__, kp);
Branch: 2 branches
BranchTrueFalseTotal
if (!he || !SvOK(HeVAL(he))) croak("%s: \"%s\" has no sequence in the hash", __func__, kp); 14 1 15
if (!he || !SvOK(HeVAL(he))) croak("%s: \"%s\" has no sequence in the hash", __func__, kp); 0 14 14
162 14 const char *sp = SvPV_const(HeVAL(he), sl);
163 14 PerlIO_putc(fh, '>');
164 14 PerlIO_write(fh, kp, kl);
165 14 PerlIO_putc(fh, '\n');
166 14 ▶ STRLEN w = width ? width : sl;
Branch: 1 branch
BranchTrueFalseTotal
STRLEN w = width ? width : sl; 13 1 14
167 29 ▶ for (STRLEN o = 0; o < sl; o += w) {
Branch: 1 branch
BranchTrueFalseTotal
for (STRLEN o = 0; o < sl; o += w) { 15 14 29
168 15 PerlIO_write(fh, sp + o, sl - o < w ? sl - o : w);
169 15 PerlIO_putc(fh, '\n');
170 }
171 }
172 7 ▶ if (PerlIO_error(fh)) croak("%s: error writing FASTA: %s", __func__, Strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
if (PerlIO_error(fh)) croak("%s: error writing FASTA: %s", __func__, Strerror(errno)); 0 7 7
173 7 }
174  
175 MODULE = Bioinf::Basic PACKAGE = Bioinf::Basic
176 PROTOTYPES: DISABLE
177  
178 SV *
179 _read_fasta(fh, key, name, order = NULL)
180 PerlIO *fh
181 SV *key
182 const char *name
183 AV *order
184 CODE:
185 30 ▶ RETVAL = read_fasta(aTHX_ fh, SvOK(key) ? key : NULL, name, order);
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = read_fasta(aTHX_ fh, SvOK(key) ? key : NULL, name, order); 12 18 30
186 OUTPUT:
187 RETVAL
188  
189 void
190 _write_fasta(fh, h, order, width)
191 PerlIO *fh
192 HV *h
193 AV *order
194 UV width
195 CODE:
196 9 write_fasta(aTHX_ fh, h, order, (STRLEN)width);
« blib/lib/Bioinf/Basic.pm ↑ Summary