/src/ntp-dev/libntp/timexsup.c
Line | Count | Source |
1 | | /* |
2 | | * timexsup.c - 'struct timex' support functions |
3 | | * |
4 | | * Written by Juergen Perlinger (perlinger@ntp.org) for the NTP project. |
5 | | * The contents of 'html/copyright.html' apply. |
6 | | */ |
7 | | |
8 | | #include "config.h" |
9 | | #include <limits.h> |
10 | | #include <math.h> |
11 | | |
12 | | #ifdef HAVE_SYS_TIME_H |
13 | | # include <sys/time.h> |
14 | | #else |
15 | | # ifdef HAVE_TIME_H |
16 | | # include <time.h> |
17 | | # endif |
18 | | #endif |
19 | | #ifdef HAVE_SYS_TIMEX_H |
20 | | # include <sys/timex.h> |
21 | | #else |
22 | | # ifdef HAVE_TIMEX_H |
23 | | # include <timex.h> |
24 | | # endif |
25 | | #endif |
26 | | |
27 | | #include "ntp_types.h" |
28 | | #include "timexsup.h" |
29 | | |
30 | | #if defined(MOD_NANO) != defined(STA_NANO) |
31 | | # warning inconsistent definitions of MOD_NANO vs STA_NANO |
32 | | #endif |
33 | | |
34 | | static long |
35 | | clamp_rounded( |
36 | | double dval |
37 | | ) |
38 | 0 | { |
39 | | /* round */ |
40 | 0 | dval = floor(dval + 0.5); |
41 | | |
42 | | /* clamp / saturate */ |
43 | 0 | if (dval >= (double)LONG_MAX) |
44 | 0 | return LONG_MAX; |
45 | 0 | if (dval <= (double)LONG_MIN) |
46 | 0 | return LONG_MIN; |
47 | 0 | return (long)dval; |
48 | 0 | } |
49 | | |
50 | | double |
51 | | dbl_from_var_long( |
52 | | long lval, |
53 | | int status |
54 | | ) |
55 | 0 | { |
56 | 0 | #ifdef STA_NANO |
57 | 0 | if (STA_NANO & status) { |
58 | 0 | return (double)lval * 1e-9; |
59 | 0 | } |
60 | | #else |
61 | | UNUSED_ARG(status); |
62 | | #endif |
63 | 0 | return (double)lval * 1e-6; |
64 | 0 | } |
65 | | |
66 | | double |
67 | | dbl_from_usec_long( |
68 | | long lval |
69 | | ) |
70 | 0 | { |
71 | 0 | return (double)lval * 1e-6; |
72 | 0 | } |
73 | | |
74 | | long |
75 | | var_long_from_dbl( |
76 | | double dval, |
77 | | unsigned int * modes |
78 | | ) |
79 | 0 | { |
80 | 0 | #ifdef MOD_NANO |
81 | 0 | *modes |= MOD_NANO; |
82 | 0 | dval *= 1e+9; |
83 | | #else |
84 | | UNUSED_ARG(modes); |
85 | | dval *= 1e+6; |
86 | | #endif |
87 | 0 | return clamp_rounded(dval); |
88 | 0 | } |
89 | | |
90 | | long |
91 | | usec_long_from_dbl( |
92 | | double dval |
93 | | ) |
94 | 0 | { |
95 | 0 | return clamp_rounded(dval * 1e+6); |
96 | 0 | } |