time.cc 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright 2017 The Crashpad Authors. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "util/misc/time.h"
  15. #include "util/numeric/safe_assignment.h"
  16. namespace crashpad {
  17. void AddTimespec(const timespec& ts1, const timespec& ts2, timespec* result) {
  18. result->tv_sec = ts1.tv_sec + ts2.tv_sec;
  19. result->tv_nsec = ts1.tv_nsec + ts2.tv_nsec;
  20. if (result->tv_nsec >= long{kNanosecondsPerSecond}) {
  21. ++result->tv_sec;
  22. result->tv_nsec -= kNanosecondsPerSecond;
  23. }
  24. }
  25. void SubtractTimespec(const timespec& t1,
  26. const timespec& t2,
  27. timespec* result) {
  28. result->tv_sec = t1.tv_sec - t2.tv_sec;
  29. result->tv_nsec = t1.tv_nsec - t2.tv_nsec;
  30. if (result->tv_nsec < 0) {
  31. result->tv_sec -= 1;
  32. result->tv_nsec += kNanosecondsPerSecond;
  33. }
  34. }
  35. bool TimespecToTimeval(const timespec& ts, timeval* tv) {
  36. tv->tv_usec = ts.tv_nsec / 1000;
  37. // timespec::tv_sec and timeval::tv_sec should generally both be of type
  38. // time_t, however, on Windows, timeval::tv_sec is declared as a long, which
  39. // may be smaller than a time_t.
  40. return AssignIfInRange(&tv->tv_sec, ts.tv_sec);
  41. }
  42. void TimevalToTimespec(const timeval& tv, timespec* ts) {
  43. ts->tv_sec = tv.tv_sec;
  44. ts->tv_nsec = tv.tv_usec * 1000;
  45. }
  46. } // namespace crashpad