1 tplarson 1.1 /* self-contained source code for durcon,
2 converts commandline arguments given as a duration to a number of seconds.
3 compile it like this: 'cc -o durcon durcon.c' or similar
4 */
5
6 #include <stdlib.h>
7 #include <time.h>
8 #include <errno.h>
9 #include <stdio.h>
10 #include <math.h>
11
12 static int parse_duration(char **, double *);
13 int drms_names_parseduration(char **, double *);
14
15 int main(int argc, char **argv)
16 {
17 int status=0;
18 double dval;
19 while (--argc > 0)
20 {
21 status+=drms_names_parseduration(++argv,&dval);
22 tplarson 1.1 printf("%.3f ",dval);
23 }
24 printf("\n");
25 return status;
26 }
27
28
29 static inline int IsZero(double d)
30 {
31 return d == (double)0.0;
32 }
33
34 static inline int IsPosHugeVal(double d)
35 {
36 return d == HUGE_VAL;
37 }
38
39 static inline int IsNegHugeVal(double d)
40 {
41 return d == -HUGE_VAL;
42 }
43 tplarson 1.1
44 /* Parse time duration constant */
45 static int parse_duration(char **in, double *duration)
46 {
47 char *end, *p = *in;
48 double dval;
49
50 dval = strtod(p,&end);
51 if ( (IsZero(dval) && end==p) ||
52 ((IsPosHugeVal(dval) || IsNegHugeVal(dval)) && errno==ERANGE))
53 {
54 fprintf(stderr,"Syntax Error: Expected finite floating point value at "
55 "beginning of time duration, found '%s'.\n", p);
56 goto error;
57 }
58 else
59 p = end;
60 switch(*p++)
61 {
62 case 's':
63 *duration = 1.0*dval;
64 tplarson 1.1 break;
65 case 'm':
66 *duration = 60.0*dval;
67 break;
68 case 'h':
69 *duration = 3600.0*dval;
70 break;
71 case 'd':
72 *duration = 86400.0*dval;
73 break;
74 case 'u':
75 /* Means 'unit' - for SLOT type slotted keys, can have a query of the form
76 * [392.3/100u]. This just means [392.3 - 492.3). */
77 *duration = 1.0*dval;
78 break;
79 default:
80 fprintf(stderr,"Syntax Error: Time duration unit must be one of 's', "
81 "'m', 'h', 'd', 'u', found '%c', '%s'.\n", *(p-1), p);
82 goto error;
83 }
84 *in = p;
85 tplarson 1.1 return 0;
86 error:
87 return 1;
88 }
89
90 int drms_names_parseduration(char **in, double *duration)
91 {
92 char *tmp = strdup(*in);
93 int ret = 1;
94
95 if (tmp)
96 {
97 char *tmp2 = tmp;
98 ret = parse_duration(&tmp2, duration);
99 free(tmp);
100 }
101
102 return ret;
103 }
|