time_conversion_posix.cc 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "base/time/time.h"
  5. #include <stdint.h>
  6. #include <sys/time.h>
  7. #include <time.h>
  8. #include <limits>
  9. #include "base/check_op.h"
  10. namespace base {
  11. // static
  12. TimeDelta TimeDelta::FromTimeSpec(const timespec& ts) {
  13. return TimeDelta(ts.tv_sec * Time::kMicrosecondsPerSecond +
  14. ts.tv_nsec / Time::kNanosecondsPerMicrosecond);
  15. }
  16. struct timespec TimeDelta::ToTimeSpec() const {
  17. int64_t microseconds = InMicroseconds();
  18. time_t seconds = 0;
  19. if (microseconds >= Time::kMicrosecondsPerSecond) {
  20. seconds = static_cast<time_t>(InSeconds());
  21. microseconds -= seconds * Time::kMicrosecondsPerSecond;
  22. }
  23. struct timespec result = {
  24. seconds,
  25. static_cast<long>(microseconds * Time::kNanosecondsPerMicrosecond)};
  26. return result;
  27. }
  28. // static
  29. Time Time::FromTimeVal(struct timeval t) {
  30. DCHECK_LT(t.tv_usec, static_cast<int>(Time::kMicrosecondsPerSecond));
  31. DCHECK_GE(t.tv_usec, 0);
  32. if (t.tv_usec == 0 && t.tv_sec == 0)
  33. return Time();
  34. if (t.tv_usec == static_cast<suseconds_t>(Time::kMicrosecondsPerSecond) - 1 &&
  35. t.tv_sec == std::numeric_limits<time_t>::max())
  36. return Max();
  37. return Time((static_cast<int64_t>(t.tv_sec) * Time::kMicrosecondsPerSecond) +
  38. t.tv_usec + kTimeTToMicrosecondsOffset);
  39. }
  40. struct timeval Time::ToTimeVal() const {
  41. struct timeval result;
  42. if (is_null()) {
  43. result.tv_sec = 0;
  44. result.tv_usec = 0;
  45. return result;
  46. }
  47. if (is_max()) {
  48. result.tv_sec = std::numeric_limits<time_t>::max();
  49. result.tv_usec = static_cast<suseconds_t>(Time::kMicrosecondsPerSecond) - 1;
  50. return result;
  51. }
  52. int64_t us = us_ - kTimeTToMicrosecondsOffset;
  53. result.tv_sec = static_cast<time_t>(us / Time::kMicrosecondsPerSecond);
  54. result.tv_usec = us % Time::kMicrosecondsPerSecond;
  55. return result;
  56. }
  57. } // namespace base