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