Remove some base C++ wrappers. In particular: arraysize -> std::size base::data -> std::data base::is_trivially_copyable -> std::is_trivially_copyable base::nullopt -> std::nullopt base::optional -> std::optional base::size -> std::size base::void_t -> std::void_t Also some unused template classes and macros were removed. Change-Id: I55cb4ea610c80125d658c3f7b695215860d32d54 Reviewed-on: https://gn-review.googlesource.com/c/gn/+/6081 Reviewed-by: Scott Graham <scottmg@chromium.org> Commit-Queue: Brett Wilson <brettw@chromium.org>
diff --git a/base/bind_internal.h b/base/bind_internal.h index 510fcea..89c1600 100644 --- a/base/bind_internal.h +++ b/base/bind_internal.h
@@ -321,7 +321,7 @@ struct IsCallableObject : std::false_type {}; template <typename Callable> -struct IsCallableObject<Callable, void_t<decltype(&Callable::operator())>> +struct IsCallableObject<Callable, std::void_t<decltype(&Callable::operator())>> : std::true_type {}; // HasRefCountedTypeAsRawPtr selects true_type when any of the |Args| is a raw
diff --git a/base/command_line.cc b/base/command_line.cc index d6695a3..93e48cc 100644 --- a/base/command_line.cc +++ b/base/command_line.cc
@@ -5,6 +5,7 @@ #include "base/command_line.h" #include <algorithm> +#include <iterator> #include <ostream> #include <string_view> @@ -44,7 +45,7 @@ // Unixes don't use slash as a switch. const CommandLine::CharType* const kSwitchPrefixes[] = {"--", "-"}; #endif -size_t switch_prefix_count = arraysize(kSwitchPrefixes); +size_t switch_prefix_count = std::size(kSwitchPrefixes); size_t GetSwitchPrefixLength(const CommandLine::StringType& string) { for (size_t i = 0; i < switch_prefix_count; ++i) { @@ -186,9 +187,9 @@ // static void CommandLine::set_slash_is_not_a_switch() { // The last switch prefix should be slash, so adjust the size to skip it. - DCHECK(std::u16string_view(kSwitchPrefixes[arraysize(kSwitchPrefixes) - 1]) == + DCHECK(std::u16string_view(kSwitchPrefixes[std::size(kSwitchPrefixes) - 1]) == std::u16string_view(u"/")); - switch_prefix_count = arraysize(kSwitchPrefixes) - 1; + switch_prefix_count = std::size(kSwitchPrefixes) - 1; } // static
diff --git a/base/containers/flat_tree.h b/base/containers/flat_tree.h index 7856e24..65afe58 100644 --- a/base/containers/flat_tree.h +++ b/base/containers/flat_tree.h
@@ -62,7 +62,7 @@ template <typename T, typename = void> struct IsTransparentCompare : std::false_type {}; template <typename T> -struct IsTransparentCompare<T, void_t<typename T::is_transparent>> +struct IsTransparentCompare<T, std::void_t<typename T::is_transparent>> : std::true_type {}; // Implementation -------------------------------------------------------------
diff --git a/base/containers/span.h b/base/containers/span.h index 20c7f15..29c9a97 100644 --- a/base/containers/span.h +++ b/base/containers/span.h
@@ -52,12 +52,12 @@ template <typename Container, typename T> using ContainerHasConvertibleData = IsLegalDataConversion< - std::remove_pointer_t<decltype(base::data(std::declval<Container>()))>, + std::remove_pointer_t<decltype(std::data(std::declval<Container>()))>, T>; template <typename Container> using ContainerHasIntegralSize = - std::is_integral<decltype(base::size(std::declval<Container>()))>; + std::is_integral<decltype(std::size(std::declval<Container>()))>; template <typename From, size_t FromExtent, typename To, size_t ToExtent> using EnableIfLegalSpanConversion = @@ -200,14 +200,14 @@ template < size_t N, typename = internal::EnableIfSpanCompatibleArray<T (&)[N], N, T, Extent>> - constexpr span(T (&array)[N]) noexcept : span(base::data(array), N) {} + constexpr span(T (&array)[N]) noexcept : span(std::data(array), N) {} template < size_t N, typename = internal:: EnableIfSpanCompatibleArray<std::array<value_type, N>&, N, T, Extent>> constexpr span(std::array<value_type, N>& array) noexcept - : span(base::data(array), N) {} + : span(std::data(array), N) {} template <size_t N, typename = internal::EnableIfSpanCompatibleArray< @@ -216,20 +216,20 @@ T, Extent>> constexpr span(const std::array<value_type, N>& array) noexcept - : span(base::data(array), N) {} + : span(std::data(array), N) {} - // Conversion from a container that has compatible base::data() and integral - // base::size(). + // Conversion from a container that has compatible std::data() and integral + // std::size(). template <typename Container, typename = internal::EnableIfSpanCompatibleContainer<Container&, T>> constexpr span(Container& container) noexcept - : span(base::data(container), base::size(container)) {} + : span(std::data(container), std::size(container)) {} template < typename Container, typename = internal::EnableIfSpanCompatibleContainer<const Container&, T>> span(const Container& container) noexcept - : span(base::data(container), base::size(container)) {} + : span(std::data(container), std::size(container)) {} constexpr span(const span& other) noexcept = default;
diff --git a/base/containers/vector_buffer.h b/base/containers/vector_buffer.h index d40438d..7447126 100644 --- a/base/containers/vector_buffer.h +++ b/base/containers/vector_buffer.h
@@ -105,7 +105,7 @@ // Trivially copyable types can use memcpy. trivially copyable implies // that there is a trivial destructor as we don't have to call it. template <typename T2 = T, - typename std::enable_if<base::is_trivially_copyable<T2>::value, + typename std::enable_if<std::is_trivially_copyable<T2>::value, int>::type = 0> static void MoveRange(T* from_begin, T* from_end, T* to) { DCHECK(!RangesOverlap(from_begin, from_end, to)); @@ -116,7 +116,7 @@ // destruct the original. template <typename T2 = T, typename std::enable_if<std::is_move_constructible<T2>::value && - !base::is_trivially_copyable<T2>::value, + !std::is_trivially_copyable<T2>::value, int>::type = 0> static void MoveRange(T* from_begin, T* from_end, T* to) { DCHECK(!RangesOverlap(from_begin, from_end, to)); @@ -132,7 +132,7 @@ // destruct the original. template <typename T2 = T, typename std::enable_if<!std::is_move_constructible<T2>::value && - !base::is_trivially_copyable<T2>::value, + !std::is_trivially_copyable<T2>::value, int>::type = 0> static void MoveRange(T* from_begin, T* from_end, T* to) { DCHECK(!RangesOverlap(from_begin, from_end, to));
diff --git a/base/files/file_path.cc b/base/files/file_path.cc index e546761..4e98653 100644 --- a/base/files/file_path.cc +++ b/base/files/file_path.cc
@@ -7,6 +7,7 @@ #include <string.h> #include <algorithm> +#include <iterator> #include <string_view> #include "base/logging.h" @@ -134,14 +135,14 @@ return last_dot; } - for (size_t i = 0; i < arraysize(kCommonDoubleExtensions); ++i) { + for (size_t i = 0; i < std::size(kCommonDoubleExtensions); ++i) { StringType extension(path, penultimate_dot + 1); if (LowerCaseEqualsASCII(extension, kCommonDoubleExtensions[i])) return penultimate_dot; } StringType extension(path, last_dot + 1); - for (size_t i = 0; i < arraysize(kCommonDoubleExtensionSuffixes); ++i) { + for (size_t i = 0; i < std::size(kCommonDoubleExtensionSuffixes); ++i) { if (LowerCaseEqualsASCII(extension, kCommonDoubleExtensionSuffixes[i])) { if ((last_dot - penultimate_dot) <= 5U && (last_dot - penultimate_dot) > 1U) {
diff --git a/base/files/file_path.h b/base/files/file_path.h index 74fb674..b136670 100644 --- a/base/files/file_path.h +++ b/base/files/file_path.h
@@ -160,7 +160,7 @@ // when composing pathnames. static const CharType kSeparators[]; - // arraysize(kSeparators). + // std::size(kSeparators). static const size_t kSeparatorsLength; // A special path component meaning "this directory."
diff --git a/base/files/file_path_constants.cc b/base/files/file_path_constants.cc index fc7d663..9ae0388 100644 --- a/base/files/file_path_constants.cc +++ b/base/files/file_path_constants.cc
@@ -4,6 +4,8 @@ #include <stddef.h> +#include <iterator> + #include "base/files/file_path.h" #include "base/macros.h" @@ -15,7 +17,7 @@ const FilePath::CharType FilePath::kSeparators[] = FILE_PATH_LITERAL("/"); #endif // FILE_PATH_USES_WIN_SEPARATORS -const size_t FilePath::kSeparatorsLength = arraysize(kSeparators); +const size_t FilePath::kSeparatorsLength = std::size(kSeparators); const FilePath::CharType FilePath::kCurrentDirectory[] = FILE_PATH_LITERAL("."); const FilePath::CharType FilePath::kParentDirectory[] = FILE_PATH_LITERAL("..");
diff --git a/base/files/file_util_posix.cc b/base/files/file_util_posix.cc index a5822f1..3306004 100644 --- a/base/files/file_util_posix.cc +++ b/base/files/file_util_posix.cc
@@ -21,6 +21,8 @@ #include <time.h> #include <unistd.h> +#include <iterator> + #include "base/command_line.h" #include "base/containers/stack.h" #include "base/environment.h" @@ -344,7 +346,7 @@ DCHECK(!symlink_path.empty()); DCHECK(target_path); char buf[PATH_MAX]; - ssize_t count = ::readlink(symlink_path.value().c_str(), buf, arraysize(buf)); + ssize_t count = ::readlink(symlink_path.value().c_str(), buf, std::size(buf)); if (count <= 0) { target_path->clear(); @@ -714,7 +716,7 @@ const char* const kAdminGroupNames[] = {"admin", "wheel"}; std::set<gid_t> allowed_group_ids; - for (int i = 0, ie = arraysize(kAdminGroupNames); i < ie; ++i) { + for (int i = 0, ie = std::size(kAdminGroupNames); i < ie; ++i) { struct group* group_record = getgrnam(kAdminGroupNames[i]); if (!group_record) { DPLOG(ERROR) << "Could not get the group ID of group \""
diff --git a/base/files/file_util_win.cc b/base/files/file_util_win.cc index 3863f72..1556d26 100644 --- a/base/files/file_util_win.cc +++ b/base/files/file_util_win.cc
@@ -16,6 +16,7 @@ #include <winsock2.h> #include <algorithm> +#include <iterator> #include <limits> #include <string> #include <string_view> @@ -676,7 +677,7 @@ int GetMaximumPathComponentLength(const FilePath& path) { char16_t volume_path[MAX_PATH]; if (!GetVolumePathNameW(ToWCharT(&path.NormalizePathSeparators().value()), - ToWCharT(volume_path), arraysize(volume_path))) { + ToWCharT(volume_path), std::size(volume_path))) { return -1; }
diff --git a/base/json/json_parser.cc b/base/json/json_parser.cc index eac52a6..df02829 100644 --- a/base/json/json_parser.cc +++ b/base/json/json_parser.cc
@@ -68,7 +68,7 @@ JSONParser::~JSONParser() = default; -Optional<Value> JSONParser::Parse(std::string_view input) { +std::optional<Value> JSONParser::Parse(std::string_view input) { input_ = input; index_ = 0; line_number_ = 1; @@ -82,7 +82,7 @@ // that the index_ will not overflow when parsing. if (!base::IsValueInRangeForNumericType<int32_t>(input.length())) { ReportError(JSONReader::JSON_TOO_LARGE, 0); - return nullopt; + return std::nullopt; } // When the input JSON string starts with a UTF-8 Byte-Order-Mark, @@ -91,14 +91,14 @@ ConsumeIfMatch("\xEF\xBB\xBF"); // Parse the first and any nested tokens. - Optional<Value> root(ParseNextToken()); + std::optional<Value> root(ParseNextToken()); if (!root) - return nullopt; + return std::nullopt; // Make sure the input stream is at an end. if (GetNextToken() != T_END_OF_INPUT) { ReportError(JSONReader::JSON_UNEXPECTED_DATA_AFTER_ROOT, 1); - return nullopt; + return std::nullopt; } return root; @@ -163,33 +163,33 @@ // JSONParser private ////////////////////////////////////////////////////////// -Optional<std::string_view> JSONParser::PeekChars(int count) { +std::optional<std::string_view> JSONParser::PeekChars(int count) { if (static_cast<size_t>(index_) + count > input_.length()) - return nullopt; + return std::nullopt; // Using std::string_view::substr() is significantly slower (according to // base_perftests) than constructing a substring manually. return std::string_view(input_.data() + index_, count); } -Optional<char> JSONParser::PeekChar() { - Optional<std::string_view> chars = PeekChars(1); +std::optional<char> JSONParser::PeekChar() { + std::optional<std::string_view> chars = PeekChars(1); if (chars) return (*chars)[0]; - return nullopt; + return std::nullopt; } -Optional<std::string_view> JSONParser::ConsumeChars(int count) { - Optional<std::string_view> chars = PeekChars(count); +std::optional<std::string_view> JSONParser::ConsumeChars(int count) { + std::optional<std::string_view> chars = PeekChars(count); if (chars) index_ += count; return chars; } -Optional<char> JSONParser::ConsumeChar() { - Optional<std::string_view> chars = ConsumeChars(1); +std::optional<char> JSONParser::ConsumeChar() { + std::optional<std::string_view> chars = ConsumeChars(1); if (chars) return (*chars)[0]; - return nullopt; + return std::nullopt; } const char* JSONParser::pos() { @@ -200,7 +200,7 @@ JSONParser::Token JSONParser::GetNextToken() { EatWhitespaceAndComments(); - Optional<char> c = PeekChar(); + std::optional<char> c = PeekChar(); if (!c) return T_END_OF_INPUT; @@ -243,7 +243,7 @@ } void JSONParser::EatWhitespaceAndComments() { - while (Optional<char> c = PeekChar()) { + while (std::optional<char> c = PeekChar()) { switch (*c) { case '\r': case '\n': @@ -268,13 +268,13 @@ } bool JSONParser::EatComment() { - Optional<std::string_view> comment_start = ConsumeChars(2); + std::optional<std::string_view> comment_start = ConsumeChars(2); if (!comment_start) return false; if (comment_start == "//") { // Single line comment, read to newline. - while (Optional<char> c = PeekChar()) { + while (std::optional<char> c = PeekChar()) { if (c == '\n' || c == '\r') return true; ConsumeChar(); @@ -282,7 +282,7 @@ } else if (comment_start == "/*") { char previous_char = '\0'; // Block comment, read until end marker. - while (Optional<char> c = PeekChar()) { + while (std::optional<char> c = PeekChar()) { if (previous_char == '*' && c == '/') { // EatWhitespaceAndComments will inspect pos(), which will still be on // the last / of the comment, so advance once more (which may also be @@ -299,11 +299,11 @@ return false; } -Optional<Value> JSONParser::ParseNextToken() { +std::optional<Value> JSONParser::ParseNextToken() { return ParseToken(GetNextToken()); } -Optional<Value> JSONParser::ParseToken(Token token) { +std::optional<Value> JSONParser::ParseToken(Token token) { switch (token) { case T_OBJECT_BEGIN: return ConsumeDictionary(); @@ -319,20 +319,20 @@ return ConsumeLiteral(); default: ReportError(JSONReader::JSON_UNEXPECTED_TOKEN, 1); - return nullopt; + return std::nullopt; } } -Optional<Value> JSONParser::ConsumeDictionary() { +std::optional<Value> JSONParser::ConsumeDictionary() { if (ConsumeChar() != '{') { ReportError(JSONReader::JSON_UNEXPECTED_TOKEN, 1); - return nullopt; + return std::nullopt; } StackMarker depth_check(max_depth_, &stack_depth_); if (depth_check.IsTooDeep()) { ReportError(JSONReader::JSON_TOO_MUCH_NESTING, 0); - return nullopt; + return std::nullopt; } std::vector<Value::DictStorage::value_type> dict_storage; @@ -341,28 +341,28 @@ while (token != T_OBJECT_END) { if (token != T_STRING) { ReportError(JSONReader::JSON_UNQUOTED_DICTIONARY_KEY, 1); - return nullopt; + return std::nullopt; } // First consume the key. StringBuilder key; if (!ConsumeStringRaw(&key)) { - return nullopt; + return std::nullopt; } // Read the separator. token = GetNextToken(); if (token != T_OBJECT_PAIR_SEPARATOR) { ReportError(JSONReader::JSON_SYNTAX_ERROR, 1); - return nullopt; + return std::nullopt; } // The next token is the value. Ownership transfers to |dict|. ConsumeChar(); - Optional<Value> value = ParseNextToken(); + std::optional<Value> value = ParseNextToken(); if (!value) { // ReportError from deeper level. - return nullopt; + return std::nullopt; } dict_storage.emplace_back(key.DestructiveAsString(), @@ -374,11 +374,11 @@ token = GetNextToken(); if (token == T_OBJECT_END && !(options_ & JSON_ALLOW_TRAILING_COMMAS)) { ReportError(JSONReader::JSON_TRAILING_COMMA, 1); - return nullopt; + return std::nullopt; } } else if (token != T_OBJECT_END) { ReportError(JSONReader::JSON_SYNTAX_ERROR, 0); - return nullopt; + return std::nullopt; } } @@ -387,26 +387,26 @@ return Value(Value::DictStorage(std::move(dict_storage), KEEP_LAST_OF_DUPES)); } -Optional<Value> JSONParser::ConsumeList() { +std::optional<Value> JSONParser::ConsumeList() { if (ConsumeChar() != '[') { ReportError(JSONReader::JSON_UNEXPECTED_TOKEN, 1); - return nullopt; + return std::nullopt; } StackMarker depth_check(max_depth_, &stack_depth_); if (depth_check.IsTooDeep()) { ReportError(JSONReader::JSON_TOO_MUCH_NESTING, 0); - return nullopt; + return std::nullopt; } Value::ListStorage list_storage; Token token = GetNextToken(); while (token != T_ARRAY_END) { - Optional<Value> item = ParseToken(token); + std::optional<Value> item = ParseToken(token); if (!item) { // ReportError from deeper level. - return nullopt; + return std::nullopt; } list_storage.push_back(std::move(*item)); @@ -417,11 +417,11 @@ token = GetNextToken(); if (token == T_ARRAY_END && !(options_ & JSON_ALLOW_TRAILING_COMMAS)) { ReportError(JSONReader::JSON_TRAILING_COMMA, 1); - return nullopt; + return std::nullopt; } } else if (token != T_ARRAY_END) { ReportError(JSONReader::JSON_SYNTAX_ERROR, 1); - return nullopt; + return std::nullopt; } } @@ -430,10 +430,10 @@ return Value(std::move(list_storage)); } -Optional<Value> JSONParser::ConsumeString() { +std::optional<Value> JSONParser::ConsumeString() { StringBuilder string; if (!ConsumeStringRaw(&string)) - return nullopt; + return std::nullopt; return Value(string.DestructiveAsString()); } @@ -480,7 +480,7 @@ string.Convert(); // Read past the escape '\' and ensure there's a character following. - Optional<std::string_view> escape_sequence = ConsumeChars(2); + std::optional<std::string_view> escape_sequence = ConsumeChars(2); if (!escape_sequence) { ReportError(JSONReader::JSON_INVALID_ESCAPE, 0); return false; @@ -558,7 +558,7 @@ // Entry is at the first X in \uXXXX. bool JSONParser::DecodeUTF16(uint32_t* out_code_point) { - Optional<std::string_view> escape_sequence = ConsumeChars(4); + std::optional<std::string_view> escape_sequence = ConsumeChars(4); if (!escape_sequence) return false; @@ -614,7 +614,7 @@ return true; } -Optional<Value> JSONParser::ConsumeNumber() { +std::optional<Value> JSONParser::ConsumeNumber() { const char* num_start = pos(); const int start_index = index_; int end_index = start_index; @@ -624,7 +624,7 @@ if (!ReadInt(false)) { ReportError(JSONReader::JSON_SYNTAX_ERROR, 1); - return nullopt; + return std::nullopt; } end_index = index_; @@ -633,13 +633,13 @@ ConsumeChar(); if (!ReadInt(true)) { ReportError(JSONReader::JSON_SYNTAX_ERROR, 1); - return nullopt; + return std::nullopt; } end_index = index_; } // Optional exponent part. - Optional<char> c = PeekChar(); + std::optional<char> c = PeekChar(); if (c == 'e' || c == 'E') { ConsumeChar(); if (PeekChar() == '-' || PeekChar() == '+') { @@ -647,7 +647,7 @@ } if (!ReadInt(true)) { ReportError(JSONReader::JSON_SYNTAX_ERROR, 1); - return nullopt; + return std::nullopt; } end_index = index_; } @@ -666,7 +666,7 @@ break; default: ReportError(JSONReader::JSON_SYNTAX_ERROR, 1); - return nullopt; + return std::nullopt; } index_ = exit_index; @@ -677,14 +677,14 @@ if (StringToInt(num_string, &num_int)) return Value(num_int); - return nullopt; + return std::nullopt; } bool JSONParser::ReadInt(bool allow_leading_zeros) { size_t len = 0; char first = 0; - while (Optional<char> c = PeekChar()) { + while (std::optional<char> c = PeekChar()) { if (!IsAsciiDigit(c)) break; @@ -704,7 +704,7 @@ return true; } -Optional<Value> JSONParser::ConsumeLiteral() { +std::optional<Value> JSONParser::ConsumeLiteral() { if (ConsumeIfMatch("true")) { return Value(true); } else if (ConsumeIfMatch("false")) { @@ -713,7 +713,7 @@ return Value(Value::Type::NONE); } else { ReportError(JSONReader::JSON_SYNTAX_ERROR, 1); - return nullopt; + return std::nullopt; } }
diff --git a/base/json/json_parser.h b/base/json/json_parser.h index 6bd61a4..0ba1d9d 100644 --- a/base/json/json_parser.h +++ b/base/json/json_parser.h
@@ -9,6 +9,7 @@ #include <stdint.h> #include <memory> +#include <optional> #include <string> #include <string_view> @@ -16,7 +17,6 @@ #include "base/gtest_prod_util.h" #include "base/json/json_reader.h" #include "base/macros.h" -#include "base/optional.h" namespace base { @@ -49,7 +49,7 @@ // result as a Value. // Wrap this in base::FooValue::From() to check the Value is of type Foo and // convert to a FooValue at the same time. - Optional<Value> Parse(std::string_view input); + std::optional<Value> Parse(std::string_view input); // Returns the error code. JSONReader::JsonParseError error_code() const; @@ -123,22 +123,22 @@ // The copied string representation. Will be unset until Convert() is // called. - base::Optional<std::string> string_; + std::optional<std::string> string_; }; // Returns the next |count| bytes of the input stream, or nullopt if fewer // than |count| bytes remain. - Optional<std::string_view> PeekChars(int count); + std::optional<std::string_view> PeekChars(int count); // Calls PeekChars() with a |count| of 1. - Optional<char> PeekChar(); + std::optional<char> PeekChar(); // Returns the next |count| bytes of the input stream, or nullopt if fewer // than |count| bytes remain, and advances the parser position by |count|. - Optional<std::string_view> ConsumeChars(int count); + std::optional<std::string_view> ConsumeChars(int count); // Calls ConsumeChars() with a |count| of 1. - Optional<char> ConsumeChar(); + std::optional<char> ConsumeChar(); // Returns a pointer to the current character position. const char* pos(); @@ -155,22 +155,22 @@ bool EatComment(); // Calls GetNextToken() and then ParseToken(). - Optional<Value> ParseNextToken(); + std::optional<Value> ParseNextToken(); // Takes a token that represents the start of a Value ("a structural token" // in RFC terms) and consumes it, returning the result as a Value. - Optional<Value> ParseToken(Token token); + std::optional<Value> ParseToken(Token token); // Assuming that the parser is currently wound to '{', this parses a JSON // object into a Value. - Optional<Value> ConsumeDictionary(); + std::optional<Value> ConsumeDictionary(); // Assuming that the parser is wound to '[', this parses a JSON list into a // Value. - Optional<Value> ConsumeList(); + std::optional<Value> ConsumeList(); // Calls through ConsumeStringRaw and wraps it in a value. - Optional<Value> ConsumeString(); + std::optional<Value> ConsumeString(); // Assuming that the parser is wound to a double quote, this parses a string, // decoding any escape sequences and converts UTF-16 to UTF-8. Returns true on @@ -185,14 +185,14 @@ // Assuming that the parser is wound to the start of a valid JSON number, // this parses and converts it to either an int or double value. - Optional<Value> ConsumeNumber(); + std::optional<Value> ConsumeNumber(); // Helper that reads characters that are ints. Returns true if a number was // read and false on error. bool ReadInt(bool allow_leading_zeros); // Consumes the literal values of |true|, |false|, and |null|, assuming the // parser is wound to the first character of any of those. - Optional<Value> ConsumeLiteral(); + std::optional<Value> ConsumeLiteral(); // Helper function that returns true if the byte squence |match| can be // consumed at the current parser position. Returns false if there are fewer
diff --git a/base/json/json_reader.cc b/base/json/json_reader.cc index d7eb7d9..7b5b8eb 100644 --- a/base/json/json_reader.cc +++ b/base/json/json_reader.cc
@@ -9,7 +9,6 @@ #include "base/json/json_parser.h" #include "base/logging.h" -#include "base/optional.h" #include "base/values.h" namespace base { @@ -45,7 +44,7 @@ int options, int max_depth) { internal::JSONParser parser(options, max_depth); - Optional<Value> root = parser.Parse(json); + std::optional<Value> root = parser.Parse(json); return root ? std::make_unique<Value>(std::move(*root)) : nullptr; } @@ -58,7 +57,7 @@ int* error_line_out, int* error_column_out) { internal::JSONParser parser(options); - Optional<Value> root = parser.Parse(json); + std::optional<Value> root = parser.Parse(json); if (!root) { if (error_code_out) *error_code_out = parser.error_code(); @@ -104,7 +103,7 @@ } std::unique_ptr<Value> JSONReader::ReadToValue(std::string_view json) { - Optional<Value> value = parser_->Parse(json); + std::optional<Value> value = parser_->Parse(json); return value ? std::make_unique<Value>(std::move(*value)) : nullptr; }
diff --git a/base/logging.cc b/base/logging.cc index 16449ee..11cef81 100644 --- a/base/logging.cc +++ b/base/logging.cc
@@ -7,6 +7,7 @@ #include <limits.h> #include <stdint.h> +#include <iterator> #include <thread> #include "base/macros.h" @@ -61,7 +62,7 @@ namespace { const char* const log_severity_names[] = {"INFO", "WARNING", "ERROR", "FATAL"}; -static_assert(LOG_NUM_SEVERITIES == arraysize(log_severity_names), +static_assert(LOG_NUM_SEVERITIES == std::size(log_severity_names), "Incorrect number of log_severity_names"); const char* log_severity_name(int severity) { @@ -250,7 +251,7 @@ char msgbuf[kErrorMessageBufferSize]; DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf, - arraysize(msgbuf), nullptr); + std::size(msgbuf), nullptr); if (len) { // Messages returned by system end with line breaks. return base::CollapseWhitespaceASCII(msgbuf, true) +
diff --git a/base/macros.h b/base/macros.h index 321f65b..750d54d 100644 --- a/base/macros.h +++ b/base/macros.h
@@ -10,8 +10,6 @@ #ifndef BASE_MACROS_H_ #define BASE_MACROS_H_ -#include <stddef.h> // For size_t. - // Distinguish mips32. #if defined(__mips__) && (_MIPS_SIM == _ABIO32) && !defined(__mips32__) #define __mips32__ @@ -40,22 +38,6 @@ TypeName() = delete; \ DISALLOW_COPY_AND_ASSIGN(TypeName) -// The arraysize(arr) macro returns the # of elements in an array arr. The -// expression is a compile-time constant, and therefore can be used in defining -// new arrays, for example. If you use arraysize on a pointer by mistake, you -// will get a compile-time error. For the technical details, refer to -// http://blogs.msdn.com/b/the1/archive/2004/05/07/128242.aspx. - -// This template function declaration is used in defining arraysize. -// Note that the function doesn't need an implementation, as we only -// use its type. -// -// DEPRECATED, please use base::size(array) instead. -// TODO(https://crbug.com/837308): Replace existing arraysize usages. -template <typename T, size_t N> -char (&ArraySizeHelper(T (&array)[N]))[N]; -#define arraysize(array) (sizeof(ArraySizeHelper(array))) - // Used to explicitly mark the return value of a function as unused. If you are // really sure you don't want to do anything with the return value of a function // that has been marked WARN_UNUSED_RESULT, wrap it with this. Example: @@ -67,28 +49,4 @@ template <typename T> inline void ignore_result(const T&) {} -namespace base { - -// Use these to declare and define a static local variable (static T;) so that -// it is leaked so that its destructors are not called at exit. This is -// thread-safe. -// -// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! DEPRECATED !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -// Please don't use this macro. Use a function-local static of type -// base::NoDestructor<T> instead: -// -// Factory& Factory::GetInstance() { -// static base::NoDestructor<Factory> instance; -// return *instance; -// } -// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -#define CR_DEFINE_STATIC_LOCAL(type, name, arguments) \ - static type& name = *new type arguments - -// Workaround for MSVC, which expands __VA_ARGS__ as one macro argument. To -// work around this bug, wrap the entire expression in this macro... -#define CR_EXPAND_ARG(arg) arg - -} // namespace base - #endif // BASE_MACROS_H_
diff --git a/base/memory/raw_scoped_refptr_mismatch_checker.h b/base/memory/raw_scoped_refptr_mismatch_checker.h index ab8b2ab..4309849 100644 --- a/base/memory/raw_scoped_refptr_mismatch_checker.h +++ b/base/memory/raw_scoped_refptr_mismatch_checker.h
@@ -27,8 +27,8 @@ template <typename T> struct IsRefCountedType<T, - void_t<decltype(std::declval<T*>()->AddRef()), - decltype(std::declval<T*>()->Release())>> + std::void_t<decltype(std::declval<T*>()->AddRef()), + decltype(std::declval<T*>()->Release())>> : std::true_type {}; template <typename T>
diff --git a/base/optional.h b/base/optional.h deleted file mode 100644 index 931305c..0000000 --- a/base/optional.h +++ /dev/null
@@ -1,922 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_OPTIONAL_H_ -#define BASE_OPTIONAL_H_ - -#include <type_traits> -#include <utility> - -#include "base/logging.h" -#include "base/template_util.h" - -namespace base { - -// Specification: -// http://en.cppreference.com/w/cpp/utility/optional/in_place_t -struct in_place_t {}; - -// Specification: -// http://en.cppreference.com/w/cpp/utility/optional/nullopt_t -struct nullopt_t { - constexpr explicit nullopt_t(int) {} -}; - -// Specification: -// http://en.cppreference.com/w/cpp/utility/optional/in_place -constexpr in_place_t in_place = {}; - -// Specification: -// http://en.cppreference.com/w/cpp/utility/optional/nullopt -constexpr nullopt_t nullopt(0); - -// Forward declaration, which is refered by following helpers. -template <typename T> -class Optional; - -namespace internal { - -template <typename T, bool = std::is_trivially_destructible<T>::value> -struct OptionalStorageBase { - // Initializing |empty_| here instead of using default member initializing - // to avoid errors in g++ 4.8. - constexpr OptionalStorageBase() : empty_('\0') {} - - template <class... Args> - constexpr explicit OptionalStorageBase(in_place_t, Args&&... args) - : is_populated_(true), value_(std::forward<Args>(args)...) {} - - // When T is not trivially destructible we must call its - // destructor before deallocating its memory. - // Note that this hides the (implicitly declared) move constructor, which - // would be used for constexpr move constructor in OptionalStorage<T>. - // It is needed iff T is trivially move constructible. However, the current - // is_trivially_{copy,move}_constructible implementation requires - // is_trivially_destructible (which looks a bug, cf: - // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=51452 and - // http://cplusplus.github.io/LWG/lwg-active.html#2116), so it is not - // necessary for this case at the moment. Please see also the destructor - // comment in "is_trivially_destructible = true" specialization below. - ~OptionalStorageBase() { - if (is_populated_) - value_.~T(); - } - - template <class... Args> - void Init(Args&&... args) { - DCHECK(!is_populated_); - ::new (&value_) T(std::forward<Args>(args)...); - is_populated_ = true; - } - - bool is_populated_ = false; - union { - // |empty_| exists so that the union will always be initialized, even when - // it doesn't contain a value. Union members must be initialized for the - // constructor to be 'constexpr'. - char empty_; - T value_; - }; -}; - -template <typename T> -struct OptionalStorageBase<T, true /* trivially destructible */> { - // Initializing |empty_| here instead of using default member initializing - // to avoid errors in g++ 4.8. - constexpr OptionalStorageBase() : empty_('\0') {} - - template <class... Args> - constexpr explicit OptionalStorageBase(in_place_t, Args&&... args) - : is_populated_(true), value_(std::forward<Args>(args)...) {} - - // When T is trivially destructible (i.e. its destructor does nothing) there - // is no need to call it. Implicitly defined destructor is trivial, because - // both members (bool and union containing only variants which are trivially - // destructible) are trivially destructible. - // Explicitly-defaulted destructor is also trivial, but do not use it here, - // because it hides the implicit move constructor. It is needed to implement - // constexpr move constructor in OptionalStorage iff T is trivially move - // constructible. Note that, if T is trivially move constructible, the move - // constructor of OptionalStorageBase<T> is also implicitly defined and it is - // trivially move constructor. If T is not trivially move constructible, - // "not declaring move constructor without destructor declaration" here means - // "delete move constructor", which works because any move constructor of - // OptionalStorage will not refer to it in that case. - - template <class... Args> - void Init(Args&&... args) { - DCHECK(!is_populated_); - ::new (&value_) T(std::forward<Args>(args)...); - is_populated_ = true; - } - - bool is_populated_ = false; - union { - // |empty_| exists so that the union will always be initialized, even when - // it doesn't contain a value. Union members must be initialized for the - // constructor to be 'constexpr'. - char empty_; - T value_; - }; -}; - -// Implement conditional constexpr copy and move constructors. These are -// constexpr if is_trivially_{copy,move}_constructible<T>::value is true -// respectively. If each is true, the corresponding constructor is defined as -// "= default;", which generates a constexpr constructor (In this case, -// the condition of constexpr-ness is satisfied because the base class also has -// compiler generated constexpr {copy,move} constructors). Note that -// placement-new is prohibited in constexpr. -template <typename T, - bool = is_trivially_copy_constructible<T>::value, - bool = std::is_trivially_move_constructible<T>::value> -struct OptionalStorage : OptionalStorageBase<T> { - // This is no trivially {copy,move} constructible case. Other cases are - // defined below as specializations. - - // Accessing the members of template base class requires explicit - // declaration. - using OptionalStorageBase<T>::is_populated_; - using OptionalStorageBase<T>::value_; - using OptionalStorageBase<T>::Init; - - // Inherit constructors (specifically, the in_place constructor). - using OptionalStorageBase<T>::OptionalStorageBase; - - // User defined constructor deletes the default constructor. - // Define it explicitly. - OptionalStorage() = default; - - OptionalStorage(const OptionalStorage& other) { - if (other.is_populated_) - Init(other.value_); - } - - OptionalStorage(OptionalStorage&& other) noexcept( - std::is_nothrow_move_constructible<T>::value) { - if (other.is_populated_) - Init(std::move(other.value_)); - } -}; - -template <typename T> -struct OptionalStorage<T, - true /* trivially copy constructible */, - false /* trivially move constructible */> - : OptionalStorageBase<T> { - using OptionalStorageBase<T>::is_populated_; - using OptionalStorageBase<T>::value_; - using OptionalStorageBase<T>::Init; - using OptionalStorageBase<T>::OptionalStorageBase; - - OptionalStorage() = default; - OptionalStorage(const OptionalStorage& other) = default; - - OptionalStorage(OptionalStorage&& other) noexcept( - std::is_nothrow_move_constructible<T>::value) { - if (other.is_populated_) - Init(std::move(other.value_)); - } -}; - -template <typename T> -struct OptionalStorage<T, - false /* trivially copy constructible */, - true /* trivially move constructible */> - : OptionalStorageBase<T> { - using OptionalStorageBase<T>::is_populated_; - using OptionalStorageBase<T>::value_; - using OptionalStorageBase<T>::Init; - using OptionalStorageBase<T>::OptionalStorageBase; - - OptionalStorage() = default; - OptionalStorage(OptionalStorage&& other) = default; - - OptionalStorage(const OptionalStorage& other) { - if (other.is_populated_) - Init(other.value_); - } -}; - -template <typename T> -struct OptionalStorage<T, - true /* trivially copy constructible */, - true /* trivially move constructible */> - : OptionalStorageBase<T> { - // If both trivially {copy,move} constructible are true, it is not necessary - // to use user-defined constructors. So, just inheriting constructors - // from the base class works. - using OptionalStorageBase<T>::OptionalStorageBase; -}; - -// Base class to support conditionally usable copy-/move- constructors -// and assign operators. -template <typename T> -class OptionalBase { - // This class provides implementation rather than public API, so everything - // should be hidden. Often we use composition, but we cannot in this case - // because of C++ language restriction. - protected: - constexpr OptionalBase() = default; - constexpr OptionalBase(const OptionalBase& other) = default; - constexpr OptionalBase(OptionalBase&& other) = default; - - template <class... Args> - constexpr explicit OptionalBase(in_place_t, Args&&... args) - : storage_(in_place, std::forward<Args>(args)...) {} - - // Implementation of converting constructors. - template <typename U> - explicit OptionalBase(const OptionalBase<U>& other) { - if (other.storage_.is_populated_) - storage_.Init(other.storage_.value_); - } - - template <typename U> - explicit OptionalBase(OptionalBase<U>&& other) { - if (other.storage_.is_populated_) - storage_.Init(std::move(other.storage_.value_)); - } - - ~OptionalBase() = default; - - OptionalBase& operator=(const OptionalBase& other) { - CopyAssign(other); - return *this; - } - - OptionalBase& operator=(OptionalBase&& other) noexcept( - std::is_nothrow_move_assignable<T>::value&& - std::is_nothrow_move_constructible<T>::value) { - MoveAssign(std::move(other)); - return *this; - } - - template <typename U> - void CopyAssign(const OptionalBase<U>& other) { - if (other.storage_.is_populated_) - InitOrAssign(other.storage_.value_); - else - FreeIfNeeded(); - } - - template <typename U> - void MoveAssign(OptionalBase<U>&& other) { - if (other.storage_.is_populated_) - InitOrAssign(std::move(other.storage_.value_)); - else - FreeIfNeeded(); - } - - template <typename U> - void InitOrAssign(U&& value) { - if (storage_.is_populated_) - storage_.value_ = std::forward<U>(value); - else - storage_.Init(std::forward<U>(value)); - } - - void FreeIfNeeded() { - if (!storage_.is_populated_) - return; - storage_.value_.~T(); - storage_.is_populated_ = false; - } - - // For implementing conversion, allow access to other typed OptionalBase - // class. - template <typename U> - friend class OptionalBase; - - OptionalStorage<T> storage_; -}; - -// The following {Copy,Move}{Constructible,Assignable} structs are helpers to -// implement constructor/assign-operator overloading. Specifically, if T is -// is not movable but copyable, Optional<T>'s move constructor should not -// participate in overload resolution. This inheritance trick implements that. -template <bool is_copy_constructible> -struct CopyConstructible {}; - -template <> -struct CopyConstructible<false> { - constexpr CopyConstructible() = default; - constexpr CopyConstructible(const CopyConstructible&) = delete; - constexpr CopyConstructible(CopyConstructible&&) = default; - CopyConstructible& operator=(const CopyConstructible&) = default; - CopyConstructible& operator=(CopyConstructible&&) = default; -}; - -template <bool is_move_constructible> -struct MoveConstructible {}; - -template <> -struct MoveConstructible<false> { - constexpr MoveConstructible() = default; - constexpr MoveConstructible(const MoveConstructible&) = default; - constexpr MoveConstructible(MoveConstructible&&) = delete; - MoveConstructible& operator=(const MoveConstructible&) = default; - MoveConstructible& operator=(MoveConstructible&&) = default; -}; - -template <bool is_copy_assignable> -struct CopyAssignable {}; - -template <> -struct CopyAssignable<false> { - constexpr CopyAssignable() = default; - constexpr CopyAssignable(const CopyAssignable&) = default; - constexpr CopyAssignable(CopyAssignable&&) = default; - CopyAssignable& operator=(const CopyAssignable&) = delete; - CopyAssignable& operator=(CopyAssignable&&) = default; -}; - -template <bool is_move_assignable> -struct MoveAssignable {}; - -template <> -struct MoveAssignable<false> { - constexpr MoveAssignable() = default; - constexpr MoveAssignable(const MoveAssignable&) = default; - constexpr MoveAssignable(MoveAssignable&&) = default; - MoveAssignable& operator=(const MoveAssignable&) = default; - MoveAssignable& operator=(MoveAssignable&&) = delete; -}; - -// Helper to conditionally enable converting constructors and assign operators. -template <typename T, typename U> -struct IsConvertibleFromOptional - : std::integral_constant< - bool, - std::is_constructible<T, Optional<U>&>::value || - std::is_constructible<T, const Optional<U>&>::value || - std::is_constructible<T, Optional<U>&&>::value || - std::is_constructible<T, const Optional<U>&&>::value || - std::is_convertible<Optional<U>&, T>::value || - std::is_convertible<const Optional<U>&, T>::value || - std::is_convertible<Optional<U>&&, T>::value || - std::is_convertible<const Optional<U>&&, T>::value> {}; - -template <typename T, typename U> -struct IsAssignableFromOptional - : std::integral_constant< - bool, - IsConvertibleFromOptional<T, U>::value || - std::is_assignable<T&, Optional<U>&>::value || - std::is_assignable<T&, const Optional<U>&>::value || - std::is_assignable<T&, Optional<U>&&>::value || - std::is_assignable<T&, const Optional<U>&&>::value> {}; - -// Forward compatibility for C++17. -// Introduce one more deeper nested namespace to avoid leaking using std::swap. -namespace swappable_impl { -using std::swap; - -struct IsSwappableImpl { - // Tests if swap can be called. Check<T&>(0) returns true_type iff swap - // is available for T. Otherwise, Check's overload resolution falls back - // to Check(...) declared below thanks to SFINAE, so returns false_type. - template <typename T> - static auto Check(int) - -> decltype(swap(std::declval<T>(), std::declval<T>()), std::true_type()); - - template <typename T> - static std::false_type Check(...); -}; -} // namespace swappable_impl - -template <typename T> -struct IsSwappable : decltype(swappable_impl::IsSwappableImpl::Check<T&>(0)) {}; - -// Forward compatibility for C++20. -template <typename T> -using RemoveCvRefT = std::remove_cv_t<std::remove_reference_t<T>>; - -} // namespace internal - -// On Windows, by default, empty-base class optimization does not work, -// which means even if the base class is empty struct, it still consumes one -// byte for its body. __declspec(empty_bases) enables the optimization. -// cf) -// https://blogs.msdn.microsoft.com/vcblog/2016/03/30/optimizing-the-layout-of-empty-base-classes-in-vs2015-update-2-3/ -#ifdef OS_WIN -#define OPTIONAL_DECLSPEC_EMPTY_BASES __declspec(empty_bases) -#else -#define OPTIONAL_DECLSPEC_EMPTY_BASES -#endif - -// base::Optional is a Chromium version of the C++17 optional class: -// std::optional documentation: -// http://en.cppreference.com/w/cpp/utility/optional -// Chromium documentation: -// https://chromium.googlesource.com/chromium/src/+/master/docs/optional.md -// -// These are the differences between the specification and the implementation: -// - Constructors do not use 'constexpr' as it is a C++14 extension. -// - 'constexpr' might be missing in some places for reasons specified locally. -// - No exceptions are thrown, because they are banned from Chromium. -// Marked noexcept for only move constructor and move assign operators. -// - All the non-members are in the 'base' namespace instead of 'std'. -// -// Note that T cannot have a constructor T(Optional<T>) etc. Optional<T> checks -// T's constructor (specifically via IsConvertibleFromOptional), and in the -// check whether T can be constructible from Optional<T>, which is recursive -// so it does not work. As of Feb 2018, std::optional C++17 implementation in -// both clang and gcc has same limitation. MSVC SFINAE looks to have different -// behavior, but anyway it reports an error, too. -template <typename T> -class OPTIONAL_DECLSPEC_EMPTY_BASES Optional - : public internal::OptionalBase<T>, - public internal::CopyConstructible<std::is_copy_constructible<T>::value>, - public internal::MoveConstructible<std::is_move_constructible<T>::value>, - public internal::CopyAssignable<std::is_copy_constructible<T>::value && - std::is_copy_assignable<T>::value>, - public internal::MoveAssignable<std::is_move_constructible<T>::value && - std::is_move_assignable<T>::value> { - public: -#undef OPTIONAL_DECLSPEC_EMPTY_BASES - using value_type = T; - - // Defer default/copy/move constructor implementation to OptionalBase. - constexpr Optional() = default; - constexpr Optional(const Optional& other) = default; - constexpr Optional(Optional&& other) noexcept( - std::is_nothrow_move_constructible<T>::value) = default; - - constexpr Optional(nullopt_t) {} // NOLINT(runtime/explicit) - - // Converting copy constructor. "explicit" only if - // std::is_convertible<const U&, T>::value is false. It is implemented by - // declaring two almost same constructors, but that condition in enable_if_t - // is different, so that either one is chosen, thanks to SFINAE. - template < - typename U, - std::enable_if_t<std::is_constructible<T, const U&>::value && - !internal::IsConvertibleFromOptional<T, U>::value && - std::is_convertible<const U&, T>::value, - bool> = false> - Optional(const Optional<U>& other) : internal::OptionalBase<T>(other) {} - - template < - typename U, - std::enable_if_t<std::is_constructible<T, const U&>::value && - !internal::IsConvertibleFromOptional<T, U>::value && - !std::is_convertible<const U&, T>::value, - bool> = false> - explicit Optional(const Optional<U>& other) - : internal::OptionalBase<T>(other) {} - - // Converting move constructor. Similar to converting copy constructor, - // declaring two (explicit and non-explicit) constructors. - template < - typename U, - std::enable_if_t<std::is_constructible<T, U&&>::value && - !internal::IsConvertibleFromOptional<T, U>::value && - std::is_convertible<U&&, T>::value, - bool> = false> - Optional(Optional<U>&& other) : internal::OptionalBase<T>(std::move(other)) {} - - template < - typename U, - std::enable_if_t<std::is_constructible<T, U&&>::value && - !internal::IsConvertibleFromOptional<T, U>::value && - !std::is_convertible<U&&, T>::value, - bool> = false> - explicit Optional(Optional<U>&& other) - : internal::OptionalBase<T>(std::move(other)) {} - - template <class... Args> - constexpr explicit Optional(in_place_t, Args&&... args) - : internal::OptionalBase<T>(in_place, std::forward<Args>(args)...) {} - - template < - class U, - class... Args, - class = std::enable_if_t<std::is_constructible<value_type, - std::initializer_list<U>&, - Args...>::value>> - constexpr explicit Optional(in_place_t, - std::initializer_list<U> il, - Args&&... args) - : internal::OptionalBase<T>(in_place, il, std::forward<Args>(args)...) {} - - // Forward value constructor. Similar to converting constructors, - // conditionally explicit. - template < - typename U = value_type, - std::enable_if_t< - std::is_constructible<T, U&&>::value && - !std::is_same<internal::RemoveCvRefT<U>, in_place_t>::value && - !std::is_same<internal::RemoveCvRefT<U>, Optional<T>>::value && - std::is_convertible<U&&, T>::value, - bool> = false> - constexpr Optional(U&& value) - : internal::OptionalBase<T>(in_place, std::forward<U>(value)) {} - - template < - typename U = value_type, - std::enable_if_t< - std::is_constructible<T, U&&>::value && - !std::is_same<internal::RemoveCvRefT<U>, in_place_t>::value && - !std::is_same<internal::RemoveCvRefT<U>, Optional<T>>::value && - !std::is_convertible<U&&, T>::value, - bool> = false> - constexpr explicit Optional(U&& value) - : internal::OptionalBase<T>(in_place, std::forward<U>(value)) {} - - ~Optional() = default; - - // Defer copy-/move- assign operator implementation to OptionalBase. - Optional& operator=(const Optional& other) = default; - Optional& operator=(Optional&& other) noexcept( - std::is_nothrow_move_assignable<T>::value&& - std::is_nothrow_move_constructible<T>::value) = default; - - Optional& operator=(nullopt_t) { - FreeIfNeeded(); - return *this; - } - - // Perfect-forwarded assignment. - template <typename U> - std::enable_if_t< - !std::is_same<internal::RemoveCvRefT<U>, Optional<T>>::value && - std::is_constructible<T, U>::value && - std::is_assignable<T&, U>::value && - (!std::is_scalar<T>::value || - !std::is_same<std::decay_t<U>, T>::value), - Optional&> - operator=(U&& value) { - InitOrAssign(std::forward<U>(value)); - return *this; - } - - // Copy assign the state of other. - template <typename U> - std::enable_if_t<!internal::IsAssignableFromOptional<T, U>::value && - std::is_constructible<T, const U&>::value && - std::is_assignable<T&, const U&>::value, - Optional&> - operator=(const Optional<U>& other) { - CopyAssign(other); - return *this; - } - - // Move assign the state of other. - template <typename U> - std::enable_if_t<!internal::IsAssignableFromOptional<T, U>::value && - std::is_constructible<T, U>::value && - std::is_assignable<T&, U>::value, - Optional&> - operator=(Optional<U>&& other) { - MoveAssign(std::move(other)); - return *this; - } - - constexpr const T* operator->() const { - CHECK(storage_.is_populated_); - return &storage_.value_; - } - - constexpr T* operator->() { - CHECK(storage_.is_populated_); - return &storage_.value_; - } - - constexpr const T& operator*() const& { - CHECK(storage_.is_populated_); - return storage_.value_; - } - - constexpr T& operator*() & { - CHECK(storage_.is_populated_); - return storage_.value_; - } - - constexpr const T&& operator*() const&& { - CHECK(storage_.is_populated_); - return std::move(storage_.value_); - } - - constexpr T&& operator*() && { - CHECK(storage_.is_populated_); - return std::move(storage_.value_); - } - - constexpr explicit operator bool() const { return storage_.is_populated_; } - - constexpr bool has_value() const { return storage_.is_populated_; } - - constexpr T& value() & { - CHECK(storage_.is_populated_); - return storage_.value_; - } - - constexpr const T& value() const& { - CHECK(storage_.is_populated_); - return storage_.value_; - } - - constexpr T&& value() && { - CHECK(storage_.is_populated_); - return std::move(storage_.value_); - } - - constexpr const T&& value() const&& { - CHECK(storage_.is_populated_); - return std::move(storage_.value_); - } - - template <class U> - constexpr T value_or(U&& default_value) const& { - // TODO(mlamouri): add the following assert when possible: - // static_assert(std::is_copy_constructible<T>::value, - // "T must be copy constructible"); - static_assert(std::is_convertible<U, T>::value, - "U must be convertible to T"); - return storage_.is_populated_ - ? value() - : static_cast<T>(std::forward<U>(default_value)); - } - - template <class U> - constexpr T value_or(U&& default_value) && { - // TODO(mlamouri): add the following assert when possible: - // static_assert(std::is_move_constructible<T>::value, - // "T must be move constructible"); - static_assert(std::is_convertible<U, T>::value, - "U must be convertible to T"); - return storage_.is_populated_ - ? std::move(value()) - : static_cast<T>(std::forward<U>(default_value)); - } - - void swap(Optional& other) { - if (!storage_.is_populated_ && !other.storage_.is_populated_) - return; - - if (storage_.is_populated_ != other.storage_.is_populated_) { - if (storage_.is_populated_) { - other.storage_.Init(std::move(storage_.value_)); - FreeIfNeeded(); - } else { - storage_.Init(std::move(other.storage_.value_)); - other.FreeIfNeeded(); - } - return; - } - - DCHECK(storage_.is_populated_ && other.storage_.is_populated_); - using std::swap; - swap(**this, *other); - } - - void reset() { FreeIfNeeded(); } - - template <class... Args> - T& emplace(Args&&... args) { - FreeIfNeeded(); - storage_.Init(std::forward<Args>(args)...); - return storage_.value_; - } - - template <class U, class... Args> - std::enable_if_t< - std::is_constructible<T, std::initializer_list<U>&, Args&&...>::value, - T&> - emplace(std::initializer_list<U> il, Args&&... args) { - FreeIfNeeded(); - storage_.Init(il, std::forward<Args>(args)...); - return storage_.value_; - } - - private: - // Accessing template base class's protected member needs explicit - // declaration to do so. - using internal::OptionalBase<T>::CopyAssign; - using internal::OptionalBase<T>::FreeIfNeeded; - using internal::OptionalBase<T>::InitOrAssign; - using internal::OptionalBase<T>::MoveAssign; - using internal::OptionalBase<T>::storage_; -}; - -// Here after defines comparation operators. The definition follows -// http://en.cppreference.com/w/cpp/utility/optional/operator_cmp -// while bool() casting is replaced by has_value() to meet the chromium -// style guide. -template <class T, class U> -constexpr bool operator==(const Optional<T>& lhs, const Optional<U>& rhs) { - if (lhs.has_value() != rhs.has_value()) - return false; - if (!lhs.has_value()) - return true; - return *lhs == *rhs; -} - -template <class T, class U> -constexpr bool operator!=(const Optional<T>& lhs, const Optional<U>& rhs) { - if (lhs.has_value() != rhs.has_value()) - return true; - if (!lhs.has_value()) - return false; - return *lhs != *rhs; -} - -template <class T, class U> -constexpr bool operator<(const Optional<T>& lhs, const Optional<U>& rhs) { - if (!rhs.has_value()) - return false; - if (!lhs.has_value()) - return true; - return *lhs < *rhs; -} - -template <class T, class U> -constexpr bool operator<=(const Optional<T>& lhs, const Optional<U>& rhs) { - if (!lhs.has_value()) - return true; - if (!rhs.has_value()) - return false; - return *lhs <= *rhs; -} - -template <class T, class U> -constexpr bool operator>(const Optional<T>& lhs, const Optional<U>& rhs) { - if (!lhs.has_value()) - return false; - if (!rhs.has_value()) - return true; - return *lhs > *rhs; -} - -template <class T, class U> -constexpr bool operator>=(const Optional<T>& lhs, const Optional<U>& rhs) { - if (!rhs.has_value()) - return true; - if (!lhs.has_value()) - return false; - return *lhs >= *rhs; -} - -template <class T> -constexpr bool operator==(const Optional<T>& opt, nullopt_t) { - return !opt; -} - -template <class T> -constexpr bool operator==(nullopt_t, const Optional<T>& opt) { - return !opt; -} - -template <class T> -constexpr bool operator!=(const Optional<T>& opt, nullopt_t) { - return opt.has_value(); -} - -template <class T> -constexpr bool operator!=(nullopt_t, const Optional<T>& opt) { - return opt.has_value(); -} - -template <class T> -constexpr bool operator<(const Optional<T>& opt, nullopt_t) { - return false; -} - -template <class T> -constexpr bool operator<(nullopt_t, const Optional<T>& opt) { - return opt.has_value(); -} - -template <class T> -constexpr bool operator<=(const Optional<T>& opt, nullopt_t) { - return !opt; -} - -template <class T> -constexpr bool operator<=(nullopt_t, const Optional<T>& opt) { - return true; -} - -template <class T> -constexpr bool operator>(const Optional<T>& opt, nullopt_t) { - return opt.has_value(); -} - -template <class T> -constexpr bool operator>(nullopt_t, const Optional<T>& opt) { - return false; -} - -template <class T> -constexpr bool operator>=(const Optional<T>& opt, nullopt_t) { - return true; -} - -template <class T> -constexpr bool operator>=(nullopt_t, const Optional<T>& opt) { - return !opt; -} - -template <class T, class U> -constexpr bool operator==(const Optional<T>& opt, const U& value) { - return opt.has_value() ? *opt == value : false; -} - -template <class T, class U> -constexpr bool operator==(const U& value, const Optional<T>& opt) { - return opt.has_value() ? value == *opt : false; -} - -template <class T, class U> -constexpr bool operator!=(const Optional<T>& opt, const U& value) { - return opt.has_value() ? *opt != value : true; -} - -template <class T, class U> -constexpr bool operator!=(const U& value, const Optional<T>& opt) { - return opt.has_value() ? value != *opt : true; -} - -template <class T, class U> -constexpr bool operator<(const Optional<T>& opt, const U& value) { - return opt.has_value() ? *opt < value : true; -} - -template <class T, class U> -constexpr bool operator<(const U& value, const Optional<T>& opt) { - return opt.has_value() ? value < *opt : false; -} - -template <class T, class U> -constexpr bool operator<=(const Optional<T>& opt, const U& value) { - return opt.has_value() ? *opt <= value : true; -} - -template <class T, class U> -constexpr bool operator<=(const U& value, const Optional<T>& opt) { - return opt.has_value() ? value <= *opt : false; -} - -template <class T, class U> -constexpr bool operator>(const Optional<T>& opt, const U& value) { - return opt.has_value() ? *opt > value : false; -} - -template <class T, class U> -constexpr bool operator>(const U& value, const Optional<T>& opt) { - return opt.has_value() ? value > *opt : true; -} - -template <class T, class U> -constexpr bool operator>=(const Optional<T>& opt, const U& value) { - return opt.has_value() ? *opt >= value : false; -} - -template <class T, class U> -constexpr bool operator>=(const U& value, const Optional<T>& opt) { - return opt.has_value() ? value >= *opt : true; -} - -template <class T> -constexpr Optional<std::decay_t<T>> make_optional(T&& value) { - return Optional<std::decay_t<T>>(std::forward<T>(value)); -} - -template <class T, class... Args> -constexpr Optional<T> make_optional(Args&&... args) { - return Optional<T>(in_place, std::forward<Args>(args)...); -} - -template <class T, class U, class... Args> -constexpr Optional<T> make_optional(std::initializer_list<U> il, - Args&&... args) { - return Optional<T>(in_place, il, std::forward<Args>(args)...); -} - -// Partial specialization for a function template is not allowed. Also, it is -// not allowed to add overload function to std namespace, while it is allowed -// to specialize the template in std. Thus, swap() (kind of) overloading is -// defined in base namespace, instead. -template <class T> -std::enable_if_t<std::is_move_constructible<T>::value && - internal::IsSwappable<T>::value> -swap(Optional<T>& lhs, Optional<T>& rhs) { - lhs.swap(rhs); -} - -} // namespace base - -namespace std { - -template <class T> -struct hash<base::Optional<T>> { - size_t operator()(const base::Optional<T>& opt) const { - return opt == base::nullopt ? 0 : std::hash<T>()(*opt); - } -}; - -} // namespace std - -#endif // BASE_OPTIONAL_H_
diff --git a/base/stl_util.h b/base/stl_util.h index d9e3484..d08c018 100644 --- a/base/stl_util.h +++ b/base/stl_util.h
@@ -22,7 +22,6 @@ #include <vector> #include "base/logging.h" -#include "base/optional.h" namespace base { @@ -41,99 +40,6 @@ } // namespace internal -// C++14 implementation of C++17's std::size(): -// http://en.cppreference.com/w/cpp/iterator/size -template <typename Container> -constexpr auto size(const Container& c) -> decltype(c.size()) { - return c.size(); -} - -template <typename T, size_t N> -constexpr size_t size(const T (&array)[N]) noexcept { - return N; -} - -// C++14 implementation of C++17's std::empty(): -// http://en.cppreference.com/w/cpp/iterator/empty -template <typename Container> -constexpr auto empty(const Container& c) -> decltype(c.empty()) { - return c.empty(); -} - -template <typename T, size_t N> -constexpr bool empty(const T (&array)[N]) noexcept { - return false; -} - -template <typename T> -constexpr bool empty(std::initializer_list<T> il) noexcept { - return il.size() == 0; -} - -// C++14 implementation of C++17's std::data(): -// http://en.cppreference.com/w/cpp/iterator/data -template <typename Container> -constexpr auto data(Container& c) -> decltype(c.data()) { - return c.data(); -} - -// std::basic_string::data() had no mutable overload prior to C++17 [1]. -// Hence this overload is provided. -// Note: str[0] is safe even for empty strings, as they are guaranteed to be -// null-terminated [2]. -// -// [1] http://en.cppreference.com/w/cpp/string/basic_string/data -// [2] http://en.cppreference.com/w/cpp/string/basic_string/operator_at -template <typename CharT, typename Traits, typename Allocator> -CharT* data(std::basic_string<CharT, Traits, Allocator>& str) { - return std::addressof(str[0]); -} - -template <typename Container> -constexpr auto data(const Container& c) -> decltype(c.data()) { - return c.data(); -} - -template <typename T, size_t N> -constexpr T* data(T (&array)[N]) noexcept { - return array; -} - -template <typename T> -constexpr const T* data(std::initializer_list<T> il) noexcept { - return il.begin(); -} - -// Returns a const reference to the underlying container of a container adapter. -// Works for std::priority_queue, std::queue, and std::stack. -template <class A> -const typename A::container_type& GetUnderlyingContainer(const A& adapter) { - struct ExposedAdapter : A { - using A::c; - }; - return adapter.*&ExposedAdapter::c; -} - -// Clears internal memory of an STL object. -// STL clear()/reserve(0) does not always free internal memory allocated -// This function uses swap/destructor to ensure the internal memory is freed. -template <class T> -void STLClearObject(T* obj) { - T tmp; - tmp.swap(*obj); - // Sometimes "T tmp" allocates objects with memory (arena implementation?). - // Hence using additional reserve(0) even if it doesn't always work. - obj->reserve(0); -} - -// Counts the number of instances of val in a container. -template <typename Container, typename T> -typename std::iterator_traits< - typename Container::const_iterator>::difference_type -STLCount(const Container& container, const T& val) { - return std::count(container.begin(), container.end(), val); -} - // Test to see if a set or map contains a particular key. // Returns true if the key is in the collection. template <typename Collection, typename Key> @@ -361,46 +267,6 @@ internal::IterateAndEraseIf(container, pred); } -// A helper class to be used as the predicate with |EraseIf| to implement -// in-place set intersection. Helps implement the algorithm of going through -// each container an element at a time, erasing elements from the first -// container if they aren't in the second container. Requires each container be -// sorted. Note that the logic below appears inverted since it is returning -// whether an element should be erased. -template <class Collection> -class IsNotIn { - public: - explicit IsNotIn(const Collection& collection) - : i_(collection.begin()), end_(collection.end()) {} - - bool operator()(const typename Collection::value_type& x) { - while (i_ != end_ && *i_ < x) - ++i_; - if (i_ == end_) - return true; - if (*i_ == x) { - ++i_; - return false; - } - return true; - } - - private: - typename Collection::const_iterator i_; - const typename Collection::const_iterator end_; -}; - -// Helper for returning the optional value's address, or nullptr. -template <class T> -T* OptionalOrNullptr(base::Optional<T>& optional) { - return optional.has_value() ? &optional.value() : nullptr; -} - -template <class T> -const T* OptionalOrNullptr(const base::Optional<T>& optional) { - return optional.has_value() ? &optional.value() : nullptr; -} - } // namespace base #endif // BASE_STL_UTIL_H_
diff --git a/base/strings/string_util.cc b/base/strings/string_util.cc index d8f28d4..ba918ad 100644 --- a/base/strings/string_util.cc +++ b/base/strings/string_util.cc
@@ -17,6 +17,7 @@ #include <wctype.h> #include <algorithm> +#include <iterator> #include <limits> #include <vector> @@ -603,17 +604,17 @@ size_t dimension = 0; const int kKilo = 1024; while (unit_amount >= kKilo && - dimension < arraysize(kByteStringsUnlocalized) - 1) { + dimension < std::size(kByteStringsUnlocalized) - 1) { unit_amount /= kKilo; dimension++; } char buf[64]; if (bytes != 0 && dimension > 0 && unit_amount < 100) { - base::snprintf(buf, arraysize(buf), "%.1lf%s", unit_amount, + base::snprintf(buf, std::size(buf), "%.1lf%s", unit_amount, kByteStringsUnlocalized[dimension]); } else { - base::snprintf(buf, arraysize(buf), "%.0lf%s", unit_amount, + base::snprintf(buf, std::size(buf), "%.0lf%s", unit_amount, kByteStringsUnlocalized[dimension]); }
diff --git a/base/strings/stringprintf.cc b/base/strings/stringprintf.cc index 20ddfc6..c00bdbc 100644 --- a/base/strings/stringprintf.cc +++ b/base/strings/stringprintf.cc
@@ -7,6 +7,7 @@ #include <errno.h> #include <stddef.h> +#include <iterator> #include <vector> #include "base/macros.h" @@ -49,17 +50,17 @@ #if !defined(OS_WIN) ScopedClearErrno clear_errno; #endif - int result = vsnprintfT(stack_buf, arraysize(stack_buf), format, ap_copy); + int result = vsnprintfT(stack_buf, std::size(stack_buf), format, ap_copy); va_end(ap_copy); - if (result >= 0 && result < static_cast<int>(arraysize(stack_buf))) { + if (result >= 0 && result < static_cast<int>(std::size(stack_buf))) { // It fit. dst->append(stack_buf, result); return; } // Repeatedly increase buffer size until it fits. - int mem_length = arraysize(stack_buf); + int mem_length = std::size(stack_buf); while (true) { if (result < 0) { #if defined(OS_WIN)
diff --git a/base/template_util.h b/base/template_util.h index dda9587..41028c4 100644 --- a/base/template_util.h +++ b/base/template_util.h
@@ -5,65 +5,13 @@ #ifndef BASE_TEMPLATE_UTIL_H_ #define BASE_TEMPLATE_UTIL_H_ -#include <stddef.h> #include <iosfwd> #include <iterator> #include <type_traits> #include <utility> -#include <vector> - -#include "util/build_config.h" - -// Some versions of libstdc++ have partial support for type_traits, but misses -// a smaller subset while removing some of the older non-standard stuff. Assume -// that all versions below 5.0 fall in this category, along with one 5.0 -// experimental release. Test for this by consulting compiler major version, -// the only reliable option available, so theoretically this could fail should -// you attempt to mix an earlier version of libstdc++ with >= GCC5. But -// that's unlikely to work out, especially as GCC5 changed ABI. -#define CR_GLIBCXX_5_0_0 20150123 -#if (defined(__GNUC__) && __GNUC__ < 5) || \ - (defined(__GLIBCXX__) && __GLIBCXX__ == CR_GLIBCXX_5_0_0) -#define CR_USE_FALLBACKS_FOR_OLD_EXPERIMENTAL_GLIBCXX -#endif - -// This hacks around using gcc with libc++ which has some incompatibilies. -// - is_trivially_* doesn't work: https://llvm.org/bugs/show_bug.cgi?id=27538 -// TODO(danakj): Remove this when android builders are all using a newer version -// of gcc, or the android ndk is updated to a newer libc++ that works with older -// gcc versions. -#if !defined(__clang__) && defined(_LIBCPP_VERSION) -#define CR_USE_FALLBACKS_FOR_GCC_WITH_LIBCXX -#endif namespace base { -template <class T> -struct is_non_const_reference : std::false_type {}; -template <class T> -struct is_non_const_reference<T&> : std::true_type {}; -template <class T> -struct is_non_const_reference<const T&> : std::false_type {}; - -namespace internal { - -// Implementation detail of base::void_t below. -template <typename...> -struct make_void { - using type = void; -}; - -} // namespace internal - -// base::void_t is an implementation of std::void_t from C++17. -// -// We use |base::internal::make_void| as a helper struct to avoid a C++14 -// defect: -// http://en.cppreference.com/w/cpp/types/void_t -// http://open-std.org/JTC1/SC22/WG21/docs/cwg_defects.html#1558 -template <typename... Ts> -using void_t = typename ::base::internal::make_void<Ts...>::type; - namespace internal { // Uses expression SFINAE to detect whether using operator<< would work. @@ -82,75 +30,13 @@ struct is_iterator : std::false_type {}; template <typename T> -struct is_iterator<T, - void_t<typename std::iterator_traits<T>::iterator_category>> +struct is_iterator< + T, + std::void_t<typename std::iterator_traits<T>::iterator_category>> : std::true_type {}; } // namespace internal -// is_trivially_copyable is especially hard to get right. -// - Older versions of libstdc++ will fail to have it like they do for other -// type traits. This has become a subset of the second point, but used to be -// handled independently. -// - An experimental release of gcc includes most of type_traits but misses -// is_trivially_copyable, so we still have to avoid using libstdc++ in this -// case, which is covered by CR_USE_FALLBACKS_FOR_OLD_EXPERIMENTAL_GLIBCXX. -// - When compiling libc++ from before r239653, with a gcc compiler, the -// std::is_trivially_copyable can fail. So we need to work around that by not -// using the one in libc++ in this case. This is covered by the -// CR_USE_FALLBACKS_FOR_GCC_WITH_LIBCXX define, and is discussed in -// https://llvm.org/bugs/show_bug.cgi?id=27538#c1 where they point out that -// in libc++'s commit r239653 this is fixed by libc++ checking for gcc 5.1. -// - In both of the above cases we are using the gcc compiler. When defining -// this ourselves on compiler intrinsics, the __is_trivially_copyable() -// intrinsic is not available on gcc before version 5.1 (see the discussion in -// https://llvm.org/bugs/show_bug.cgi?id=27538#c1 again), so we must check for -// that version. -// - When __is_trivially_copyable() is not available because we are on gcc older -// than 5.1, we need to fall back to something, so we use __has_trivial_copy() -// instead based on what was done one-off in bit_cast() previously. - -// TODO(crbug.com/554293): Remove this when all platforms have this in the std -// namespace and it works with gcc as needed. -#if defined(CR_USE_FALLBACKS_FOR_OLD_EXPERIMENTAL_GLIBCXX) || \ - defined(CR_USE_FALLBACKS_FOR_GCC_WITH_LIBCXX) -template <typename T> -struct is_trivially_copyable { -// TODO(danakj): Remove this when android builders are all using a newer version -// of gcc, or the android ndk is updated to a newer libc++ that does this for -// us. -#if _GNUC_VER >= 501 - static constexpr bool value = __is_trivially_copyable(T); -#else - static constexpr bool value = - __has_trivial_copy(T) && __has_trivial_destructor(T); -#endif -}; -#else -template <class T> -using is_trivially_copyable = std::is_trivially_copyable<T>; -#endif - -#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ <= 7 -// Workaround for g++7 and earlier family. -// Due to https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80654, without this -// Optional<std::vector<T>> where T is non-copyable causes a compile error. -// As we know it is not trivially copy constructible, explicitly declare so. -template <typename T> -struct is_trivially_copy_constructible - : std::is_trivially_copy_constructible<T> {}; - -template <typename... T> -struct is_trivially_copy_constructible<std::vector<T...>> : std::false_type {}; -#else -// Otherwise use std::is_trivially_copy_constructible as is. -template <typename T> -using is_trivially_copy_constructible = std::is_trivially_copy_constructible<T>; -#endif - } // namespace base -#undef CR_USE_FALLBACKS_FOR_GCC_WITH_LIBCXX -#undef CR_USE_FALLBACKS_FOR_OLD_EXPERIMENTAL_GLIBCXX - #endif // BASE_TEMPLATE_UTIL_H_
diff --git a/base/values.cc b/base/values.cc index 9c34803..d660365 100644 --- a/base/values.cc +++ b/base/values.cc
@@ -8,6 +8,7 @@ #include <algorithm> #include <cmath> +#include <iterator> #include <new> #include <ostream> #include <utility> @@ -25,7 +26,7 @@ const char* const kTypeNames[] = {"null", "boolean", "integer", "string", "binary", "dictionary", "list"}; -static_assert(arraysize(kTypeNames) == +static_assert(std::size(kTypeNames) == static_cast<size_t>(Value::Type::LIST) + 1, "kTypeNames Has Wrong Size"); @@ -205,7 +206,7 @@ // static const char* Value::GetTypeName(Value::Type type) { DCHECK_GE(static_cast<int>(type), 0); - DCHECK_LT(static_cast<size_t>(type), arraysize(kTypeNames)); + DCHECK_LT(static_cast<size_t>(type), std::size(kTypeNames)); return kTypeNames[static_cast<size_t>(type)]; } @@ -1300,7 +1301,7 @@ std::ostream& operator<<(std::ostream& out, const Value::Type& type) { if (static_cast<int>(type) < 0 || - static_cast<size_t>(type) >= arraysize(kTypeNames)) + static_cast<size_t>(type) >= std::size(kTypeNames)) return out << "Invalid Type (index = " << static_cast<int>(type) << ")"; return out << Value::GetTypeName(type); }
diff --git a/base/win/registry.cc b/base/win/registry.cc index 2ea2de3..5acfda7 100644 --- a/base/win/registry.cc +++ b/base/win/registry.cc
@@ -6,7 +6,9 @@ #include <shlwapi.h> #include <stddef.h> + #include <algorithm> +#include <iterator> #include "base/logging.h" #include "base/macros.h" @@ -181,7 +183,7 @@ LONG RegKey::GetValueNameAt(int index, std::u16string* name) const { char16_t buf[256]; - DWORD bufsize = arraysize(buf); + DWORD bufsize = std::size(buf); LONG r = ::RegEnumValue(key_, index, ToWCharT(buf), &bufsize, NULL, NULL, NULL, NULL); if (r == ERROR_SUCCESS) @@ -581,7 +583,7 @@ bool RegistryKeyIterator::Read() { if (Valid()) { - DWORD ncount = arraysize(name_); + DWORD ncount = std::size(name_); FILETIME written; LONG r = ::RegEnumKeyEx(key_, index_, ToWCharT(name_), &ncount, NULL, NULL, NULL, &written);
diff --git a/tools/gn/c_include_iterator.cc b/tools/gn/c_include_iterator.cc index 077609f..f20d749 100644 --- a/tools/gn/c_include_iterator.cc +++ b/tools/gn/c_include_iterator.cc
@@ -4,6 +4,8 @@ #include "tools/gn/c_include_iterator.h" +#include <iterator> + #include "base/logging.h" #include "base/macros.h" #include "base/strings/string_util.h" @@ -63,9 +65,9 @@ std::string_view* path, int* begin_char) { static const char kInclude[] = "include"; - static const size_t kIncludeLen = arraysize(kInclude) - 1; // No null. + static const size_t kIncludeLen = std::size(kInclude) - 1; // No null. static const char kImport[] = "import"; - static const size_t kImportLen = arraysize(kImport) - 1; // No null. + static const size_t kImportLen = std::size(kImport) - 1; // No null. std::string_view trimmed = TrimLeadingWhitespace(line); if (trimmed.empty())
diff --git a/tools/gn/input_conversion.cc b/tools/gn/input_conversion.cc index d2acb71..75cd158 100644 --- a/tools/gn/input_conversion.cc +++ b/tools/gn/input_conversion.cc
@@ -4,6 +4,7 @@ #include "tools/gn/input_conversion.h" +#include <iterator> #include <memory> #include <utility> @@ -218,7 +219,7 @@ // Remove "trim" prefix from the input conversion and re-run. return DoConvertInputToValue( settings, trimmed, origin, original_input_conversion, - input_conversion.substr(arraysize(kTrimPrefix) - 1), err); + input_conversion.substr(std::size(kTrimPrefix) - 1), err); } if (input_conversion == "value")
diff --git a/tools/gn/label_pattern_unittest.cc b/tools/gn/label_pattern_unittest.cc index 7457a9b..6f0b0e0 100644 --- a/tools/gn/label_pattern_unittest.cc +++ b/tools/gn/label_pattern_unittest.cc
@@ -4,6 +4,8 @@ #include <stddef.h> +#include <iterator> + #include "base/macros.h" #include "tools/gn/err.h" #include "tools/gn/label_pattern.h" @@ -70,7 +72,7 @@ #endif }; - for (size_t i = 0; i < arraysize(cases); i++) { + for (size_t i = 0; i < std::size(cases); i++) { const PatternCase& cur = cases[i]; Err err; LabelPattern result =
diff --git a/tools/gn/label_unittest.cc b/tools/gn/label_unittest.cc index 26a276c..f31bfdd 100644 --- a/tools/gn/label_unittest.cc +++ b/tools/gn/label_unittest.cc
@@ -4,6 +4,8 @@ #include <stddef.h> +#include <iterator> + #include "base/macros.h" #include "tools/gn/err.h" #include "tools/gn/label.h" @@ -73,7 +75,7 @@ Label default_toolchain(SourceDir("//t/"), "d"); - for (size_t i = 0; i < arraysize(cases); i++) { + for (size_t i = 0; i < std::size(cases); i++) { const ParseDepStringCase& cur = cases[i]; std::string location, name;
diff --git a/tools/gn/ninja_create_bundle_target_writer.cc b/tools/gn/ninja_create_bundle_target_writer.cc index dab4485..2cf597d 100644 --- a/tools/gn/ninja_create_bundle_target_writer.cc +++ b/tools/gn/ninja_create_bundle_target_writer.cc
@@ -4,6 +4,8 @@ #include "tools/gn/ninja_create_bundle_target_writer.h" +#include <iterator> + #include "base/macros.h" #include "base/strings/string_util.h" #include "tools/gn/filesystem_utils.h" @@ -41,7 +43,7 @@ GeneralTool::kGeneralToolStamp, }; - for (size_t i = 0; i < arraysize(kRequiredTools); ++i) { + for (size_t i = 0; i < std::size(kRequiredTools); ++i) { if (!target->toolchain()->GetTool(kRequiredTools[i])) { FailWithMissingToolError(kRequiredTools[i], target); return false;
diff --git a/tools/gn/pattern_unittest.cc b/tools/gn/pattern_unittest.cc index 9e14ca2..cefde4f 100644 --- a/tools/gn/pattern_unittest.cc +++ b/tools/gn/pattern_unittest.cc
@@ -4,6 +4,8 @@ #include <stddef.h> +#include <iterator> + #include "base/macros.h" #include "tools/gn/pattern.h" #include "util/test/test.h" @@ -54,7 +56,7 @@ {"*\\bfoo\\b*", "foob", false}, {"*\\bfoo\\b*", "lala/foo/bar/baz", true}, }; - for (size_t i = 0; i < arraysize(pattern_cases); i++) { + for (size_t i = 0; i < std::size(pattern_cases); i++) { const Case& c = pattern_cases[i]; Pattern pattern(c.pattern); bool result = pattern.MatchesString(c.candidate);
diff --git a/tools/gn/qt_creator_writer.cc b/tools/gn/qt_creator_writer.cc index c245024..f0d8c7e 100644 --- a/tools/gn/qt_creator_writer.cc +++ b/tools/gn/qt_creator_writer.cc
@@ -4,6 +4,7 @@ #include "tools/gn/qt_creator_writer.h" +#include <optional> #include <set> #include <sstream> #include <string> @@ -11,7 +12,6 @@ #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/strings/utf_string_conversions.h" -#include "base/optional.h" #include "tools/gn/builder.h" #include "tools/gn/config_values_extractors.h" @@ -133,12 +133,12 @@ std::string ToMacro(CVersion version) { const std::string s = "__STDC_VERSION__"; - switch(version) { + switch (version) { case CVersion::C99: return s + " 199901L"; case CVersion::C11: return s + " 201112L"; - } + } return std::string(); } @@ -146,7 +146,7 @@ std::string ToMacro(CxxVersion version) { const std::string name = "__cplusplus"; - switch(version) { + switch (version) { case CxxVersion::CXX98: case CxxVersion::CXX03: return name + " 199711L"; @@ -156,29 +156,27 @@ return name + " 201402L"; case CxxVersion::CXX17: return name + " 201703L"; - } + } return std::string(); } const std::map<std::string, CVersion> kFlagToCVersion{ - {"-std=gnu99" , CVersion::C99}, - {"-std=c99" , CVersion::C99}, - {"-std=gnu11" , CVersion::C11}, - {"-std=c11" , CVersion::C11} -}; + {"-std=gnu99", CVersion::C99}, + {"-std=c99", CVersion::C99}, + {"-std=gnu11", CVersion::C11}, + {"-std=c11", CVersion::C11}}; const std::map<std::string, CxxVersion> kFlagToCxxVersion{ - {"-std=gnu++11", CxxVersion::CXX11}, {"-std=c++11", CxxVersion::CXX11}, - {"-std=gnu++98", CxxVersion::CXX98}, {"-std=c++98", CxxVersion::CXX98}, - {"-std=gnu++03", CxxVersion::CXX03}, {"-std=c++03", CxxVersion::CXX03}, - {"-std=gnu++14", CxxVersion::CXX14}, {"-std=c++14", CxxVersion::CXX14}, - {"-std=c++1y" , CxxVersion::CXX14}, - {"-std=gnu++17", CxxVersion::CXX17}, {"-std=c++17", CxxVersion::CXX17}, - {"-std=c++1z" , CxxVersion::CXX17}, + {"-std=gnu++11", CxxVersion::CXX11}, {"-std=c++11", CxxVersion::CXX11}, + {"-std=gnu++98", CxxVersion::CXX98}, {"-std=c++98", CxxVersion::CXX98}, + {"-std=gnu++03", CxxVersion::CXX03}, {"-std=c++03", CxxVersion::CXX03}, + {"-std=gnu++14", CxxVersion::CXX14}, {"-std=c++14", CxxVersion::CXX14}, + {"-std=c++1y", CxxVersion::CXX14}, {"-std=gnu++17", CxxVersion::CXX17}, + {"-std=c++17", CxxVersion::CXX17}, {"-std=c++1z", CxxVersion::CXX17}, }; -template<typename Enum> +template <typename Enum> struct CompVersion { bool operator()(Enum a, Enum b) { return static_cast<int>(a) < static_cast<int>(b); @@ -186,22 +184,18 @@ }; struct CompilerOptions { - base::Optional<CVersion> c_version_; - base::Optional<CxxVersion> cxx_version_; + std::optional<CVersion> c_version_; + std::optional<CxxVersion> cxx_version_; - void SetCVersion(CVersion ver) { - SetVersionImpl(c_version_, ver); - } + void SetCVersion(CVersion ver) { SetVersionImpl(c_version_, ver); } - void SetCxxVersion(CxxVersion ver) { - SetVersionImpl(cxx_version_, ver); - } + void SetCxxVersion(CxxVersion ver) { SetVersionImpl(cxx_version_, ver); } -private: - template<typename Version> - void SetVersionImpl(base::Optional<Version> &cur_ver, Version ver) { + private: + template <typename Version> + void SetVersionImpl(std::optional<Version>& cur_ver, Version ver) { if (cur_ver) - cur_ver = std::max(*cur_ver, ver, CompVersion<Version> {}); + cur_ver = std::max(*cur_ver, ver, CompVersion<Version>{}); else cur_ver = ver; } @@ -223,7 +217,7 @@ ParseCompilerOption(flag, options); } -} // QtCreatorWriterUtils +} // namespace QtCreatorWriterUtils void QtCreatorWriter::HandleTarget(const Target* target) { using namespace QtCreatorWriterUtils; @@ -250,7 +244,7 @@ FilePathToUTF8(build_settings_->GetFullPath(include_dir))); } - static constexpr const char *define_str = "#define "; + static constexpr const char* define_str = "#define "; for (std::string define : it.cur().defines()) { size_t equal_pos = define.find('='); if (equal_pos != std::string::npos) @@ -264,7 +258,7 @@ ParseCompilerOptions(it.cur().cflags_c(), &options); ParseCompilerOptions(it.cur().cflags_cc(), &options); - auto add_define_version = [this] (auto &ver) { + auto add_define_version = [this](auto& ver) { if (ver) defines_.insert(define_str + ToMacro(*ver)); };
diff --git a/tools/gn/xcode_object.cc b/tools/gn/xcode_object.cc index 7509547..8d81246 100644 --- a/tools/gn/xcode_object.cc +++ b/tools/gn/xcode_object.cc
@@ -5,6 +5,7 @@ #include "tools/gn/xcode_object.h" #include <iomanip> +#include <iterator> #include <memory> #include <sstream> #include <utility> @@ -141,7 +142,7 @@ }; const char* GetSourceType(const std::string_view& ext) { - for (size_t i = 0; i < arraysize(kSourceTypeForExt); ++i) { + for (size_t i = 0; i < std::size(kSourceTypeForExt); ++i) { if (kSourceTypeForExt[i].ext == ext) return kSourceTypeForExt[i].source_type; }
diff --git a/tools/gn/xcode_writer.cc b/tools/gn/xcode_writer.cc index 0d4a35a..922b10a 100644 --- a/tools/gn/xcode_writer.cc +++ b/tools/gn/xcode_writer.cc
@@ -5,6 +5,7 @@ #include "tools/gn/xcode_writer.h" #include <iomanip> +#include <iterator> #include <map> #include <memory> #include <sstream> @@ -135,7 +136,7 @@ bool IsXCTestFile(const SourceFile& file) { std::string file_name = file.GetName(); - for (size_t i = 0; i < arraysize(kXCTestFileSuffixes); ++i) { + for (size_t i = 0; i < std::size(kXCTestFileSuffixes); ++i) { if (base::EndsWith(file_name, kXCTestFileSuffixes[i], base::CompareCase::SENSITIVE)) { return true;