1 // Copyright 2021 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 #ifndef BASE_TIME_TIME_DELTA_FROM_STRING_H_ 6 #define BASE_TIME_TIME_DELTA_FROM_STRING_H_ 7 8 #include <optional> 9 #include <string_view> 10 11 #include "base/base_export.h" 12 13 namespace base { 14 15 class TimeDelta; 16 17 // Helper function for TimeDelta. 18 // This is not part of TimeDelta to avoid dragging the includes above into 19 // base/time/time.h. 20 // 21 // Adapted from Go's doc at https://golang.org/pkg/time/#ParseDuration 22 // [ParseDuration] parses a duration string. A duration string is 23 // a possibly signed sequence of decimal numbers, each with optional 24 // fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". 25 // Valid time units are "ns", "us" "ms", "s", "m", "h", "d". 26 // 27 // Special values that are allowed without specifying units: 28 // "0", "+0", "-0" -> TimeDelta() 29 // "inf", "+inf" -> TimeDelta::Max() 30 // "-inf" -> TimeDelta::Min() 31 // Returns `std::nullopt` when parsing fails. Numbers larger than 2^63-1 32 // will fail parsing. Overflowing `number * unit` will return +/-inf, as 33 // appropriate. 34 BASE_EXPORT std::optional<TimeDelta> TimeDeltaFromString( 35 std::string_view duration_string); 36 37 } // namespace base 38 39 #endif // BASE_TIME_TIME_DELTA_FROM_STRING_H_ 40