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 "partition_alloc/partition_alloc_base/time/time.h" 6 7 #include <stdint.h> 8 #include <sys/time.h> 9 #include <time.h> 10 11 #include <limits> 12 13 #include "partition_alloc/partition_alloc_base/check.h" 14 15 namespace partition_alloc::internal::base { 16 17 // static FromTimeSpec(const timespec & ts)18TimeDelta TimeDelta::FromTimeSpec(const timespec& ts) { 19 return TimeDelta(ts.tv_sec * Time::kMicrosecondsPerSecond + 20 ts.tv_nsec / Time::kNanosecondsPerMicrosecond); 21 } 22 ToTimeSpec() const23struct timespec TimeDelta::ToTimeSpec() const { 24 int64_t microseconds = InMicroseconds(); 25 time_t seconds = 0; 26 if (microseconds >= Time::kMicrosecondsPerSecond) { 27 seconds = InSeconds(); 28 microseconds -= seconds * Time::kMicrosecondsPerSecond; 29 } 30 struct timespec result = { 31 seconds, 32 static_cast<long>(microseconds * Time::kNanosecondsPerMicrosecond)}; 33 return result; 34 } 35 36 // static FromTimeVal(struct timeval t)37Time Time::FromTimeVal(struct timeval t) { 38 PA_BASE_DCHECK(t.tv_usec < static_cast<int>(Time::kMicrosecondsPerSecond)); 39 PA_BASE_DCHECK(t.tv_usec >= 0); 40 if (t.tv_usec == 0 && t.tv_sec == 0) { 41 return Time(); 42 } 43 if (t.tv_usec == static_cast<suseconds_t>(Time::kMicrosecondsPerSecond) - 1 && 44 t.tv_sec == std::numeric_limits<time_t>::max()) { 45 return Max(); 46 } 47 return Time((static_cast<int64_t>(t.tv_sec) * Time::kMicrosecondsPerSecond) + 48 t.tv_usec + kTimeTToMicrosecondsOffset); 49 } 50 ToTimeVal() const51struct timeval Time::ToTimeVal() const { 52 struct timeval result; 53 if (is_null()) { 54 result.tv_sec = 0; 55 result.tv_usec = 0; 56 return result; 57 } 58 if (is_max()) { 59 result.tv_sec = std::numeric_limits<time_t>::max(); 60 result.tv_usec = static_cast<suseconds_t>(Time::kMicrosecondsPerSecond) - 1; 61 return result; 62 } 63 int64_t us = us_ - kTimeTToMicrosecondsOffset; 64 result.tv_sec = us / Time::kMicrosecondsPerSecond; 65 result.tv_usec = us % Time::kMicrosecondsPerSecond; 66 return result; 67 } 68 69 } // namespace partition_alloc::internal::base 70