003477c63c00768211c53ca6e4896c16b51083ed
[platform/upstream/cmake.git] / Utilities / cmcurl / lib / timediff.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2022, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at https://curl.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  ***************************************************************************/
22
23 #include "timediff.h"
24
25 /*
26  * Converts number of milliseconds into a timeval structure.
27  *
28  * Return values:
29  *    NULL IF tv is NULL or ms < 0 (eg. no timeout -> blocking select)
30  *    tv with 0 in both fields IF ms == 0 (eg. 0ms timeout -> polling select)
31  *    tv with converted fields IF ms > 0 (eg. >0ms timeout -> waiting select)
32  */
33 struct timeval *curlx_mstotv(struct timeval *tv, timediff_t ms)
34 {
35   if(!tv)
36     return NULL;
37
38   if(ms < 0)
39     return NULL;
40
41   if(ms > 0) {
42     timediff_t tv_sec = ms / 1000;
43     timediff_t tv_usec = (ms % 1000) * 1000; /* max=999999 */
44 #ifdef HAVE_SUSECONDS_T
45 #if TIMEDIFF_T_MAX > TIME_T_MAX
46     /* tv_sec overflow check in case time_t is signed */
47     if(tv_sec > TIME_T_MAX)
48       tv_sec = TIME_T_MAX;
49 #endif
50     tv->tv_sec = (time_t)tv_sec;
51     tv->tv_usec = (suseconds_t)tv_usec;
52 #elif defined(WIN32) /* maybe also others in the future */
53 #if TIMEDIFF_T_MAX > LONG_MAX
54     /* tv_sec overflow check on Windows there we know it is long */
55     if(tv_sec > LONG_MAX)
56       tv_sec = LONG_MAX;
57 #endif
58     tv->tv_sec = (long)tv_sec;
59     tv->tv_usec = (long)tv_usec;
60 #else
61 #if TIMEDIFF_T_MAX > INT_MAX
62     /* tv_sec overflow check in case time_t is signed */
63     if(tv_sec > INT_MAX)
64       tv_sec = INT_MAX;
65 #endif
66     tv->tv_sec = (int)tv_sec;
67     tv->tv_usec = (int)tv_usec;
68 #endif
69   }
70   else {
71     tv->tv_sec = 0;
72     tv->tv_usec = 0;
73   }
74
75   return tv;
76 }
77
78 /*
79  * Converts a timeval structure into number of milliseconds.
80  */
81 timediff_t curlx_tvtoms(struct timeval *tv)
82 {
83   return (tv->tv_sec*1000) + (timediff_t)(((double)tv->tv_usec)/1000.0);
84 }