xref: /freebsd/contrib/ntp/libntp/timexsup.c (revision fe75646a0234a261c0013bf1840fdac4acaf0cec)
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 "timexsup.h"
10 #include <limits.h>
11 #include <math.h>
12 
13 #ifdef HAVE_SYS_TIMEX_H
14 # include <sys/timex.h>
15 #endif
16 
17 #if defined(MOD_NANO) != defined(STA_NANO)
18 # warning inconsistent definitions of MOD_NANO vs STA_NANO
19 #endif
20 
21 static long
22 clamp_rounded(
23 	double dval
24 	)
25 {
26 	/* round */
27 	dval = floor(dval + 0.5);
28 
29 	/* clamp / saturate */
30 	if (dval >= (double)LONG_MAX)
31 		return LONG_MAX;
32 	if (dval <= (double)LONG_MIN)
33 		return LONG_MIN;
34 	return (long)dval;
35 }
36 
37 double
38 dbl_from_var_long(
39 	long	lval,
40 	int	status
41 	)
42 {
43 #ifdef STA_NANO
44 	if (status & STA_NANO)
45 		return (double)lval * 1e-9;
46 #else
47 	(void)status;
48 #endif
49 	return (double)lval * 1e-6;
50 }
51 
52 double
53 dbl_from_usec_long(
54 	long	lval
55 	)
56 {
57 	return (double)lval * 1e-6;
58 }
59 
60 long
61 var_long_from_dbl(
62 	double		dval,
63 	unsigned int *	modes
64 	)
65 {
66 #ifdef MOD_NANO
67 	*modes |= MOD_NANO;
68 	dval *= 1e+9;
69 #else
70 	(void)modes;
71 	dval *= 1e+6;
72 #endif
73 	return clamp_rounded(dval);
74 }
75 
76 long
77 usec_long_from_dbl(
78 	double	dval
79 	)
80 {
81 	return clamp_rounded(dval * 1e+6);
82 }
83