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