uloop: add a clock_gettime() implementation for mac os x
[project/libubox.git] / utils.c
1 /*
2 * utils - misc libubox utility functions
3 *
4 * Copyright (C) 2012 Felix Fietkau <nbd@openwrt.org>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18
19 #include "utils.h"
20 #include <stdarg.h>
21 #include <stdlib.h>
22 #include <stdio.h>
23
24 #define foreach_arg(_arg, _addr, _len, _first_addr, _first_len) \
25 for (_addr = (_first_addr), _len = (_first_len); \
26 _addr; \
27 _addr = va_arg(_arg, void **), _len = _addr ? va_arg(_arg, size_t) : 0)
28
29 void *__calloc_a(size_t len, ...)
30 {
31 va_list ap, ap1;
32 void *ret;
33 void **cur_addr;
34 size_t cur_len;
35 int alloc_len = 0;
36 char *ptr;
37
38 va_start(ap, len);
39
40 va_copy(ap1, ap);
41 foreach_arg(ap1, cur_addr, cur_len, &ret, len)
42 alloc_len += cur_len;
43 va_end(ap1);
44
45 ptr = calloc(1, alloc_len);
46 alloc_len = 0;
47 foreach_arg(ap, cur_addr, cur_len, &ret, len) {
48 *cur_addr = &ptr[alloc_len];
49 alloc_len += cur_len;
50 }
51 va_end(ap);
52
53 return ret;
54 }
55
56 #ifdef __APPLE__
57 #include <mach/mach_time.h>
58
59 static void clock_gettime_realtime(struct timespec *tv)
60 {
61 struct timeval _tv;
62
63 gettimeofday(&_tv, NULL);
64 tv->tv_sec = _tv.tv_sec;
65 tv->tv_nsec = _tv.tv_usec * 1000;
66 }
67
68 static void clock_gettime_monotonic(struct timespec *tv)
69 {
70 mach_timebase_info_data_t info;
71 float sec;
72 uint64_t val;
73
74 mach_timebase_info(&info);
75
76 val = mach_absolute_time();
77 tv->tv_nsec = (val * info.numer / info.denom) % 1000000000;
78
79 sec = val;
80 sec *= info.numer;
81 sec /= info.denom;
82 sec /= 1000000000;
83 tv->tv_sec = sec;
84 }
85
86 void clock_gettime(int type, struct timespec *tv)
87 {
88 if (type == CLOCK_REALTIME)
89 return clock_gettime_realtime(tv);
90 else
91 return clock_gettime_monotonic(tv);
92 }
93
94 #endif