misc.c
Raw
1#include <cutils/misc.h>
2
3void sleep_ms(unsigned int milliseconds)
4{
5 #ifdef __unix__
6 usleep(milliseconds * 1000);
7 #endif
8 #ifdef _WIN32
9 Sleep(milliseconds);
10 #endif
11}
12
13#if __STDC_VERSION__ >= 199901L
14#ifdef UINT32_MAX
15uint32_t nethost32(uint32_t const net)
16{
17 uint8_t data[4];
18 memcpy(&data, &net, sizeof(data));
19
20 return ((uint32_t) data[3] << 0)
21 | ((uint32_t) data[2] << 8)
22 | ((uint32_t) data[1] << 16)
23 | ((uint32_t) data[0] << 24);
24}
25#endif
26#endif
27
28#if __STDC_VERSION__ >= 201112L
29
30bool timespec_bigger(const struct timespec* ts1, const struct timespec* ts2)
31{
32 if(ts1->tv_sec > ts2->tv_sec)
33 {
34 return true;
35 } else if(ts1->tv_sec < ts2->tv_sec) {
36 return false;
37 } else {
38 if(ts1->tv_nsec > ts2->tv_nsec)
39 {
40 return true;
41 } else if(ts1->tv_nsec < ts2->tv_nsec) {
42 return false;
43 } else {
44 return false;
45 }
46 }
47}
48
49bool timespec_equal(const struct timespec* ts1, const struct timespec* ts2)
50{
51 if(ts1->tv_sec == ts2->tv_sec && ts1->tv_nsec == ts2->tv_nsec)
52 {
53 return true;
54 } else {
55 return false;
56 }
57}
58
59bool timespec_smaller(const struct timespec* ts1, const struct timespec* ts2)
60{
61 if(timespec_equal(ts1, ts2))
62 {
63 return false;
64 } else if(timespec_bigger(ts1, ts2)) {
65 return false;
66 } else {
67 return true;
68 }
69}
70
71struct timespec timespec_diff(const struct timespec* ts1, const struct timespec* ts2)
72{
73 struct timespec result;
74
75 if((ts1->tv_sec < ts2->tv_sec) ||
76 ((ts1->tv_sec == ts2->tv_sec) &&
77 (ts1->tv_nsec <= ts2->tv_nsec)))
78 {
79 result.tv_sec = result.tv_nsec = 0 ;
80 } else {
81 result.tv_sec = ts1->tv_sec - ts2->tv_sec ;
82 if (ts1->tv_nsec < ts2->tv_nsec) {
83 result.tv_nsec = ts1->tv_nsec + 1000000000L - ts2->tv_nsec ;
84 result.tv_sec-- ;
85 } else {
86 result.tv_nsec = ts1->tv_nsec - ts2->tv_nsec ;
87 }
88 }
89
90 return result;
91
92}
93
94struct timespec timespec_add(const struct timespec* ts_1, const struct timespec* ts_2)
95{
96 struct timespec res;
97
98 if (999999999 - ts_1->tv_nsec < ts_2->tv_nsec)
99 {
100 res.tv_sec = ts_1->tv_sec + ts_2->tv_sec + 1;
101 res.tv_nsec = ts_1->tv_nsec + (ts_2->tv_nsec - 1000000000) ;
102 } else {
103 res.tv_sec = ts_1->tv_sec + ts_2->tv_sec;
104 res.tv_nsec = ts_1->tv_nsec + ts_2->tv_nsec;
105 }
106
107 return res;
108}
109
110
111uintmax_t timespec_ms(const struct timespec* ts)
112{
113 return (uintmax_t)ts->tv_sec * 1000 + (uintmax_t)ts->tv_nsec/1000000;
114}
115#endif
116