]> sigrok.org Git - libsigrok.git/blob - strutil.c
01bdbd11bcf821f75e10a35f781c0552553ee7ed
[libsigrok.git] / 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 <stdint.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <errno.h>
25 #include "libsigrok.h"
26 #include "libsigrok-internal.h"
27
28 /** @cond PRIVATE */
29 #define LOG_PREFIX "strutil"
30 /** @endcond */
31
32 /**
33  * @file
34  *
35  * Helper functions for handling or converting libsigrok-related strings.
36  */
37
38 /**
39  * @defgroup grp_strutil String utilities
40  *
41  * Helper functions for handling or converting libsigrok-related strings.
42  *
43  * @{
44  */
45
46 /**
47  * @private
48  *
49  * Convert a string representation of a numeric value to a long integer. The
50  * conversion is strict and will fail if the complete string does not represent
51  * a valid long integer. The function sets errno according to the details of the
52  * failure.
53  *
54  * @param str The string representation to convert.
55  * @param ret Pointer to long where the result of the conversion will be stored.
56  *
57  * @return SR_OK if conversion is successful, otherwise SR_ERR.
58  *
59  * @since 0.3.0
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, 0);
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 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  * @return SR_OK if conversion is successful, otherwise SR_ERR.
91  *
92  * @since 0.3.0
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  * @return SR_OK if conversion is successful, otherwise SR_ERR.
122  *
123  * @since 0.3.0
124  */
125 SR_PRIV int sr_atod(const char *str, double *ret)
126 {
127         double tmp;
128         char *endptr = NULL;
129
130         errno = 0;
131         tmp = strtof(str, &endptr);
132
133         if (!endptr || *endptr || errno) {
134                 if (!errno)
135                         errno = EINVAL;
136                 return SR_ERR;
137         }
138
139         *ret = tmp;
140         return SR_OK;
141 }
142
143 /**
144  * @private
145  *
146  * Convert a string representation of a numeric value to a float. The
147  * conversion is strict and will fail if the complete string does not represent
148  * a valid float. The function sets errno according to the details of the
149  * failure.
150  *
151  * @param str The string representation to convert.
152  * @param ret Pointer to float where the result of the conversion will be stored.
153  *
154  * @return SR_OK if conversion is successful, otherwise SR_ERR.
155  *
156  * @since 0.3.0
157  */
158 SR_PRIV int sr_atof(const char *str, float *ret)
159 {
160         double tmp;
161
162         if (sr_atod(str, &tmp) != SR_OK)
163                 return SR_ERR;
164
165         if ((float) tmp != tmp) {
166                 errno = ERANGE;
167                 return SR_ERR;
168         }
169
170         *ret = (float) tmp;
171         return SR_OK;
172 }
173
174 /**
175  * @private
176  *
177  * Convert a string representation of a numeric value to a float. The
178  * conversion is strict and will fail if the complete string does not represent
179  * a valid float. The function sets errno according to the details of the
180  * failure. This version ignores the locale.
181  *
182  * @param str The string representation to convert.
183  * @param ret Pointer to float where the result of the conversion will be stored.
184  *
185  * @return SR_OK if conversion is successful, otherwise SR_ERR.
186  *
187  * @since 0.3.0
188  */
189 SR_PRIV int sr_atof_ascii(const char *str, float *ret)
190 {
191         double tmp;
192         char *endptr = NULL;
193
194         errno = 0;
195         tmp = g_ascii_strtod(str, &endptr);
196
197         if (!endptr || *endptr || errno) {
198                 if (!errno)
199                         errno = EINVAL;
200                 return SR_ERR;
201         }
202
203         /* FIXME This fails unexpectedly. Some other method to safel downcast
204          * needs to be found. Checking against FLT_MAX doesn't work as well. */
205         /*
206         if ((float) tmp != tmp) {
207                 errno = ERANGE;
208                 sr_dbg("ERANGEEEE %e != %e", (float) tmp, tmp);
209                 return SR_ERR;
210         }
211         */
212
213         *ret = (float) tmp;
214         return SR_OK;
215 }
216
217 /**
218  * Convert a numeric value value to its "natural" string representation
219  * in SI units.
220  *
221  * E.g. a value of 3000000, with units set to "W", would be converted
222  * to "3 MW", 20000 to "20 kW", 31500 would become "31.5 kW".
223  *
224  * @param x The value to convert.
225  * @param unit The unit to append to the string, or NULL if the string
226  *             has no units.
227  *
228  * @return A g_try_malloc()ed string representation of the samplerate value,
229  *         or NULL upon errors. The caller is responsible to g_free() the
230  *         memory.
231  */
232 SR_API char *sr_si_string_u64(uint64_t x, const char *unit)
233 {
234         uint8_t i;
235         uint64_t quot, divisor[] = {
236                 SR_HZ(1), SR_KHZ(1), SR_MHZ(1), SR_GHZ(1),
237                 SR_GHZ(1000), SR_GHZ(1000 * 1000), SR_GHZ(1000 * 1000 * 1000),
238         };
239         const char *p, prefix[] = "\0kMGTPE";
240         char fmt[16], fract[20] = "", *f;
241
242         if (unit == NULL)
243                 unit = "";
244
245         for (i = 0; (quot = x / divisor[i]) >= 1000; i++);
246
247         if (i) {
248                 sprintf(fmt, ".%%0%d"PRIu64, i * 3);
249                 f = fract + sprintf(fract, fmt, x % divisor[i]) - 1;
250
251                 while (f >= fract && strchr("0.", *f))
252                         *f-- = 0;
253         }
254
255         p = prefix + i;
256
257         return g_strdup_printf("%" PRIu64 "%s %.1s%s", quot, fract, p, unit);
258 }
259
260 /**
261  * Convert a numeric samplerate value to its "natural" string representation.
262  *
263  * E.g. a value of 3000000 would be converted to "3 MHz", 20000 to "20 kHz",
264  * 31500 would become "31.5 kHz".
265  *
266  * @param samplerate The samplerate in Hz.
267  *
268  * @return A g_try_malloc()ed string representation of the samplerate value,
269  *         or NULL upon errors. The caller is responsible to g_free() the
270  *         memory.
271  */
272 SR_API char *sr_samplerate_string(uint64_t samplerate)
273 {
274         return sr_si_string_u64(samplerate, "Hz");
275 }
276
277 /**
278  * Convert a numeric frequency value to the "natural" string representation
279  * of its period.
280  *
281  * E.g. a value of 3000000 would be converted to "3 us", 20000 to "50 ms".
282  *
283  * @param frequency The frequency in Hz.
284  *
285  * @return A g_try_malloc()ed string representation of the frequency value,
286  *         or NULL upon errors. The caller is responsible to g_free() the
287  *         memory.
288  */
289 SR_API char *sr_period_string(uint64_t frequency)
290 {
291         char *o;
292         int r;
293
294         /* Allocate enough for a uint64_t as string + " ms". */
295         if (!(o = g_try_malloc0(30 + 1))) {
296                 sr_err("%s: o malloc failed", __func__);
297                 return NULL;
298         }
299
300         if (frequency >= SR_GHZ(1))
301                 r = snprintf(o, 30, "%" PRIu64 " ns", frequency / 1000000000);
302         else if (frequency >= SR_MHZ(1))
303                 r = snprintf(o, 30, "%" PRIu64 " us", frequency / 1000000);
304         else if (frequency >= SR_KHZ(1))
305                 r = snprintf(o, 30, "%" PRIu64 " ms", frequency / 1000);
306         else
307                 r = snprintf(o, 30, "%" PRIu64 " s", frequency);
308
309         if (r < 0) {
310                 /* Something went wrong... */
311                 g_free(o);
312                 return NULL;
313         }
314
315         return o;
316 }
317
318 /**
319  * Convert a numeric voltage value to the "natural" string representation
320  * of its voltage value. The voltage is specified as a rational number's
321  * numerator and denominator.
322  *
323  * E.g. a value of 300000 would be converted to "300mV", 2 to "2V".
324  *
325  * @param v_p The voltage numerator.
326  * @param v_q The voltage denominator.
327  *
328  * @return A g_try_malloc()ed string representation of the voltage value,
329  *         or NULL upon errors. The caller is responsible to g_free() the
330  *         memory.
331  */
332 SR_API char *sr_voltage_string(uint64_t v_p, uint64_t v_q)
333 {
334         int r;
335         char *o;
336
337         if (!(o = g_try_malloc0(30 + 1))) {
338                 sr_err("%s: o malloc failed", __func__);
339                 return NULL;
340         }
341
342         if (v_q == 1000)
343                 r = snprintf(o, 30, "%" PRIu64 "mV", v_p);
344         else if (v_q == 1)
345                 r = snprintf(o, 30, "%" PRIu64 "V", v_p);
346         else
347                 r = snprintf(o, 30, "%gV", (float)v_p / (float)v_q);
348
349         if (r < 0) {
350                 /* Something went wrong... */
351                 g_free(o);
352                 return NULL;
353         }
354
355         return o;
356 }
357
358 /**
359  * Parse a trigger specification string.
360  *
361  * @param sdi The device instance for which the trigger specification is
362  *            intended. Must not be NULL. Also, sdi->driver and
363  *            sdi->driver->info_get must not be NULL.
364  * @param triggerstring The string containing the trigger specification for
365  *        one or more channels of this device. Entries for multiple channels are
366  *        comma-separated. Triggers are specified in the form key=value,
367  *        where the key is a channel number (or channel name) and the value is
368  *        the requested trigger type. Valid trigger types currently
369  *        include 'r' (rising edge), 'f' (falling edge), 'c' (any pin value
370  *        change), '0' (low value), or '1' (high value).
371  *        Example: "1=r,sck=f,miso=0,7=c"
372  *
373  * @return Pointer to a list of trigger types (strings), or NULL upon errors.
374  *         The pointer list (if non-NULL) has as many entries as the
375  *         respective device has channels (all physically available channels,
376  *         not just enabled ones). Entries of the list which don't have
377  *         a trigger value set in 'triggerstring' are NULL, the other entries
378  *         contain the respective trigger type which is requested for the
379  *         respective channel (e.g. "r", "c", and so on).
380  */
381 SR_API char **sr_parse_triggerstring(const struct sr_dev_inst *sdi,
382                                      const char *triggerstring)
383 {
384         GSList *l;
385         GVariant *gvar;
386         struct sr_channel *ch;
387         int max_channels, channelnum, i;
388         char **tokens, **triggerlist, *trigger, *tc;
389         const char *trigger_types;
390         gboolean error;
391
392         max_channels = g_slist_length(sdi->channels);
393         error = FALSE;
394
395         if (!(triggerlist = g_try_malloc0(max_channels * sizeof(char *)))) {
396                 sr_err("%s: triggerlist malloc failed", __func__);
397                 return NULL;
398         }
399
400         if (sdi->driver->config_list(SR_CONF_TRIGGER_TYPE,
401                                 &gvar, sdi, NULL) != SR_OK) {
402                 sr_err("%s: Device doesn't support any triggers.", __func__);
403                 return NULL;
404         }
405         trigger_types = g_variant_get_string(gvar, NULL);
406
407         tokens = g_strsplit(triggerstring, ",", max_channels);
408         for (i = 0; tokens[i]; i++) {
409                 channelnum = -1;
410                 for (l = sdi->channels; l; l = l->next) {
411                         ch = (struct sr_channel *)l->data;
412                         if (ch->enabled
413                                 && !strncmp(ch->name, tokens[i],
414                                         strlen(ch->name))) {
415                                 channelnum = ch->index;
416                                 break;
417                         }
418                 }
419
420                 if (channelnum < 0 || channelnum >= max_channels) {
421                         sr_err("Invalid channel.");
422                         error = TRUE;
423                         break;
424                 }
425
426                 if ((trigger = strchr(tokens[i], '='))) {
427                         for (tc = ++trigger; *tc; tc++) {
428                                 if (strchr(trigger_types, *tc) == NULL) {
429                                         sr_err("Unsupported trigger "
430                                                "type '%c'.", *tc);
431                                         error = TRUE;
432                                         break;
433                                 }
434                         }
435                         if (!error)
436                                 triggerlist[channelnum] = g_strdup(trigger);
437                 }
438         }
439         g_strfreev(tokens);
440         g_variant_unref(gvar);
441
442         if (error) {
443                 for (i = 0; i < max_channels; i++)
444                         g_free(triggerlist[i]);
445                 g_free(triggerlist);
446                 triggerlist = NULL;
447         }
448
449         return triggerlist;
450 }
451
452 /**
453  * Convert a "natural" string representation of a size value to uint64_t.
454  *
455  * E.g. a value of "3k" or "3 K" would be converted to 3000, a value
456  * of "15M" would be converted to 15000000.
457  *
458  * Value representations other than decimal (such as hex or octal) are not
459  * supported. Only 'k' (kilo), 'm' (mega), 'g' (giga) suffixes are supported.
460  * Spaces (but not other whitespace) between value and suffix are allowed.
461  *
462  * @param sizestring A string containing a (decimal) size value.
463  * @param size Pointer to uint64_t which will contain the string's size value.
464  *
465  * @return SR_OK upon success, SR_ERR upon errors.
466  */
467 SR_API int sr_parse_sizestring(const char *sizestring, uint64_t *size)
468 {
469         int multiplier, done;
470         double frac_part;
471         char *s;
472
473         *size = strtoull(sizestring, &s, 10);
474         multiplier = 0;
475         frac_part = 0;
476         done = FALSE;
477         while (s && *s && multiplier == 0 && !done) {
478                 switch (*s) {
479                 case ' ':
480                         break;
481                 case '.':
482                         frac_part = g_ascii_strtod(s, &s);
483                         break;
484                 case 'k':
485                 case 'K':
486                         multiplier = SR_KHZ(1);
487                         break;
488                 case 'm':
489                 case 'M':
490                         multiplier = SR_MHZ(1);
491                         break;
492                 case 'g':
493                 case 'G':
494                         multiplier = SR_GHZ(1);
495                         break;
496                 default:
497                         done = TRUE;
498                         s--;
499                 }
500                 s++;
501         }
502         if (multiplier > 0) {
503                 *size *= multiplier;
504                 *size += frac_part * multiplier;
505         } else
506                 *size += frac_part;
507
508         if (*s && strcasecmp(s, "Hz"))
509                 return SR_ERR;
510
511         return SR_OK;
512 }
513
514 /**
515  * Convert a "natural" string representation of a time value to an
516  * uint64_t value in milliseconds.
517  *
518  * E.g. a value of "3s" or "3 s" would be converted to 3000, a value
519  * of "15ms" would be converted to 15.
520  *
521  * Value representations other than decimal (such as hex or octal) are not
522  * supported. Only lower-case "s" and "ms" time suffixes are supported.
523  * Spaces (but not other whitespace) between value and suffix are allowed.
524  *
525  * @param timestring A string containing a (decimal) time value.
526  * @return The string's time value as uint64_t, in milliseconds.
527  *
528  * @todo Add support for "m" (minutes) and others.
529  * @todo Add support for picoseconds?
530  * @todo Allow both lower-case and upper-case? If no, document it.
531  */
532 SR_API uint64_t sr_parse_timestring(const char *timestring)
533 {
534         uint64_t time_msec;
535         char *s;
536
537         /* TODO: Error handling, logging. */
538
539         time_msec = strtoull(timestring, &s, 10);
540         if (time_msec == 0 && s == timestring)
541                 return 0;
542
543         if (s && *s) {
544                 while (*s == ' ')
545                         s++;
546                 if (!strcmp(s, "s"))
547                         time_msec *= 1000;
548                 else if (!strcmp(s, "ms"))
549                         ; /* redundant */
550                 else
551                         return 0;
552         }
553
554         return time_msec;
555 }
556
557 SR_API gboolean sr_parse_boolstring(const char *boolstr)
558 {
559         if (!boolstr)
560                 return FALSE;
561
562         if (!g_ascii_strncasecmp(boolstr, "true", 4) ||
563             !g_ascii_strncasecmp(boolstr, "yes", 3) ||
564             !g_ascii_strncasecmp(boolstr, "on", 2) ||
565             !g_ascii_strncasecmp(boolstr, "1", 1))
566                 return TRUE;
567
568         return FALSE;
569 }
570
571 SR_API int sr_parse_period(const char *periodstr, uint64_t *p, uint64_t *q)
572 {
573         char *s;
574
575         *p = strtoull(periodstr, &s, 10);
576         if (*p == 0 && s == periodstr)
577                 /* No digits found. */
578                 return SR_ERR_ARG;
579
580         if (s && *s) {
581                 while (*s == ' ')
582                         s++;
583                 if (!strcmp(s, "fs"))
584                         *q = 1000000000000000ULL;
585                 else if (!strcmp(s, "ps"))
586                         *q = 1000000000000ULL;
587                 else if (!strcmp(s, "ns"))
588                         *q = 1000000000ULL;
589                 else if (!strcmp(s, "us"))
590                         *q = 1000000;
591                 else if (!strcmp(s, "ms"))
592                         *q = 1000;
593                 else if (!strcmp(s, "s"))
594                         *q = 1;
595                 else
596                         /* Must have a time suffix. */
597                         return SR_ERR_ARG;
598         }
599
600         return SR_OK;
601 }
602
603
604 SR_API int sr_parse_voltage(const char *voltstr, uint64_t *p, uint64_t *q)
605 {
606         char *s;
607
608         *p = strtoull(voltstr, &s, 10);
609         if (*p == 0 && s == voltstr)
610                 /* No digits found. */
611                 return SR_ERR_ARG;
612
613         if (s && *s) {
614                 while (*s == ' ')
615                         s++;
616                 if (!strcasecmp(s, "mv"))
617                         *q = 1000L;
618                 else if (!strcasecmp(s, "v"))
619                         *q = 1;
620                 else
621                         /* Must have a base suffix. */
622                         return SR_ERR_ARG;
623         }
624
625         return SR_OK;
626 }
627
628 /** @} */