timediff.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. #include "timediff.h"
  23. /*
  24. * Converts number of milliseconds into a timeval structure.
  25. *
  26. * Return values:
  27. * NULL IF tv is NULL or ms < 0 (eg. no timeout -> blocking select)
  28. * tv with 0 in both fields IF ms == 0 (eg. 0ms timeout -> polling select)
  29. * tv with converted fields IF ms > 0 (eg. >0ms timeout -> waiting select)
  30. */
  31. struct timeval *curlx_mstotv(struct timeval *tv, timediff_t ms)
  32. {
  33. if(!tv)
  34. return NULL;
  35. if(ms < 0)
  36. return NULL;
  37. if(ms > 0) {
  38. timediff_t tv_sec = ms / 1000;
  39. timediff_t tv_usec = (ms % 1000) * 1000; /* max=999999 */
  40. #ifdef HAVE_SUSECONDS_T
  41. #if TIMEDIFF_T_MAX > TIME_T_MAX
  42. /* tv_sec overflow check in case time_t is signed */
  43. if(tv_sec > TIME_T_MAX)
  44. tv_sec = TIME_T_MAX;
  45. #endif
  46. tv->tv_sec = (time_t)tv_sec;
  47. tv->tv_usec = (suseconds_t)tv_usec;
  48. #elif defined(WIN32) /* maybe also others in the future */
  49. #if TIMEDIFF_T_MAX > LONG_MAX
  50. /* tv_sec overflow check on Windows there we know it is long */
  51. if(tv_sec > LONG_MAX)
  52. tv_sec = LONG_MAX;
  53. #endif
  54. tv->tv_sec = (long)tv_sec;
  55. tv->tv_usec = (long)tv_usec;
  56. #else
  57. #if TIMEDIFF_T_MAX > INT_MAX
  58. /* tv_sec overflow check in case time_t is signed */
  59. if(tv_sec > INT_MAX)
  60. tv_sec = INT_MAX;
  61. #endif
  62. tv->tv_sec = (int)tv_sec;
  63. tv->tv_usec = (int)tv_usec;
  64. #endif
  65. }
  66. else {
  67. tv->tv_sec = 0;
  68. tv->tv_usec = 0;
  69. }
  70. return tv;
  71. }
  72. /*
  73. * Converts a timeval structure into number of milliseconds.
  74. */
  75. timediff_t curlx_tvtoms(struct timeval *tv)
  76. {
  77. return (tv->tv_sec*1000) + (timediff_t)(((double)tv->tv_usec)/1000.0);
  78. }