Merge from vendor branch GCC:
[dragonfly.git] / contrib / ntpd / util.c
1 /*      $OpenBSD: src/usr.sbin/ntpd/util.c,v 1.10 2004/12/08 15:47:38 mickey Exp $ */
2
3 /*
4  * Copyright (c) 2004 Alexander Guy <alexander.guy@andern.org>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
15  * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
16  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18
19 #include <sys/time.h>
20 #include <limits.h>
21
22 #include "ntpd.h"
23
24 double
25 gettime(void)
26 {
27         struct timeval  tv;
28
29         if (gettimeofday(&tv, NULL) == -1)
30                 fatal("gettimeofday");
31
32         return (tv.tv_sec + JAN_1970 + 1.0e-6 * tv.tv_usec);
33 }
34
35
36 void
37 d_to_tv(double d, struct timeval *tv)
38 {
39         tv->tv_sec = (long)d;
40         tv->tv_usec = (d - tv->tv_sec) * 1000000;
41 }
42
43 double
44 lfp_to_d(struct l_fixedpt lfp)
45 {
46         double  ret;
47
48         lfp.int_partl = ntohl(lfp.int_partl);
49         lfp.fractionl = ntohl(lfp.fractionl);
50
51         ret = (double)(lfp.int_partl) + ((double)lfp.fractionl / UINT_MAX);
52
53         return (ret);
54 }
55
56 struct l_fixedpt
57 d_to_lfp(double d)
58 {
59         struct l_fixedpt        lfp;
60
61         lfp.int_partl = htonl((u_int32_t)d);
62         lfp.fractionl = htonl((u_int32_t)((d - (u_int32_t)d) * UINT_MAX));
63
64         return (lfp);
65 }
66
67 double
68 sfp_to_d(struct s_fixedpt sfp)
69 {
70         double  ret;
71
72         sfp.int_parts = ntohs(sfp.int_parts);
73         sfp.fractions = ntohs(sfp.fractions);
74
75         ret = (double)(sfp.int_parts) + ((double)sfp.fractions / USHRT_MAX);
76
77         return (ret);
78 }
79
80 struct s_fixedpt
81 d_to_sfp(double d)
82 {
83         struct s_fixedpt        sfp;
84
85         sfp.int_parts = htons((u_int16_t)d);
86         sfp.fractions = htons((u_int16_t)((d - (u_int16_t)d) * USHRT_MAX));
87
88         return (sfp);
89 }