]> sigrok.org Git - libsigrok.git/blob - src/strutil.c
strutil.c: Fix a Doxygen warning.
[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, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19  */
20
21 #include <config.h>
22 #include <stdint.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <strings.h>
26 #include <errno.h>
27 #include <libsigrok/libsigrok.h>
28 #include "libsigrok-internal.h"
29
30 /** @cond PRIVATE */
31 #define LOG_PREFIX "strutil"
32 /** @endcond */
33
34 /**
35  * @file
36  *
37  * Helper functions for handling or converting libsigrok-related strings.
38  */
39
40 /**
41  * @defgroup grp_strutil String utilities
42  *
43  * Helper functions for handling or converting libsigrok-related strings.
44  *
45  * @{
46  */
47
48 /**
49  * @private
50  *
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
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  *
59  * @retval SR_OK Conversion successful.
60  * @retval SR_ERR Failure.
61  */
62 SR_PRIV int sr_atol(const char *str, long *ret)
63 {
64         long tmp;
65         char *endptr = NULL;
66
67         errno = 0;
68         tmp = strtol(str, &endptr, 10);
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 /**
81  * @private
82  *
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
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  *
91  * @retval SR_OK Conversion successful.
92  * @retval SR_ERR Failure.
93  */
94 SR_PRIV int sr_atoi(const char *str, int *ret)
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 /**
111  * @private
112  *
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  *
121  * @retval SR_OK Conversion successful.
122  * @retval SR_ERR Failure.
123  */
124 SR_PRIV int sr_atod(const char *str, double *ret)
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 /**
143  * @private
144  *
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  *
153  * @retval SR_OK Conversion successful.
154  * @retval SR_ERR Failure.
155  */
156 SR_PRIV int sr_atof(const char *str, float *ret)
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
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  *
183  * @retval SR_OK Conversion successful.
184  * @retval SR_ERR Failure.
185  */
186 SR_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
214 /**
215  * Convert a string representation of a numeric value to a sr_rational.
216  *
217  * The conversion is strict and will fail if the complete string does not
218  * represent a valid number. The function sets errno according to the details
219  * of the failure. This version ignores the locale.
220  *
221  * @param str The string representation to convert.
222  * @param ret Pointer to sr_rational where the result of the conversion will be stored.
223  *
224  * @retval SR_OK Conversion successful.
225  * @retval SR_ERR Failure.
226  *
227  * @since 0.5.0
228  */
229 SR_API int sr_parse_rational(const char *str, struct sr_rational *ret)
230 {
231         char *endptr = NULL;
232         int64_t integral;
233         int64_t fractional = 0;
234         int64_t denominator = 1;
235         int32_t fractional_len = 0;
236         int32_t exponent = 0;
237
238         errno = 0;
239         integral = g_ascii_strtoll(str, &endptr, 10);
240
241         if (errno)
242                 return SR_ERR;
243
244         if (*endptr == '.') {
245                 const char* start = endptr + 1;
246                 fractional = g_ascii_strtoll(start, &endptr, 10);
247                 if (errno)
248                         return SR_ERR;
249                 fractional_len = endptr - start;
250         }
251
252         if ((*endptr == 'E') || (*endptr == 'e')) {
253                 exponent = g_ascii_strtoll(endptr + 1, &endptr, 10);
254                 if (errno)
255                         return SR_ERR;
256         }
257
258         if (*endptr != '\0')
259                 return SR_ERR;
260
261         for (int i = 0; i < fractional_len; i++)
262                 integral *= 10;
263         exponent -= fractional_len;
264
265         if (integral >= 0)
266                 integral += fractional;
267         else
268                 integral -= fractional;
269
270         while (exponent > 0) {
271                 integral *= 10;
272                 exponent--;
273         }
274
275         while (exponent < 0) {
276                 denominator *= 10;
277                 exponent++;
278         }
279
280         ret->p = integral;
281         ret->q = denominator;
282
283         return SR_OK;
284 }
285
286 /**
287  * Convert a numeric value value to its "natural" string representation
288  * in SI units.
289  *
290  * E.g. a value of 3000000, with units set to "W", would be converted
291  * to "3 MW", 20000 to "20 kW", 31500 would become "31.5 kW".
292  *
293  * @param x The value to convert.
294  * @param unit The unit to append to the string, or NULL if the string
295  *             has no units.
296  *
297  * @return A newly allocated string representation of the samplerate value,
298  *         or NULL upon errors. The caller is responsible to g_free() the
299  *         memory.
300  *
301  * @since 0.2.0
302  */
303 SR_API char *sr_si_string_u64(uint64_t x, const char *unit)
304 {
305         uint8_t i;
306         uint64_t quot, divisor[] = {
307                 SR_HZ(1), SR_KHZ(1), SR_MHZ(1), SR_GHZ(1),
308                 SR_GHZ(1000), SR_GHZ(1000 * 1000), SR_GHZ(1000 * 1000 * 1000),
309         };
310         const char *p, prefix[] = "\0kMGTPE";
311         char fmt[16], fract[20] = "", *f;
312
313         if (!unit)
314                 unit = "";
315
316         for (i = 0; (quot = x / divisor[i]) >= 1000; i++);
317
318         if (i) {
319                 sprintf(fmt, ".%%0%d"PRIu64, i * 3);
320                 f = fract + sprintf(fract, fmt, x % divisor[i]) - 1;
321
322                 while (f >= fract && strchr("0.", *f))
323                         *f-- = 0;
324         }
325
326         p = prefix + i;
327
328         return g_strdup_printf("%" PRIu64 "%s %.1s%s", quot, fract, p, unit);
329 }
330
331 /**
332  * Convert a numeric samplerate value to its "natural" string representation.
333  *
334  * E.g. a value of 3000000 would be converted to "3 MHz", 20000 to "20 kHz",
335  * 31500 would become "31.5 kHz".
336  *
337  * @param samplerate The samplerate in Hz.
338  *
339  * @return A newly allocated string representation of the samplerate value,
340  *         or NULL upon errors. The caller is responsible to g_free() the
341  *         memory.
342  *
343  * @since 0.1.0
344  */
345 SR_API char *sr_samplerate_string(uint64_t samplerate)
346 {
347         return sr_si_string_u64(samplerate, "Hz");
348 }
349
350 /**
351  * Convert a numeric frequency value to the "natural" string representation
352  * of its period.
353  *
354  * E.g. a value of 3000000 would be converted to "3 us", 20000 to "50 ms".
355  *
356  * @param frequency The frequency in Hz.
357  *
358  * @return A newly allocated string representation of the frequency value,
359  *         or NULL upon errors. The caller is responsible to g_free() the
360  *         memory.
361  *
362  * @since 0.1.0
363  */
364 SR_API char *sr_period_string(uint64_t frequency)
365 {
366         char *o;
367         int r;
368
369         /* Allocate enough for a uint64_t as string + " ms". */
370         o = g_malloc0(30 + 1);
371
372         if (frequency >= SR_GHZ(1))
373                 r = snprintf(o, 30, "%" PRIu64 " ns", frequency / 1000000000);
374         else if (frequency >= SR_MHZ(1))
375                 r = snprintf(o, 30, "%" PRIu64 " us", frequency / 1000000);
376         else if (frequency >= SR_KHZ(1))
377                 r = snprintf(o, 30, "%" PRIu64 " ms", frequency / 1000);
378         else
379                 r = snprintf(o, 30, "%" PRIu64 " s", frequency);
380
381         if (r < 0) {
382                 /* Something went wrong... */
383                 g_free(o);
384                 return NULL;
385         }
386
387         return o;
388 }
389
390 /**
391  * Convert a numeric voltage value to the "natural" string representation
392  * of its voltage value. The voltage is specified as a rational number's
393  * numerator and denominator.
394  *
395  * E.g. a value of 300000 would be converted to "300mV", 2 to "2V".
396  *
397  * @param v_p The voltage numerator.
398  * @param v_q The voltage denominator.
399  *
400  * @return A newly allocated string representation of the voltage value,
401  *         or NULL upon errors. The caller is responsible to g_free() the
402  *         memory.
403  *
404  * @since 0.2.0
405  */
406 SR_API char *sr_voltage_string(uint64_t v_p, uint64_t v_q)
407 {
408         int r;
409         char *o;
410
411         o = g_malloc0(30 + 1);
412
413         if (v_q == 1000)
414                 r = snprintf(o, 30, "%" PRIu64 "mV", v_p);
415         else if (v_q == 1)
416                 r = snprintf(o, 30, "%" PRIu64 "V", v_p);
417         else
418                 r = snprintf(o, 30, "%gV", (float)v_p / (float)v_q);
419
420         if (r < 0) {
421                 /* Something went wrong... */
422                 g_free(o);
423                 return NULL;
424         }
425
426         return o;
427 }
428
429 /**
430  * Convert a "natural" string representation of a size value to uint64_t.
431  *
432  * E.g. a value of "3k" or "3 K" would be converted to 3000, a value
433  * of "15M" would be converted to 15000000.
434  *
435  * Value representations other than decimal (such as hex or octal) are not
436  * supported. Only 'k' (kilo), 'm' (mega), 'g' (giga) suffixes are supported.
437  * Spaces (but not other whitespace) between value and suffix are allowed.
438  *
439  * @param sizestring A string containing a (decimal) size value.
440  * @param size Pointer to uint64_t which will contain the string's size value.
441  *
442  * @return SR_OK upon success, SR_ERR upon errors.
443  *
444  * @since 0.1.0
445  */
446 SR_API int sr_parse_sizestring(const char *sizestring, uint64_t *size)
447 {
448         int multiplier, done;
449         double frac_part;
450         char *s;
451
452         *size = strtoull(sizestring, &s, 10);
453         multiplier = 0;
454         frac_part = 0;
455         done = FALSE;
456         while (s && *s && multiplier == 0 && !done) {
457                 switch (*s) {
458                 case ' ':
459                         break;
460                 case '.':
461                         frac_part = g_ascii_strtod(s, &s);
462                         break;
463                 case 'k':
464                 case 'K':
465                         multiplier = SR_KHZ(1);
466                         break;
467                 case 'm':
468                 case 'M':
469                         multiplier = SR_MHZ(1);
470                         break;
471                 case 'g':
472                 case 'G':
473                         multiplier = SR_GHZ(1);
474                         break;
475                 default:
476                         done = TRUE;
477                         s--;
478                 }
479                 s++;
480         }
481         if (multiplier > 0) {
482                 *size *= multiplier;
483                 *size += frac_part * multiplier;
484         } else
485                 *size += frac_part;
486
487         if (s && *s && g_ascii_strcasecmp(s, "Hz"))
488                 return SR_ERR;
489
490         return SR_OK;
491 }
492
493 /**
494  * Convert a "natural" string representation of a time value to an
495  * uint64_t value in milliseconds.
496  *
497  * E.g. a value of "3s" or "3 s" would be converted to 3000, a value
498  * of "15ms" would be converted to 15.
499  *
500  * Value representations other than decimal (such as hex or octal) are not
501  * supported. Only lower-case "s" and "ms" time suffixes are supported.
502  * Spaces (but not other whitespace) between value and suffix are allowed.
503  *
504  * @param timestring A string containing a (decimal) time value.
505  * @return The string's time value as uint64_t, in milliseconds.
506  *
507  * @todo Add support for "m" (minutes) and others.
508  * @todo Add support for picoseconds?
509  * @todo Allow both lower-case and upper-case? If no, document it.
510  *
511  * @since 0.1.0
512  */
513 SR_API uint64_t sr_parse_timestring(const char *timestring)
514 {
515         uint64_t time_msec;
516         char *s;
517
518         /* TODO: Error handling, logging. */
519
520         time_msec = strtoull(timestring, &s, 10);
521         if (time_msec == 0 && s == timestring)
522                 return 0;
523
524         if (s && *s) {
525                 while (*s == ' ')
526                         s++;
527                 if (!strcmp(s, "s"))
528                         time_msec *= 1000;
529                 else if (!strcmp(s, "ms"))
530                         ; /* redundant */
531                 else
532                         return 0;
533         }
534
535         return time_msec;
536 }
537
538 /** @since 0.1.0 */
539 SR_API gboolean sr_parse_boolstring(const char *boolstr)
540 {
541         if (!boolstr)
542                 return FALSE;
543
544         if (!g_ascii_strncasecmp(boolstr, "true", 4) ||
545             !g_ascii_strncasecmp(boolstr, "yes", 3) ||
546             !g_ascii_strncasecmp(boolstr, "on", 2) ||
547             !g_ascii_strncasecmp(boolstr, "1", 1))
548                 return TRUE;
549
550         return FALSE;
551 }
552
553 /** @since 0.2.0 */
554 SR_API int sr_parse_period(const char *periodstr, uint64_t *p, uint64_t *q)
555 {
556         char *s;
557
558         *p = strtoull(periodstr, &s, 10);
559         if (*p == 0 && s == periodstr)
560                 /* No digits found. */
561                 return SR_ERR_ARG;
562
563         if (s && *s) {
564                 while (*s == ' ')
565                         s++;
566                 if (!strcmp(s, "fs"))
567                         *q = 1000000000000000ULL;
568                 else if (!strcmp(s, "ps"))
569                         *q = 1000000000000ULL;
570                 else if (!strcmp(s, "ns"))
571                         *q = 1000000000ULL;
572                 else if (!strcmp(s, "us"))
573                         *q = 1000000;
574                 else if (!strcmp(s, "ms"))
575                         *q = 1000;
576                 else if (!strcmp(s, "s"))
577                         *q = 1;
578                 else
579                         /* Must have a time suffix. */
580                         return SR_ERR_ARG;
581         }
582
583         return SR_OK;
584 }
585
586 /** @since 0.2.0 */
587 SR_API int sr_parse_voltage(const char *voltstr, uint64_t *p, uint64_t *q)
588 {
589         char *s;
590
591         *p = strtoull(voltstr, &s, 10);
592         if (*p == 0 && s == voltstr)
593                 /* No digits found. */
594                 return SR_ERR_ARG;
595
596         if (s && *s) {
597                 while (*s == ' ')
598                         s++;
599                 if (!g_ascii_strcasecmp(s, "mv"))
600                         *q = 1000L;
601                 else if (!g_ascii_strcasecmp(s, "v"))
602                         *q = 1;
603                 else
604                         /* Must have a base suffix. */
605                         return SR_ERR_ARG;
606         }
607
608         return SR_OK;
609 }
610
611 /** @} */