2 * This file is part of the libsigrok project.
4 * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
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.
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.
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/>.
27 #include <libsigrok/libsigrok.h>
28 #include "libsigrok-internal.h"
31 #define LOG_PREFIX "strutil"
37 * Helper functions for handling or converting libsigrok-related strings.
41 * @defgroup grp_strutil String utilities
43 * Helper functions for handling or converting libsigrok-related strings.
51 * Convert a string representation of a numeric value (base 10) to a long integer. The
52 * conversion is strict and will fail if the complete string does not represent
53 * a valid long integer. The function sets errno according to the details of the
56 * @param str The string representation to convert.
57 * @param ret Pointer to long where the result of the conversion will be stored.
59 * @retval SR_OK Conversion successful.
60 * @retval SR_ERR Failure.
62 SR_PRIV int sr_atol(const char *str, long *ret)
68 tmp = strtol(str, &endptr, 10);
70 if (!endptr || *endptr || errno) {
83 * Convert a string representation of a numeric value (base 10) to an integer. The
84 * conversion is strict and will fail if the complete string does not represent
85 * a valid integer. The function sets errno according to the details of the
88 * @param str The string representation to convert.
89 * @param ret Pointer to int where the result of the conversion will be stored.
91 * @retval SR_OK Conversion successful.
92 * @retval SR_ERR Failure.
94 SR_PRIV int sr_atoi(const char *str, int *ret)
98 if (sr_atol(str, &tmp) != SR_OK)
101 if ((int) tmp != tmp) {
113 * Convert a string representation of a numeric value to a double. The
114 * conversion is strict and will fail if the complete string does not represent
115 * a valid double. The function sets errno according to the details of the
118 * @param str The string representation to convert.
119 * @param ret Pointer to double where the result of the conversion will be stored.
121 * @retval SR_OK Conversion successful.
122 * @retval SR_ERR Failure.
124 SR_PRIV int sr_atod(const char *str, double *ret)
130 tmp = strtof(str, &endptr);
132 if (!endptr || *endptr || errno) {
145 * Convert a string representation of a numeric value to a float. The
146 * conversion is strict and will fail if the complete string does not represent
147 * a valid float. The function sets errno according to the details of the
150 * @param str The string representation to convert.
151 * @param ret Pointer to float where the result of the conversion will be stored.
153 * @retval SR_OK Conversion successful.
154 * @retval SR_ERR Failure.
156 SR_PRIV int sr_atof(const char *str, float *ret)
160 if (sr_atod(str, &tmp) != SR_OK)
163 if ((float) tmp != tmp) {
175 * Convert a string representation of a numeric value to a double. The
176 * conversion is strict and will fail if the complete string does not represent
177 * a valid double. The function sets errno according to the details of the
178 * failure. This version ignores the locale.
180 * @param str The string representation to convert.
181 * @param ret Pointer to double where the result of the conversion will be stored.
183 * @retval SR_OK Conversion successful.
184 * @retval SR_ERR Failure.
186 SR_PRIV int sr_atod_ascii(const char *str, double *ret)
192 tmp = g_ascii_strtod(str, &endptr);
194 if (!endptr || *endptr || errno) {
207 * Convert a string representation of a numeric value to a float. The
208 * conversion is strict and will fail if the complete string does not represent
209 * a valid float. The function sets errno according to the details of the
210 * failure. This version ignores the locale.
212 * @param str The string representation to convert.
213 * @param ret Pointer to float where the result of the conversion will be stored.
215 * @retval SR_OK Conversion successful.
216 * @retval SR_ERR Failure.
218 SR_PRIV int sr_atof_ascii(const char *str, float *ret)
224 tmp = g_ascii_strtod(str, &endptr);
226 if (!endptr || *endptr || errno) {
232 /* FIXME This fails unexpectedly. Some other method to safel downcast
233 * needs to be found. Checking against FLT_MAX doesn't work as well. */
235 if ((float) tmp != tmp) {
237 sr_dbg("ERANGEEEE %e != %e", (float) tmp, tmp);
247 * Convert a string representation of a numeric value to a sr_rational.
249 * The conversion is strict and will fail if the complete string does not
250 * represent a valid number. The function sets errno according to the details
251 * of the failure. This version ignores the locale.
253 * @param str The string representation to convert.
254 * @param ret Pointer to sr_rational where the result of the conversion will be stored.
256 * @retval SR_OK Conversion successful.
257 * @retval SR_ERR Failure.
261 SR_API int sr_parse_rational(const char *str, struct sr_rational *ret)
265 int64_t fractional = 0;
266 int64_t denominator = 1;
267 int32_t fractional_len = 0;
268 int32_t exponent = 0;
269 bool is_negative = false;
272 integral = g_ascii_strtoll(str, &endptr, 10);
274 if (str == endptr && (str[0] == '-' || str[0] == '+') && str[1] == '.')
279 if (integral < 0 || str[0] == '-')
282 if (*endptr == '.') {
283 const char* start = endptr + 1;
284 fractional = g_ascii_strtoll(start, &endptr, 10);
287 fractional_len = endptr - start;
290 if ((*endptr == 'E') || (*endptr == 'e')) {
291 exponent = g_ascii_strtoll(endptr + 1, &endptr, 10);
299 for (int i = 0; i < fractional_len; i++)
301 exponent -= fractional_len;
304 integral += fractional;
306 integral -= fractional;
308 while (exponent > 0) {
313 while (exponent < 0) {
319 ret->q = denominator;
325 * Convert a numeric value value to its "natural" string representation
328 * E.g. a value of 3000000, with units set to "W", would be converted
329 * to "3 MW", 20000 to "20 kW", 31500 would become "31.5 kW".
331 * @param x The value to convert.
332 * @param unit The unit to append to the string, or NULL if the string
335 * @return A newly allocated string representation of the samplerate value,
336 * or NULL upon errors. The caller is responsible to g_free() the
341 SR_API char *sr_si_string_u64(uint64_t x, const char *unit)
344 uint64_t quot, divisor[] = {
345 SR_HZ(1), SR_KHZ(1), SR_MHZ(1), SR_GHZ(1),
346 SR_GHZ(1000), SR_GHZ(1000 * 1000), SR_GHZ(1000 * 1000 * 1000),
348 const char *p, prefix[] = "\0kMGTPE";
349 char fmt[16], fract[20] = "", *f;
354 for (i = 0; (quot = x / divisor[i]) >= 1000; i++);
357 sprintf(fmt, ".%%0%d"PRIu64, i * 3);
358 f = fract + sprintf(fract, fmt, x % divisor[i]) - 1;
360 while (f >= fract && strchr("0.", *f))
366 return g_strdup_printf("%" PRIu64 "%s %.1s%s", quot, fract, p, unit);
370 * Convert a numeric samplerate value to its "natural" string representation.
372 * E.g. a value of 3000000 would be converted to "3 MHz", 20000 to "20 kHz",
373 * 31500 would become "31.5 kHz".
375 * @param samplerate The samplerate in Hz.
377 * @return A newly allocated string representation of the samplerate value,
378 * or NULL upon errors. The caller is responsible to g_free() the
383 SR_API char *sr_samplerate_string(uint64_t samplerate)
385 return sr_si_string_u64(samplerate, "Hz");
389 * Convert a numeric period value to the "natural" string representation
390 * of its period value.
392 * The period is specified as a rational number's numerator and denominator.
394 * E.g. a pair of (1, 5) would be converted to "200 ms", (10, 100) to "100 ms".
396 * @param v_p The period numerator.
397 * @param v_q The period denominator.
399 * @return A newly allocated string representation of the period value,
400 * or NULL upon errors. The caller is responsible to g_free() the
405 SR_API char *sr_period_string(uint64_t v_p, uint64_t v_q)
410 freq = 1 / ((double)v_p / v_q);
412 if (freq > SR_GHZ(1)) {
413 v = (double)v_p / v_q * 1000000000000.0;
414 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
415 return g_strdup_printf("%.*f ps", prec, v);
416 } else if (freq > SR_MHZ(1)) {
417 v = (double)v_p / v_q * 1000000000.0;
418 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
419 return g_strdup_printf("%.*f ns", prec, v);
420 } else if (freq > SR_KHZ(1)) {
421 v = (double)v_p / v_q * 1000000.0;
422 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
423 return g_strdup_printf("%.*f us", prec, v);
424 } else if (freq > 1) {
425 v = (double)v_p / v_q * 1000.0;
426 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
427 return g_strdup_printf("%.*f ms", prec, v);
429 v = (double)v_p / v_q;
430 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
431 return g_strdup_printf("%.*f s", prec, v);
436 * Convert a numeric voltage value to the "natural" string representation
437 * of its voltage value. The voltage is specified as a rational number's
438 * numerator and denominator.
440 * E.g. a value of 300000 would be converted to "300mV", 2 to "2V".
442 * @param v_p The voltage numerator.
443 * @param v_q The voltage denominator.
445 * @return A newly allocated string representation of the voltage value,
446 * or NULL upon errors. The caller is responsible to g_free() the
451 SR_API char *sr_voltage_string(uint64_t v_p, uint64_t v_q)
454 return g_strdup_printf("%" PRIu64 " mV", v_p);
456 return g_strdup_printf("%" PRIu64 " V", v_p);
458 return g_strdup_printf("%g V", (float)v_p / (float)v_q);
462 * Convert a "natural" string representation of a size value to uint64_t.
464 * E.g. a value of "3k" or "3 K" would be converted to 3000, a value
465 * of "15M" would be converted to 15000000.
467 * Value representations other than decimal (such as hex or octal) are not
468 * supported. Only 'k' (kilo), 'm' (mega), 'g' (giga) suffixes are supported.
469 * Spaces (but not other whitespace) between value and suffix are allowed.
471 * @param sizestring A string containing a (decimal) size value.
472 * @param size Pointer to uint64_t which will contain the string's size value.
474 * @return SR_OK upon success, SR_ERR upon errors.
478 SR_API int sr_parse_sizestring(const char *sizestring, uint64_t *size)
480 int multiplier, done;
484 *size = strtoull(sizestring, &s, 10);
488 while (s && *s && multiplier == 0 && !done) {
493 frac_part = g_ascii_strtod(s, &s);
497 multiplier = SR_KHZ(1);
501 multiplier = SR_MHZ(1);
505 multiplier = SR_GHZ(1);
513 if (multiplier > 0) {
515 *size += frac_part * multiplier;
519 if (s && *s && g_ascii_strcasecmp(s, "Hz"))
526 * Convert a "natural" string representation of a time value to an
527 * uint64_t value in milliseconds.
529 * E.g. a value of "3s" or "3 s" would be converted to 3000, a value
530 * of "15ms" would be converted to 15.
532 * Value representations other than decimal (such as hex or octal) are not
533 * supported. Only lower-case "s" and "ms" time suffixes are supported.
534 * Spaces (but not other whitespace) between value and suffix are allowed.
536 * @param timestring A string containing a (decimal) time value.
537 * @return The string's time value as uint64_t, in milliseconds.
539 * @todo Add support for "m" (minutes) and others.
540 * @todo Add support for picoseconds?
541 * @todo Allow both lower-case and upper-case? If no, document it.
545 SR_API uint64_t sr_parse_timestring(const char *timestring)
550 /* TODO: Error handling, logging. */
552 time_msec = strtoull(timestring, &s, 10);
553 if (time_msec == 0 && s == timestring)
561 else if (!strcmp(s, "ms"))
571 SR_API gboolean sr_parse_boolstring(const char *boolstr)
574 * Complete absence of an input spec is assumed to mean TRUE,
575 * as in command line option strings like this:
576 * ...:samplerate=100k:header:numchannels=4:...
578 if (!boolstr || !*boolstr)
581 if (!g_ascii_strncasecmp(boolstr, "true", 4) ||
582 !g_ascii_strncasecmp(boolstr, "yes", 3) ||
583 !g_ascii_strncasecmp(boolstr, "on", 2) ||
584 !g_ascii_strncasecmp(boolstr, "1", 1))
591 SR_API int sr_parse_period(const char *periodstr, uint64_t *p, uint64_t *q)
595 *p = strtoull(periodstr, &s, 10);
596 if (*p == 0 && s == periodstr)
597 /* No digits found. */
603 if (!strcmp(s, "fs"))
604 *q = 1000000000000000ULL;
605 else if (!strcmp(s, "ps"))
606 *q = 1000000000000ULL;
607 else if (!strcmp(s, "ns"))
609 else if (!strcmp(s, "us"))
611 else if (!strcmp(s, "ms"))
613 else if (!strcmp(s, "s"))
616 /* Must have a time suffix. */
624 SR_API int sr_parse_voltage(const char *voltstr, uint64_t *p, uint64_t *q)
628 *p = strtoull(voltstr, &s, 10);
629 if (*p == 0 && s == voltstr)
630 /* No digits found. */
636 if (!g_ascii_strcasecmp(s, "mv"))
638 else if (!g_ascii_strcasecmp(s, "v"))
641 /* Must have a base suffix. */