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 { 39 /* round */ 40 dval = floor(dval + 0.5); 41 42 /* clamp / saturate */ 43 if (dval >= (double)LONG_MAX) 44 return LONG_MAX; 45 if (dval <= (double)LONG_MIN) 46 return LONG_MIN; 47 return (long)dval; 48 } 49 50 double 51 dbl_from_var_long( 52 long lval, 53 int status 54 ) 55 { 56 #ifdef STA_NANO 57 if (STA_NANO & status) { 58 return (double)lval * 1e-9; 59 } 60 #else 61 UNUSED_ARG(status); 62 #endif 63 return (double)lval * 1e-6; 64 } 65 66 double 67 dbl_from_usec_long( 68 long lval 69 ) 70 { 71 return (double)lval * 1e-6; 72 } 73 74 long 75 var_long_from_dbl( 76 double dval, 77 unsigned int * modes 78 ) 79 { 80 #ifdef MOD_NANO 81 *modes |= MOD_NANO; 82 dval *= 1e+9; 83 #else 84 UNUSED_ARG(modes); 85 dval *= 1e+6; 86 #endif 87 return clamp_rounded(dval); 88 } 89 90 long 91 usec_long_from_dbl( 92 double dval 93 ) 94 { 95 return clamp_rounded(dval * 1e+6); 96 } 97