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/>.
26 #include <libsigrok/libsigrok.h>
27 #include "libsigrok-internal.h"
30 #define LOG_PREFIX "strutil"
36 * Helper functions for handling or converting libsigrok-related strings.
40 * @defgroup grp_strutil String utilities
42 * Helper functions for handling or converting libsigrok-related strings.
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
55 * @param str The string representation to convert.
56 * @param ret Pointer to long where the result of the conversion will be stored.
58 * @retval SR_OK Conversion successful.
59 * @retval SR_ERR Failure.
61 SR_PRIV int sr_atol(const char *str, long *ret)
67 tmp = strtol(str, &endptr, 10);
69 if (!endptr || *endptr || errno) {
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
87 * @param str The string representation to convert.
88 * @param ret Pointer to int where the result of the conversion will be stored.
90 * @retval SR_OK Conversion successful.
91 * @retval SR_ERR Failure.
93 SR_PRIV int sr_atoi(const char *str, int *ret)
97 if (sr_atol(str, &tmp) != SR_OK)
100 if ((int) tmp != tmp) {
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
117 * @param str The string representation to convert.
118 * @param ret Pointer to double where the result of the conversion will be stored.
120 * @retval SR_OK Conversion successful.
121 * @retval SR_ERR Failure.
123 SR_PRIV int sr_atod(const char *str, double *ret)
129 tmp = strtof(str, &endptr);
131 if (!endptr || *endptr || errno) {
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
149 * @param str The string representation to convert.
150 * @param ret Pointer to float where the result of the conversion will be stored.
152 * @retval SR_OK Conversion successful.
153 * @retval SR_ERR Failure.
155 SR_PRIV int sr_atof(const char *str, float *ret)
159 if (sr_atod(str, &tmp) != SR_OK)
162 if ((float) tmp != tmp) {
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.
179 * @param str The string representation to convert.
180 * @param ret Pointer to float where the result of the conversion will be stored.
182 * @retval SR_OK Conversion successful.
183 * @retval SR_ERR Failure.
185 SR_PRIV int sr_atof_ascii(const char *str, float *ret)
191 tmp = g_ascii_strtod(str, &endptr);
193 if (!endptr || *endptr || errno) {
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. */
202 if ((float) tmp != tmp) {
204 sr_dbg("ERANGEEEE %e != %e", (float) tmp, tmp);
214 * Convert a string representation of a numeric value to a sr_rational.
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.
220 * @param str The string representation to convert.
221 * @param ret Pointer to sr_rational where the result of the conversion will be stored.
223 * @retval SR_OK Conversion successful.
224 * @retval SR_ERR Failure.
228 SR_API int sr_parse_rational(const char *str, struct sr_rational *ret)
232 int64_t fractional = 0;
233 int64_t denominator = 1;
234 int32_t fractional_len = 0;
235 int32_t exponent = 0;
238 integral = g_ascii_strtoll(str, &endptr, 10);
243 if (*endptr == '.') {
244 const char* start = endptr + 1;
245 fractional = g_ascii_strtoll(start, &endptr, 10);
248 fractional_len = endptr - start;
251 if ((*endptr == 'E') || (*endptr == 'e')) {
252 exponent = g_ascii_strtoll(endptr + 1, &endptr, 10);
260 for (int i = 0; i < fractional_len; i++)
262 exponent -= fractional_len;
265 integral += fractional;
267 integral -= fractional;
269 while (exponent > 0) {
274 while (exponent < 0) {
280 ret->q = denominator;
286 * Convert a numeric value value to its "natural" string representation
289 * E.g. a value of 3000000, with units set to "W", would be converted
290 * to "3 MW", 20000 to "20 kW", 31500 would become "31.5 kW".
292 * @param x The value to convert.
293 * @param unit The unit to append to the string, or NULL if the string
296 * @return A newly allocated string representation of the samplerate value,
297 * or NULL upon errors. The caller is responsible to g_free() the
302 SR_API char *sr_si_string_u64(uint64_t x, const char *unit)
305 uint64_t quot, divisor[] = {
306 SR_HZ(1), SR_KHZ(1), SR_MHZ(1), SR_GHZ(1),
307 SR_GHZ(1000), SR_GHZ(1000 * 1000), SR_GHZ(1000 * 1000 * 1000),
309 const char *p, prefix[] = "\0kMGTPE";
310 char fmt[16], fract[20] = "", *f;
315 for (i = 0; (quot = x / divisor[i]) >= 1000; i++);
318 sprintf(fmt, ".%%0%d"PRIu64, i * 3);
319 f = fract + sprintf(fract, fmt, x % divisor[i]) - 1;
321 while (f >= fract && strchr("0.", *f))
327 return g_strdup_printf("%" PRIu64 "%s %.1s%s", quot, fract, p, unit);
331 * Convert a numeric samplerate value to its "natural" string representation.
333 * E.g. a value of 3000000 would be converted to "3 MHz", 20000 to "20 kHz",
334 * 31500 would become "31.5 kHz".
336 * @param samplerate The samplerate in Hz.
338 * @return A newly allocated string representation of the samplerate value,
339 * or NULL upon errors. The caller is responsible to g_free() the
344 SR_API char *sr_samplerate_string(uint64_t samplerate)
346 return sr_si_string_u64(samplerate, "Hz");
350 * Convert a numeric period value to the "natural" string representation
351 * of its period value.
353 * The period is specified as a rational number's numerator and denominator.
355 * E.g. a pair of (1, 5) would be converted to "200 ms", (10, 100) to "100 ms".
357 * @param v_p The period numerator.
358 * @param v_q The period denominator.
360 * @return A newly allocated string representation of the period value,
361 * or NULL upon errors. The caller is responsible to g_free() the
366 SR_API char *sr_period_string(uint64_t v_p, uint64_t v_q)
371 freq = 1 / ((double)v_p / v_q);
373 if (freq > SR_GHZ(1)) {
374 v = (double)v_p / v_q * 1000000000000.0;
375 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
376 return g_strdup_printf("%.*f ps", prec, v);
377 } else if (freq > SR_MHZ(1)) {
378 v = (double)v_p / v_q * 1000000000.0;
379 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
380 return g_strdup_printf("%.*f ns", prec, v);
381 } else if (freq > SR_KHZ(1)) {
382 v = (double)v_p / v_q * 1000000.0;
383 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
384 return g_strdup_printf("%.*f us", prec, v);
385 } else if (freq > 1) {
386 v = (double)v_p / v_q * 1000.0;
387 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
388 return g_strdup_printf("%.*f ms", prec, v);
390 v = (double)v_p / v_q;
391 prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
392 return g_strdup_printf("%.*f s", prec, v);
397 * Convert a numeric voltage value to the "natural" string representation
398 * of its voltage value. The voltage is specified as a rational number's
399 * numerator and denominator.
401 * E.g. a value of 300000 would be converted to "300mV", 2 to "2V".
403 * @param v_p The voltage numerator.
404 * @param v_q The voltage denominator.
406 * @return A newly allocated string representation of the voltage value,
407 * or NULL upon errors. The caller is responsible to g_free() the
412 SR_API char *sr_voltage_string(uint64_t v_p, uint64_t v_q)
415 return g_strdup_printf("%" PRIu64 "mV", v_p);
417 return g_strdup_printf("%" PRIu64 "V", v_p);
419 return g_strdup_printf("%gV", (float)v_p / (float)v_q);
423 * Convert a "natural" string representation of a size value to uint64_t.
425 * E.g. a value of "3k" or "3 K" would be converted to 3000, a value
426 * of "15M" would be converted to 15000000.
428 * Value representations other than decimal (such as hex or octal) are not
429 * supported. Only 'k' (kilo), 'm' (mega), 'g' (giga) suffixes are supported.
430 * Spaces (but not other whitespace) between value and suffix are allowed.
432 * @param sizestring A string containing a (decimal) size value.
433 * @param size Pointer to uint64_t which will contain the string's size value.
435 * @return SR_OK upon success, SR_ERR upon errors.
439 SR_API int sr_parse_sizestring(const char *sizestring, uint64_t *size)
441 int multiplier, done;
445 *size = strtoull(sizestring, &s, 10);
449 while (s && *s && multiplier == 0 && !done) {
454 frac_part = g_ascii_strtod(s, &s);
458 multiplier = SR_KHZ(1);
462 multiplier = SR_MHZ(1);
466 multiplier = SR_GHZ(1);
474 if (multiplier > 0) {
476 *size += frac_part * multiplier;
480 if (s && *s && g_ascii_strcasecmp(s, "Hz"))
487 * Convert a "natural" string representation of a time value to an
488 * uint64_t value in milliseconds.
490 * E.g. a value of "3s" or "3 s" would be converted to 3000, a value
491 * of "15ms" would be converted to 15.
493 * Value representations other than decimal (such as hex or octal) are not
494 * supported. Only lower-case "s" and "ms" time suffixes are supported.
495 * Spaces (but not other whitespace) between value and suffix are allowed.
497 * @param timestring A string containing a (decimal) time value.
498 * @return The string's time value as uint64_t, in milliseconds.
500 * @todo Add support for "m" (minutes) and others.
501 * @todo Add support for picoseconds?
502 * @todo Allow both lower-case and upper-case? If no, document it.
506 SR_API uint64_t sr_parse_timestring(const char *timestring)
511 /* TODO: Error handling, logging. */
513 time_msec = strtoull(timestring, &s, 10);
514 if (time_msec == 0 && s == timestring)
522 else if (!strcmp(s, "ms"))
532 SR_API gboolean sr_parse_boolstring(const char *boolstr)
535 * Complete absence of an input spec is assumed to mean TRUE,
536 * as in command line option strings like this:
537 * ...:samplerate=100k:header:numchannels=4:...
539 if (!boolstr || !*boolstr)
542 if (!g_ascii_strncasecmp(boolstr, "true", 4) ||
543 !g_ascii_strncasecmp(boolstr, "yes", 3) ||
544 !g_ascii_strncasecmp(boolstr, "on", 2) ||
545 !g_ascii_strncasecmp(boolstr, "1", 1))
552 SR_API int sr_parse_period(const char *periodstr, uint64_t *p, uint64_t *q)
556 *p = strtoull(periodstr, &s, 10);
557 if (*p == 0 && s == periodstr)
558 /* No digits found. */
564 if (!strcmp(s, "fs"))
565 *q = 1000000000000000ULL;
566 else if (!strcmp(s, "ps"))
567 *q = 1000000000000ULL;
568 else if (!strcmp(s, "ns"))
570 else if (!strcmp(s, "us"))
572 else if (!strcmp(s, "ms"))
574 else if (!strcmp(s, "s"))
577 /* Must have a time suffix. */
585 SR_API int sr_parse_voltage(const char *voltstr, uint64_t *p, uint64_t *q)
589 *p = strtoull(voltstr, &s, 10);
590 if (*p == 0 && s == voltstr)
591 /* No digits found. */
597 if (!g_ascii_strcasecmp(s, "mv"))
599 else if (!g_ascii_strcasecmp(s, "v"))
602 /* Must have a base suffix. */