1 /**
2  * The config module contains utility routines and configuration information
3  * specific to this package.
4  *
5  * Copyright: Copyright (C) 2005-2006 Sean Kelly.  All rights reserved.
6  * License:   BSD style: $(LICENSE)
7  * Author:    Sean Kelly
8  */
9 module tango.core.sync.Config;
10 
11 
12 public import tango.core.Exception : SyncException;
13 
14 
15 version( Posix )
16 {
17     private import tango.stdc.posix.time;
18     private import tango.stdc.posix.sys.time;
19 
20 
21     void getTimespec( ref timespec t )
22     {
23         static if( is( typeof( clock_gettime ) ) )
24         {
25             clock_gettime( CLOCK_REALTIME, &t );
26         }
27         else
28         {
29             timeval tv;
30 
31             gettimeofday( &tv, null );
32             (cast(byte*) &t)[0 .. t.sizeof] = 0;
33             t.tv_sec  = cast(typeof(t.tv_sec))  tv.tv_sec;
34             t.tv_nsec = cast(typeof(t.tv_nsec)) tv.tv_usec * 1_000;
35         }
36     }
37 
38 
39     void adjTimespec( ref timespec t, double v )
40     {
41         enum
42         {
43             SECS_TO_NANOS = 1_000_000_000
44         }
45 
46         // NOTE: The fractional value added to period is to correct fp error.
47         v += 0.000_000_000_1;
48 
49         if( t.tv_sec.max - t.tv_sec < v )
50         {
51             t.tv_sec  = t.tv_sec.max;
52             t.tv_nsec = 0;
53         }
54         else
55         {
56             alias typeof(t.tv_sec)  Secs;
57             alias typeof(t.tv_nsec) Nanos;
58 
59             t.tv_sec  += cast(Secs) v;
60             auto  ns   = cast(long)((v % 1.0) * SECS_TO_NANOS);
61             if( SECS_TO_NANOS - t.tv_nsec <= ns )
62             {
63                 t.tv_sec += 1;
64                 ns -= SECS_TO_NANOS;
65             }
66             t.tv_nsec += cast(Nanos) ns;
67         }
68     }
69 }