Debian Codegraph @

easel/esl_mem.c

raw symbols SCIP
1 /* str*()-like functions for raw char arrays (non-NUL-terminated strings).
2 *
3 * esl_mem.md has additional notes.
4 *
5 * Contents:
6 * 1. The esl_mem*() API.
7 * 2. Unit tests.
8 * 3. Test driver.
9 */
10 #include <esl_config.h>
11
12 #include <stdint.h>
13 #include <limits.h>
14 #include <string.h>
15 #include <ctype.h>
16
17 #include "easel.h"
18 #include "esl_mem.h"
19
20 /*****************************************************************
21 *# 1. The esl_mem*() API.
22 *****************************************************************/
23
24 /* Function: esl_mem_strtoi32()
25 * Synopsis: Convert a chunk of text memory to an int32_t.
26 *
27 * Purpose: Convert the text starting at <p> to an <int32_t>, converting
28 * no more than <n> characters (the valid length of non-<NUL>
29 * terminated memory buffer <p>). Interpret the text as
30 * base <base> (2 or 10, for example). <base> must be 2..36,
31 * or 0. 0 is treated specially as base 8, 10, or 16, autodetected
32 * according to the leading characters of the number format.
33 *
34 * Any leading whitespace is skipped. The next letter may
35 * be a '-' for a negative number. If <base> is 0 or 16,
36 * the next two characters may be "0x", in which case hex base
37 * 16 is assumed. Else if <base> is 0 and the next
38 * character is '0', octal base 8 is assumed. All subsequent
39 * characters are converted to a number, until an invalid
40 * character is reached. Upper or lower case letters are
41 * accepted, starting at A or a, for bases over 10. For
42 * example, In base 16, characters A-F or a-f are accepted.
43 * The base of the representation is limited to 36 because
44 * 'Z' or 'z' represents 35.
45 *
46 * The converted value is optionally returned in <*opt_val>.
47 * The number of characters parsed (up to the first invalid
48 * character, or <n>, whichever comes first) is optionally
49 * returned in <*opt_nc>. The caller can reposition a parser
50 * to <p + *opt_nc> to exactly skip past the parsed number.
51 *
52 * If no valid digit is found (including pathological cases
53 * of leader-only, such as "0x" or "-"), then return <eslEFORMAT>,
54 * and <*opt_nc> and <*opt_val> are both 0.
55 *
56 * This syntax is essentially identical to <strtol()>,
57 * except that we can operate on a non-NUL-terminated
58 * memory buffer of maximum length <n>, rather than on a
59 * NUL-terminated string.
60 *
61 * Args: p - pointer to text buffer to convert to int32_t
62 * n - maximum number of chars to parse in <p>: p[0..n-1] are valid.
63 * base - integer base. Often 10, 2, 8, or 16. Must be
64 * <2..36>, or 0. 0 means base 8, 10, or 16 depending on
65 * autodetected format.
66 * *opt_nc - optRETURN: number of valid chars parsed from p.
67 * First invalid char is p[*opt_nc].
68 * *opt_val - optRETURN: parsed value.
69 *
70 * Returns: <eslOK> on success.
71 *
72 * <eslEFORMAT> if no valid integer digits are found. Now
73 * <*opt_val> and <*opt_nc> are 0.
74 *
75 * <eslERANGE> on overflow or underflow error. Now
76 * <*opt_val> is <INT32_MAX> or <INT32_MIN> for an
77 * overflow or underflow, respectively. <*opt_nc> is
78 * set to the number of characters parsed INCLUDING
79 * the digit that caused the overflow. There might
80 * be even more digits following, so parsers need to
81 * be careful before blithely advancing by <nc>.
82 *
83 * Throws: <eslEINVAL> if <base> isn't in range <0..36>. Now
84 * <*opt_nc> and <*opt_val> are 0.
85 *
86 * Note: An example of why you need this instead of
87 * strtol(): suppose you've mmap()'ed a file to memory,
88 * and it ends in ... "12345". You can't strtol the
89 * end of the mmap'ed memory buffer because it is not
90 * a NUL-terminated string. (Same goes anywhere in the file,
91 * though elsewhere in the file you could overwrite
92 * a NUL where you need it. At EOF of an mmap'ed() buffer,
93 * you can't even do that.)
94 *
95 * sscanf() doesn't work either - I don't see a way to
96 * limit it to a buffer of at most <n> chars.
97 *
98 * I could copy <p> to a temporary allocated string that I
99 * NUL-terminate, then use strtol() or suchlike, but that's
100 * even more horrible than what I've done here (rewriting
101 * strtol()). Plus, here I get complete control of the
102 * integer type (<int32_t>) whereas strtol() gives me the
103 * less satisfying <long>.
104 *
105 * esl_mem_strtoi32(), _strtoi64(), and _strtoi() repeat
106 * near-identical code. If you change one, change them all.
107 *
108 * Stripped-down version of same code is used in
109 * esl_json_ReadInt().
110 */
111 int
112 esl_mem_strtoi32(char *p, esl_pos_t n, int base, int *opt_nc, int32_t *opt_val)
113 {
114 esl_pos_t i = 0;
115 int32_t sign = 1;
116 int32_t currval = 0;
117 int32_t digit = 0;
118 int ndigits = 0;
119
120 if (base < 0 || base == 1 || base > 36) ESL_EXCEPTION(eslEINVAL, "base must be 2..36 or 0");
121 while (i < n && isspace(p[i])) i++; /* skip leading whitespace */
122 if (i < n && p[i] == '-') { sign = -1; i++; }
123
124 if ((base == 0 || base == 16) && i < n-1 && p[i] == '0' && p[i+1] == 'x')
125 { i += 2; base = 16; }
126 else if (base == 0 && i < n && p[i] == '0')
127 { i += 1; base = 8; ndigits++; } // ndigits++ because "0" by itself is 0: weirdly, "0" is an octal literal.
128 else if (base == 0)
129 { base = 10; }
130
131 for (; i < n; i++, ndigits++)
132 {
133 if (isdigit(p[i])) digit = p[i] - '0';
134 else if (isupper(p[i])) digit = 10 + (p[i] - 'A');
135 else if (islower(p[i])) digit = 10 + (p[i] - 'a');
136 else break;
137 if (digit >= base) break;
138
139 if (sign == 1)
140 {
141 if (currval > (INT32_MAX - digit) / base)
142 {
143 if (opt_val) *opt_val = INT32_MAX;
144 if (opt_nc) *opt_nc = i+1;
145 return eslERANGE;
146 }
147 currval = currval * base + digit;
148 }
149 else
150 {
151 if (currval < (INT32_MIN + digit) / base)
152 {
153 if (opt_val) *opt_val = INT32_MIN;
154 if (opt_nc) *opt_nc = i+1;
155 return eslERANGE;
156 }
157 currval = currval * base - digit;
158 }
159 }
160
161 if (opt_nc) { *opt_nc = (ndigits ? i : 0); }
162 if (opt_val) { *opt_val = currval; }
163 return (ndigits ? eslOK : eslEFORMAT);
164 }
165
166
167 /* Function: esl_mem_strtoi64()
168 * Synopsis: Convert a chunk of memory to an int64_t.
169 * Incept: SRE, Thu 02 Aug 2018 [Slaid Cleaves, Drunken Barber's Hand]
170 *
171 * Purpose: Same as <esl_mem_strtoi32()> but converts to <int64_t>.
172 */
173 int
174 esl_mem_strtoi64(char *p, esl_pos_t n, int base, int *opt_nc, int64_t *opt_val)
175 {
176 esl_pos_t i = 0;
177 int64_t sign = 1;
178 int64_t currval = 0;
179 int64_t digit = 0;
180 int ndigits = 0;
181
182 if (base < 0 || base == 1 || base > 36) ESL_EXCEPTION(eslEINVAL, "base must be 2..36 or 0");
183 while (i < n && isspace(p[i])) i++; /* skip leading whitespace */
184 if (i < n && p[i] == '-') { sign = -1; i++; }
185
186 if ((base == 0 || base == 16) && i < n-1 && p[i] == '0' && p[i+1] == 'x')
187 { i += 2; base = 16; }
188 else if (base == 0 && i < n && p[i] == '0')
189 { i += 1; base = 8; ndigits++; }
190 else if (base == 0)
191 { base = 10; }
192
193 for (; i < n; i++, ndigits++)
194 {
195 if (isdigit(p[i])) digit = p[i] - '0';
196 else if (isupper(p[i])) digit = 10 + (p[i] - 'A');
197 else if (islower(p[i])) digit = 10 + (p[i] - 'a');
198 else break;
199 if (digit >= base) break;
200
201 if (sign == 1)
202 {
203 if (currval > (INT64_MAX - digit) / base)
204 {
205 if (opt_val) *opt_val = INT64_MAX;
206 if (opt_nc) *opt_nc = i+1;
207 return eslERANGE;
208 }
209 currval = currval * base + digit;
210 }
211 else
212 {
213 if (currval < (INT64_MIN + digit) / base)
214 {
215 if (opt_val) *opt_val = INT64_MIN;
216 if (opt_nc) *opt_nc = i+1;
217 return eslERANGE;
218 }
219 currval = currval * base - digit;
220 }
221 }
222 if (opt_nc) { *opt_nc = (ndigits ? i : 0); }
223 if (opt_val) { *opt_val = currval; }
224 return (ndigits ? eslOK : eslEFORMAT);
225 }
226
227 /* Function: esl_mem_strtoi()
228 * Synopsis: Convert a chunk of memory to an int.
229 * Incept: SRE, Thu 02 Aug 2018 [Slaid Cleaves, Junkyard]
230 *
231 * Purpose: Same as <esl_mem_strtoi32()> but converts to generic <int>.
232 */
233 int
234 esl_mem_strtoi(char *p, esl_pos_t n, int base, int *opt_nc, int *opt_val)
235 {
236 esl_pos_t i = 0;
237 int sign = 1;
238 int currval = 0;
239 int digit = 0;
240 int ndigits = 0;
241
242 if (base < 0 || base == 1 || base > 36) ESL_EXCEPTION(eslEINVAL, "base must be 2..36 or 0");
243 while (i < n && isspace(p[i])) i++; /* skip leading whitespace */
244 if (i < n && p[i] == '-') { sign = -1; i++; }
245
246 if ((base == 0 || base == 16) && i < n-1 && p[i] == '0' && p[i+1] == 'x')
247 { i += 2; base = 16; }
248 else if (base == 0 && i < n && p[i] == '0')
249 { i += 1; base = 8; ndigits++; }
250 else if (base == 0)
251 { base = 10; }
252
253 for (; i < n; i++, ndigits++)
254 {
255 if (isdigit(p[i])) digit = p[i] - '0';
256 else if (isupper(p[i])) digit = 10 + (p[i] - 'A');
257 else if (islower(p[i])) digit = 10 + (p[i] - 'a');
258 else break;
259 if (digit >= base) break;
260
261 if (sign == 1)
262 {
263 if (currval > (INT_MAX - digit) / base)
264 {
265 if (opt_val) *opt_val = INT_MAX;
266 if (opt_nc) *opt_nc = i+1;
267 return eslERANGE;
268 }
269 currval = currval * base + digit;
270 }
271 else
272 {
273 if (currval < (INT_MIN + digit) / base)
274 {
275 if (opt_val) *opt_val = INT_MIN;
276 if (opt_nc) *opt_nc = i+1;
277 return eslERANGE;
278 }
279 currval = currval * base - digit;
280 }
281 }
282 if (opt_nc) { *opt_nc = (ndigits ? i : 0); }
283 if (opt_val) { *opt_val = currval; }
284 return (ndigits ? eslOK : eslEFORMAT);
285 }
286
287
288 /* Function: esl_mem_strtof()
289 * Synopsis: Convert a chunk of memory to a float.
290 * Incept: SRE, Fri Jun 3 10:52:07 2016 [Hamilton]
291 *
292 * Purpose: Convert a prefix of the char array starting at <p> to a float, converting no
293 * more than <n> characters, i.e. the valid length of
294 * non-NUL terminated memory buffer <p>.
295 *
296 * The decimal string representation is parsed as:
297 * - leading whitespace is skipped
298 * - an optional sign for the significand, +/-
299 * - a significand: (at least one digit must be present)
300 * - an optional string of digits
301 * - an optional '.'
302 * - an optional string of digits
303 * - an optional 'e' or 'E', indicating an exponent:
304 * - an optional sign '+' or '-'
305 * - a string of digits
306 *
307 * Or, after whitespace and the optional sign, one of the
308 * following special strings (case-insensitive):
309 * "inf", "infinity", "nan"
310 *
311 * Parsing stops at the first character that isn't part of
312 * a decimal string representation. For example, given "
313 * 42.0xx", 5 characters are parsed (including the skipped
314 * leading whitespace, for a result of 42.0. A missing
315 * exponent, as in " 42.0e-" isn't an <eslEFORMAT> error,
316 * because it's also parsed as 5 chars to 42.0.
317 *
318 * The converted value is optionally returned in
319 * <*opt_val>, and the number of characters parsed (up to
320 * <n>) is optionally returned in <*opt_n>. The caller can
321 * reposition a parser to <p + *opt_nc> to exactly skip a
322 * parsed number.
323 *
324 * Only decimal representations are recognized. Compare to
325 * <strtof()>, which also allows hexadecimal representation
326 * (when the significand leads with 0x or 0X).
327 *
328 * If the representation overflows (e.g. "1e999") the
329 * result is +/-infinity. If it underflows (e.g. "1e-999")
330 * the result is 0. These conversions still return
331 * <eslOK>.
332 *
333 * This function incurs a small roundoff error, typically
334 * around +/-1 ulp. See notes in esl_mem.md for details.
335 * When an accuracy guarantee is more important than a
336 * ~three-fold speed difference, use <esl_memtof()>
337 * instead.
338 *
339 * Args: p - pointer to text buffer to convert
340 * n - max number of chars to convert in <p>: p[0..n-1] are valid
341 * *opt_nc - optRETURN: number of valid chars parsed from p
342 * *opt_val - optRETURN: parsed value
343 *
344 * Returns: <eslOK> on success.
345 *
346 * <eslEFORMAT> if no significand digits are found.
347 * Now <*opt_val> is set to 0 and <*opt_nc> is set to 0.
348 */
349 int
350 esl_mem_strtof(char *p, esl_pos_t n, int *opt_nc, float *opt_val)
351 {
352 float sign = 1.;
353 float val = 0.;
354 float frac = 0.1;
355 float exp = 0.;
356 float expsign = 1.;
357 int m = 0; // number of digits parsed in mantissa. We check that this is >0.
358 int e = 0;
359 esl_pos_t i = 0;
360 esl_pos_t i2;
361
362 while (i < n && isspace(p[i])) i++; // skip leading whitespace
363 if (i < n) {
364 if (p[i] == '-') { sign = -1.0; i++; }
365 else if (p[i] == '+') { sign = 1.0; i++; }
366 else sign = 1.0;
367 }
368
369 if ( esl_memstrpfx_case(p+i, n-i, "infinity") ) { val = eslINFINITY; i += strlen("infinity"); m = 1; } // check "infinity" first, before "inf"
370 else if ( esl_memstrpfx_case(p+i, n-i, "inf") ) { val = eslINFINITY; i += strlen("inf"); m = 1; }
371 else if ( esl_memstrpfx_case(p+i, n-i, "nan") ) { val = eslNaN; i += strlen("nan"); m = 1; }
372 else
373 {
374 while (i < n && isdigit(p[i]))
375 {
376 val = 10. * val + (p[i]-'0');
377 m++;
378 i++;
379 }
380
381 if (i < n && p[i] == '.')
382 {
383 i++;
384 while (i < n && isdigit(p[i]))
385 {
386 val += (p[i]-'0') * frac;
387 frac *= 0.1; // roundoff error here, sigh.
388 m++;
389 i++;
390 }
391 }
392
393 i2 = i; // remember where i was as we look at [eE]?[+-]?; we need to see exponent digits before we decide that we're eating these letters
394 if (i < n && (p[i] == 'e' || p[i] == 'E'))
395 {
396 i++;
397 if (i < n) {
398 if (p[i] == '-') { expsign = -1.; i++; }
399 else if (p[i] == '+') { expsign = 1.; i++; }
400 else { expsign = 1.; }
401
402 while (i < n && isdigit(p[i]))
403 {
404 exp = 10.*exp + (p[i]-'0');
405 i++;
406 e++;
407 }
408 }
409 if (e == 0) i = i2; // no exponent digits after that [eE]? then roll i back, it was really an [eE]. (Do not attempt to parse anything after this reset, you're done)
410 }
411 }
412
413 if (m == 0)
414 {
415 if (opt_val) *opt_val = 0.;
416 if (opt_nc) *opt_nc = 0;
417 return eslEFORMAT;
418 }
419 else
420 {
421 if (opt_val) *opt_val = sign * val * powf(10.,expsign*exp);
422 if (opt_nc) *opt_nc = i;
423 return eslOK;
424 }
425 }
426
427
428
429
430 /* Function: esl_memnewline()
431 * Synopsis: Find next newline in memory.
432 *
433 * Purpose: Given a memory buffer <*m> of <n> bytes, delimit a
434 * next line by finding the next newline character(s).
435 * Store the number of bytes in the line (exclusive of
436 * the newline character(s)) in <*ret_nline>. Store
437 * the number of bytes in the newline in <*ret_nterm>.
438 *
439 * If no newline is found, <nline=n> and <nterm=0>, and the
440 * return status is <eslEOD>.
441 *
442 * Currently we assume newlines are either UNIX-style \verb+\n+
443 * or Windows-style \verb+\r\n+, in this implementation.
444 *
445 * Caller should not rely on this, though. Caller may only
446 * assume that a newline is an arbitrary one- or two-byte
447 * code.
448 *
449 * For example, if <*m> = \verb+"line one\r\nline two"+, <nline>
450 * is 8 and <nterm> is 2. If <*m> = \verb+"try two\ntry three"+,
451 * <nline> is 7 and <nterm> is 1. If <*m> = "attempt
452 * four", <nline> is 12 and <nterm> is 0.
453 *
454 * In cases where the caller may have an incompletely read
455 * buffer, it should be careful of cases where one possible
456 * newline may be a prefix of another; for example, suppose
457 * a file has \verb+"line one\r\nline two"+, but we only input the
458 * buffer \verb+"line one\r"+ at first. The \verb+"\r"+ looks like an old
459 * MacOS newline. Now we read more input, and we think the
460 * buffer is \verb+"\nline two"+. Now we think the \verb+"\n"+ is a UNIX
461 * newline. The result is that we read two newlines where
462 * there's only one. Instead, caller should check for the
463 * case of nterm==1 at the end of its buffer, and try to
464 * extend the buffer. See <esl_buffer_GetLine()> for an
465 * example.
466 *
467 * Args: m - ptr to memory buffer
468 * n - length of p in bytes
469 * *ret_nline - length of line found starting at p[0], exclusive of newline; up to n
470 * *ret_nterm - # of bytes in newline code: 1 or 2, or 0 if no newline found
471 *
472 * Returns: <eslOK> on success. Now <*ret_nline> is the number of
473 * bytes in the next line (exclusive of newline) and
474 * <*ret_nterm> is the number of bytes in the newline code
475 * (1 or 2). Thus the next line is <m[0..nline-1]>, and
476 * the line after this starts at <m[nline+nterm]>.
477 *
478 * <eslEOD> if no newline is found. Now <*ret_nline> is <n>,
479 * and <*ret_nterm> is 0.
480 *
481 * Xref: http://en.wikipedia.org/wiki/Newline
482 */
483 int
484 esl_memnewline(const char *m, esl_pos_t n, esl_pos_t *ret_nline, int *ret_nterm)
485 {
486 char *ptr = memchr(m, '\n', n);
487 if (ptr == NULL) { *ret_nline = n; *ret_nterm = 0; }
488 else if (ptr > m && *(ptr-1) == '\r') { *ret_nline = ptr-m-1; *ret_nterm = 2; }
489 else { *ret_nline = ptr-m; *ret_nterm = 1; }
490 return eslOK;
491 }
492
493 /* Function: esl_memtok()
494 * Synopsis: Get next delimited token from a line.
495 *
496 * Purpose: Given references to a line and its length, <*p> and <*n>,
497 * find the next token delimited by any of the characters
498 * in the string <delim>. Set <*ret_tok> to point at the
499 * start of the token, and <*ret_toklen> to its length.
500 * Increment <*p> to point to the next non-delim character
501 * that follows, and decrement <*n> by the same,
502 * so that <*p> and <*n> are ready for another
503 * call to <esl_memtok()>.
504 *
505 * Three differences between <esl_strtok()> and <esl_memtok()>:
506 * first, <esl_strtok()> expects a NUL-terminated string,
507 * whereas <esl_memtok()>'s line does not need to be
508 * NUL-terminated; second, <esl_memtok()> does not modify
509 * the string, whereas <esl_strtok()> writes NUL bytes
510 * to delimit tokens; third, <esl_memtok()> skips trailing
511 * <delim> characters as well as leading ones.
512 *
513 * Args: *p - pointer to line;
514 * will be incremented to next byte after token.
515 * *n - pointer to line length, in bytes;
516 * will be decremented
517 * delim - delimiter chars (example: " \t\r\n")
518 * *ret_tok - RETURN: ptr to token found in <*p>
519 * *ret_toklen - RETURN: length of token
520 *
521 * Returns: <eslOK> if a delimited token is found.
522 * <eslEOL> if not; now <*ret_tok> is <NULL> and <*ret_toklen> is <0>.
523 *
524 */
525 int
526 esl_memtok(char **p, esl_pos_t *n, const char *delim, char **ret_tok, esl_pos_t *ret_toklen)
527 {
528 char *s = *p;
529 esl_pos_t so, xo, eo;
530
531 for (so = 0; so < *n; so++) if (strchr(delim, s[so]) == NULL) break;
532 for (xo = so; xo < *n; xo++) if (strchr(delim, s[xo]) != NULL) break;
533 for (eo = xo; eo < *n; eo++) if (strchr(delim, s[eo]) == NULL) break;
534
535 if (so == *n) { *ret_tok = NULL; *ret_toklen = 0; return eslEOL; }
536 else { *p += eo; *n -= eo; *ret_tok = s + so; *ret_toklen = xo - so; return eslOK; }
537 }
538
539
540 /* Function: esl_memspn()
541 * Synopsis: Finds length of prefix consisting only of given chars
542 *
543 * Purpose: For line <p> of length <n>, return the length of
544 * a prefix that consists only of characters in the
545 * string <allow>.
546 *
547 * A commonly used idiom for "buffer is all whitespace"
548 * is <esl_memspn(p, n, " \t\r\n") == n>.
549 */
550 esl_pos_t
551 esl_memspn(char *p, esl_pos_t n, const char *allow)
552 {
553 esl_pos_t so;
554 for (so = 0; so < n; so++) if (strchr(allow, p[so]) == NULL) break;
555 return so;
556 }
557
558 /* Function: esl_memcspn()
559 * Synopsis: Finds length of prefix consisting of anything other than given chars
560 *
561 * Purpose: For line <p> of length <n>, return the length of
562 * a prefix that consists only of characters NOT in the
563 * string <disallow>.
564 */
565 esl_pos_t
566 esl_memcspn(char *p, esl_pos_t n, const char *disallow)
567 {
568 esl_pos_t so;
569 for (so = 0; so < n; so++) if (strchr(disallow, p[so]) != NULL) break;
570 return so;
571 }
572
573 /* Function: esl_memstrcmp()
574 * Synopsis: Compare a memory line and string for equality.
575 *
576 * Purpose: Compare line <p> of length <n> to a NUL-terminated
577 * string <s>, and return TRUE if they are exactly
578 * equal: <strlen(s) == n> and <p[0..n-1] == s[0..n-1]>.
579 * Else, return FALSE.
580 */
581 int
582 esl_memstrcmp(const char *p, esl_pos_t n, const char *s)
583 {
584 esl_pos_t pos;
585
586 if (p == NULL && n == 0 && (s == NULL || s[0] == '\0')) return TRUE;
587 if (!p || !s) return FALSE;
588
589 for (pos = 0; pos < n && s[pos] != '\0'; pos++)
590 if (p[pos] != s[pos]) return FALSE;
591 if (pos != n) return FALSE;
592 if (s[pos] != '\0') return FALSE;
593 return TRUE;
594 }
595
596
597 /* Function: esl_memstrcmp_case()
598 * Synopsis: Compare memory chunk and string for equality, case-insensitive
599 * Incept: SRE, Thu 02 Aug 2018 [Gurf Morlix, One More Second]
600 *
601 * Purpose: Compare line <p> of length <n> to a NUL-terminated string
602 * <s>, case-insensitively, and return TRUE if they are
603 * exactly equal: <strlen(s) == n> and <p[0..n-1] ==
604 * s[0..n-1]>. Else, return FALSE.
605 *
606 * Note: Return convention differs from strcmp(), which may be confusing.
607 * strcmp()'s convention of -1/0/+1 return is convenient for use
608 * in sorting, and we should probably sync to that.
609 */
610 int
611 esl_memstrcmp_case(const char *p, esl_pos_t n, const char *s)
612 {
613 esl_pos_t pos;
614
615 if (p == NULL && n == 0 && (s == NULL || s[0] == '\0')) return TRUE;
616 if (!p || !s) return FALSE;
617 for (pos = 0; pos < n && s[pos] != '\0'; pos++)
618 if (toupper(p[pos]) != toupper(s[pos])) return FALSE;
619 if (pos != n) return FALSE;
620 if (s[pos] != '\0') return FALSE;
621 return TRUE;
622 }
623
624
625 /* Function: esl_memstrpfx()
626 * Synopsis: Return TRUE if memory line starts with string.
627 *
628 * Purpose: Compare line <p> of length <n> to a NUL-terminated
629 * string <s>. Return TRUE if the prefix of <p> exactly
630 * matches <s> up to its NUL sentinel byte. Else,
631 * return FALSE.
632 *
633 * Case-sensitive. For case-insensitive matching, see
634 * <esl_memstrpfx_case()>.
635 */
636 int
637 esl_memstrpfx(const char *p, esl_pos_t n, const char *s)
638 {
639 esl_pos_t pos;
640
641 if (!p || !s) return FALSE;
642
643 for (pos = 0; pos < n && s[pos] != '\0'; pos++)
644 if (p[pos] != s[pos]) return FALSE;
645 if (s[pos] != '\0') return FALSE;
646 return TRUE;
647 }
648
649
650
651 /* Function: esl_memstrpfx_case()
652 * Synopsis: Return TRUE if memory line starts with string (case-insensitive)
653 * Incept: SRE, Fri Jun 3 11:54:47 2016 [Hamilton]
654 *
655 * Purpose: Same as <esl_memstrpfx()> but case-insensitive.
656 */
657 int
658 esl_memstrpfx_case(const char *p, esl_pos_t n, const char *s)
659 {
660 esl_pos_t pos;
661 if (!p || !s) return FALSE;
662
663 for (pos = 0; pos < n && s[pos] != '\0'; pos++)
664 if (toupper(p[pos]) != toupper(s[pos])) return FALSE;
665 if (s[pos] != '\0') return FALSE;
666 return TRUE;
667 }
668
669
670
671
672 /* Function: esl_memstrcontains()
673 * Synopsis: Return TRUE if memory line matches a string.
674 *
675 * Purpose: Compare line <p> of length <n> to NUL-terminated
676 * string <s>. Return <TRUE> if <p> contains an exact
677 * match to <s> at any position.
678 */
679 int
680 esl_memstrcontains(const char *p, esl_pos_t n, const char *s)
681 {
682 esl_pos_t s0, pos;
683
684 if (! p || ! s) return FALSE;
685 for (s0 = 0; s0 < n; s0++)
686 {
687 for (pos = 0; s0+pos < n && s[pos] != '\0'; pos++)
688 if (p[s0+pos] != s[pos]) break;
689 if (s[pos] == '\0') return TRUE;
690 }
691 return FALSE;
692 }
693
694 /* Function: esl_memstrdup()
695 * Synopsis: Duplicate a memory line as a NUL-terminated string.
696 *
697 * Purpose: Given memory line <p> of length <n>, duplicate it
698 * as a NUL-terminated string; return the new string
699 * in <*ret_s>.
700 *
701 * Returns: <eslOK> on success.
702 *
703 * Throws: <eslEMEM> on allocation failure; now <*ret_s> is <NULL>.
704 */
705 int
706 esl_memstrdup(const char *p, esl_pos_t n, char **ret_s)
707 {
708 char *s = NULL;
709 int status;
710
711 if (! p) { *ret_s = NULL; return eslOK; }
712
713 ESL_ALLOC(s, sizeof(char) * (n+1));
714 memcpy(s, p, n);
715 s[n] = '\0';
716 *ret_s = s;
717 return eslOK;
718
719 ERROR:
720 *ret_s = NULL;
721 return status;
722 }
723
724 /* Function: esl_memstrcpy()
725 * Synopsis: Copy a memory line as a string.
726 *
727 * Purpose: Given memory line <p> of length <n>, copy
728 * it to <dest> and NUL-terminate it. Caller must
729 * be sure that <dest> is already allocated for
730 * at least <n+1> bytes.
731 *
732 * Returns: <eslOK> on success.
733 */
734 int
735 esl_memstrcpy(const char *p, esl_pos_t n, char *dest)
736 {
737 memcpy(dest, p, n);
738 dest[n] = '\0';
739 return eslOK;
740 }
741
742
743
744 /* Function: esl_memtod()
745 * Synopsis: esl_mem equivalent to strtod().
746 *
747 * Purpose: Given a buffer <p> of length <n>, convert it to a
748 * double-precision floating point value, just as
749 * <strtod()> would do for a NUL-terminated string.
750 *
751 * Returns: <eslOK> on success, and <*ret_val> contains the
752 * converted value.
753 *
754 * Throws: <eslEMEM> on allocation error, and <*ret_val> is 0.
755 */
756 int
757 esl_memtod(const char *p, esl_pos_t n, double *ret_val)
758 {
759 char fixedbuf[128];
760 char *bigbuf = NULL;
761 int status;
762
763 if (n < 128)
764 {
765 memcpy(fixedbuf, p, sizeof(char) * n);
766 fixedbuf[n] = '\0';
767 *ret_val = strtod(fixedbuf, NULL);
768 return eslOK;
769 }
770 else
771 {
772 ESL_ALLOC(bigbuf, sizeof(char) * (n+1));
773 memcpy(bigbuf, p, sizeof(char) * n);
774 bigbuf[n] = '\0';
775 *ret_val = strtod(bigbuf, NULL);
776 free(bigbuf);
777 return eslOK;
778 }
779
780 ERROR:
781 *ret_val = 0.;
782 return status;
783 }
784
785 /* Function: esl_memtof()
786 * Synopsis: esl_mem equivalent to strtod(), for a float
787 *
788 * Purpose: Given a buffer <p> of length <n>, convert it to a
789 * single-precision floating point value, just as
790 * <strtod()> would do for a NUL-terminated string.
791 *
792 * Returns: <eslOK> on success, and <*ret_val> contains the
793 * converted value.
794 *
795 * Throws: <eslEMEM> on allocation error, and <*ret_val> is 0.
796 */
797 int
798 esl_memtof(const char *p, esl_pos_t n, float *ret_val)
799 {
800 char fixedbuf[128];
801 char *bigbuf = NULL;
802 int status;
803
804 if (n < 128)
805 {
806 memcpy(fixedbuf, p, sizeof(char) * n);
807 fixedbuf[n] = '\0';
808 *ret_val = (float) strtod(fixedbuf, NULL);
809 return eslOK;
810 }
811 else
812 {
813 ESL_ALLOC(bigbuf, sizeof(char) * (n+1));
814 memcpy(bigbuf, p, sizeof(char) * n);
815 bigbuf[n] = '\0';
816 *ret_val = (float) strtod(bigbuf, NULL);
817 free(bigbuf);
818 return eslOK;
819 }
820
821 ERROR:
822 *ret_val = 0.;
823 return status;
824 }
825
826
827 /* Function: esl_mem_IsReal()
828 * Synopsis: Return TRUE if <p> is a real number; else FALSE.
829 *
830 * Purpose: If the memory <p> of <n> bytes is convertible
831 * to a floating point real number by the rules of
832 * atof(), return TRUE; else return FALSE.
833 *
834 * Xref: easel.c::esl_str_IsReal() for string version.
835 */
836 int
837 esl_mem_IsReal(const char *p, esl_pos_t n)
838 {
839 int gotdecimal = 0;
840 int gotexp = 0;
841 int gotreal = 0;
842
843 if (!p || !n) return FALSE;
844
845 while (n && isspace((int) *p)) { p++; n--; } /* skip leading whitespace */
846 if (n && (*p == '-' || *p == '+')) { p++; n--; } /* skip leading sign */
847
848 /* Examine remainder for garbage. Allowed one '.' and
849 * one 'e' or 'E'; if both '.' and e/E occur, '.'
850 * must be first.
851 */
852 while (n)
853 {
854 if (isdigit((int) (*p))) gotreal++;
855 else if (*p == '.')
856 {
857 if (gotdecimal) return FALSE; /* can't have two */
858 if (gotexp) return FALSE; /* e/E preceded . */
859 else gotdecimal++;
860 }
861 else if (*p == 'e' || *p == 'E')
862 {
863 if (gotexp) return FALSE; /* can't have two */
864 else gotexp++;
865 }
866 else if (isspace((int) (*p))) break;
867 p++;
868 n--;
869 }
870 while (n && isspace((int) *p)) { p++; n--; } /* skip trailing whitespace */
871
872 return ( (n == 0 && gotreal) ? TRUE : FALSE);
873 }
874
875 /*----------------- end, esl_mem*() API ------------------------*/
876
877
878 /*****************************************************************
879 * 2. Benchmark driver.
880 *****************************************************************/
881 #ifdef eslMEM_BENCHMARK
882 #include <esl_config.h>
883
884 #include <stdio.h>
885
886 #include "easel.h"
887 #include "esl_buffer.h"
888 #include "esl_getopts.h"
889 #include "esl_stopwatch.h"
890
891 static ESL_OPTIONS options[] = {
892 /* name type default env range togs reqs incomp help docgrp */
893 {"-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show help and usage", 0},
894 { 0,0,0,0,0,0,0,0,0,0},
895 };
896 static char usage[] = "[-options] <infile>";
897 static char banner[] = "benchmark driver for mem module";
898
899 int
900 main(int argc, char **argv)
901 {
902 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 1, argc, argv, banner, usage);
903 ESL_STOPWATCH *w = esl_stopwatch_Create();
904 char *infile = esl_opt_GetArg(go, 1);
905 ESL_BUFFER *bf = NULL;
906 int64_t nlines = 0;
907 int64_t ntokens = 0;
908 int64_t nchar = 0;
909 char *p, *tok;
910 esl_pos_t n, toklen;
911 int status;
912
913 esl_stopwatch_Start(w);
914
915 if ( esl_buffer_Open(infile, NULL, &bf) != eslOK) esl_fatal("open failed");
916 while ( (status = esl_buffer_GetLine(bf, &p, &n)) == eslOK)
917 {
918 nlines++;
919 while ( (status = esl_memtok(&p, &n, " \t", &tok, &toklen)) == eslOK)
920 {
921 ntokens++;
922 nchar += toklen;
923 }
924 if (status != eslEOL) esl_fatal("memtok failure");
925 }
926 if (status != eslEOF) esl_fatal("GetLine failure");
927
928 esl_stopwatch_Stop(w);
929 esl_stopwatch_Display(stdout, w, NULL);
930 printf("lines = %" PRId64 "\n", nlines);
931 printf("tokens = %" PRId64 "\n", ntokens);
932 printf("chars = %" PRId64 "\n", nchar);
933
934 esl_buffer_Close(bf);
935 esl_stopwatch_Destroy(w);
936 esl_getopts_Destroy(go);
937 return 0;
938 }
939 #endif /*eslMEM_BENCHMARK*/
940 /*---------------- end, benchmark driver ------------------------*/
941
942 /*****************************************************************
943 * 2. Unit tests
944 *****************************************************************/
945 #ifdef eslMEM_TESTDRIVE
946
947 #include "esl_random.h"
948
949 static void
950 utest_mem_strtoi32(void)
951 {
952 char msg[] = "esl_mem_strtoi32() unit test failed";
953 int nc;
954 int32_t val;
955 int status;
956
957 if ( (status = esl_mem_strtoi32("-1234", 5, 10, &nc, &val)) != eslOK || nc != 5 || val != -1234) esl_fatal(msg);
958 if ( (status = esl_mem_strtoi32("\t -1234", 8, 10, &nc, &val)) != eslOK || nc != 8 || val != -1234) esl_fatal(msg); // leading whitespace is skipped
959 if ( (status = esl_mem_strtoi32("1234", 4, 0, &nc, &val)) != eslOK || nc != 4 || val != 1234) esl_fatal(msg);
960 if ( (status = esl_mem_strtoi32("12345", 4, 0, &nc, &val)) != eslOK || nc != 4 || val != 1234) esl_fatal(msg); // n=4 is respected
961 if ( (status = esl_mem_strtoi32(" 0xff", 5, 0, &nc, &val)) != eslOK || nc != 5 || val != 255) esl_fatal(msg); // leading 0x is detected as hexadecimal
962 if ( (status = esl_mem_strtoi32(" 0777", 4, 0, &nc, &val)) != eslOK || nc != 4 || val != 63) esl_fatal(msg); // leading 0 is detected as octal
963 if ( (status = esl_mem_strtoi32("FFGG", 4, 16, &nc, &val)) != eslOK || nc != 2 || val != 255) esl_fatal(msg); // parse stops at trailing non-integer chars
964 if ( (status = esl_mem_strtoi32("0xffff", 6, 0, &nc, &val)) != eslOK || nc != 6 || val != 65535) esl_fatal(msg);
965 if ( (status = esl_mem_strtoi32("0xffffff", 8, 0, &nc, &val)) != eslOK || nc != 8 || val != 16777215) esl_fatal(msg);
966 if ( (status = esl_mem_strtoi32(" 2147483647", 11, 0, &nc, &val)) != eslOK || nc != 11 || val != INT32_MAX) esl_fatal(msg); // largest valid int32
967 if ( (status = esl_mem_strtoi32("-2147483648", 11, 0, &nc, &val)) != eslOK || nc != 11 || val != INT32_MIN) esl_fatal(msg); // smallest valid int32
968 if ( (status = esl_mem_strtoi32(" 2147483648", 11, 0, &nc, &val)) != eslERANGE || nc != 11 || val != INT32_MAX) esl_fatal(msg); // overflow
969 if ( (status = esl_mem_strtoi32("-2147483649", 11, 0, &nc, &val)) != eslERANGE || nc != 11 || val != INT32_MIN) esl_fatal(msg); // underflow
970 if ( (status = esl_mem_strtoi32(" 214748364800", 13, 0, &nc, &val)) != eslERANGE || nc != 11 || val != INT32_MAX) esl_fatal(msg); // <nc> is for the digit that overflowed
971 if ( (status = esl_mem_strtoi32("-214748364900", 13, 0, &nc, &val)) != eslERANGE || nc != 11 || val != INT32_MIN) esl_fatal(msg); // ... or underflowed
972 if ( (status = esl_mem_strtoi32(" 0x1234", 3, 16, &nc, &val)) != eslEFORMAT || nc != 0 || val != 0) esl_fatal(msg); // leading bare "0x" is an error
973 if ( (status = esl_mem_strtoi32("0XX", 3, 0, &nc, &val)) != eslOK || nc != 1 || val != 0) esl_fatal(msg); // but a leading 0 is 0 (!)
974 }
975
976 static void
977 utest_mem_strtoi64(void)
978 {
979 char msg[] = "esl_mem_strtoi64() unit test failed";
980 int nc;
981 int64_t val;
982 int status;
983
984 if ( (status = esl_mem_strtoi64("-1234", 5, 10, &nc, &val)) != eslOK || nc != 5 || val != -1234) esl_fatal(msg);
985 if ( (status = esl_mem_strtoi64("\t -1234", 8, 10, &nc, &val)) != eslOK || nc != 8 || val != -1234) esl_fatal(msg);
986 if ( (status = esl_mem_strtoi64("1234", 4, 0, &nc, &val)) != eslOK || nc != 4 || val != 1234) esl_fatal(msg);
987 if ( (status = esl_mem_strtoi64("12345", 4, 0, &nc, &val)) != eslOK || nc != 4 || val != 1234) esl_fatal(msg);
988 if ( (status = esl_mem_strtoi64(" 0xff", 5, 0, &nc, &val)) != eslOK || nc != 5 || val != 255) esl_fatal(msg);
989 if ( (status = esl_mem_strtoi64(" 0777", 4, 0, &nc, &val)) != eslOK || nc != 4 || val != 63) esl_fatal(msg);
990 if ( (status = esl_mem_strtoi64("FFGG", 4, 16, &nc, &val)) != eslOK || nc != 2 || val != 255) esl_fatal(msg);
991 if ( (status = esl_mem_strtoi64("0xffff", 6, 0, &nc, &val)) != eslOK || nc != 6 || val != 65535) esl_fatal(msg);
992 if ( (status = esl_mem_strtoi64("0xffffff", 8, 0, &nc, &val)) != eslOK || nc != 8 || val != 16777215) esl_fatal(msg);
993 if ( (status = esl_mem_strtoi64(" 9223372036854775807", 20, 0, &nc, &val)) != eslOK || nc != 20 || val != INT64_MAX) esl_fatal(msg);
994 if ( (status = esl_mem_strtoi64("-9223372036854775808", 20, 0, &nc, &val)) != eslOK || nc != 20 || val != INT64_MIN) esl_fatal(msg);
995 if ( (status = esl_mem_strtoi64(" 9223372036854775808", 20, 0, &nc, &val)) != eslERANGE || nc != 20 || val != INT64_MAX) esl_fatal(msg);
996 if ( (status = esl_mem_strtoi64("-9223372036854775809", 20, 0, &nc, &val)) != eslERANGE || nc != 20 || val != INT64_MIN) esl_fatal(msg);
997 if ( (status = esl_mem_strtoi64(" 922337203685477580800", 22, 0, &nc, &val)) != eslERANGE || nc != 20 || val != INT64_MAX) esl_fatal(msg);
998 if ( (status = esl_mem_strtoi64("-922337203685477580900", 22, 0, &nc, &val)) != eslERANGE || nc != 20 || val != INT64_MIN) esl_fatal(msg);
999 if ( (status = esl_mem_strtoi64(" 0x1234", 3, 16, &nc, &val)) != eslEFORMAT || nc != 0 || val != 0) esl_fatal(msg);
1000 if ( (status = esl_mem_strtoi64("0XX", 3, 0, &nc, &val)) != eslOK || nc != 1 || val != 0) esl_fatal(msg);
1001 }
1002
1003
1004 static void
1005 utest_mem_strtoi(void)
1006 {
1007 char msg[] = "esl_mem_strtoi64() unit test failed";
1008 int nc;
1009 int val;
1010 int status;
1011
1012 if ( (status = esl_mem_strtoi("-1234", 5, 10, &nc, &val)) != eslOK || nc != 5 || val != -1234) esl_fatal(msg);
1013 if ( (status = esl_mem_strtoi("\t -1234", 8, 10, &nc, &val)) != eslOK || nc != 8 || val != -1234) esl_fatal(msg);
1014 if ( (status = esl_mem_strtoi("1234", 4, 0, &nc, &val)) != eslOK || nc != 4 || val != 1234) esl_fatal(msg);
1015 if ( (status = esl_mem_strtoi("12345", 4, 0, &nc, &val)) != eslOK || nc != 4 || val != 1234) esl_fatal(msg);
1016 if ( (status = esl_mem_strtoi(" 0xff", 5, 0, &nc, &val)) != eslOK || nc != 5 || val != 255) esl_fatal(msg);
1017 if ( (status = esl_mem_strtoi(" 0777", 4, 0, &nc, &val)) != eslOK || nc != 4 || val != 63) esl_fatal(msg);
1018 if ( (status = esl_mem_strtoi("FFGG", 4, 16, &nc, &val)) != eslOK || nc != 2 || val != 255) esl_fatal(msg);
1019 if ( (status = esl_mem_strtoi("0xffff", 6, 0, &nc, &val)) != eslOK || nc != 6 || val != 65535) esl_fatal(msg);
1020 if ( (status = esl_mem_strtoi("0xffffff", 8, 0, &nc, &val)) != eslOK || nc != 8 || val != 16777215) esl_fatal(msg);
1021 if (sizeof(int) == 4) {
1022 if ( (status = esl_mem_strtoi(" 2147483647", 11, 0, &nc, &val)) != eslOK || nc != 11 || val != INT32_MAX) esl_fatal(msg); // largest valid int32
1023 if ( (status = esl_mem_strtoi("-2147483648", 11, 0, &nc, &val)) != eslOK || nc != 11 || val != INT32_MIN) esl_fatal(msg); // smallest valid int32
1024 if ( (status = esl_mem_strtoi(" 2147483648", 11, 0, &nc, &val)) != eslERANGE || nc != 11 || val != INT32_MAX) esl_fatal(msg); // overflow
1025 if ( (status = esl_mem_strtoi("-2147483649", 11, 0, &nc, &val)) != eslERANGE || nc != 11 || val != INT32_MIN) esl_fatal(msg); // underflow
1026 if ( (status = esl_mem_strtoi(" 214748364800", 13, 0, &nc, &val)) != eslERANGE || nc != 11 || val != INT32_MAX) esl_fatal(msg); // <nc> is for the digit that overflowed
1027 if ( (status = esl_mem_strtoi("-214748364900", 13, 0, &nc, &val)) != eslERANGE || nc != 11 || val != INT32_MIN) esl_fatal(msg); // ... or underflowed
1028 } else if (sizeof(int) == 8) {
1029 if ( (status = esl_mem_strtoi(" 9223372036854775807", 20, 0, &nc, &val)) != eslOK || nc != 20 || val != INT64_MAX) esl_fatal(msg);
1030 if ( (status = esl_mem_strtoi("-9223372036854775808", 20, 0, &nc, &val)) != eslOK || nc != 20 || val != INT64_MIN) esl_fatal(msg);
1031 if ( (status = esl_mem_strtoi(" 9223372036854775808", 20, 0, &nc, &val)) != eslERANGE || nc != 20 || val != INT64_MAX) esl_fatal(msg);
1032 if ( (status = esl_mem_strtoi("-9223372036854775809", 20, 0, &nc, &val)) != eslERANGE || nc != 20 || val != INT64_MIN) esl_fatal(msg);
1033 if ( (status = esl_mem_strtoi(" 922337203685477580800", 22, 0, &nc, &val)) != eslERANGE || nc != 20 || val != INT64_MAX) esl_fatal(msg);
1034 if ( (status = esl_mem_strtoi("-922337203685477580900", 22, 0, &nc, &val)) != eslERANGE || nc != 20 || val != INT64_MIN) esl_fatal(msg);
1035 }
1036 if ( (status = esl_mem_strtoi(" 0x1234", 3, 16, &nc, &val)) != eslEFORMAT || nc != 0 || val != 0) esl_fatal(msg);
1037 if ( (status = esl_mem_strtoi("0XX", 3, 0, &nc, &val)) != eslOK || nc != 1 || val != 0) esl_fatal(msg);
1038 }
1039
1040
1041
1042 static void
1043 utest_mem_strtof(void)
1044 {
1045 char msg[] = "esl_mem_strtof() unit test failed";
1046 float tol = 1e-6;
1047 float val;
1048 int nc;
1049 int status;
1050
1051 if (( status = esl_mem_strtof("-1.0", 4, &nc, &val) ) != eslOK || nc != 4 || esl_FCompare_old(val, -1.0, tol) != eslOK ) esl_fatal(msg);
1052 if (( status = esl_mem_strtof(" -1.0", 6, &nc, &val) ) != eslOK || nc != 6 || esl_FCompare_old(val, -1.0, tol) != eslOK ) esl_fatal(msg); // leading space
1053 if (( status = esl_mem_strtof("+1.0", 4, &nc, &val) ) != eslOK || nc != 4 || esl_FCompare_old(val, 1.0, tol) != eslOK ) esl_fatal(msg); // + is a valid sign
1054 if (( status = esl_mem_strtof("1234", 4, &nc, &val) ) != eslOK || nc != 4 || esl_FCompare_old(val, 1234., tol) != eslOK ) esl_fatal(msg); // no decimal point
1055 if (( status = esl_mem_strtof("1234.", 5, &nc, &val) ) != eslOK || nc != 5 || esl_FCompare_old(val, 1234., tol) != eslOK ) esl_fatal(msg); // decimal point, no fraction
1056 if (( status = esl_mem_strtof("1234.567", 8, &nc, &val) ) != eslOK || nc != 8 || esl_FCompare_old(val, 1234.567, tol) != eslOK ) esl_fatal(msg); // mantissa doesn't have to be normalized
1057 if (( status = esl_mem_strtof("1234.e-1", 8, &nc, &val) ) != eslOK || nc != 8 || esl_FCompare_old(val, 123.4, tol) != eslOK ) esl_fatal(msg);
1058 if (( status = esl_mem_strtof("1234.e-01", 9, &nc, &val) ) != eslOK || nc != 9 || esl_FCompare_old(val, 123.4, tol) != eslOK ) esl_fatal(msg);
1059 if (( status = esl_mem_strtof("1234.e+01", 9, &nc, &val) ) != eslOK || nc != 9 || esl_FCompare_old(val, 12340, tol) != eslOK ) esl_fatal(msg);
1060 if (( status = esl_mem_strtof("1234.E+01", 9, &nc, &val) ) != eslOK || nc != 9 || esl_FCompare_old(val, 12340, tol) != eslOK ) esl_fatal(msg);
1061 if (( status = esl_mem_strtof("1234.567E+01", 12, &nc, &val) ) != eslOK || nc != 12 || esl_FCompare_old(val, 12345.67, tol) != eslOK ) esl_fatal(msg);
1062 if (( status = esl_mem_strtof("1234.567E", 9, &nc, &val) ) != eslOK || nc != 8 || esl_FCompare_old(val, 1234.567, tol) != eslOK ) esl_fatal(msg);
1063
1064 if (( status = esl_mem_strtof("infinity", 8, &nc, &val) ) != eslOK || nc != 8 || !isinf(val)) esl_fatal(msg);
1065 if (( status = esl_mem_strtof("-inf", 4, &nc, &val) ) != eslOK || nc != 4 || !isinf(val)) esl_fatal(msg);
1066 if (( status = esl_mem_strtof("NaN", 3, &nc, &val) ) != eslOK || nc != 3 || !isnan(val)) esl_fatal(msg);
1067 if (( status = esl_mem_strtof("InFiNitY", 8, &nc, &val) ) != eslOK || nc != 8 || !isinf(val)) esl_fatal(msg);
1068 if (( status = esl_mem_strtof("iNf", 3, &nc, &val) ) != eslOK || nc != 3 || !isinf(val)) esl_fatal(msg);
1069 if (( status = esl_mem_strtof("nAn", 3, &nc, &val) ) != eslOK || nc != 3 || !isnan(val)) esl_fatal(msg);
1070
1071 /* same, with trailing text */
1072 if (( status = esl_mem_strtof("-1.0XYZ", 7, &nc, &val) ) != eslOK || nc != 4 || esl_FCompare_old(val, -1.0, tol) != eslOK ) esl_fatal(msg);
1073 if (( status = esl_mem_strtof(" -1.0XYZ", 9, &nc, &val) ) != eslOK || nc != 6 || esl_FCompare_old(val, -1.0, tol) != eslOK ) esl_fatal(msg);
1074 if (( status = esl_mem_strtof("+1.0XYZ", 7, &nc, &val) ) != eslOK || nc != 4 || esl_FCompare_old(val, 1.0, tol) != eslOK ) esl_fatal(msg);
1075 if (( status = esl_mem_strtof("1234XYZ", 7, &nc, &val) ) != eslOK || nc != 4 || esl_FCompare_old(val, 1234., tol) != eslOK ) esl_fatal(msg);
1076 if (( status = esl_mem_strtof("1234.XYZ", 8, &nc, &val) ) != eslOK || nc != 5 || esl_FCompare_old(val, 1234., tol) != eslOK ) esl_fatal(msg);
1077 if (( status = esl_mem_strtof("1234.567XYZ", 11, &nc, &val) ) != eslOK || nc != 8 || esl_FCompare_old(val, 1234.567, tol) != eslOK ) esl_fatal(msg);
1078 if (( status = esl_mem_strtof("1234.e-1XYZ", 11, &nc, &val) ) != eslOK || nc != 8 || esl_FCompare_old(val, 123.4, tol) != eslOK ) esl_fatal(msg);
1079 if (( status = esl_mem_strtof("1234.e-01XYZ", 12, &nc, &val) ) != eslOK || nc != 9 || esl_FCompare_old(val, 123.4, tol) != eslOK ) esl_fatal(msg);
1080 if (( status = esl_mem_strtof("1234.e+01XYZ", 12, &nc, &val) ) != eslOK || nc != 9 || esl_FCompare_old(val, 12340, tol) != eslOK ) esl_fatal(msg);
1081 if (( status = esl_mem_strtof("1234.E+01XYZ", 12, &nc, &val) ) != eslOK || nc != 9 || esl_FCompare_old(val, 12340, tol) != eslOK ) esl_fatal(msg);
1082 if (( status = esl_mem_strtof("1234.567E+01XYZ", 15, &nc, &val) ) != eslOK || nc != 12 || esl_FCompare_old(val, 12345.67, tol) != eslOK ) esl_fatal(msg);
1083 if (( status = esl_mem_strtof("1234.567EEEE", 12, &nc, &val) ) != eslOK || nc != 8 || esl_FCompare_old(val, 1234.567, tol) != eslOK ) esl_fatal(msg);
1084
1085 if (( status = esl_mem_strtof("infinityXYZ", 11, &nc, &val) ) != eslOK || nc != 8 || !isinf(val)) esl_fatal(msg);
1086 if (( status = esl_mem_strtof("-infXYZ", 7, &nc, &val) ) != eslOK || nc != 4 || !isinf(val)) esl_fatal(msg);
1087 if (( status = esl_mem_strtof("NaNXYZ", 6, &nc, &val) ) != eslOK || nc != 3 || !isnan(val)) esl_fatal(msg);
1088 if (( status = esl_mem_strtof("InFiNitYXYZ", 11, &nc, &val) ) != eslOK || nc != 8 || !isinf(val)) esl_fatal(msg);
1089 if (( status = esl_mem_strtof("iNfXYZ", 6, &nc, &val) ) != eslOK || nc != 3 || !isinf(val)) esl_fatal(msg);
1090 if (( status = esl_mem_strtof("nAnXYZ", 6, &nc, &val) ) != eslOK || nc != 3 || !isnan(val)) esl_fatal(msg);
1091
1092 /* terrifying edge cases that expose some flaws in our implementation, even aside from roundoff error */
1093 if (( status = esl_mem_strtof("9999999999999999999999999999999999999999e-10", 44, &nc, &val) ) != eslOK || nc != 44 || val != eslINFINITY) esl_fatal(msg); // a real strtof() gets this right: it's 1e30
1094 if (( status = esl_mem_strtof("-9999999999999999999999999999999999999999e-10", 45, &nc, &val) ) != eslOK || nc != 45 || val != -eslINFINITY) esl_fatal(msg); // ... and this should be -1e30
1095 if (( status = esl_mem_strtof("0.0000000000000000000000000000000000000000000001e10", 51, &nc, &val) ) != eslOK || nc != 51 || val != 0.0) esl_fatal(msg); // ... 1-e36
1096 if (( status = esl_mem_strtof("-0.0000000000000000000000000000000000000000000001e10", 52, &nc, &val) ) != eslOK || nc != 52 || val != 0.0) esl_fatal(msg); // ... -1-e36
1097
1098 /* Bad formats correctly detected: */
1099 if (( status = esl_mem_strtof("XYZXYZ", 6, &nc, &val) ) != eslEFORMAT || nc != 0 || val != 0.0) esl_fatal(msg);
1100 if (( status = esl_mem_strtof("intinity", 8, &nc, &val) ) != eslEFORMAT || nc != 0 || val != 0.0) esl_fatal(msg);
1101 }
1102
1103
1104 /* utest_mem_strtof_error()
1105 *
1106 * Compares <esl_mem_strtof()> to <strtof()>. Assumes that <strtof()>
1107 * is accurate: that it finds the nearest floating point
1108 * representation for the input string (within +/- 1 ulp and correctly
1109 * rounded). Makes sure that error in <esl_mem_strtof()> is tolerable:
1110 * that its relative error is no more than 4 ulps away from
1111 * <strtof()>, corresponding to a maximum relative error of ~5e-7.
1112 *
1113 * There is an error distribution, and this test can stochastically
1114 * fail normally. We force a fixed RNG seed unless caller toggles an
1115 * <allow_badluck> option to <TRUE>.
1116 *
1117 * See esl_mem.md for notes on rationale for rolling our own strtof(),
1118 * and its tradeoffs.
1119 */
1120 static void
1121 utest_mem_strtof_error(ESL_RANDOMNESS *rng, int allow_badluck)
1122 {
1123 char msg[] = "mem_strtof() error unit test failed";
1124 char s[32]; // random generated string representation of a float. Max len of slen+'.'+flen+'e'+"-xx" = 18.
1125 typedef union { float f; uint32_t rep; } flunion; // union gives us access to IEEE754 bitwise representation of a float
1126 flunion v1; // value deduced by strtof(), which we assume is accurate
1127 flunion v2; // value deduced by esl_mem_strtof(), which is fast and not too inaccurate
1128 int ulperr; // error in integer representation of significand
1129 int trial;
1130
1131 if (! allow_badluck) esl_randomness_Init(rng, 42);
1132
1133 for (trial = 0; trial < 100000; trial++) // check 100,000 numbers
1134 {
1135 esl_rnd_floatstring(rng, s);
1136
1137 v1.f = strtof(s, NULL);
1138 esl_mem_strtof(s, strlen(s), NULL, &(v2.f));
1139 ulperr = (v1.rep & 0x7fffff) - (v2.rep & 0x7fffff);
1140
1141 if (ulperr > 4) esl_fatal(msg); // 4 ulp = up to 4 \epsilon ~ 5e-7 rel error.
1142 }
1143 }
1144
1145
1146
1147 static void
1148 utest_memtok(void)
1149 {
1150 char msg[] = "esl_memtok() unit test failed";
1151 char *teststring;
1152 esl_pos_t n;
1153 char *s;
1154 char *tok;
1155 esl_pos_t toklen;
1156
1157 if (esl_strdup("This is\t a sentence.", -1, &teststring) != eslOK) esl_fatal(msg);
1158
1159 s = teststring;
1160 n = strlen(teststring);
1161 if (esl_memtok(&s, &n, " ", &tok, &toklen) != eslOK) esl_fatal(msg);
1162 if (toklen != 4) esl_fatal(msg);
1163 if (memcmp(tok, "This", toklen) != 0) esl_fatal(msg);
1164 if (*s != 'i') esl_fatal(msg);
1165
1166 if (esl_memtok(&s, &n, " \t", &tok, &toklen) != eslOK) esl_fatal(msg);
1167 if (toklen != 2) esl_fatal(msg);
1168 if (memcmp(tok, "is", toklen) != 0) esl_fatal(msg);
1169 if (*s != 'a') esl_fatal(msg);
1170
1171 if (esl_memtok(&s, &n, "\n", &tok, &toklen) != eslOK) esl_fatal(msg);
1172 if (toklen != 11) esl_fatal(msg);
1173 if (memcmp(tok, "a sentence.", toklen) != 0) esl_fatal(msg);
1174 if (*s != '\0') esl_fatal(msg);
1175 if (n != 0) esl_fatal(msg);
1176
1177 if (esl_memtok(&s, &n, "\n", &tok, &toklen) != eslEOL) esl_fatal(msg);
1178 if (toklen != 0) esl_fatal(msg);
1179 if (tok != NULL) esl_fatal(msg);
1180
1181 free(teststring);
1182 return;
1183 }
1184
1185
1186 /* memspn, memcspn() */
1187 static void
1188 utest_memspn_memcspn(void)
1189 {
1190 char msg[] = "memspn/memcspn unit test failed";
1191 char test1[] = " this is a test";
1192 char *p;
1193 esl_pos_t n;
1194
1195 p = test1;
1196 n = 13; /* so the memory is " this is a t" */
1197 if (esl_memspn (p, n, " \t\n\r") != 2) esl_fatal(msg);
1198 if (esl_memcspn(p, n, " \t\n\r") != 0) esl_fatal(msg);
1199
1200 p = test1+2;
1201 n = 11; /* "this is a t" */
1202 if (esl_memspn (p, n, " \t\n\r") != 0) esl_fatal(msg);
1203 if (esl_memcspn(p, n, " \t\n\r") != 4) esl_fatal(msg);
1204
1205 p = test1;
1206 n = 2;
1207 if (esl_memspn (p, n, " \t\n\r") != 2) esl_fatal(msg);
1208 if (esl_memcspn(p, n, " \t\n\r") != 0) esl_fatal(msg);
1209
1210 p = test1+2;
1211 n = 4;
1212 if (esl_memspn (p, n, " \t\n\r") != 0) esl_fatal(msg);
1213 if (esl_memcspn(p, n, " \t\n\r") != 4) esl_fatal(msg);
1214 }
1215
1216 /* memstrcmp/memstrpfx */
1217 static void
1218 utest_memstrcmp_memstrpfx(void)
1219 {
1220 char msg[] = "memstrcmp/memstrpfx unit test failed";
1221 char test[] = "this is a test";
1222 char *p;
1223 esl_pos_t n;
1224
1225 p = test;
1226 n = strlen(p);
1227 if (! esl_memstrcmp(p, n, test)) esl_fatal(msg);
1228 if ( esl_memstrcmp(p, n, "this")) esl_fatal(msg);
1229 if (! esl_memstrpfx(p, n, "this")) esl_fatal(msg);
1230 if ( esl_memstrpfx(p, n, "that")) esl_fatal(msg);
1231
1232 p = test;
1233 n = 2; /* now p is just "th" */
1234 if (! esl_memstrcmp(p, n, "th")) esl_fatal(msg);
1235 if ( esl_memstrcmp(p, n, test)) esl_fatal(msg);
1236 if (! esl_memstrpfx(p, n, "th")) esl_fatal(msg);
1237 if ( esl_memstrpfx(p, n, "this")) esl_fatal(msg);
1238
1239 /* special cases involving NULLs */
1240 p = test;
1241 n = strlen(p);
1242 if (! esl_memstrcmp(NULL, 0, NULL)) esl_fatal(msg);
1243 if ( esl_memstrcmp(NULL, 0, test)) esl_fatal(msg);
1244 if ( esl_memstrcmp(p, n, NULL)) esl_fatal(msg);
1245 if ( esl_memstrpfx(NULL, 0, NULL)) esl_fatal(msg);
1246 if ( esl_memstrpfx(NULL, 0, "this")) esl_fatal(msg);
1247 if ( esl_memstrpfx(p, n, NULL)) esl_fatal(msg);
1248 }
1249
1250 static void
1251 utest_memstrcontains(void)
1252 {
1253 char msg[] = "memstrcontains unit test failed";
1254 char test[] = "CLUSTAL W (1.83) multiple sequence alignment";
1255 char *p;
1256 esl_pos_t n;
1257
1258 p = test;
1259 n = strlen(p);
1260 if (! esl_memstrcontains(p, n, "multiple sequence alignment")) esl_fatal(msg);
1261 if (! esl_memstrcontains(p, n, "CLUSTAL")) esl_fatal(msg);
1262 if ( esl_memstrcontains(p, n, "alignmentx")) esl_fatal(msg);
1263 }
1264
1265 #endif /*eslMEM_TESTDRIVE*/
1266 /*------------------ end, unit tests ----------------------------*/
1267
1268
1269
1270
1271 /*****************************************************************
1272 * 3. Test driver
1273 *****************************************************************/
1274 #ifdef eslMEM_TESTDRIVE
1275 #include <esl_config.h>
1276
1277 #include <stdio.h>
1278
1279 #include "easel.h"
1280 #include "esl_mem.h"
1281 #include "esl_getopts.h"
1282
1283 static ESL_OPTIONS options[] = {
1284 /* name type default env range togs reqs incomp help docgrp */
1285 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show help and usage", 0},
1286 { "-s", eslARG_INT, "0", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0 },
1287 { "-x", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "allow bad luck (stochastic failures)", 0 },
1288 { 0,0,0,0,0,0,0,0,0,0},
1289 };
1290 static char usage[] = "[-options]";
1291 static char banner[] = "test driver for mem module";
1292
1293 int
1294 main(int argc, char **argv)
1295 {
1296 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);
1297 ESL_RANDOMNESS *rng = esl_randomness_Create(esl_opt_GetInteger(go, "-s"));
1298 int allow_badluck = esl_opt_GetBoolean(go, "-x"); // if a utest can fail just by chance, let it, instead of suppressing
1299
1300 fprintf(stderr, "## %s\n", argv[0]);
1301 fprintf(stderr, "# rng seed = %" PRIu32 "\n", esl_randomness_GetSeed(rng));
1302
1303 utest_mem_strtoi32();
1304 utest_mem_strtoi64();
1305 utest_mem_strtoi();
1306
1307 utest_mem_strtof();
1308 utest_memtok();
1309 utest_memspn_memcspn();
1310 utest_memstrcmp_memstrpfx();
1311 utest_memstrcontains();
1312
1313 /* tests that can fail stochastically go last, because they reset RNG seed by default */
1314 utest_mem_strtof_error(rng, allow_badluck);
1315
1316 fprintf(stderr, "# status = ok\n");
1317
1318 esl_randomness_Destroy(rng);
1319 esl_getopts_Destroy(go);
1320 return 0;
1321 }
1322 #endif /* eslMEM_TESTDRIVE */
1323
1324
1325 /*------------------ end, test driver ---------------------------*/
1326
1327