]> sigrok.org Git - libsigrok.git/blame - src/strutil.c
strutil: add method to get an sr_rational from a string
[libsigrok.git] / src / strutil.c
CommitLineData
25e7d9b1 1/*
50985c20 2 * This file is part of the libsigrok project.
25e7d9b1
UH
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, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
6ec6c43b 21#include <config.h>
25e7d9b1
UH
22#include <stdint.h>
23#include <stdlib.h>
24#include <string.h>
ba464a12 25#include <strings.h>
9e4f8cf9 26#include <errno.h>
c1aae900 27#include <libsigrok/libsigrok.h>
45c59c8b 28#include "libsigrok-internal.h"
25e7d9b1 29
2ad1deb8 30/** @cond PRIVATE */
3544f848 31#define LOG_PREFIX "strutil"
2ad1deb8 32/** @endcond */
a885ce3e 33
393fb9cb
UH
34/**
35 * @file
36 *
37 * Helper functions for handling or converting libsigrok-related strings.
38 */
39
7b870c38
UH
40/**
41 * @defgroup grp_strutil String utilities
42 *
43 * Helper functions for handling or converting libsigrok-related strings.
44 *
45 * @{
46 */
47
9e4f8cf9 48/**
df823ac4
UH
49 * @private
50 *
1ba4a1cf 51 * Convert a string representation of a numeric value (base 10) to a long integer. The
9e4f8cf9
DJ
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
54 * failure.
55 *
56 * @param str The string representation to convert.
57 * @param ret Pointer to long where the result of the conversion will be stored.
58 *
1ba4a1cf
MH
59 * @retval SR_OK Conversion successful.
60 * @retval SR_ERR Failure.
9e4f8cf9 61 */
8d558c7a 62SR_PRIV int sr_atol(const char *str, long *ret)
9e4f8cf9
DJ
63{
64 long tmp;
65 char *endptr = NULL;
66
67 errno = 0;
1ba4a1cf 68 tmp = strtol(str, &endptr, 10);
9e4f8cf9
DJ
69
70 if (!endptr || *endptr || errno) {
71 if (!errno)
72 errno = EINVAL;
73 return SR_ERR;
74 }
75
76 *ret = tmp;
77 return SR_OK;
78}
79
80/**
df823ac4
UH
81 * @private
82 *
1ba4a1cf 83 * Convert a string representation of a numeric value (base 10) to an integer. The
9e4f8cf9
DJ
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
86 * failure.
87 *
88 * @param str The string representation to convert.
89 * @param ret Pointer to int where the result of the conversion will be stored.
90 *
1ba4a1cf
MH
91 * @retval SR_OK Conversion successful.
92 * @retval SR_ERR Failure.
9e4f8cf9 93 */
8d558c7a 94SR_PRIV int sr_atoi(const char *str, int *ret)
9e4f8cf9
DJ
95{
96 long tmp;
97
98 if (sr_atol(str, &tmp) != SR_OK)
99 return SR_ERR;
100
101 if ((int) tmp != tmp) {
102 errno = ERANGE;
103 return SR_ERR;
104 }
105
106 *ret = (int) tmp;
107 return SR_OK;
108}
109
110/**
df823ac4
UH
111 * @private
112 *
9e4f8cf9
DJ
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
116 * failure.
117 *
118 * @param str The string representation to convert.
119 * @param ret Pointer to double where the result of the conversion will be stored.
120 *
1ba4a1cf
MH
121 * @retval SR_OK Conversion successful.
122 * @retval SR_ERR Failure.
9e4f8cf9 123 */
8d558c7a 124SR_PRIV int sr_atod(const char *str, double *ret)
9e4f8cf9
DJ
125{
126 double tmp;
127 char *endptr = NULL;
128
129 errno = 0;
130 tmp = strtof(str, &endptr);
131
132 if (!endptr || *endptr || errno) {
133 if (!errno)
134 errno = EINVAL;
135 return SR_ERR;
136 }
137
138 *ret = tmp;
139 return SR_OK;
140}
141
142/**
df823ac4
UH
143 * @private
144 *
9e4f8cf9
DJ
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
148 * failure.
149 *
150 * @param str The string representation to convert.
151 * @param ret Pointer to float where the result of the conversion will be stored.
152 *
1ba4a1cf
MH
153 * @retval SR_OK Conversion successful.
154 * @retval SR_ERR Failure.
9e4f8cf9 155 */
8d558c7a 156SR_PRIV int sr_atof(const char *str, float *ret)
9e4f8cf9
DJ
157{
158 double tmp;
159
160 if (sr_atod(str, &tmp) != SR_OK)
161 return SR_ERR;
162
163 if ((float) tmp != tmp) {
164 errno = ERANGE;
165 return SR_ERR;
166 }
167
168 *ret = (float) tmp;
169 return SR_OK;
170}
171
9806c2d5
DJ
172/**
173 * @private
174 *
175 * Convert a string representation of a numeric value to a float. The
176 * conversion is strict and will fail if the complete string does not represent
177 * a valid float. The function sets errno according to the details of the
178 * failure. This version ignores the locale.
179 *
180 * @param str The string representation to convert.
181 * @param ret Pointer to float where the result of the conversion will be stored.
182 *
1ba4a1cf
MH
183 * @retval SR_OK Conversion successful.
184 * @retval SR_ERR Failure.
9806c2d5
DJ
185 */
186SR_PRIV int sr_atof_ascii(const char *str, float *ret)
187{
188 double tmp;
189 char *endptr = NULL;
190
191 errno = 0;
192 tmp = g_ascii_strtod(str, &endptr);
193
194 if (!endptr || *endptr || errno) {
195 if (!errno)
196 errno = EINVAL;
197 return SR_ERR;
198 }
199
200 /* FIXME This fails unexpectedly. Some other method to safel downcast
201 * needs to be found. Checking against FLT_MAX doesn't work as well. */
202 /*
203 if ((float) tmp != tmp) {
204 errno = ERANGE;
205 sr_dbg("ERANGEEEE %e != %e", (float) tmp, tmp);
206 return SR_ERR;
207 }
208 */
209
210 *ret = (float) tmp;
211 return SR_OK;
212}
213
5ec172d7
SB
214/**
215 * Convert a string representation of a numeric value to a @sr_rational. The
216 * conversion is strict and will fail if the complete string does not represent
217 * a valid number. The function sets errno according to the details of the
218 * 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 */
228SR_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
237 errno = 0;
238 integral = g_ascii_strtoll(str, &endptr, 10);
239
240 if (errno)
241 return SR_ERR;
242
243 if (*endptr == '.') {
244 const char* start = endptr + 1;
245 fractional = g_ascii_strtoll(start, &endptr, 10);
246 if (errno)
247 return SR_ERR;
248 fractional_len = endptr - start;
249 }
250
251 if ((*endptr == 'E') || (*endptr == 'e')) {
252 exponent = g_ascii_strtoll(endptr + 1, &endptr, 10);
253 if (errno)
254 return SR_ERR;
255 }
256
257 if (*endptr != '\0')
258 return SR_ERR;
259
260 for (int i = 0; i < fractional_len; i++)
261 integral *= 10;
262 exponent -= fractional_len;
263
264 if (integral >= 0)
265 integral += fractional;
266 else
267 integral -= fractional;
268
269 while (exponent > 0) {
270 integral *= 10;
271 exponent--;
272 }
273
274 while (exponent < 0) {
275 denominator *= 10;
276 exponent++;
277 }
278
279 ret->p = integral;
280 ret->q = denominator;
281
282 return SR_OK;
283}
284
25e7d9b1 285/**
b07b42f3
UH
286 * Convert a numeric value value to its "natural" string representation
287 * in SI units.
25e7d9b1 288 *
4cc9aea1
JH
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".
25e7d9b1 291 *
4cc9aea1
JH
292 * @param x The value to convert.
293 * @param unit The unit to append to the string, or NULL if the string
294 * has no units.
44dae539 295 *
91219afc 296 * @return A newly allocated string representation of the samplerate value,
133a37bf
UH
297 * or NULL upon errors. The caller is responsible to g_free() the
298 * memory.
47117241
UH
299 *
300 * @since 0.2.0
25e7d9b1 301 */
4cc9aea1 302SR_API char *sr_si_string_u64(uint64_t x, const char *unit)
25e7d9b1 303{
094e6b81
PS
304 uint8_t i;
305 uint64_t quot, divisor[] = {
b07b42f3
UH
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),
094e6b81
PS
308 };
309 const char *p, prefix[] = "\0kMGTPE";
69d83be9 310 char fmt[16], fract[20] = "", *f;
094e6b81 311
98fec29e 312 if (!unit)
4cc9aea1 313 unit = "";
25e7d9b1 314
094e6b81
PS
315 for (i = 0; (quot = x / divisor[i]) >= 1000; i++);
316
317 if (i) {
69d83be9 318 sprintf(fmt, ".%%0%d"PRIu64, i * 3);
094e6b81
PS
319 f = fract + sprintf(fract, fmt, x % divisor[i]) - 1;
320
321 while (f >= fract && strchr("0.", *f))
322 *f-- = 0;
133a37bf 323 }
25e7d9b1 324
094e6b81
PS
325 p = prefix + i;
326
327 return g_strdup_printf("%" PRIu64 "%s %.1s%s", quot, fract, p, unit);
4cc9aea1 328}
25e7d9b1 329
4cc9aea1
JH
330/**
331 * Convert a numeric samplerate value to its "natural" string representation.
332 *
333 * E.g. a value of 3000000 would be converted to "3 MHz", 20000 to "20 kHz",
334 * 31500 would become "31.5 kHz".
335 *
336 * @param samplerate The samplerate in Hz.
337 *
91219afc 338 * @return A newly allocated string representation of the samplerate value,
4cc9aea1
JH
339 * or NULL upon errors. The caller is responsible to g_free() the
340 * memory.
47117241
UH
341 *
342 * @since 0.1.0
4cc9aea1
JH
343 */
344SR_API char *sr_samplerate_string(uint64_t samplerate)
345{
346 return sr_si_string_u64(samplerate, "Hz");
25e7d9b1 347}
2a3f9541 348
2a3f9541 349/**
dfcc0bf9 350 * Convert a numeric frequency value to the "natural" string representation
2a3f9541
BV
351 * of its period.
352 *
2507648e 353 * E.g. a value of 3000000 would be converted to "3 us", 20000 to "50 ms".
2a3f9541
BV
354 *
355 * @param frequency The frequency in Hz.
44dae539 356 *
91219afc 357 * @return A newly allocated string representation of the frequency value,
133a37bf
UH
358 * or NULL upon errors. The caller is responsible to g_free() the
359 * memory.
47117241
UH
360 *
361 * @since 0.1.0
2a3f9541 362 */
1a081ca6 363SR_API char *sr_period_string(uint64_t frequency)
2a3f9541
BV
364{
365 char *o;
366 int r;
367
133a37bf 368 /* Allocate enough for a uint64_t as string + " ms". */
91219afc 369 o = g_malloc0(30 + 1);
2a3f9541 370
59df0c77 371 if (frequency >= SR_GHZ(1))
2a3f9541 372 r = snprintf(o, 30, "%" PRIu64 " ns", frequency / 1000000000);
59df0c77 373 else if (frequency >= SR_MHZ(1))
2507648e 374 r = snprintf(o, 30, "%" PRIu64 " us", frequency / 1000000);
59df0c77 375 else if (frequency >= SR_KHZ(1))
2a3f9541
BV
376 r = snprintf(o, 30, "%" PRIu64 " ms", frequency / 1000);
377 else
378 r = snprintf(o, 30, "%" PRIu64 " s", frequency);
379
380 if (r < 0) {
381 /* Something went wrong... */
133a37bf 382 g_free(o);
2a3f9541
BV
383 return NULL;
384 }
385
386 return o;
387}
40f5ddac 388
79afc8ca 389/**
e0e15067
BV
390 * Convert a numeric voltage value to the "natural" string representation
391 * of its voltage value. The voltage is specified as a rational number's
392 * numerator and denominator.
79afc8ca
BV
393 *
394 * E.g. a value of 300000 would be converted to "300mV", 2 to "2V".
395 *
e0e15067
BV
396 * @param v_p The voltage numerator.
397 * @param v_q The voltage denominator.
79afc8ca 398 *
91219afc 399 * @return A newly allocated string representation of the voltage value,
79afc8ca
BV
400 * or NULL upon errors. The caller is responsible to g_free() the
401 * memory.
47117241
UH
402 *
403 * @since 0.2.0
79afc8ca 404 */
e0e15067 405SR_API char *sr_voltage_string(uint64_t v_p, uint64_t v_q)
79afc8ca 406{
79afc8ca 407 int r;
d5a669a9 408 char *o;
79afc8ca 409
91219afc 410 o = g_malloc0(30 + 1);
79afc8ca 411
e0e15067
BV
412 if (v_q == 1000)
413 r = snprintf(o, 30, "%" PRIu64 "mV", v_p);
414 else if (v_q == 1)
415 r = snprintf(o, 30, "%" PRIu64 "V", v_p);
79afc8ca 416 else
e0e15067 417 r = snprintf(o, 30, "%gV", (float)v_p / (float)v_q);
79afc8ca
BV
418
419 if (r < 0) {
420 /* Something went wrong... */
421 g_free(o);
422 return NULL;
423 }
424
425 return o;
426}
427
dfcc0bf9
UH
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.
f64c1414 439 * @param size Pointer to uint64_t which will contain the string's size value.
dfcc0bf9 440 *
44dae539 441 * @return SR_OK upon success, SR_ERR upon errors.
47117241
UH
442 *
443 * @since 0.1.0
dfcc0bf9 444 */
1a081ca6 445SR_API int sr_parse_sizestring(const char *sizestring, uint64_t *size)
40f5ddac 446{
f64c1414 447 int multiplier, done;
580f3099 448 double frac_part;
40f5ddac
BV
449 char *s;
450
f64c1414 451 *size = strtoull(sizestring, &s, 10);
40f5ddac 452 multiplier = 0;
580f3099 453 frac_part = 0;
f64c1414
BV
454 done = FALSE;
455 while (s && *s && multiplier == 0 && !done) {
40f5ddac
BV
456 switch (*s) {
457 case ' ':
458 break;
580f3099
DJ
459 case '.':
460 frac_part = g_ascii_strtod(s, &s);
461 break;
40f5ddac
BV
462 case 'k':
463 case 'K':
59df0c77 464 multiplier = SR_KHZ(1);
40f5ddac
BV
465 break;
466 case 'm':
467 case 'M':
59df0c77 468 multiplier = SR_MHZ(1);
40f5ddac
BV
469 break;
470 case 'g':
471 case 'G':
59df0c77 472 multiplier = SR_GHZ(1);
40f5ddac
BV
473 break;
474 default:
f64c1414
BV
475 done = TRUE;
476 s--;
40f5ddac
BV
477 }
478 s++;
479 }
580f3099 480 if (multiplier > 0) {
f64c1414 481 *size *= multiplier;
580f3099
DJ
482 *size += frac_part * multiplier;
483 } else
484 *size += frac_part;
40f5ddac 485
34577da6 486 if (s && *s && g_ascii_strcasecmp(s, "Hz"))
f64c1414
BV
487 return SR_ERR;
488
489 return SR_OK;
40f5ddac
BV
490}
491
dfcc0bf9
UH
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 *
6b2d8d3e
UH
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.
47117241
UH
509 *
510 * @since 0.1.0
dfcc0bf9 511 */
1a081ca6 512SR_API uint64_t sr_parse_timestring(const char *timestring)
40f5ddac
BV
513{
514 uint64_t time_msec;
515 char *s;
516
6b2d8d3e
UH
517 /* TODO: Error handling, logging. */
518
40f5ddac
BV
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}
4d436e71 536
47117241 537/** @since 0.1.0 */
1a081ca6 538SR_API gboolean sr_parse_boolstring(const char *boolstr)
4d436e71
GM
539{
540 if (!boolstr)
541 return FALSE;
542
993526f8
BV
543 if (!g_ascii_strncasecmp(boolstr, "true", 4) ||
544 !g_ascii_strncasecmp(boolstr, "yes", 3) ||
545 !g_ascii_strncasecmp(boolstr, "on", 2) ||
546 !g_ascii_strncasecmp(boolstr, "1", 1))
4d436e71
GM
547 return TRUE;
548
549 return FALSE;
550}
76f4c610 551
47117241 552/** @since 0.2.0 */
76e107d6 553SR_API int sr_parse_period(const char *periodstr, uint64_t *p, uint64_t *q)
76f4c610
BV
554{
555 char *s;
556
76e107d6
BV
557 *p = strtoull(periodstr, &s, 10);
558 if (*p == 0 && s == periodstr)
76f4c610
BV
559 /* No digits found. */
560 return SR_ERR_ARG;
561
562 if (s && *s) {
563 while (*s == ' ')
564 s++;
8c012adb 565 if (!strcmp(s, "fs"))
76e107d6 566 *q = 1000000000000000ULL;
8c012adb 567 else if (!strcmp(s, "ps"))
76e107d6 568 *q = 1000000000000ULL;
8c012adb 569 else if (!strcmp(s, "ns"))
76e107d6 570 *q = 1000000000ULL;
76f4c610 571 else if (!strcmp(s, "us"))
76e107d6 572 *q = 1000000;
76f4c610 573 else if (!strcmp(s, "ms"))
76e107d6 574 *q = 1000;
76f4c610 575 else if (!strcmp(s, "s"))
76e107d6 576 *q = 1;
76f4c610
BV
577 else
578 /* Must have a time suffix. */
579 return SR_ERR_ARG;
580 }
581
582 return SR_OK;
583}
584
47117241 585/** @since 0.2.0 */
76e107d6 586SR_API int sr_parse_voltage(const char *voltstr, uint64_t *p, uint64_t *q)
79afc8ca
BV
587{
588 char *s;
589
76e107d6
BV
590 *p = strtoull(voltstr, &s, 10);
591 if (*p == 0 && s == voltstr)
79afc8ca
BV
592 /* No digits found. */
593 return SR_ERR_ARG;
594
595 if (s && *s) {
596 while (*s == ' ')
597 s++;
34577da6 598 if (!g_ascii_strcasecmp(s, "mv"))
76e107d6 599 *q = 1000L;
34577da6 600 else if (!g_ascii_strcasecmp(s, "v"))
76e107d6 601 *q = 1;
79afc8ca
BV
602 else
603 /* Must have a base suffix. */
604 return SR_ERR_ARG;
605 }
606
607 return SR_OK;
608}
609
7b870c38 610/** @} */