timespec-sub.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /* Subtract two struct timespec values.
  2. Copyright (C) 2011-2015 Free Software Foundation, Inc.
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 3 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  13. /* Written by Paul Eggert. */
  14. /* Return the difference between two timespec values A and B. On
  15. overflow, return an extremal value. This assumes 0 <= tv_nsec <
  16. TIMESPEC_RESOLUTION. */
  17. #include <config.h>
  18. #include "timespec.h"
  19. #include "intprops.h"
  20. struct timespec
  21. timespec_sub (struct timespec a, struct timespec b)
  22. {
  23. time_t rs = a.tv_sec;
  24. time_t bs = b.tv_sec;
  25. int ns = a.tv_nsec - b.tv_nsec;
  26. int rns = ns;
  27. if (ns < 0)
  28. {
  29. rns = ns + TIMESPEC_RESOLUTION;
  30. if (rs == TYPE_MINIMUM (time_t))
  31. {
  32. if (bs <= 0)
  33. goto low_overflow;
  34. bs--;
  35. }
  36. else
  37. rs--;
  38. }
  39. if (INT_SUBTRACT_OVERFLOW (rs, bs))
  40. {
  41. if (rs < 0)
  42. {
  43. low_overflow:
  44. rs = TYPE_MINIMUM (time_t);
  45. rns = 0;
  46. }
  47. else
  48. {
  49. rs = TYPE_MAXIMUM (time_t);
  50. rns = TIMESPEC_RESOLUTION - 1;
  51. }
  52. }
  53. else
  54. rs -= bs;
  55. return make_timespec (rs, rns);
  56. }