]> sigrok.org Git - libsigrok.git/blob - src/strutil.c
Various NULL-check consistency fixes.
[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 <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 (base 10) 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  * @retval SR_OK Conversion successful.
58  * @retval SR_ERR Failure.
59  *
60  * @since 0.3.0
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  * @since 0.3.0
95  */
96 SR_PRIV int sr_atoi(const char *str, int *ret)
97 {
98         long tmp;
99
100         if (sr_atol(str, &tmp) != SR_OK)
101                 return SR_ERR;
102
103         if ((int) tmp != tmp) {
104                 errno = ERANGE;
105                 return SR_ERR;
106         }
107
108         *ret = (int) tmp;
109         return SR_OK;
110 }
111
112 /**
113  * @private
114  *
115  * Convert a string representation of a numeric value to a double. The
116  * conversion is strict and will fail if the complete string does not represent
117  * a valid double. The function sets errno according to the details of the
118  * failure.
119  *
120  * @param str The string representation to convert.
121  * @param ret Pointer to double where the result of the conversion will be stored.
122  *
123  * @retval SR_OK Conversion successful.
124  * @retval SR_ERR Failure.
125  *
126  * @since 0.3.0
127  */
128 SR_PRIV int sr_atod(const char *str, double *ret)
129 {
130         double tmp;
131         char *endptr = NULL;
132
133         errno = 0;
134         tmp = strtof(str, &endptr);
135
136         if (!endptr || *endptr || errno) {
137                 if (!errno)
138                         errno = EINVAL;
139                 return SR_ERR;
140         }
141
142         *ret = tmp;
143         return SR_OK;
144 }
145
146 /**
147  * @private
148  *
149  * Convert a string representation of a numeric value to a float. The
150  * conversion is strict and will fail if the complete string does not represent
151  * a valid float. The function sets errno according to the details of the
152  * failure.
153  *
154  * @param str The string representation to convert.
155  * @param ret Pointer to float where the result of the conversion will be stored.
156  *
157  * @retval SR_OK Conversion successful.
158  * @retval SR_ERR Failure.
159  *
160  * @since 0.3.0
161  */
162 SR_PRIV int sr_atof(const char *str, float *ret)
163 {
164         double tmp;
165
166         if (sr_atod(str, &tmp) != SR_OK)
167                 return SR_ERR;
168
169         if ((float) tmp != tmp) {
170                 errno = ERANGE;
171                 return SR_ERR;
172         }
173
174         *ret = (float) tmp;
175         return SR_OK;
176 }
177
178 /**
179  * @private
180  *
181  * Convert a string representation of a numeric value to a float. The
182  * conversion is strict and will fail if the complete string does not represent
183  * a valid float. The function sets errno according to the details of the
184  * failure. This version ignores the locale.
185  *
186  * @param str The string representation to convert.
187  * @param ret Pointer to float where the result of the conversion will be stored.
188  *
189  * @retval SR_OK Conversion successful.
190  * @retval SR_ERR Failure.
191  *
192  * @since 0.3.0
193  */
194 SR_PRIV int sr_atof_ascii(const char *str, float *ret)
195 {
196         double tmp;
197         char *endptr = NULL;
198
199         errno = 0;
200         tmp = g_ascii_strtod(str, &endptr);
201
202         if (!endptr || *endptr || errno) {
203                 if (!errno)
204                         errno = EINVAL;
205                 return SR_ERR;
206         }
207
208         /* FIXME This fails unexpectedly. Some other method to safel downcast
209          * needs to be found. Checking against FLT_MAX doesn't work as well. */
210         /*
211         if ((float) tmp != tmp) {
212                 errno = ERANGE;
213                 sr_dbg("ERANGEEEE %e != %e", (float) tmp, tmp);
214                 return SR_ERR;
215         }
216         */
217
218         *ret = (float) tmp;
219         return SR_OK;
220 }
221
222 /**
223  * Convert a numeric value value to its "natural" string representation
224  * in SI units.
225  *
226  * E.g. a value of 3000000, with units set to "W", would be converted
227  * to "3 MW", 20000 to "20 kW", 31500 would become "31.5 kW".
228  *
229  * @param x The value to convert.
230  * @param unit The unit to append to the string, or NULL if the string
231  *             has no units.
232  *
233  * @return A newly allocated string representation of the samplerate value,
234  *         or NULL upon errors. The caller is responsible to g_free() the
235  *         memory.
236  *
237  * @since 0.2.0
238  */
239 SR_API char *sr_si_string_u64(uint64_t x, const char *unit)
240 {
241         uint8_t i;
242         uint64_t quot, divisor[] = {
243                 SR_HZ(1), SR_KHZ(1), SR_MHZ(1), SR_GHZ(1),
244                 SR_GHZ(1000), SR_GHZ(1000 * 1000), SR_GHZ(1000 * 1000 * 1000),
245         };
246         const char *p, prefix[] = "\0kMGTPE";
247         char fmt[16], fract[20] = "", *f;
248
249         if (!unit)
250                 unit = "";
251
252         for (i = 0; (quot = x / divisor[i]) >= 1000; i++);
253
254         if (i) {
255                 sprintf(fmt, ".%%0%d"PRIu64, i * 3);
256                 f = fract + sprintf(fract, fmt, x % divisor[i]) - 1;
257
258                 while (f >= fract && strchr("0.", *f))
259                         *f-- = 0;
260         }
261
262         p = prefix + i;
263
264         return g_strdup_printf("%" PRIu64 "%s %.1s%s", quot, fract, p, unit);
265 }
266
267 /**
268  * Convert a numeric samplerate value to its "natural" string representation.
269  *
270  * E.g. a value of 3000000 would be converted to "3 MHz", 20000 to "20 kHz",
271  * 31500 would become "31.5 kHz".
272  *
273  * @param samplerate The samplerate in Hz.
274  *
275  * @return A newly allocated string representation of the samplerate value,
276  *         or NULL upon errors. The caller is responsible to g_free() the
277  *         memory.
278  *
279  * @since 0.1.0
280  */
281 SR_API char *sr_samplerate_string(uint64_t samplerate)
282 {
283         return sr_si_string_u64(samplerate, "Hz");
284 }
285
286 /**
287  * Convert a numeric frequency value to the "natural" string representation
288  * of its period.
289  *
290  * E.g. a value of 3000000 would be converted to "3 us", 20000 to "50 ms".
291  *
292  * @param frequency The frequency in Hz.
293  *
294  * @return A newly allocated string representation of the frequency value,
295  *         or NULL upon errors. The caller is responsible to g_free() the
296  *         memory.
297  *
298  * @since 0.1.0
299  */
300 SR_API char *sr_period_string(uint64_t frequency)
301 {
302         char *o;
303         int r;
304
305         /* Allocate enough for a uint64_t as string + " ms". */
306         o = g_malloc0(30 + 1);
307
308         if (frequency >= SR_GHZ(1))
309                 r = snprintf(o, 30, "%" PRIu64 " ns", frequency / 1000000000);
310         else if (frequency >= SR_MHZ(1))
311                 r = snprintf(o, 30, "%" PRIu64 " us", frequency / 1000000);
312         else if (frequency >= SR_KHZ(1))
313                 r = snprintf(o, 30, "%" PRIu64 " ms", frequency / 1000);
314         else
315                 r = snprintf(o, 30, "%" PRIu64 " s", frequency);
316
317         if (r < 0) {
318                 /* Something went wrong... */
319                 g_free(o);
320                 return NULL;
321         }
322
323         return o;
324 }
325
326 /**
327  * Convert a numeric voltage value to the "natural" string representation
328  * of its voltage value. The voltage is specified as a rational number's
329  * numerator and denominator.
330  *
331  * E.g. a value of 300000 would be converted to "300mV", 2 to "2V".
332  *
333  * @param v_p The voltage numerator.
334  * @param v_q The voltage denominator.
335  *
336  * @return A newly allocated string representation of the voltage value,
337  *         or NULL upon errors. The caller is responsible to g_free() the
338  *         memory.
339  *
340  * @since 0.2.0
341  */
342 SR_API char *sr_voltage_string(uint64_t v_p, uint64_t v_q)
343 {
344         int r;
345         char *o;
346
347         o = g_malloc0(30 + 1);
348
349         if (v_q == 1000)
350                 r = snprintf(o, 30, "%" PRIu64 "mV", v_p);
351         else if (v_q == 1)
352                 r = snprintf(o, 30, "%" PRIu64 "V", v_p);
353         else
354                 r = snprintf(o, 30, "%gV", (float)v_p / (float)v_q);
355
356         if (r < 0) {
357                 /* Something went wrong... */
358                 g_free(o);
359                 return NULL;
360         }
361
362         return o;
363 }
364
365 /**
366  * Convert a "natural" string representation of a size value to uint64_t.
367  *
368  * E.g. a value of "3k" or "3 K" would be converted to 3000, a value
369  * of "15M" would be converted to 15000000.
370  *
371  * Value representations other than decimal (such as hex or octal) are not
372  * supported. Only 'k' (kilo), 'm' (mega), 'g' (giga) suffixes are supported.
373  * Spaces (but not other whitespace) between value and suffix are allowed.
374  *
375  * @param sizestring A string containing a (decimal) size value.
376  * @param size Pointer to uint64_t which will contain the string's size value.
377  *
378  * @return SR_OK upon success, SR_ERR upon errors.
379  *
380  * @since 0.1.0
381  */
382 SR_API int sr_parse_sizestring(const char *sizestring, uint64_t *size)
383 {
384         int multiplier, done;
385         double frac_part;
386         char *s;
387
388         *size = strtoull(sizestring, &s, 10);
389         multiplier = 0;
390         frac_part = 0;
391         done = FALSE;
392         while (s && *s && multiplier == 0 && !done) {
393                 switch (*s) {
394                 case ' ':
395                         break;
396                 case '.':
397                         frac_part = g_ascii_strtod(s, &s);
398                         break;
399                 case 'k':
400                 case 'K':
401                         multiplier = SR_KHZ(1);
402                         break;
403                 case 'm':
404                 case 'M':
405                         multiplier = SR_MHZ(1);
406                         break;
407                 case 'g':
408                 case 'G':
409                         multiplier = SR_GHZ(1);
410                         break;
411                 default:
412                         done = TRUE;
413                         s--;
414                 }
415                 s++;
416         }
417         if (multiplier > 0) {
418                 *size *= multiplier;
419                 *size += frac_part * multiplier;
420         } else
421                 *size += frac_part;
422
423         if (s && *s && strcasecmp(s, "Hz"))
424                 return SR_ERR;
425
426         return SR_OK;
427 }
428
429 /**
430  * Convert a "natural" string representation of a time value to an
431  * uint64_t value in milliseconds.
432  *
433  * E.g. a value of "3s" or "3 s" would be converted to 3000, a value
434  * of "15ms" would be converted to 15.
435  *
436  * Value representations other than decimal (such as hex or octal) are not
437  * supported. Only lower-case "s" and "ms" time suffixes are supported.
438  * Spaces (but not other whitespace) between value and suffix are allowed.
439  *
440  * @param timestring A string containing a (decimal) time value.
441  * @return The string's time value as uint64_t, in milliseconds.
442  *
443  * @todo Add support for "m" (minutes) and others.
444  * @todo Add support for picoseconds?
445  * @todo Allow both lower-case and upper-case? If no, document it.
446  *
447  * @since 0.1.0
448  */
449 SR_API uint64_t sr_parse_timestring(const char *timestring)
450 {
451         uint64_t time_msec;
452         char *s;
453
454         /* TODO: Error handling, logging. */
455
456         time_msec = strtoull(timestring, &s, 10);
457         if (time_msec == 0 && s == timestring)
458                 return 0;
459
460         if (s && *s) {
461                 while (*s == ' ')
462                         s++;
463                 if (!strcmp(s, "s"))
464                         time_msec *= 1000;
465                 else if (!strcmp(s, "ms"))
466                         ; /* redundant */
467                 else
468                         return 0;
469         }
470
471         return time_msec;
472 }
473
474 /** @since 0.1.0 */
475 SR_API gboolean sr_parse_boolstring(const char *boolstr)
476 {
477         if (!boolstr)
478                 return FALSE;
479
480         if (!g_ascii_strncasecmp(boolstr, "true", 4) ||
481             !g_ascii_strncasecmp(boolstr, "yes", 3) ||
482             !g_ascii_strncasecmp(boolstr, "on", 2) ||
483             !g_ascii_strncasecmp(boolstr, "1", 1))
484                 return TRUE;
485
486         return FALSE;
487 }
488
489 /** @since 0.2.0 */
490 SR_API int sr_parse_period(const char *periodstr, uint64_t *p, uint64_t *q)
491 {
492         char *s;
493
494         *p = strtoull(periodstr, &s, 10);
495         if (*p == 0 && s == periodstr)
496                 /* No digits found. */
497                 return SR_ERR_ARG;
498
499         if (s && *s) {
500                 while (*s == ' ')
501                         s++;
502                 if (!strcmp(s, "fs"))
503                         *q = 1000000000000000ULL;
504                 else if (!strcmp(s, "ps"))
505                         *q = 1000000000000ULL;
506                 else if (!strcmp(s, "ns"))
507                         *q = 1000000000ULL;
508                 else if (!strcmp(s, "us"))
509                         *q = 1000000;
510                 else if (!strcmp(s, "ms"))
511                         *q = 1000;
512                 else if (!strcmp(s, "s"))
513                         *q = 1;
514                 else
515                         /* Must have a time suffix. */
516                         return SR_ERR_ARG;
517         }
518
519         return SR_OK;
520 }
521
522 /** @since 0.2.0 */
523 SR_API int sr_parse_voltage(const char *voltstr, uint64_t *p, uint64_t *q)
524 {
525         char *s;
526
527         *p = strtoull(voltstr, &s, 10);
528         if (*p == 0 && s == voltstr)
529                 /* No digits found. */
530                 return SR_ERR_ARG;
531
532         if (s && *s) {
533                 while (*s == ' ')
534                         s++;
535                 if (!strcasecmp(s, "mv"))
536                         *q = 1000L;
537                 else if (!strcasecmp(s, "v"))
538                         *q = 1;
539                 else
540                         /* Must have a base suffix. */
541                         return SR_ERR_ARG;
542         }
543
544         return SR_OK;
545 }
546
547 /** @} */