aboutsummaryrefslogtreecommitdiffstats
path: root/libntp/timexsup.c
blob: 979a7c4aea8eaf1ff2871ef24f1e5ce23743a89f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
 * timexsup.c - 'struct timex' support functions
 *
 * Written by Juergen Perlinger (perlinger@ntp.org) for the NTP project.
 * The contents of 'html/copyright.html' apply.
 */

#include "config.h"
#include "timexsup.h"
#include <limits.h>
#include <math.h>

#ifdef HAVE_SYS_TIMEX_H
# include <sys/timex.h>
#endif

#if defined(MOD_NANO) != defined(STA_NANO)
# warning inconsistent definitions of MOD_NANO vs STA_NANO
#endif

static long
clamp_rounded(
	double dval
	)
{
	/* round */
	dval = floor(dval + 0.5);

	/* clamp / saturate */
	if (dval >= (double)LONG_MAX)
		return LONG_MAX;
	if (dval <= (double)LONG_MIN)
		return LONG_MIN;
	return (long)dval;
}

double
dbl_from_var_long(
	long	lval,
	int	status
	)
{
#ifdef STA_NANO
	if (status & STA_NANO)
		return (double)lval * 1e-9;
#else
	(void)status;
#endif
	return (double)lval * 1e-6;
}

double
dbl_from_usec_long(
	long	lval
	)
{
	return (double)lval * 1e-6;
}

long
var_long_from_dbl(
	double		dval,
	unsigned int *	modes
	)
{
#ifdef MOD_NANO
	*modes |= MOD_NANO;
	dval *= 1e+9;
#else
	(void)modes;
	dval *= 1e+6;
#endif
	return clamp_rounded(dval);
}

long
usec_long_from_dbl(
	double	dval
	)
{
	return clamp_rounded(dval * 1e+6);
}