]> sigrok.org Git - libsigrok.git/blob - src/strutil.c
strutil: Fix sr_parse_rational for integral parts between -0 and -1
[libsigrok.git] / src / strutil.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include <config.h>
21 #include <stdint.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <strings.h>
25 #include <errno.h>
26 #include <libsigrok/libsigrok.h>
27 #include "libsigrok-internal.h"
28
29 /** @cond PRIVATE */
30 #define LOG_PREFIX "strutil"
31 /** @endcond */
32
33 /**
34  * @file
35  *
36  * Helper functions for handling or converting libsigrok-related strings.
37  */
38
39 /**
40  * @defgroup grp_strutil String utilities
41  *
42  * Helper functions for handling or converting libsigrok-related strings.
43  *
44  * @{
45  */
46
47 /**
48  * @private
49  *
50  * Convert a string representation of a numeric value (base 10) to a long integer. The
51  * conversion is strict and will fail if the complete string does not represent
52  * a valid long integer. The function sets errno according to the details of the
53  * failure.
54  *
55  * @param str The string representation to convert.
56  * @param ret Pointer to long where the result of the conversion will be stored.
57  *
58  * @retval SR_OK Conversion successful.
59  * @retval SR_ERR Failure.
60  */
61 SR_PRIV int sr_atol(const char *str, long *ret)
62 {
63         long tmp;
64         char *endptr = NULL;
65
66         errno = 0;
67         tmp = strtol(str, &endptr, 10);
68
69         if (!endptr || *endptr || errno) {
70                 if (!errno)
71                         errno = EINVAL;
72                 return SR_ERR;
73         }
74
75         *ret = tmp;
76         return SR_OK;
77 }
78
79 /**
80  * @private
81  *
82  * Convert a string representation of a numeric value (base 10) to an integer. The
83  * conversion is strict and will fail if the complete string does not represent
84  * a valid integer. The function sets errno according to the details of the
85  * failure.
86  *
87  * @param str The string representation to convert.
88  * @param ret Pointer to int where the result of the conversion will be stored.
89  *
90  * @retval SR_OK Conversion successful.
91  * @retval SR_ERR Failure.
92  */
93 SR_PRIV int sr_atoi(const char *str, int *ret)
94 {
95         long tmp;
96
97         if (sr_atol(str, &tmp) != SR_OK)
98                 return SR_ERR;
99
100         if ((int) tmp != tmp) {
101                 errno = ERANGE;
102                 return SR_ERR;
103         }
104
105         *ret = (int) tmp;
106         return SR_OK;
107 }
108
109 /**
110  * @private
111  *
112  * Convert a string representation of a numeric value to a double. The
113  * conversion is strict and will fail if the complete string does not represent
114  * a valid double. The function sets errno according to the details of the
115  * failure.
116  *
117  * @param str The string representation to convert.
118  * @param ret Pointer to double where the result of the conversion will be stored.
119  *
120  * @retval SR_OK Conversion successful.
121  * @retval SR_ERR Failure.
122  */
123 SR_PRIV int sr_atod(const char *str, double *ret)
124 {
125         double tmp;
126         char *endptr = NULL;
127
128         errno = 0;
129         tmp = strtof(str, &endptr);
130
131         if (!endptr || *endptr || errno) {
132                 if (!errno)
133                         errno = EINVAL;
134                 return SR_ERR;
135         }
136
137         *ret = tmp;
138         return SR_OK;
139 }
140
141 /**
142  * @private
143  *
144  * Convert a string representation of a numeric value to a float. The
145  * conversion is strict and will fail if the complete string does not represent
146  * a valid float. The function sets errno according to the details of the
147  * failure.
148  *
149  * @param str The string representation to convert.
150  * @param ret Pointer to float where the result of the conversion will be stored.
151  *
152  * @retval SR_OK Conversion successful.
153  * @retval SR_ERR Failure.
154  */
155 SR_PRIV int sr_atof(const char *str, float *ret)
156 {
157         double tmp;
158
159         if (sr_atod(str, &tmp) != SR_OK)
160                 return SR_ERR;
161
162         if ((float) tmp != tmp) {
163                 errno = ERANGE;
164                 return SR_ERR;
165         }
166
167         *ret = (float) tmp;
168         return SR_OK;
169 }
170
171 /**
172  * @private
173  *
174  * Convert a string representation of a numeric value to a float. The
175  * conversion is strict and will fail if the complete string does not represent
176  * a valid float. The function sets errno according to the details of the
177  * failure. This version ignores the locale.
178  *
179  * @param str The string representation to convert.
180  * @param ret Pointer to float where the result of the conversion will be stored.
181  *
182  * @retval SR_OK Conversion successful.
183  * @retval SR_ERR Failure.
184  */
185 SR_PRIV int sr_atof_ascii(const char *str, float *ret)
186 {
187         double tmp;
188         char *endptr = NULL;
189
190         errno = 0;
191         tmp = g_ascii_strtod(str, &endptr);
192
193         if (!endptr || *endptr || errno) {
194                 if (!errno)
195                         errno = EINVAL;
196                 return SR_ERR;
197         }
198
199         /* FIXME This fails unexpectedly. Some other method to safel downcast
200          * needs to be found. Checking against FLT_MAX doesn't work as well. */
201         /*
202         if ((float) tmp != tmp) {
203                 errno = ERANGE;
204                 sr_dbg("ERANGEEEE %e != %e", (float) tmp, tmp);
205                 return SR_ERR;
206         }
207         */
208
209         *ret = (float) tmp;
210         return SR_OK;
211 }
212
213 /**
214  * Convert a string representation of a numeric value to a sr_rational.
215  *
216  * The conversion is strict and will fail if the complete string does not
217  * represent a valid number. The function sets errno according to the details
218  * of the failure. This version ignores the locale.
219  *
220  * @param str The string representation to convert.
221  * @param ret Pointer to sr_rational where the result of the conversion will be stored.
222  *
223  * @retval SR_OK Conversion successful.
224  * @retval SR_ERR Failure.
225  *
226  * @since 0.5.0
227  */
228 SR_API int sr_parse_rational(const char *str, struct sr_rational *ret)
229 {
230         char *endptr = NULL;
231         int64_t integral;
232         int64_t fractional = 0;
233         int64_t denominator = 1;
234         int32_t fractional_len = 0;
235         int32_t exponent = 0;
236         int is_negative = 0;
237
238         errno = 0;
239         integral = g_ascii_strtoll(str, &endptr, 10);
240
241         if (str == endptr && (str[0] == '-' || str[0] == '+') && str[1] == '.')
242                 endptr += 1;
243         else if (errno)
244                 return SR_ERR;
245
246         if (integral < 0 || str[0] == '-')
247                 is_negative = 1;
248
249         if (*endptr == '.') {
250                 const char* start = endptr + 1;
251                 fractional = g_ascii_strtoll(start, &endptr, 10);
252                 if (errno)
253                         return SR_ERR;
254                 fractional_len = endptr - start;
255         }
256
257         if ((*endptr == 'E') || (*endptr == 'e')) {
258                 exponent = g_ascii_strtoll(endptr + 1, &endptr, 10);
259                 if (errno)
260                         return SR_ERR;
261         }
262
263         if (*endptr != '\0')
264                 return SR_ERR;
265
266         for (int i = 0; i < fractional_len; i++)
267                 integral *= 10;
268         exponent -= fractional_len;
269
270         if (!is_negative)
271                 integral += fractional;
272         else
273                 integral -= fractional;
274
275         while (exponent > 0) {
276                 integral *= 10;
277                 exponent--;
278         }
279
280         while (exponent < 0) {
281                 denominator *= 10;
282                 exponent++;
283         }
284
285         ret->p = integral;
286         ret->q = denominator;
287
288         return SR_OK;
289 }
290
291 /**
292  * Convert a numeric value value to its "natural" string representation
293  * in SI units.
294  *
295  * E.g. a value of 3000000, with units set to "W", would be converted
296  * to "3 MW", 20000 to "20 kW", 31500 would become "31.5 kW".
297  *
298  * @param x The value to convert.
299  * @param unit The unit to append to the string, or NULL if the string
300  *             has no units.
301  *
302  * @return A newly allocated string representation of the samplerate value,
303  *         or NULL upon errors. The caller is responsible to g_free() the
304  *         memory.
305  *
306  * @since 0.2.0
307  */
308 SR_API char *sr_si_string_u64(uint64_t x, const char *unit)
309 {
310         uint8_t i;
311         uint64_t quot, divisor[] = {
312                 SR_HZ(1), SR_KHZ(1), SR_MHZ(1), SR_GHZ(1),
313                 SR_GHZ(1000), SR_GHZ(1000 * 1000), SR_GHZ(1000 * 1000 * 1000),
314         };
315         const char *p, prefix[] = "\0kMGTPE";
316         char fmt[16], fract[20] = "", *f;
317
318         if (!unit)
319                 unit = "";
320
321         for (i = 0; (quot = x / divisor[i]) >= 1000; i++);
322
323         if (i) {
324                 sprintf(fmt, ".%%0%d"PRIu64, i * 3);
325                 f = fract + sprintf(fract, fmt, x % divisor[i]) - 1;
326
327                 while (f >= fract && strchr("0.", *f))
328                         *f-- = 0;
329         }
330
331         p = prefix + i;
332
333         return g_strdup_printf("%" PRIu64 "%s %.1s%s", quot, fract, p, unit);
334 }
335
336 /**
337  * Convert a numeric samplerate value to its "natural" string representation.
338  *
339  * E.g. a value of 3000000 would be converted to "3 MHz", 20000 to "20 kHz",
340  * 31500 would become "31.5 kHz".
341  *
342  * @param samplerate The samplerate in Hz.
343  *
344  * @return A newly allocated string representation of the samplerate value,
345  *         or NULL upon errors. The caller is responsible to g_free() the
346  *         memory.
347  *
348  * @since 0.1.0
349  */
350 SR_API char *sr_samplerate_string(uint64_t samplerate)
351 {
352         return sr_si_string_u64(samplerate, "Hz");
353 }
354
355 /**
356  * Convert a numeric period value to the "natural" string representation
357  * of its period value.
358  *
359  * The period is specified as a rational number's numerator and denominator.
360  *
361  * E.g. a pair of (1, 5) would be converted to "200 ms", (10, 100) to "100 ms".
362  *
363  * @param v_p The period numerator.
364  * @param v_q The period denominator.
365  *
366  * @return A newly allocated string representation of the period value,
367  *         or NULL upon errors. The caller is responsible to g_free() the
368  *         memory.
369  *
370  * @since 0.5.0
371  */
372 SR_API char *sr_period_string(uint64_t v_p, uint64_t v_q)
373 {
374         double freq, v;
375         int prec;
376
377         freq = 1 / ((double)v_p / v_q);
378
379         if (freq > SR_GHZ(1)) {
380                 v = (double)v_p / v_q * 1000000000000.0;
381                 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
382                 return g_strdup_printf("%.*f ps", prec, v);
383         } else if (freq > SR_MHZ(1)) {
384                 v = (double)v_p / v_q * 1000000000.0;
385                 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
386                 return g_strdup_printf("%.*f ns", prec, v);
387         } else if (freq > SR_KHZ(1)) {
388                 v = (double)v_p / v_q * 1000000.0;
389                 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
390                 return g_strdup_printf("%.*f us", prec, v);
391         } else if (freq > 1) {
392                 v = (double)v_p / v_q * 1000.0;
393                 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
394                 return g_strdup_printf("%.*f ms", prec, v);
395         } else {
396                 v = (double)v_p / v_q;
397                 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
398                 return g_strdup_printf("%.*f s", prec, v);
399         }
400 }
401
402 /**
403  * Convert a numeric voltage value to the "natural" string representation
404  * of its voltage value. The voltage is specified as a rational number's
405  * numerator and denominator.
406  *
407  * E.g. a value of 300000 would be converted to "300mV", 2 to "2V".
408  *
409  * @param v_p The voltage numerator.
410  * @param v_q The voltage denominator.
411  *
412  * @return A newly allocated string representation of the voltage value,
413  *         or NULL upon errors. The caller is responsible to g_free() the
414  *         memory.
415  *
416  * @since 0.2.0
417  */
418 SR_API char *sr_voltage_string(uint64_t v_p, uint64_t v_q)
419 {
420         if (v_q == 1000)
421                 return g_strdup_printf("%" PRIu64 " mV", v_p);
422         else if (v_q == 1)
423                 return g_strdup_printf("%" PRIu64 " V", v_p);
424         else
425                 return g_strdup_printf("%g V", (float)v_p / (float)v_q);
426 }
427
428 /**
429  * Convert a "natural" string representation of a size value to uint64_t.
430  *
431  * E.g. a value of "3k" or "3 K" would be converted to 3000, a value
432  * of "15M" would be converted to 15000000.
433  *
434  * Value representations other than decimal (such as hex or octal) are not
435  * supported. Only 'k' (kilo), 'm' (mega), 'g' (giga) suffixes are supported.
436  * Spaces (but not other whitespace) between value and suffix are allowed.
437  *
438  * @param sizestring A string containing a (decimal) size value.
439  * @param size Pointer to uint64_t which will contain the string's size value.
440  *
441  * @return SR_OK upon success, SR_ERR upon errors.
442  *
443  * @since 0.1.0
444  */
445 SR_API int sr_parse_sizestring(const char *sizestring, uint64_t *size)
446 {
447         int multiplier, done;
448         double frac_part;
449         char *s;
450
451         *size = strtoull(sizestring, &s, 10);
452         multiplier = 0;
453         frac_part = 0;
454         done = FALSE;
455         while (s && *s && multiplier == 0 && !done) {
456                 switch (*s) {
457                 case ' ':
458                         break;
459                 case '.':
460                         frac_part = g_ascii_strtod(s, &s);
461                         break;
462                 case 'k':
463                 case 'K':
464                         multiplier = SR_KHZ(1);
465                         break;
466                 case 'm':
467                 case 'M':
468                         multiplier = SR_MHZ(1);
469                         break;
470                 case 'g':
471                 case 'G':
472                         multiplier = SR_GHZ(1);
473                         break;
474                 default:
475                         done = TRUE;
476                         s--;
477                 }
478                 s++;
479         }
480         if (multiplier > 0) {
481                 *size *= multiplier;
482                 *size += frac_part * multiplier;
483         } else
484                 *size += frac_part;
485
486         if (s && *s && g_ascii_strcasecmp(s, "Hz"))
487                 return SR_ERR;
488
489         return SR_OK;
490 }
491
492 /**
493  * Convert a "natural" string representation of a time value to an
494  * uint64_t value in milliseconds.
495  *
496  * E.g. a value of "3s" or "3 s" would be converted to 3000, a value
497  * of "15ms" would be converted to 15.
498  *
499  * Value representations other than decimal (such as hex or octal) are not
500  * supported. Only lower-case "s" and "ms" time suffixes are supported.
501  * Spaces (but not other whitespace) between value and suffix are allowed.
502  *
503  * @param timestring A string containing a (decimal) time value.
504  * @return The string's time value as uint64_t, in milliseconds.
505  *
506  * @todo Add support for "m" (minutes) and others.
507  * @todo Add support for picoseconds?
508  * @todo Allow both lower-case and upper-case? If no, document it.
509  *
510  * @since 0.1.0
511  */
512 SR_API uint64_t sr_parse_timestring(const char *timestring)
513 {
514         uint64_t time_msec;
515         char *s;
516
517         /* TODO: Error handling, logging. */
518
519         time_msec = strtoull(timestring, &s, 10);
520         if (time_msec == 0 && s == timestring)
521                 return 0;
522
523         if (s && *s) {
524                 while (*s == ' ')
525                         s++;
526                 if (!strcmp(s, "s"))
527                         time_msec *= 1000;
528                 else if (!strcmp(s, "ms"))
529                         ; /* redundant */
530                 else
531                         return 0;
532         }
533
534         return time_msec;
535 }
536
537 /** @since 0.1.0 */
538 SR_API gboolean sr_parse_boolstring(const char *boolstr)
539 {
540         /*
541          * Complete absence of an input spec is assumed to mean TRUE,
542          * as in command line option strings like this:
543          *   ...:samplerate=100k:header:numchannels=4:...
544          */
545         if (!boolstr || !*boolstr)
546                 return TRUE;
547
548         if (!g_ascii_strncasecmp(boolstr, "true", 4) ||
549             !g_ascii_strncasecmp(boolstr, "yes", 3) ||
550             !g_ascii_strncasecmp(boolstr, "on", 2) ||
551             !g_ascii_strncasecmp(boolstr, "1", 1))
552                 return TRUE;
553
554         return FALSE;
555 }
556
557 /** @since 0.2.0 */
558 SR_API int sr_parse_period(const char *periodstr, uint64_t *p, uint64_t *q)
559 {
560         char *s;
561
562         *p = strtoull(periodstr, &s, 10);
563         if (*p == 0 && s == periodstr)
564                 /* No digits found. */
565                 return SR_ERR_ARG;
566
567         if (s && *s) {
568                 while (*s == ' ')
569                         s++;
570                 if (!strcmp(s, "fs"))
571                         *q = 1000000000000000ULL;
572                 else if (!strcmp(s, "ps"))
573                         *q = 1000000000000ULL;
574                 else if (!strcmp(s, "ns"))
575                         *q = 1000000000ULL;
576                 else if (!strcmp(s, "us"))
577                         *q = 1000000;
578                 else if (!strcmp(s, "ms"))
579                         *q = 1000;
580                 else if (!strcmp(s, "s"))
581                         *q = 1;
582                 else
583                         /* Must have a time suffix. */
584                         return SR_ERR_ARG;
585         }
586
587         return SR_OK;
588 }
589
590 /** @since 0.2.0 */
591 SR_API int sr_parse_voltage(const char *voltstr, uint64_t *p, uint64_t *q)
592 {
593         char *s;
594
595         *p = strtoull(voltstr, &s, 10);
596         if (*p == 0 && s == voltstr)
597                 /* No digits found. */
598                 return SR_ERR_ARG;
599
600         if (s && *s) {
601                 while (*s == ' ')
602                         s++;
603                 if (!g_ascii_strcasecmp(s, "mv"))
604                         *q = 1000L;
605                 else if (!g_ascii_strcasecmp(s, "v"))
606                         *q = 1;
607                 else
608                         /* Must have a base suffix. */
609                         return SR_ERR_ARG;
610         }
611
612         return SR_OK;
613 }
614
615 /** @} */