]> mj.ucw.cz Git - libucw.git/blob - ucw/time-conf.c
Mainloop: Avoid polling for an empty set of events
[libucw.git] / ucw / time-conf.c
1 /*
2  *      UCW Library -- A Parser of Time Intervals
3  *
4  *      (c) 2012 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #include <ucw/lib.h>
11 #include <ucw/conf.h>
12 #include <ucw/time.h>
13 #include <ucw/fastbuf.h>
14
15 static char *
16 timestamp_parser(char *c, void *ptr)
17 {
18   timestamp_t *ts = ptr;
19   double d;
20
21   char *err = cf_parse_double(c, &d);
22   if (err)
23     return err;
24   if (d > 1e16)
25     return "Time too large";
26
27   *ts = (timestamp_t)(d*1000 + 0.5);
28   if (!*ts && d)
29     return "Non-zero time rounds down to zero milliseconds";
30
31   return NULL;
32 }
33
34 static void
35 timestamp_dumper(struct fastbuf *fb, void *ptr)
36 {
37   timestamp_t *ts = ptr;
38   bprintf(fb, "%jd", (intmax_t) *ts);
39 }
40
41 struct cf_user_type timestamp_type = {
42   .size = sizeof(timestamp_t),
43   .name = "timestamp",
44   .parser = timestamp_parser,
45   .dumper = timestamp_dumper
46 };
47
48 #ifdef TEST
49
50 #include <stdio.h>
51
52 int main(void)
53 {
54   char line[256];
55
56   while (fgets(line, sizeof(line), stdin))
57     {
58       char *nl = strchr(line, '\n');
59       if (nl)
60         *nl = 0;
61       timestamp_t t = -1;
62       char *err = timestamp_parser(line, &t);
63       if (err)
64         puts(err);
65       else
66         printf("%jd\n", (intmax_t) t);
67     }
68   return 0;
69 }
70
71 #endif