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