// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/time/time_delta_from_string.h" #include <limits> #include <string_view> #include <utility> #include "base/strings/string_util.h" #include "base/time/time.h" namespace base { namespace { // Strips the |expected| prefix from the start of the given string, returning // |true| if the strip operation succeeded or false otherwise. // // Example: // // std::string_view input("abc"); // EXPECT_TRUE(ConsumePrefix(input, "a")); // EXPECT_EQ(input, "bc"); // // Adapted from absl::ConsumePrefix(): // https://cs.chromium.org/chromium/src/third_party/abseil-cpp/absl/strings/strip.h?l=45&rcl=2c22e9135f107a4319582ae52e2e3e6b201b6b7c bool ConsumePrefix(std::string_view& str, std::string_view expected) { … } // Utility struct used by ConsumeDurationNumber() to parse decimal numbers. // A ParsedDecimal represents the number `int_part` + `frac_part`/`frac_scale`, // where: // (i) 0 <= `frac_part` < `frac_scale` (implies `frac_part`/`frac_scale` < 1) // (ii) `frac_scale` is 10^[number of digits after the decimal point] // // Example: // -42 => {.int_part = -42, .frac_part = 0, .frac_scale = 1} // 1.23 => {.int_part = 1, .frac_part = 23, .frac_scale = 100} struct ParsedDecimal { … }; // A helper for FromString() that tries to parse a leading number from the given // std::string_view. |number_string| is modified to start from the first // unconsumed char. // // Adapted from absl: // https://cs.chromium.org/chromium/src/third_party/abseil-cpp/absl/time/duration.cc?l=807&rcl=2c22e9135f107a4319582ae52e2e3e6b201b6b7c constexpr std::optional<ParsedDecimal> ConsumeDurationNumber( std::string_view& number_string) { … } // A helper for FromString() that tries to parse a leading unit designator // (e.g., ns, us, ms, s, m, h, d) from the given std::string_view. |unit_string| // is modified to start from the first unconsumed char. // // Adapted from absl: // https://cs.chromium.org/chromium/src/third_party/abseil-cpp/absl/time/duration.cc?l=841&rcl=2c22e9135f107a4319582ae52e2e3e6b201b6b7c std::optional<TimeDelta> ConsumeDurationUnit(std::string_view& unit_string) { … } } // namespace std::optional<TimeDelta> TimeDeltaFromString(std::string_view duration_string) { … } } // namespace base