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 5 #include "quiche/quic/core/quic_time.h" 6 7 #include <cinttypes> 8 #include <cstdlib> 9 #include <limits> 10 #include <string> 11 12 #include "absl/strings/str_cat.h" 13 14 namespace quic { 15 ToDebuggingValue() const16std::string QuicTime::Delta::ToDebuggingValue() const { 17 constexpr int64_t kMillisecondInMicroseconds = 1000; 18 constexpr int64_t kSecondInMicroseconds = 1000 * kMillisecondInMicroseconds; 19 20 int64_t absolute_value = std::abs(time_offset_); 21 22 // For debugging purposes, always display the value with the highest precision 23 // available. 24 if (absolute_value >= kSecondInMicroseconds && 25 absolute_value % kSecondInMicroseconds == 0) { 26 return absl::StrCat(time_offset_ / kSecondInMicroseconds, "s"); 27 } 28 if (absolute_value >= kMillisecondInMicroseconds && 29 absolute_value % kMillisecondInMicroseconds == 0) { 30 return absl::StrCat(time_offset_ / kMillisecondInMicroseconds, "ms"); 31 } 32 return absl::StrCat(time_offset_, "us"); 33 } 34 ToUNIXSeconds() const35uint64_t QuicWallTime::ToUNIXSeconds() const { return microseconds_ / 1000000; } 36 ToUNIXMicroseconds() const37uint64_t QuicWallTime::ToUNIXMicroseconds() const { return microseconds_; } 38 IsAfter(QuicWallTime other) const39bool QuicWallTime::IsAfter(QuicWallTime other) const { 40 return microseconds_ > other.microseconds_; 41 } 42 IsBefore(QuicWallTime other) const43bool QuicWallTime::IsBefore(QuicWallTime other) const { 44 return microseconds_ < other.microseconds_; 45 } 46 IsZero() const47bool QuicWallTime::IsZero() const { return microseconds_ == 0; } 48 AbsoluteDifference(QuicWallTime other) const49QuicTime::Delta QuicWallTime::AbsoluteDifference(QuicWallTime other) const { 50 uint64_t d; 51 52 if (microseconds_ > other.microseconds_) { 53 d = microseconds_ - other.microseconds_; 54 } else { 55 d = other.microseconds_ - microseconds_; 56 } 57 58 if (d > static_cast<uint64_t>(std::numeric_limits<int64_t>::max())) { 59 d = std::numeric_limits<int64_t>::max(); 60 } 61 return QuicTime::Delta::FromMicroseconds(d); 62 } 63 Add(QuicTime::Delta delta) const64QuicWallTime QuicWallTime::Add(QuicTime::Delta delta) const { 65 uint64_t microseconds = microseconds_ + delta.ToMicroseconds(); 66 if (microseconds < microseconds_) { 67 microseconds = std::numeric_limits<uint64_t>::max(); 68 } 69 return QuicWallTime(microseconds); 70 } 71 72 // TODO(ianswett) Test this. Subtract(QuicTime::Delta delta) const73QuicWallTime QuicWallTime::Subtract(QuicTime::Delta delta) const { 74 uint64_t microseconds = microseconds_ - delta.ToMicroseconds(); 75 if (microseconds > microseconds_) { 76 microseconds = 0; 77 } 78 return QuicWallTime(microseconds); 79 } 80 81 } // namespace quic 82