Rename typefdefs for C++17 These typedefs are no longer necessary: base::char16 -> char16_t base::string16 -> std::u16string base::StringPiece -> std::string_view base::StringPiece16 -> std::u16string_view There should be no behavior change since the objects are already the C++17 types. Change-Id: I482a9371bc668e72d12811c17b4f1128715ea62a Reviewed-on: https://gn-review.googlesource.com/c/gn/+/6060 Reviewed-by: Scott Graham <scottmg@chromium.org> Commit-Queue: Brett Wilson <brettw@chromium.org>
diff --git a/base/command_line.cc b/base/command_line.cc index b2bf5a8..d6695a3 100644 --- a/base/command_line.cc +++ b/base/command_line.cc
@@ -107,21 +107,21 @@ #if defined(OS_WIN) // Quote a string as necessary for CommandLineToArgvW compatiblity *on Windows*. -string16 QuoteForCommandLineToArgvW(const string16& arg, - bool quote_placeholders) { +std::u16string QuoteForCommandLineToArgvW(const std::u16string& arg, + bool quote_placeholders) { // We follow the quoting rules of CommandLineToArgvW. // http://msdn.microsoft.com/en-us/library/17w5ykft.aspx - string16 quotable_chars(u" \\\""); + std::u16string quotable_chars(u" \\\""); // We may also be required to quote '%', which is commonly used in a command // line as a placeholder. (It may be substituted for a string with spaces.) if (quote_placeholders) quotable_chars.push_back('%'); - if (arg.find_first_of(quotable_chars) == string16::npos) { + if (arg.find_first_of(quotable_chars) == std::u16string::npos) { // No quoting necessary. return arg; } - string16 out; + std::u16string out; out.push_back('"'); for (size_t i = 0; i < arg.size(); ++i) { if (arg[i] == '\\') { @@ -195,7 +195,7 @@ void CommandLine::InitUsingArgvForTesting(int argc, const char* const* argv) { DCHECK(!current_process_commandline_); current_process_commandline_ = new CommandLine(NO_PROGRAM); - // On Windows we need to convert the command line arguments to string16. + // On Windows we need to convert the command line arguments to std::u16string. base::CommandLine::StringVector argv_vector; for (int i = 0; i < argc; ++i) argv_vector.push_back(UTF8ToUTF16(argv[i])); @@ -245,7 +245,7 @@ #if defined(OS_WIN) // static -CommandLine CommandLine::FromString(const string16& command_line) { +CommandLine CommandLine::FromString(const std::u16string& command_line) { CommandLine cmd(NO_PROGRAM); cmd.ParseFromString(command_line); return cmd; @@ -282,17 +282,17 @@ #endif } -bool CommandLine::HasSwitch(const base::StringPiece& switch_string) const { +bool CommandLine::HasSwitch(const std::string_view& switch_string) const { DCHECK_EQ(ToLowerASCII(switch_string), switch_string); return ContainsKey(switches_, switch_string); } bool CommandLine::HasSwitch(const char switch_constant[]) const { - return HasSwitch(base::StringPiece(switch_constant)); + return HasSwitch(std::string_view(switch_constant)); } std::string CommandLine::GetSwitchValueASCII( - const base::StringPiece& switch_string) const { + const std::string_view& switch_string) const { StringType value = GetSwitchValueNative(switch_string); if (!IsStringASCII(value)) { DLOG(WARNING) << "Value of switch (" << switch_string << ") must be ASCII."; @@ -306,12 +306,12 @@ } FilePath CommandLine::GetSwitchValuePath( - const base::StringPiece& switch_string) const { + const std::string_view& switch_string) const { return FilePath(GetSwitchValueNative(switch_string)); } CommandLine::StringType CommandLine::GetSwitchValueNative( - const base::StringPiece& switch_string) const { + const std::string_view& switch_string) const { DCHECK_EQ(ToLowerASCII(switch_string), switch_string); auto result = switches_.find(switch_string); return result == switches_.end() ? StringType() : result->second; @@ -424,8 +424,8 @@ } #if defined(OS_WIN) -void CommandLine::ParseFromString(const string16& command_line) { - string16 command_line_string; +void CommandLine::ParseFromString(const std::u16string& command_line) { + std::u16string command_line_string; TrimWhitespace(command_line, TRIM_ALL, &command_line_string); if (command_line_string.empty()) return;
diff --git a/base/command_line.h b/base/command_line.h index 0161457..46c1fcc 100644 --- a/base/command_line.h +++ b/base/command_line.h
@@ -18,10 +18,9 @@ #include <stddef.h> #include <map> #include <string> +#include <string_view> #include <vector> -#include "base/strings/string16.h" -#include "base/strings/string_piece.h" #include "util/build_config.h" namespace base { @@ -32,7 +31,7 @@ public: #if defined(OS_WIN) // The native command line string type. - using StringType = string16; + using StringType = std::u16string; #elif defined(OS_POSIX) || defined(OS_FUCHSIA) using StringType = std::string; #endif @@ -100,7 +99,7 @@ static bool InitializedForCurrentProcess(); #if defined(OS_WIN) - static CommandLine FromString(const string16& command_line); + static CommandLine FromString(const std::u16string& command_line); #endif // Initialize from an argv vector. @@ -164,16 +163,16 @@ // Switch names must be lowercase. // The second override provides an optimized version to avoid inlining codegen // at every callsite to find the length of the constant and construct a - // StringPiece. - bool HasSwitch(const StringPiece& switch_string) const; + // std::string_view. + bool HasSwitch(const std::string_view& switch_string) const; bool HasSwitch(const char switch_constant[]) const; // Returns the value associated with the given switch. If the switch has no // value or isn't present, this method returns the empty string. // Switch names must be lowercase. - std::string GetSwitchValueASCII(const StringPiece& switch_string) const; - FilePath GetSwitchValuePath(const StringPiece& switch_string) const; - StringType GetSwitchValueNative(const StringPiece& switch_string) const; + std::string GetSwitchValueASCII(const std::string_view& switch_string) const; + FilePath GetSwitchValuePath(const std::string_view& switch_string) const; + StringType GetSwitchValueNative(const std::string_view& switch_string) const; // Get a copy of all switches, along with their values. const SwitchMap& GetSwitches() const { return switches_; } @@ -215,7 +214,7 @@ #if defined(OS_WIN) // Initialize by parsing the given command line string. // The program name is assumed to be the first item in the string. - void ParseFromString(const string16& command_line); + void ParseFromString(const std::u16string& command_line); #endif private:
diff --git a/base/containers/span.h b/base/containers/span.h index c971861..20c7f15 100644 --- a/base/containers/span.h +++ b/base/containers/span.h
@@ -88,8 +88,8 @@ // own the underlying memory, so care must be taken to ensure that a span does // not outlive the backing store. // -// span is somewhat analogous to StringPiece, but with arbitrary element types, -// allowing mutation if T is non-const. +// span is somewhat analogous to std::string_view, but with arbitrary element +// types, allowing mutation if T is non-const. // // span is implicitly convertible from C++ arrays, as well as most [1] // container-like types that provide a data() and size() method (such as
diff --git a/base/environment.cc b/base/environment.cc index 41951b7..427e3e5 100644 --- a/base/environment.cc +++ b/base/environment.cc
@@ -6,10 +6,10 @@ #include <stddef.h> +#include <string_view> #include <vector> #include "base/memory/ptr_util.h" -#include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "util/build_config.h" @@ -26,7 +26,7 @@ class EnvironmentImpl : public Environment { public: - bool GetVar(StringPiece variable_name, std::string* result) override { + bool GetVar(std::string_view variable_name, std::string* result) override { if (GetVarImpl(variable_name, result)) return true; @@ -45,17 +45,17 @@ return GetVarImpl(alternate_case_var, result); } - bool SetVar(StringPiece variable_name, + bool SetVar(std::string_view variable_name, const std::string& new_value) override { return SetVarImpl(variable_name, new_value); } - bool UnSetVar(StringPiece variable_name) override { + bool UnSetVar(std::string_view variable_name) override { return UnSetVarImpl(variable_name); } private: - bool GetVarImpl(StringPiece variable_name, std::string* result) { + bool GetVarImpl(std::string_view variable_name, std::string* result) { #if defined(OS_WIN) DWORD value_length = ::GetEnvironmentVariable( reinterpret_cast<LPCWSTR>(UTF8ToUTF16(variable_name).c_str()), nullptr, @@ -81,7 +81,8 @@ #endif } - bool SetVarImpl(StringPiece variable_name, const std::string& new_value) { + bool SetVarImpl(std::string_view variable_name, + const std::string& new_value) { #if defined(OS_WIN) // On success, a nonzero value is returned. return !!SetEnvironmentVariable( @@ -93,7 +94,7 @@ #endif } - bool UnSetVarImpl(StringPiece variable_name) { + bool UnSetVarImpl(std::string_view variable_name) { #if defined(OS_WIN) // On success, a nonzero value is returned. return !!SetEnvironmentVariable( @@ -141,18 +142,19 @@ return std::make_unique<EnvironmentImpl>(); } -bool Environment::HasVar(StringPiece variable_name) { +bool Environment::HasVar(std::string_view variable_name) { return GetVar(variable_name, nullptr); } #if defined(OS_WIN) -string16 AlterEnvironment(const char16_t* env, const EnvironmentMap& changes) { - string16 result; +std::u16string AlterEnvironment(const char16_t* env, + const EnvironmentMap& changes) { + std::u16string result; // First copy all unmodified values to the output. size_t cur_env = 0; - string16 key; + std::u16string key; while (env[cur_env]) { const char16_t* line = &env[cur_env]; size_t line_length = ParseEnvLine(line, &key);
diff --git a/base/environment.h b/base/environment.h index 201b1a8..f9a2f55 100644 --- a/base/environment.h +++ b/base/environment.h
@@ -8,9 +8,8 @@ #include <map> #include <memory> #include <string> +#include <string_view> -#include "base/strings/string16.h" -#include "base/strings/string_piece.h" #include "util/build_config.h" namespace base { @@ -32,22 +31,22 @@ // Gets an environment variable's value and stores it in |result|. // Returns false if the key is unset. - virtual bool GetVar(StringPiece variable_name, std::string* result) = 0; + virtual bool GetVar(std::string_view variable_name, std::string* result) = 0; // Syntactic sugar for GetVar(variable_name, nullptr); - virtual bool HasVar(StringPiece variable_name); + virtual bool HasVar(std::string_view variable_name); // Returns true on success, otherwise returns false. - virtual bool SetVar(StringPiece variable_name, + virtual bool SetVar(std::string_view variable_name, const std::string& new_value) = 0; // Returns true on success, otherwise returns false. - virtual bool UnSetVar(StringPiece variable_name) = 0; + virtual bool UnSetVar(std::string_view variable_name) = 0; }; #if defined(OS_WIN) -typedef string16 NativeEnvironmentString; +typedef std::u16string NativeEnvironmentString; typedef std::map<NativeEnvironmentString, NativeEnvironmentString> EnvironmentMap; @@ -61,7 +60,8 @@ // which is a concatenated list of null-terminated 16-bit strings. The end is // marked by a double-null terminator. The size of the returned string will // include the terminators. -string16 AlterEnvironment(const char16_t* env, const EnvironmentMap& changes); +std::u16string AlterEnvironment(const char16_t* env, + const EnvironmentMap& changes); #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
diff --git a/base/files/file_path.cc b/base/files/file_path.cc index 3ecb009..e546761 100644 --- a/base/files/file_path.cc +++ b/base/files/file_path.cc
@@ -5,11 +5,12 @@ #include "base/files/file_path.h" #include <string.h> + #include <algorithm> +#include <string_view> #include "base/logging.h" #include "base/macros.h" -#include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "util/build_config.h" @@ -28,7 +29,7 @@ namespace base { using StringType = FilePath::StringType; -using StringPieceType = FilePath::StringPieceType; +using StringViewType = FilePath::StringViewType; namespace { @@ -42,7 +43,7 @@ // otherwise returns npos. This can only be true on Windows, when a pathname // begins with a letter followed by a colon. On other platforms, this always // returns npos. -StringPieceType::size_type FindDriveLetter(StringPieceType path) { +StringViewType::size_type FindDriveLetter(StringViewType path) { #if defined(FILE_PATH_USES_DRIVE_LETTERS) // This is dependent on an ASCII-based character set, but that's a // reasonable assumption. iswalpha can be too inclusive here. @@ -56,25 +57,25 @@ } #if defined(FILE_PATH_USES_DRIVE_LETTERS) -bool EqualDriveLetterCaseInsensitive(StringPieceType a, StringPieceType b) { +bool EqualDriveLetterCaseInsensitive(StringViewType a, StringViewType b) { size_t a_letter_pos = FindDriveLetter(a); size_t b_letter_pos = FindDriveLetter(b); if (a_letter_pos == StringType::npos || b_letter_pos == StringType::npos) return a == b; - StringPieceType a_letter(a.substr(0, a_letter_pos + 1)); - StringPieceType b_letter(b.substr(0, b_letter_pos + 1)); + StringViewType a_letter(a.substr(0, a_letter_pos + 1)); + StringViewType b_letter(b.substr(0, b_letter_pos + 1)); if (!StartsWith(a_letter, b_letter, CompareCase::INSENSITIVE_ASCII)) return false; - StringPieceType a_rest(a.substr(a_letter_pos + 1)); - StringPieceType b_rest(b.substr(b_letter_pos + 1)); + StringViewType a_rest(a.substr(a_letter_pos + 1)); + StringViewType b_rest(b.substr(b_letter_pos + 1)); return a_rest == b_rest; } #endif // defined(FILE_PATH_USES_DRIVE_LETTERS) -bool IsPathAbsolute(StringPieceType path) { +bool IsPathAbsolute(StringViewType path) { #if defined(FILE_PATH_USES_DRIVE_LETTERS) StringType::size_type letter = FindDriveLetter(path); if (letter != StringType::npos) { @@ -170,7 +171,7 @@ FilePath::FilePath(const FilePath& that) = default; FilePath::FilePath(FilePath&& that) noexcept = default; -FilePath::FilePath(StringPieceType path) { +FilePath::FilePath(StringViewType path) { path_.assign(path); StringType::size_type nul_pos = path_.find(kStringTerminator); if (nul_pos != StringType::npos) @@ -392,7 +393,7 @@ return FilePath(path_.substr(0, dot)); } -FilePath FilePath::InsertBeforeExtension(StringPieceType suffix) const { +FilePath FilePath::InsertBeforeExtension(StringViewType suffix) const { if (suffix.empty()) return FilePath(path_); @@ -406,7 +407,7 @@ return FilePath(ret); } -FilePath FilePath::InsertBeforeExtensionASCII(StringPiece suffix) const { +FilePath FilePath::InsertBeforeExtensionASCII(std::string_view suffix) const { DCHECK(IsStringASCII(suffix)); #if defined(OS_WIN) return InsertBeforeExtension(ASCIIToUTF16(suffix)); @@ -415,7 +416,7 @@ #endif } -FilePath FilePath::AddExtension(StringPieceType extension) const { +FilePath FilePath::AddExtension(StringViewType extension) const { if (IsEmptyOrSpecialCase(BaseName().value())) return FilePath(); @@ -433,7 +434,7 @@ return FilePath(str); } -FilePath FilePath::ReplaceExtension(StringPieceType extension) const { +FilePath FilePath::ReplaceExtension(StringViewType extension) const { if (IsEmptyOrSpecialCase(BaseName().value())) return FilePath(); @@ -450,14 +451,14 @@ return FilePath(str); } -FilePath FilePath::Append(StringPieceType component) const { - StringPieceType appended = component; +FilePath FilePath::Append(StringViewType component) const { + StringViewType appended = component; StringType without_nuls; StringType::size_type nul_pos = component.find(kStringTerminator); - if (nul_pos != StringPieceType::npos) { + if (nul_pos != StringViewType::npos) { without_nuls.assign(component.substr(0, nul_pos)); - appended = StringPieceType(without_nuls); + appended = StringViewType(without_nuls); } DCHECK(!IsPathAbsolute(appended)); @@ -498,7 +499,7 @@ return Append(component.value()); } -FilePath FilePath::AppendASCII(StringPiece component) const { +FilePath FilePath::AppendASCII(std::string_view component) const { DCHECK(base::IsStringASCII(component)); #if defined(OS_WIN) return Append(ASCIIToUTF16(component)); @@ -564,7 +565,7 @@ #if defined(OS_WIN) -string16 FilePath::LossyDisplayName() const { +std::u16string FilePath::LossyDisplayName() const { return path_; }
diff --git a/base/files/file_path.h b/base/files/file_path.h index a8322c4..74fb674 100644 --- a/base/files/file_path.h +++ b/base/files/file_path.h
@@ -106,12 +106,11 @@ #include <iosfwd> #include <string> +#include <string_view> #include <vector> #include "base/compiler_specific.h" #include "base/macros.h" -#include "base/strings/string16.h" -#include "base/strings/string_piece.h" #include "util/build_config.h" // Windows-style drive letter support and pathname separator characters can be @@ -153,7 +152,7 @@ #endif // OS_WIN using CharType = StringType::value_type; - using StringPieceType = std::basic_string_view<CharType>; + using StringViewType = std::basic_string_view<CharType>; // Null-terminated array of separators used to separate components in // hierarchical paths. Each character in this array is a valid separator, @@ -175,7 +174,7 @@ FilePath(); FilePath(const FilePath& that); - explicit FilePath(StringPieceType path); + explicit FilePath(StringViewType path); ~FilePath(); FilePath& operator=(const FilePath& that); @@ -282,20 +281,20 @@ // path == "jojo.jpg" suffix == " (1)", returns "jojo (1).jpg" // path == "C:\pics\jojo" suffix == " (1)", returns "C:\pics\jojo (1)" // path == "C:\pics.old\jojo" suffix == " (1)", returns "C:\pics.old\jojo (1)" - FilePath InsertBeforeExtension(StringPieceType suffix) const + FilePath InsertBeforeExtension(StringViewType suffix) const WARN_UNUSED_RESULT; - FilePath InsertBeforeExtensionASCII(StringPiece suffix) const + FilePath InsertBeforeExtensionASCII(std::string_view suffix) const WARN_UNUSED_RESULT; // Adds |extension| to |file_name|. Returns the current FilePath if // |extension| is empty. Returns "" if BaseName() == "." or "..". - FilePath AddExtension(StringPieceType extension) const WARN_UNUSED_RESULT; + FilePath AddExtension(StringViewType extension) const WARN_UNUSED_RESULT; // Replaces the extension of |file_name| with |extension|. If |file_name| // does not have an extension, then |extension| is added. If |extension| is // empty, then the extension is removed from |file_name|. // Returns "" if BaseName() == "." or "..". - FilePath ReplaceExtension(StringPieceType extension) const WARN_UNUSED_RESULT; + FilePath ReplaceExtension(StringViewType extension) const WARN_UNUSED_RESULT; // Returns a FilePath by appending a separator and the supplied path // component to this object's path. Append takes care to avoid adding @@ -303,7 +302,7 @@ // If this object's path is kCurrentDirectory, a new FilePath corresponding // only to |component| is returned. |component| must be a relative path; // it is an error to pass an absolute path. - FilePath Append(StringPieceType component) const WARN_UNUSED_RESULT; + FilePath Append(StringViewType component) const WARN_UNUSED_RESULT; FilePath Append(const FilePath& component) const WARN_UNUSED_RESULT; // Although Windows StringType is std::u16string, since the encoding it uses @@ -312,7 +311,7 @@ // Linux, although it can use any 8-bit encoding for paths, we assume that // ASCII is a valid subset, regardless of the encoding, since many operating // system paths will always be ASCII. - FilePath AppendASCII(StringPiece component) const WARN_UNUSED_RESULT; + FilePath AppendASCII(std::string_view component) const WARN_UNUSED_RESULT; // Returns true if this FilePath contains an absolute path. On Windows, an // absolute path begins with either a drive letter specification followed by @@ -338,8 +337,8 @@ // Return a Unicode human-readable version of this path. // Warning: you can *not*, in general, go from a display name back to a real // path. Only use this when displaying paths to users, not just when you - // want to stuff a string16 into some other API. - string16 LossyDisplayName() const; + // want to stuff a std::u16string into some other API. + std::u16string LossyDisplayName() const; // Return the path as ASCII, or the empty string if the path is not ASCII. // This should only be used for cases where the FilePath is representing a
diff --git a/base/files/file_util.cc b/base/files/file_util.cc index 25b7aab..7043b75 100644 --- a/base/files/file_util.cc +++ b/base/files/file_util.cc
@@ -11,11 +11,11 @@ #include <fstream> #include <limits> +#include <string_view> #include "base/files/file_enumerator.h" #include "base/files/file_path.h" #include "base/logging.h" -#include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h"
diff --git a/base/files/file_util.h b/base/files/file_util.h index e22f40f..0478c91 100644 --- a/base/files/file_util.h +++ b/base/files/file_util.h
@@ -23,7 +23,6 @@ #include "base/files/file.h" #include "base/files/file_path.h" -#include "base/strings/string16.h" #include "util/build_config.h" #if defined(OS_WIN)
diff --git a/base/files/file_util_posix.cc b/base/files/file_util_posix.cc index 0749ac9..a5822f1 100644 --- a/base/files/file_util_posix.cc +++ b/base/files/file_util_posix.cc
@@ -183,7 +183,7 @@ // Appends |mode_char| to |mode| before the optional character set encoding; see // https://www.gnu.org/software/libc/manual/html_node/Opening-Streams.html for // details. -std::string AppendModeCharacter(StringPiece mode, char mode_char) { +std::string AppendModeCharacter(std::string_view mode, char mode_char) { std::string result(mode); size_t comma_pos = result.find(','); result.insert(comma_pos == std::string::npos ? result.length() : comma_pos, 1, @@ -394,7 +394,7 @@ return false; } - for (const StringPiece& cur_path : + for (const std::string_view& cur_path : SplitStringPiece(path, ":", KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY)) { FilePath file(cur_path); int permissions;
diff --git a/base/files/file_util_win.cc b/base/files/file_util_win.cc index 8fba87a..3863f72 100644 --- a/base/files/file_util_win.cc +++ b/base/files/file_util_win.cc
@@ -18,13 +18,13 @@ #include <algorithm> #include <limits> #include <string> +#include <string_view> #include "base/files/file_enumerator.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/macros.h" #include "base/strings/string_number_conversions.h" -#include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" @@ -86,9 +86,9 @@ // Appends |mode_char| to |mode| before the optional character set encoding; see // https://msdn.microsoft.com/library/yeby3zcb.aspx for details. -void AppendModeCharacter(base::char16 mode_char, base::string16* mode) { +void AppendModeCharacter(char16_t mode_char, std::u16string* mode) { size_t comma_pos = mode->find(L','); - mode->insert(comma_pos == base::string16::npos ? mode->length() : comma_pos, + mode->insert(comma_pos == std::u16string::npos ? mode->length() : comma_pos, 1, mode_char); } @@ -195,7 +195,7 @@ bool DeleteFile(const FilePath& path, bool recursive) { static constexpr char kRecursive[] = "DeleteFile.Recursive"; static constexpr char kNonRecursive[] = "DeleteFile.NonRecursive"; - const StringPiece operation(recursive ? kRecursive : kNonRecursive); + const std::string_view operation(recursive ? kRecursive : kNonRecursive); // Metrics for delete failures tracked in https://crbug.com/599084. Delete may // fail for a number of reasons. Log some metrics relating to failures in the @@ -359,7 +359,7 @@ for (int count = 0; count < 50; ++count) { // Try create a new temporary directory with random generated name. If // the one exists, keep trying another path name until we reach some limit. - string16 new_dir_name; + std::u16string new_dir_name; new_dir_name.assign(prefix); new_dir_name.append(IntToString16(::GetCurrentProcessId())); new_dir_name.push_back('_'); @@ -578,7 +578,7 @@ DCHECK( strchr(mode, 'N') == nullptr || (strchr(mode, ',') != nullptr && strchr(mode, 'N') > strchr(mode, ','))); - string16 w_mode = ASCIIToUTF16(mode); + std::u16string w_mode = ASCIIToUTF16(mode); AppendModeCharacter(L'N', &w_mode); return _wfsopen(ToWCharT(&filename.value()), ToWCharT(&w_mode), _SH_DENYNO); }
diff --git a/base/json/json_parser.cc b/base/json/json_parser.cc index 713f692..eac52a6 100644 --- a/base/json/json_parser.cc +++ b/base/json/json_parser.cc
@@ -5,6 +5,7 @@ #include "base/json/json_parser.h" #include <cmath> +#include <string_view> #include <utility> #include <vector> @@ -12,7 +13,6 @@ #include "base/macros.h" #include "base/numerics/safe_conversions.h" #include "base/strings/string_number_conversions.h" -#include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversion_utils.h" @@ -68,7 +68,7 @@ JSONParser::~JSONParser() = default; -Optional<Value> JSONParser::Parse(StringPiece input) { +Optional<Value> JSONParser::Parse(std::string_view input) { input_ = input; index_ = 0; line_number_ = 1; @@ -163,30 +163,30 @@ // JSONParser private ////////////////////////////////////////////////////////// -Optional<StringPiece> JSONParser::PeekChars(int count) { +Optional<std::string_view> JSONParser::PeekChars(int count) { if (static_cast<size_t>(index_) + count > input_.length()) return nullopt; - // Using StringPiece::substr() is significantly slower (according to + // Using std::string_view::substr() is significantly slower (according to // base_perftests) than constructing a substring manually. - return StringPiece(input_.data() + index_, count); + return std::string_view(input_.data() + index_, count); } Optional<char> JSONParser::PeekChar() { - Optional<StringPiece> chars = PeekChars(1); + Optional<std::string_view> chars = PeekChars(1); if (chars) return (*chars)[0]; return nullopt; } -Optional<StringPiece> JSONParser::ConsumeChars(int count) { - Optional<StringPiece> chars = PeekChars(count); +Optional<std::string_view> JSONParser::ConsumeChars(int count) { + Optional<std::string_view> chars = PeekChars(count); if (chars) index_ += count; return chars; } Optional<char> JSONParser::ConsumeChar() { - Optional<StringPiece> chars = ConsumeChars(1); + Optional<std::string_view> chars = ConsumeChars(1); if (chars) return (*chars)[0]; return nullopt; @@ -268,7 +268,7 @@ } bool JSONParser::EatComment() { - Optional<StringPiece> comment_start = ConsumeChars(2); + Optional<std::string_view> comment_start = ConsumeChars(2); if (!comment_start) return false; @@ -444,7 +444,7 @@ return false; } - // StringBuilder will internally build a StringPiece unless a UTF-16 + // StringBuilder will internally build a std::string_view unless a UTF-16 // conversion occurs, at which point it will perform a copy into a // std::string. StringBuilder string(pos()); @@ -475,12 +475,12 @@ } else { // And if it is an escape sequence, the input string will be adjusted // (either by combining the two characters of an encoded escape sequence, - // or with a UTF conversion), so using StringPiece isn't possible -- force - // a conversion. + // or with a UTF conversion), so using std::string_view isn't possible -- + // force a conversion. string.Convert(); // Read past the escape '\' and ensure there's a character following. - Optional<StringPiece> escape_sequence = ConsumeChars(2); + 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<StringPiece> escape_sequence = ConsumeChars(4); + Optional<std::string_view> escape_sequence = ConsumeChars(4); if (!escape_sequence) return false; @@ -671,7 +671,7 @@ index_ = exit_index; - StringPiece num_string(num_start, end_index - start_index); + std::string_view num_string(num_start, end_index - start_index); int num_int; if (StringToInt(num_string, &num_int)) @@ -717,7 +717,7 @@ } } -bool JSONParser::ConsumeIfMatch(StringPiece match) { +bool JSONParser::ConsumeIfMatch(std::string_view match) { if (match == PeekChars(match.size())) { ConsumeChars(match.size()); return true;
diff --git a/base/json/json_parser.h b/base/json/json_parser.h index 1289560..6bd61a4 100644 --- a/base/json/json_parser.h +++ b/base/json/json_parser.h
@@ -10,13 +10,13 @@ #include <memory> #include <string> +#include <string_view> #include "base/compiler_specific.h" #include "base/gtest_prod_util.h" #include "base/json/json_reader.h" #include "base/macros.h" #include "base/optional.h" -#include "base/strings/string_piece.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(StringPiece input); + Optional<Value> Parse(std::string_view input); // Returns the error code. JSONReader::JsonParseError error_code() const; @@ -83,7 +83,7 @@ }; // A helper class used for parsing strings. One optimization performed is to - // create base::Value with a StringPiece to avoid unnecessary std::string + // create base::Value with a std::string_view to avoid unnecessary std::string // copies. This is not possible if the input string needs to be decoded from // UTF-16 to UTF-8, or if an escape sequence causes characters to be skipped. // This class centralizes that logic. @@ -104,9 +104,9 @@ // converted, or by appending the UTF8 bytes for the code point. void Append(uint32_t point); - // Converts the builder from its default StringPiece to a full std::string, - // performing a copy. Once a builder is converted, it cannot be made a - // StringPiece again. + // Converts the builder from its default std::string_view to a full + // std::string, performing a copy. Once a builder is converted, it cannot be + // made a std::string_view again. void Convert(); // Returns the builder as a string, invalidating all state. This allows @@ -128,14 +128,14 @@ // Returns the next |count| bytes of the input stream, or nullopt if fewer // than |count| bytes remain. - Optional<StringPiece> PeekChars(int count); + Optional<std::string_view> PeekChars(int count); // Calls PeekChars() with a |count| of 1. 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<StringPiece> ConsumeChars(int count); + Optional<std::string_view> ConsumeChars(int count); // Calls ConsumeChars() with a |count| of 1. Optional<char> ConsumeChar(); @@ -198,7 +198,7 @@ // consumed at the current parser position. Returns false if there are fewer // than |match|-length bytes or if the sequence does not match, and the // parser state is unchanged. - bool ConsumeIfMatch(StringPiece match); + bool ConsumeIfMatch(std::string_view match); // Sets the error information to |code| at the current column, based on // |index_| and |index_last_line_|, with an optional positive/negative @@ -218,7 +218,7 @@ const int max_depth_; // The input stream being parsed. Note: Not guaranteed to NUL-terminated. - StringPiece input_; + std::string_view input_; // The index in the input stream to which the parser is wound. int index_;
diff --git a/base/json/json_reader.cc b/base/json/json_reader.cc index 3d5475e..d7eb7d9 100644 --- a/base/json/json_reader.cc +++ b/base/json/json_reader.cc
@@ -41,7 +41,7 @@ JSONReader::~JSONReader() = default; // static -std::unique_ptr<Value> JSONReader::Read(StringPiece json, +std::unique_ptr<Value> JSONReader::Read(std::string_view json, int options, int max_depth) { internal::JSONParser parser(options, max_depth); @@ -51,7 +51,7 @@ // static std::unique_ptr<Value> JSONReader::ReadAndReturnError( - StringPiece json, + std::string_view json, int options, int* error_code_out, std::string* error_msg_out, @@ -103,7 +103,7 @@ return std::string(); } -std::unique_ptr<Value> JSONReader::ReadToValue(StringPiece json) { +std::unique_ptr<Value> JSONReader::ReadToValue(std::string_view json) { Optional<Value> value = parser_->Parse(json); return value ? std::make_unique<Value>(std::move(*value)) : nullptr; }
diff --git a/base/json/json_reader.h b/base/json/json_reader.h index c4f7c8f..c454981 100644 --- a/base/json/json_reader.h +++ b/base/json/json_reader.h
@@ -30,8 +30,7 @@ #include <memory> #include <string> - -#include "base/strings/string_piece.h" +#include <string_view> namespace base { @@ -94,7 +93,7 @@ // If |json| is not a properly formed JSON string, returns nullptr. // Wrap this in base::FooValue::From() to check the Value is of type Foo and // convert to a FooValue at the same time. - static std::unique_ptr<Value> Read(StringPiece json, + static std::unique_ptr<Value> Read(std::string_view json, int options = JSON_PARSE_RFC, int max_depth = kStackMaxDepth); @@ -103,7 +102,7 @@ // an error code and a formatted error message (including error location if // appropriate). Otherwise, they will be unmodified. static std::unique_ptr<Value> ReadAndReturnError( - StringPiece json, + std::string_view json, int options, // JSONParserOptions int* error_code_out, std::string* error_msg_out, @@ -115,7 +114,7 @@ static std::string ErrorCodeToString(JsonParseError error_code); // Non-static version of Read() above. - std::unique_ptr<Value> ReadToValue(StringPiece json); + std::unique_ptr<Value> ReadToValue(std::string_view json); // Returns the error code if the last call to ReadToValue() failed. // Returns JSON_NO_ERROR otherwise.
diff --git a/base/json/json_value_converter.cc b/base/json/json_value_converter.cc index 55506e6..ee7b094 100644 --- a/base/json/json_value_converter.cc +++ b/base/json/json_value_converter.cc
@@ -17,8 +17,8 @@ return value.GetAsString(field); } -bool BasicValueConverter<string16>::Convert(const base::Value& value, - string16* field) const { +bool BasicValueConverter<std::u16string>::Convert(const base::Value& value, + std::u16string* field) const { return value.GetAsString(field); }
diff --git a/base/json/json_value_converter.h b/base/json/json_value_converter.h index d91bead..f3030f2 100644 --- a/base/json/json_value_converter.h +++ b/base/json/json_value_converter.h
@@ -9,13 +9,12 @@ #include <memory> #include <string> +#include <string_view> #include <vector> #include "base/logging.h" #include "base/macros.h" #include "base/memory/ptr_util.h" -#include "base/strings/string16.h" -#include "base/strings/string_piece.h" #include "base/values.h" // JSONValueConverter converts a JSON value into a C++ struct in a @@ -70,8 +69,8 @@ // // Sometimes JSON format uses string representations for other types such // like enum, timestamp, or URL. You can use RegisterCustomField method -// and specify a function to convert a StringPiece to your type. -// bool ConvertFunc(StringPiece s, YourEnum* result) { +// and specify a function to convert a std::string_view to your type. +// bool ConvertFunc(std::string_view s, YourEnum* result) { // // do something and return true if succeed... // } // struct Message { @@ -158,11 +157,12 @@ }; template <> -class BasicValueConverter<string16> : public ValueConverter<string16> { +class BasicValueConverter<std::u16string> + : public ValueConverter<std::u16string> { public: BasicValueConverter() = default; - bool Convert(const base::Value& value, string16* field) const override; + bool Convert(const base::Value& value, std::u16string* field) const override; private: DISALLOW_COPY_AND_ASSIGN(BasicValueConverter); @@ -211,7 +211,7 @@ template <typename FieldType> class CustomFieldConverter : public ValueConverter<FieldType> { public: - typedef bool (*ConvertFunc)(StringPiece value, FieldType* field); + typedef bool (*ConvertFunc)(std::string_view value, FieldType* field); explicit CustomFieldConverter(ConvertFunc convert_func) : convert_func_(convert_func) {} @@ -367,10 +367,11 @@ } void RegisterStringField(const std::string& field_name, - string16 StructType::*field) { + std::u16string StructType::*field) { fields_.push_back( - std::make_unique<internal::FieldConverter<StructType, string16>>( - field_name, field, new internal::BasicValueConverter<string16>)); + std::make_unique<internal::FieldConverter<StructType, std::u16string>>( + field_name, field, + new internal::BasicValueConverter<std::u16string>)); } void RegisterBoolField(const std::string& field_name, @@ -398,7 +399,7 @@ template <typename FieldType> void RegisterCustomField(const std::string& field_name, FieldType StructType::*field, - bool (*convert_func)(StringPiece, FieldType*)) { + bool (*convert_func)(std::string_view, FieldType*)) { fields_.push_back( std::make_unique<internal::FieldConverter<StructType, FieldType>>( field_name, field, @@ -436,10 +437,12 @@ void RegisterRepeatedString( const std::string& field_name, - std::vector<std::unique_ptr<string16>> StructType::*field) { - fields_.push_back(std::make_unique<internal::FieldConverter< - StructType, std::vector<std::unique_ptr<string16>>>>( - field_name, field, new internal::RepeatedValueConverter<string16>)); + std::vector<std::unique_ptr<std::u16string>> StructType::*field) { + fields_.push_back( + std::make_unique<internal::FieldConverter< + StructType, std::vector<std::unique_ptr<std::u16string>>>>( + field_name, field, + new internal::RepeatedValueConverter<std::u16string>)); } void RegisterRepeatedDouble(
diff --git a/base/json/string_escape.cc b/base/json/string_escape.cc index 471a9d3..ea674f5 100644 --- a/base/json/string_escape.cc +++ b/base/json/string_escape.cc
@@ -116,38 +116,41 @@ } // namespace -bool EscapeJSONString(StringPiece str, bool put_in_quotes, std::string* dest) { - return EscapeJSONStringImpl(str, put_in_quotes, dest); -} - -bool EscapeJSONString(StringPiece16 str, +bool EscapeJSONString(std::string_view str, bool put_in_quotes, std::string* dest) { return EscapeJSONStringImpl(str, put_in_quotes, dest); } -std::string GetQuotedJSONString(StringPiece str) { +bool EscapeJSONString(std::u16string_view str, + bool put_in_quotes, + std::string* dest) { + return EscapeJSONStringImpl(str, put_in_quotes, dest); +} + +std::string GetQuotedJSONString(std::string_view str) { std::string dest; bool ok = EscapeJSONStringImpl(str, true, &dest); DCHECK(ok); return dest; } -std::string GetQuotedJSONString(StringPiece16 str) { +std::string GetQuotedJSONString(std::u16string_view str) { std::string dest; bool ok = EscapeJSONStringImpl(str, true, &dest); DCHECK(ok); return dest; } -std::string EscapeBytesAsInvalidJSONString(StringPiece str, +std::string EscapeBytesAsInvalidJSONString(std::string_view str, bool put_in_quotes) { std::string dest; if (put_in_quotes) dest.push_back('"'); - for (StringPiece::const_iterator it = str.begin(); it != str.end(); ++it) { + for (std::string_view::const_iterator it = str.begin(); it != str.end(); + ++it) { unsigned char c = *it; if (EscapeSpecialCodePoint(c, &dest)) continue;
diff --git a/base/json/string_escape.h b/base/json/string_escape.h index d318b6a..ada5179 100644 --- a/base/json/string_escape.h +++ b/base/json/string_escape.h
@@ -8,8 +8,7 @@ #define BASE_JSON_STRING_ESCAPE_H_ #include <string> - -#include "base/strings/string_piece.h" +#include <string_view> namespace base { @@ -25,17 +24,21 @@ // // If |put_in_quotes| is true, then a leading and trailing double-quote mark // will be appended to |dest| as well. -bool EscapeJSONString(StringPiece str, bool put_in_quotes, std::string* dest); +bool EscapeJSONString(std::string_view str, + bool put_in_quotes, + std::string* dest); -// Performs a similar function to the UTF-8 StringPiece version above, +// Performs a similar function to the UTF-8 std::string_view version above, // converting UTF-16 code units to UTF-8 code units and escaping non-printing // control characters. On return, |dest| will contain a valid UTF-8 JSON string. -bool EscapeJSONString(StringPiece16 str, bool put_in_quotes, std::string* dest); +bool EscapeJSONString(std::u16string_view str, + bool put_in_quotes, + std::string* dest); // Helper functions that wrap the above two functions but return the value // instead of appending. |put_in_quotes| is always true. -std::string GetQuotedJSONString(StringPiece str); -std::string GetQuotedJSONString(StringPiece16 str); +std::string GetQuotedJSONString(std::string_view str); +std::string GetQuotedJSONString(std::u16string_view str); // Given an arbitrary byte string |str|, this will escape all non-ASCII bytes // as \uXXXX escape sequences. This function is *NOT* meant to be used with @@ -48,7 +51,8 @@ // // The output of this function takes the *appearance* of JSON but is not in // fact valid according to RFC 4627. -std::string EscapeBytesAsInvalidJSONString(StringPiece str, bool put_in_quotes); +std::string EscapeBytesAsInvalidJSONString(std::string_view str, + bool put_in_quotes); } // namespace base
diff --git a/base/logging.cc b/base/logging.cc index 1144d61..16449ee 100644 --- a/base/logging.cc +++ b/base/logging.cc
@@ -42,12 +42,12 @@ #include <iomanip> #include <ostream> #include <string> +#include <string_view> #include <utility> #include "base/callback.h" #include "base/containers/stack.h" #include "base/posix/eintr_wrapper.h" -#include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" @@ -188,9 +188,9 @@ // writes the common header info to the stream void LogMessage::Init(const char* file, int line) { - base::StringPiece filename(file); + std::string_view filename(file); size_t last_slash_pos = filename.find_last_of("\\/"); - if (last_slash_pos != base::StringPiece::npos) + if (last_slash_pos != std::string_view::npos) filename.remove_prefix(last_slash_pos + 1); // TODO(darin): It might be nice if the columns were fixed width.
diff --git a/base/logging.h b/base/logging.h index cba1c55..78c0861 100644 --- a/base/logging.h +++ b/base/logging.h
@@ -11,13 +11,13 @@ #include <cstring> #include <sstream> #include <string> +#include <string_view> #include <type_traits> #include <utility> #include "base/callback_forward.h" #include "base/compiler_specific.h" #include "base/macros.h" -#include "base/strings/string_piece.h" #include "base/template_util.h" #include "util/build_config.h"
diff --git a/base/md5.cc b/base/md5.cc index 0b50e56..4fcab55 100644 --- a/base/md5.cc +++ b/base/md5.cc
@@ -169,7 +169,7 @@ * Update context to reflect the concatenation of another buffer full * of bytes. */ -void MD5Update(MD5Context* context, const StringPiece& data) { +void MD5Update(MD5Context* context, const std::string_view& data) { struct Context* ctx = reinterpret_cast<struct Context*>(context); const uint8_t* buf = reinterpret_cast<const uint8_t*>(data.data()); size_t len = data.size(); @@ -287,11 +287,12 @@ void MD5Sum(const void* data, size_t length, MD5Digest* digest) { MD5Context ctx; MD5Init(&ctx); - MD5Update(&ctx, StringPiece(reinterpret_cast<const char*>(data), length)); + MD5Update(&ctx, + std::string_view(reinterpret_cast<const char*>(data), length)); MD5Final(digest, &ctx); } -std::string MD5String(const StringPiece& str) { +std::string MD5String(const std::string_view& str) { MD5Digest digest; MD5Sum(str.data(), str.length(), &digest); return MD5DigestToBase16(digest);
diff --git a/base/md5.h b/base/md5.h index 802645c..d25b2fc 100644 --- a/base/md5.h +++ b/base/md5.h
@@ -9,8 +9,7 @@ #include <stdint.h> #include <string> - -#include "base/strings/string_piece.h" +#include <string_view> namespace base { @@ -50,10 +49,10 @@ // MD5Update(). void MD5Init(MD5Context* context); -// For the given buffer of |data| as a StringPiece, updates the given MD5 +// For the given buffer of |data| as a std::string_view, updates the given MD5 // context with the sum of the data. You can call this any number of times // during the computation, except that MD5Init() must have been called first. -void MD5Update(MD5Context* context, const StringPiece& data); +void MD5Update(MD5Context* context, const std::string_view& data); // Finalizes the MD5 operation and fills the buffer with the digest. void MD5Final(MD5Digest* digest, MD5Context* context); @@ -71,7 +70,7 @@ void MD5Sum(const void* data, size_t length, MD5Digest* digest); // Returns the MD5 (in hexadecimal) of a string. -std::string MD5String(const StringPiece& str); +std::string MD5String(const std::string_view& str); } // namespace base
diff --git a/base/strings/char_traits.h b/base/strings/char_traits.h index b193e21..c432849 100644 --- a/base/strings/char_traits.h +++ b/base/strings/char_traits.h
@@ -13,7 +13,7 @@ // constexpr version of http://en.cppreference.com/w/cpp/string/char_traits. // This currently just implements the bits needed to support a (mostly) -// constexpr StringPiece. +// constexpr std::string_view. // // TODO(dcheng): Once we switch to C++17, most methods will become constexpr and // we can switch over to using the one in the standard library.
diff --git a/base/strings/string16.h b/base/strings/string16.h deleted file mode 100644 index a8e6ae3..0000000 --- a/base/strings/string16.h +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2013 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_STRINGS_STRING16_H_ -#define BASE_STRINGS_STRING16_H_ - -#include <string> - -namespace base { - -// Temporary definitions. These should be removed and code using the standard -// ones. -using char16 = char16_t; -using string16 = std::u16string; - -} // namespace base - -#endif // BASE_STRINGS_STRING16_H_
diff --git a/base/strings/string_number_conversions.cc b/base/strings/string_number_conversions.cc index 5f94a56..9156fa3 100644 --- a/base/strings/string_number_conversions.cc +++ b/base/strings/string_number_conversions.cc
@@ -270,38 +270,38 @@ class BaseHexIteratorRangeToUInt64Traits : public BaseIteratorRangeToNumberTraits<ITERATOR, uint64_t, 16> {}; -typedef BaseHexIteratorRangeToIntTraits<StringPiece::const_iterator> +typedef BaseHexIteratorRangeToIntTraits<std::string_view::const_iterator> HexIteratorRangeToIntTraits; -typedef BaseHexIteratorRangeToUIntTraits<StringPiece::const_iterator> +typedef BaseHexIteratorRangeToUIntTraits<std::string_view::const_iterator> HexIteratorRangeToUIntTraits; -typedef BaseHexIteratorRangeToInt64Traits<StringPiece::const_iterator> +typedef BaseHexIteratorRangeToInt64Traits<std::string_view::const_iterator> HexIteratorRangeToInt64Traits; -typedef BaseHexIteratorRangeToUInt64Traits<StringPiece::const_iterator> +typedef BaseHexIteratorRangeToUInt64Traits<std::string_view::const_iterator> HexIteratorRangeToUInt64Traits; template <typename VALUE, int BASE> class StringPieceToNumberTraits - : public BaseIteratorRangeToNumberTraits<StringPiece::const_iterator, + : public BaseIteratorRangeToNumberTraits<std::string_view::const_iterator, VALUE, BASE> {}; template <typename VALUE> -bool StringToIntImpl(StringPiece input, VALUE* output) { +bool StringToIntImpl(std::string_view input, VALUE* output) { return IteratorRangeToNumber<StringPieceToNumberTraits<VALUE, 10>>::Invoke( input.begin(), input.end(), output); } template <typename VALUE, int BASE> -class StringPiece16ToNumberTraits - : public BaseIteratorRangeToNumberTraits<StringPiece16::const_iterator, - VALUE, - BASE> {}; +class StringPiece16ToNumberTraits : public BaseIteratorRangeToNumberTraits< + std::u16string_view::const_iterator, + VALUE, + BASE> {}; template <typename VALUE> -bool String16ToIntImpl(StringPiece16 input, VALUE* output) { +bool String16ToIntImpl(std::u16string_view input, VALUE* output) { return IteratorRangeToNumber<StringPiece16ToNumberTraits<VALUE, 10>>::Invoke( input.begin(), input.end(), output); } @@ -312,87 +312,87 @@ return IntToStringT<std::string, int>::IntToString(value); } -string16 NumberToString16(int value) { - return IntToStringT<string16, int>::IntToString(value); +std::u16string NumberToString16(int value) { + return IntToStringT<std::u16string, int>::IntToString(value); } std::string NumberToString(unsigned value) { return IntToStringT<std::string, unsigned>::IntToString(value); } -string16 NumberToString16(unsigned value) { - return IntToStringT<string16, unsigned>::IntToString(value); +std::u16string NumberToString16(unsigned value) { + return IntToStringT<std::u16string, unsigned>::IntToString(value); } std::string NumberToString(long value) { return IntToStringT<std::string, long>::IntToString(value); } -string16 NumberToString16(long value) { - return IntToStringT<string16, long>::IntToString(value); +std::u16string NumberToString16(long value) { + return IntToStringT<std::u16string, long>::IntToString(value); } std::string NumberToString(unsigned long value) { return IntToStringT<std::string, unsigned long>::IntToString(value); } -string16 NumberToString16(unsigned long value) { - return IntToStringT<string16, unsigned long>::IntToString(value); +std::u16string NumberToString16(unsigned long value) { + return IntToStringT<std::u16string, unsigned long>::IntToString(value); } std::string NumberToString(long long value) { return IntToStringT<std::string, long long>::IntToString(value); } -string16 NumberToString16(long long value) { - return IntToStringT<string16, long long>::IntToString(value); +std::u16string NumberToString16(long long value) { + return IntToStringT<std::u16string, long long>::IntToString(value); } std::string NumberToString(unsigned long long value) { return IntToStringT<std::string, unsigned long long>::IntToString(value); } -string16 NumberToString16(unsigned long long value) { - return IntToStringT<string16, unsigned long long>::IntToString(value); +std::u16string NumberToString16(unsigned long long value) { + return IntToStringT<std::u16string, unsigned long long>::IntToString(value); } -bool StringToInt(StringPiece input, int* output) { +bool StringToInt(std::string_view input, int* output) { return StringToIntImpl(input, output); } -bool StringToInt(StringPiece16 input, int* output) { +bool StringToInt(std::u16string_view input, int* output) { return String16ToIntImpl(input, output); } -bool StringToUint(StringPiece input, unsigned* output) { +bool StringToUint(std::string_view input, unsigned* output) { return StringToIntImpl(input, output); } -bool StringToUint(StringPiece16 input, unsigned* output) { +bool StringToUint(std::u16string_view input, unsigned* output) { return String16ToIntImpl(input, output); } -bool StringToInt64(StringPiece input, int64_t* output) { +bool StringToInt64(std::string_view input, int64_t* output) { return StringToIntImpl(input, output); } -bool StringToInt64(StringPiece16 input, int64_t* output) { +bool StringToInt64(std::u16string_view input, int64_t* output) { return String16ToIntImpl(input, output); } -bool StringToUint64(StringPiece input, uint64_t* output) { +bool StringToUint64(std::string_view input, uint64_t* output) { return StringToIntImpl(input, output); } -bool StringToUint64(StringPiece16 input, uint64_t* output) { +bool StringToUint64(std::u16string_view input, uint64_t* output) { return String16ToIntImpl(input, output); } -bool StringToSizeT(StringPiece input, size_t* output) { +bool StringToSizeT(std::string_view input, size_t* output) { return StringToIntImpl(input, output); } -bool StringToSizeT(StringPiece16 input, size_t* output) { +bool StringToSizeT(std::u16string_view input, size_t* output) { return String16ToIntImpl(input, output); } @@ -418,27 +418,27 @@ return ret; } -bool HexStringToInt(StringPiece input, int* output) { +bool HexStringToInt(std::string_view input, int* output) { return IteratorRangeToNumber<HexIteratorRangeToIntTraits>::Invoke( input.begin(), input.end(), output); } -bool HexStringToUInt(StringPiece input, uint32_t* output) { +bool HexStringToUInt(std::string_view input, uint32_t* output) { return IteratorRangeToNumber<HexIteratorRangeToUIntTraits>::Invoke( input.begin(), input.end(), output); } -bool HexStringToInt64(StringPiece input, int64_t* output) { +bool HexStringToInt64(std::string_view input, int64_t* output) { return IteratorRangeToNumber<HexIteratorRangeToInt64Traits>::Invoke( input.begin(), input.end(), output); } -bool HexStringToUInt64(StringPiece input, uint64_t* output) { +bool HexStringToUInt64(std::string_view input, uint64_t* output) { return IteratorRangeToNumber<HexIteratorRangeToUInt64Traits>::Invoke( input.begin(), input.end(), output); } -bool HexStringToBytes(StringPiece input, std::vector<uint8_t>* output) { +bool HexStringToBytes(std::string_view input, std::vector<uint8_t>* output) { DCHECK_EQ(output->size(), 0u); size_t count = input.size(); if (count == 0 || (count % 2) != 0)
diff --git a/base/strings/string_number_conversions.h b/base/strings/string_number_conversions.h index 8ffdd36..81360a0 100644 --- a/base/strings/string_number_conversions.h +++ b/base/strings/string_number_conversions.h
@@ -9,10 +9,9 @@ #include <stdint.h> #include <string> +#include <string_view> #include <vector> -#include "base/strings/string16.h" -#include "base/strings/string_piece.h" #include "util/build_config.h" namespace base { @@ -21,17 +20,17 @@ // Ignores locale! see warning above. std::string NumberToString(int value); -string16 NumberToString16(int value); +std::u16string NumberToString16(int value); std::string NumberToString(unsigned int value); -string16 NumberToString16(unsigned int value); +std::u16string NumberToString16(unsigned int value); std::string NumberToString(long value); -string16 NumberToString16(long value); +std::u16string NumberToString16(long value); std::string NumberToString(unsigned long value); -string16 NumberToString16(unsigned long value); +std::u16string NumberToString16(unsigned long value); std::string NumberToString(long long value); -string16 NumberToString16(long long value); +std::u16string NumberToString16(long long value); std::string NumberToString(unsigned long long value); -string16 NumberToString16(unsigned long long value); +std::u16string NumberToString16(unsigned long long value); // Type-specific naming for backwards compatibility. // @@ -40,19 +39,19 @@ inline std::string IntToString(int value) { return NumberToString(value); } -inline string16 IntToString16(int value) { +inline std::u16string IntToString16(int value) { return NumberToString16(value); } inline std::string UintToString(unsigned value) { return NumberToString(value); } -inline string16 UintToString16(unsigned value) { +inline std::u16string UintToString16(unsigned value) { return NumberToString16(value); } inline std::string Int64ToString(int64_t value) { return NumberToString(value); } -inline string16 Int64ToString16(int64_t value) { +inline std::u16string Int64ToString16(int64_t value) { return NumberToString16(value); } @@ -74,20 +73,20 @@ // - Empty string. |*output| will be set to 0. // WARNING: Will write to |output| even when returning false. // Read the comments above carefully. -bool StringToInt(StringPiece input, int* output); -bool StringToInt(StringPiece16 input, int* output); +bool StringToInt(std::string_view input, int* output); +bool StringToInt(std::u16string_view input, int* output); -bool StringToUint(StringPiece input, unsigned* output); -bool StringToUint(StringPiece16 input, unsigned* output); +bool StringToUint(std::string_view input, unsigned* output); +bool StringToUint(std::u16string_view input, unsigned* output); -bool StringToInt64(StringPiece input, int64_t* output); -bool StringToInt64(StringPiece16 input, int64_t* output); +bool StringToInt64(std::string_view input, int64_t* output); +bool StringToInt64(std::u16string_view input, int64_t* output); -bool StringToUint64(StringPiece input, uint64_t* output); -bool StringToUint64(StringPiece16 input, uint64_t* output); +bool StringToUint64(std::string_view input, uint64_t* output); +bool StringToUint64(std::u16string_view input, uint64_t* output); -bool StringToSizeT(StringPiece input, size_t* output); -bool StringToSizeT(StringPiece16 input, size_t* output); +bool StringToSizeT(std::string_view input, size_t* output); +bool StringToSizeT(std::u16string_view input, size_t* output); // Hex encoding ---------------------------------------------------------------- @@ -102,30 +101,30 @@ // Best effort conversion, see StringToInt above for restrictions. // Will only successful parse hex values that will fit into |output|, i.e. // -0x80000000 < |input| < 0x7FFFFFFF. -bool HexStringToInt(StringPiece input, int* output); +bool HexStringToInt(std::string_view input, int* output); // Best effort conversion, see StringToInt above for restrictions. // Will only successful parse hex values that will fit into |output|, i.e. // 0x00000000 < |input| < 0xFFFFFFFF. // The string is not required to start with 0x. -bool HexStringToUInt(StringPiece input, uint32_t* output); +bool HexStringToUInt(std::string_view input, uint32_t* output); // Best effort conversion, see StringToInt above for restrictions. // Will only successful parse hex values that will fit into |output|, i.e. // -0x8000000000000000 < |input| < 0x7FFFFFFFFFFFFFFF. -bool HexStringToInt64(StringPiece input, int64_t* output); +bool HexStringToInt64(std::string_view input, int64_t* output); // Best effort conversion, see StringToInt above for restrictions. // Will only successful parse hex values that will fit into |output|, i.e. // 0x0000000000000000 < |input| < 0xFFFFFFFFFFFFFFFF. // The string is not required to start with 0x. -bool HexStringToUInt64(StringPiece input, uint64_t* output); +bool HexStringToUInt64(std::string_view input, uint64_t* output); // Similar to the previous functions, except that output is a vector of bytes. // |*output| will contain as many bytes as were successfully parsed prior to the // error. There is no overflow, but input.size() must be evenly divisible by 2. // Leading 0x or +/- are not allowed. -bool HexStringToBytes(StringPiece input, std::vector<uint8_t>* output); +bool HexStringToBytes(std::string_view input, std::vector<uint8_t>* output); } // namespace base
diff --git a/base/strings/string_piece.h b/base/strings/string_piece.h deleted file mode 100644 index fa215ef..0000000 --- a/base/strings/string_piece.h +++ /dev/null
@@ -1,37 +0,0 @@ -// Copyright (c) 2012 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. -// Copied from strings/stringpiece.h with modifications -// -// A string-like object that points to a sized piece of memory. -// -// You can use StringPiece as a function or method parameter. A StringPiece -// parameter can receive a double-quoted string literal argument, a "const -// char*" argument, a string argument, or a StringPiece argument with no data -// copying. Systematic use of StringPiece for arguments reduces data -// copies and strlen() calls. -// -// Prefer passing StringPieces by value: -// void MyFunction(StringPiece arg); -// If circumstances require, you may also pass by const reference: -// void MyFunction(const StringPiece& arg); // not preferred -// Both of these have the same lifetime semantics. Passing by value -// generates slightly smaller code. For more discussion, Googlers can see -// the thread go/stringpiecebyvalue on c-users. - -#ifndef BASE_STRINGS_STRING_PIECE_H_ -#define BASE_STRINGS_STRING_PIECE_H_ - -#include <string_view> - -namespace base { - -// Temporary definitions. These should be removed and code using the standard -// ones. -using StringPiece = std::string_view; -using StringPiece16 = std::u16string_view; -using WStringPiece = std::wstring_view; - -} // namespace base - -#endif // BASE_STRINGS_STRING_PIECE_H_
diff --git a/base/strings/string_split.cc b/base/strings/string_split.cc index a57d537..f4c7eb2 100644 --- a/base/strings/string_split.cc +++ b/base/strings/string_split.cc
@@ -18,11 +18,11 @@ template <typename char_type> std::basic_string_view<char_type> WhitespaceForType(); template <> -StringPiece16 WhitespaceForType<char16_t>() { +std::u16string_view WhitespaceForType<char16_t>() { return kWhitespaceUTF16; } template <> -StringPiece WhitespaceForType<char>() { +std::string_view WhitespaceForType<char>() { return kWhitespaceASCII; } @@ -30,29 +30,34 @@ // since this is the common case and can be made faster. This could have been // done with template specialization too, but would have been less clear. // -// There is no corresponding FindFirstNotOf because StringPiece already +// There is no corresponding FindFirstNotOf because std::string_view already // implements these different versions that do the optimized searching. -size_t FindFirstOf(StringPiece piece, char c, size_t pos) { +size_t FindFirstOf(std::string_view piece, char c, size_t pos) { return piece.find(c, pos); } -size_t FindFirstOf(StringPiece16 piece, char16 c, size_t pos) { +size_t FindFirstOf(std::u16string_view piece, char16_t c, size_t pos) { return piece.find(c, pos); } -size_t FindFirstOf(StringPiece piece, StringPiece one_of, size_t pos) { +size_t FindFirstOf(std::string_view piece, + std::string_view one_of, + size_t pos) { return piece.find_first_of(one_of, pos); } -size_t FindFirstOf(StringPiece16 piece, StringPiece16 one_of, size_t pos) { +size_t FindFirstOf(std::u16string_view piece, + std::u16string_view one_of, + size_t pos) { return piece.find_first_of(one_of, pos); } // General string splitter template. Can take 8- or 16-bit input, can produce -// the corresponding string or StringPiece output, and can take single- or +// the corresponding string or std::string_view output, and can take single- or // multiple-character delimiters. // // DelimiterType is either a character (Str::value_type) or a string piece of -// multiple characters (std::basic_string_view<char>). StringPiece has a version -// of find for both of these cases, and the single-character version is the most -// common and can be implemented faster, which is why this is a template. +// multiple characters (std::basic_string_view<char>). std::string_view has a +// version of find for both of these cases, and the single-character version is +// the most common and can be implemented faster, which is why this is a +// template. template <typename char_type, typename OutputStringType, typename DelimiterType> static std::vector<OutputStringType> SplitStringT( std::basic_string_view<char_type> str, @@ -87,7 +92,7 @@ return result; } -bool AppendStringKeyValue(StringPiece input, +bool AppendStringKeyValue(std::string_view input, char delimiter, StringPairs* result) { // Always append a new item regardless of success (it might be empty). The @@ -103,9 +108,10 @@ result_pair.first.assign(input.substr(0, end_key_pos)); // Find the value string. - StringPiece remains = input.substr(end_key_pos, input.size() - end_key_pos); + std::string_view remains = + input.substr(end_key_pos, input.size() - end_key_pos); size_t begin_value_pos = remains.find_first_not_of(delimiter); - if (begin_value_pos == StringPiece::npos) { + if (begin_value_pos == std::string_view::npos) { return false; // No value. } result_pair.second.assign( @@ -141,67 +147,68 @@ } // namespace -std::vector<std::string> SplitString(StringPiece input, - StringPiece separators, +std::vector<std::string> SplitString(std::string_view input, + std::string_view separators, WhitespaceHandling whitespace, SplitResult result_type) { if (separators.size() == 1) { return SplitStringT<char, std::string, char>(input, separators[0], whitespace, result_type); } - return SplitStringT<char, std::string, StringPiece>(input, separators, - whitespace, result_type); -} - -std::vector<string16> SplitString(StringPiece16 input, - StringPiece16 separators, - WhitespaceHandling whitespace, - SplitResult result_type) { - if (separators.size() == 1) { - return SplitStringT<char16_t, string16, char16>(input, separators[0], - whitespace, result_type); - } - return SplitStringT<char16_t, string16, StringPiece16>( + return SplitStringT<char, std::string, std::string_view>( input, separators, whitespace, result_type); } -std::vector<StringPiece> SplitStringPiece(StringPiece input, - StringPiece separators, - WhitespaceHandling whitespace, - SplitResult result_type) { +std::vector<std::u16string> SplitString(std::u16string_view input, + std::u16string_view separators, + WhitespaceHandling whitespace, + SplitResult result_type) { if (separators.size() == 1) { - return SplitStringT<char, StringPiece, char>(input, separators[0], - whitespace, result_type); - } - return SplitStringT<char, StringPiece, StringPiece>(input, separators, - whitespace, result_type); -} - -std::vector<StringPiece16> SplitStringPiece(StringPiece16 input, - StringPiece16 separators, - WhitespaceHandling whitespace, - SplitResult result_type) { - if (separators.size() == 1) { - return SplitStringT<char16_t, StringPiece16, char16>( + return SplitStringT<char16_t, std::u16string, char16_t>( input, separators[0], whitespace, result_type); } - return SplitStringT<char16_t, StringPiece16, StringPiece16>( + return SplitStringT<char16_t, std::u16string, std::u16string_view>( input, separators, whitespace, result_type); } -bool SplitStringIntoKeyValuePairs(StringPiece input, +std::vector<std::string_view> SplitStringPiece(std::string_view input, + std::string_view separators, + WhitespaceHandling whitespace, + SplitResult result_type) { + if (separators.size() == 1) { + return SplitStringT<char, std::string_view, char>(input, separators[0], + whitespace, result_type); + } + return SplitStringT<char, std::string_view, std::string_view>( + input, separators, whitespace, result_type); +} + +std::vector<std::u16string_view> SplitStringPiece( + std::u16string_view input, + std::u16string_view separators, + WhitespaceHandling whitespace, + SplitResult result_type) { + if (separators.size() == 1) { + return SplitStringT<char16_t, std::u16string_view, char16_t>( + input, separators[0], whitespace, result_type); + } + return SplitStringT<char16_t, std::u16string_view, std::u16string_view>( + input, separators, whitespace, result_type); +} + +bool SplitStringIntoKeyValuePairs(std::string_view input, char key_value_delimiter, char key_value_pair_delimiter, StringPairs* key_value_pairs) { key_value_pairs->clear(); - std::vector<StringPiece> pairs = + std::vector<std::string_view> pairs = SplitStringPiece(input, std::string(1, key_value_pair_delimiter), TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY); key_value_pairs->reserve(pairs.size()); bool success = true; - for (const StringPiece& pair : pairs) { + for (const std::string_view& pair : pairs) { if (!AppendStringKeyValue(pair, key_value_delimiter, key_value_pairs)) { // Don't return here, to allow for pairs without associated // value or key; just record that the split failed. @@ -211,17 +218,18 @@ return success; } -std::vector<string16> SplitStringUsingSubstr(StringPiece16 input, - StringPiece16 delimiter, - WhitespaceHandling whitespace, - SplitResult result_type) { - std::vector<string16> result; +std::vector<std::u16string> SplitStringUsingSubstr( + std::u16string_view input, + std::u16string_view delimiter, + WhitespaceHandling whitespace, + SplitResult result_type) { + std::vector<std::u16string> result; SplitStringUsingSubstrT(input, delimiter, whitespace, result_type, &result); return result; } -std::vector<std::string> SplitStringUsingSubstr(StringPiece input, - StringPiece delimiter, +std::vector<std::string> SplitStringUsingSubstr(std::string_view input, + std::string_view delimiter, WhitespaceHandling whitespace, SplitResult result_type) { std::vector<std::string> result; @@ -229,22 +237,22 @@ return result; } -std::vector<StringPiece16> SplitStringPieceUsingSubstr( - StringPiece16 input, - StringPiece16 delimiter, +std::vector<std::u16string_view> SplitStringPieceUsingSubstr( + std::u16string_view input, + std::u16string_view delimiter, WhitespaceHandling whitespace, SplitResult result_type) { - std::vector<StringPiece16> result; + std::vector<std::u16string_view> result; SplitStringUsingSubstrT(input, delimiter, whitespace, result_type, &result); return result; } -std::vector<StringPiece> SplitStringPieceUsingSubstr( - StringPiece input, - StringPiece delimiter, +std::vector<std::string_view> SplitStringPieceUsingSubstr( + std::string_view input, + std::string_view delimiter, WhitespaceHandling whitespace, SplitResult result_type) { - std::vector<StringPiece> result; + std::vector<std::string_view> result; SplitStringUsingSubstrT(input, delimiter, whitespace, result_type, &result); return result; }
diff --git a/base/strings/string_split.h b/base/strings/string_split.h index 6f8fc7c..7ba14e1 100644 --- a/base/strings/string_split.h +++ b/base/strings/string_split.h
@@ -6,12 +6,10 @@ #define BASE_STRINGS_STRING_SPLIT_H_ #include <string> +#include <string_view> #include <utility> #include <vector> -#include "base/strings/string16.h" -#include "base/strings/string_piece.h" - namespace base { enum WhitespaceHandling { @@ -42,14 +40,14 @@ // // std::vector<std::string> tokens = base::SplitString( // input, ",;", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); -std::vector<std::string> SplitString(StringPiece input, - StringPiece separators, +std::vector<std::string> SplitString(std::string_view input, + std::string_view separators, WhitespaceHandling whitespace, SplitResult result_type); -std::vector<string16> SplitString(StringPiece16 input, - StringPiece16 separators, - WhitespaceHandling whitespace, - SplitResult result_type); +std::vector<std::u16string> SplitString(std::u16string_view input, + std::u16string_view separators, + WhitespaceHandling whitespace, + SplitResult result_type); // Like SplitString above except it returns a vector of StringPieces which // reference the original buffer without copying. Although you have to be @@ -63,14 +61,15 @@ // base::KEEP_WHITESPACE, // base::SPLIT_WANT_NONEMPTY)) { // ... -std::vector<StringPiece> SplitStringPiece(StringPiece input, - StringPiece separators, - WhitespaceHandling whitespace, - SplitResult result_type); -std::vector<StringPiece16> SplitStringPiece(StringPiece16 input, - StringPiece16 separators, - WhitespaceHandling whitespace, - SplitResult result_type); +std::vector<std::string_view> SplitStringPiece(std::string_view input, + std::string_view separators, + WhitespaceHandling whitespace, + SplitResult result_type); +std::vector<std::u16string_view> SplitStringPiece( + std::u16string_view input, + std::u16string_view separators, + WhitespaceHandling whitespace, + SplitResult result_type); using StringPairs = std::vector<std::pair<std::string, std::string>>; @@ -78,19 +77,20 @@ // removes whitespace leading each key and trailing each value. Returns true // only if each pair has a non-empty key and value. |key_value_pairs| will // include ("","") pairs for entries without |key_value_delimiter|. -bool SplitStringIntoKeyValuePairs(StringPiece input, +bool SplitStringIntoKeyValuePairs(std::string_view input, char key_value_delimiter, char key_value_pair_delimiter, StringPairs* key_value_pairs); // Similar to SplitString, but use a substring delimiter instead of a list of // characters that are all possible delimiters. -std::vector<string16> SplitStringUsingSubstr(StringPiece16 input, - StringPiece16 delimiter, - WhitespaceHandling whitespace, - SplitResult result_type); -std::vector<std::string> SplitStringUsingSubstr(StringPiece input, - StringPiece delimiter, +std::vector<std::u16string> SplitStringUsingSubstr( + std::u16string_view input, + std::u16string_view delimiter, + WhitespaceHandling whitespace, + SplitResult result_type); +std::vector<std::string> SplitStringUsingSubstr(std::string_view input, + std::string_view delimiter, WhitespaceHandling whitespace, SplitResult result_type); @@ -106,14 +106,14 @@ // base::KEEP_WHITESPACE, // base::SPLIT_WANT_NONEMPTY)) { // ... -std::vector<StringPiece16> SplitStringPieceUsingSubstr( - StringPiece16 input, - StringPiece16 delimiter, +std::vector<std::u16string_view> SplitStringPieceUsingSubstr( + std::u16string_view input, + std::u16string_view delimiter, WhitespaceHandling whitespace, SplitResult result_type); -std::vector<StringPiece> SplitStringPieceUsingSubstr( - StringPiece input, - StringPiece delimiter, +std::vector<std::string_view> SplitStringPieceUsingSubstr( + std::string_view input, + std::string_view delimiter, WhitespaceHandling whitespace, SplitResult result_type);
diff --git a/base/strings/string_tokenizer.h b/base/strings/string_tokenizer.h index 50deb88..fe9401d 100644 --- a/base/strings/string_tokenizer.h +++ b/base/strings/string_tokenizer.h
@@ -7,8 +7,7 @@ #include <algorithm> #include <string> - -#include "base/strings/string_piece.h" +#include <string_view> namespace base {
diff --git a/base/strings/string_util.cc b/base/strings/string_util.cc index f6ee491..d8f28d4 100644 --- a/base/strings/string_util.cc +++ b/base/strings/string_util.cc
@@ -67,7 +67,7 @@ template <size_t size, typename CharacterType> struct NonASCIIMask; template <> -struct NonASCIIMask<4, char16> { +struct NonASCIIMask<4, char16_t> { static inline uint32_t value() { return 0xFF80FF80U; } }; template <> @@ -75,7 +75,7 @@ static inline uint32_t value() { return 0x80808080U; } }; template <> -struct NonASCIIMask<8, char16> { +struct NonASCIIMask<8, char16_t> { static inline uint64_t value() { return 0xFF80FF80FF80FF80ULL; } }; template <> @@ -109,20 +109,20 @@ } // namespace -std::string ToLowerASCII(StringPiece str) { +std::string ToLowerASCII(std::string_view str) { return ToLowerASCIIImpl<std::string>(str); } -string16 ToLowerASCII(StringPiece16 str) { - return ToLowerASCIIImpl<string16>(str); +std::u16string ToLowerASCII(std::u16string_view str) { + return ToLowerASCIIImpl<std::u16string>(str); } -std::string ToUpperASCII(StringPiece str) { +std::string ToUpperASCII(std::string_view str) { return ToUpperASCIIImpl<std::string>(str); } -string16 ToUpperASCII(StringPiece16 str) { - return ToUpperASCIIImpl<string16>(str); +std::u16string ToUpperASCII(std::u16string_view str) { + return ToUpperASCIIImpl<std::u16string>(str); } template <class StringType> @@ -153,24 +153,24 @@ return 1; } -int CompareCaseInsensitiveASCII(StringPiece a, StringPiece b) { +int CompareCaseInsensitiveASCII(std::string_view a, std::string_view b) { return CompareCaseInsensitiveASCIIT<std::string>(a, b); } -int CompareCaseInsensitiveASCII(StringPiece16 a, StringPiece16 b) { - return CompareCaseInsensitiveASCIIT<string16>(a, b); +int CompareCaseInsensitiveASCII(std::u16string_view a, std::u16string_view b) { + return CompareCaseInsensitiveASCIIT<std::u16string>(a, b); } -bool EqualsCaseInsensitiveASCII(StringPiece a, StringPiece b) { +bool EqualsCaseInsensitiveASCII(std::string_view a, std::string_view b) { if (a.length() != b.length()) return false; return CompareCaseInsensitiveASCIIT<std::string>(a, b) == 0; } -bool EqualsCaseInsensitiveASCII(StringPiece16 a, StringPiece16 b) { +bool EqualsCaseInsensitiveASCII(std::u16string_view a, std::u16string_view b) { if (a.length() != b.length()) return false; - return CompareCaseInsensitiveASCIIT<string16>(a, b) == 0; + return CompareCaseInsensitiveASCIIT<std::u16string>(a, b) == 0; } template <class StringType> @@ -180,31 +180,32 @@ std::basic_string_view<typename StringType::value_type> replace_with, StringType* output); -bool ReplaceChars(const string16& input, - StringPiece16 replace_chars, - const string16& replace_with, - string16* output) { - return ReplaceCharsT(input, replace_chars, StringPiece16(replace_with), +bool ReplaceChars(const std::u16string& input, + std::u16string_view replace_chars, + const std::u16string& replace_with, + std::u16string* output) { + return ReplaceCharsT(input, replace_chars, std::u16string_view(replace_with), output); } bool ReplaceChars(const std::string& input, - StringPiece replace_chars, + std::string_view replace_chars, const std::string& replace_with, std::string* output) { - return ReplaceCharsT(input, replace_chars, StringPiece(replace_with), output); + return ReplaceCharsT(input, replace_chars, std::string_view(replace_with), + output); } -bool RemoveChars(const string16& input, - StringPiece16 remove_chars, - string16* output) { - return ReplaceCharsT(input, remove_chars, StringPiece16(), output); +bool RemoveChars(const std::u16string& input, + std::u16string_view remove_chars, + std::u16string* output) { + return ReplaceCharsT(input, remove_chars, std::u16string_view(), output); } bool RemoveChars(const std::string& input, - StringPiece remove_chars, + std::string_view remove_chars, std::string* output) { - return ReplaceCharsT(input, remove_chars, StringPiece(), output); + return ReplaceCharsT(input, remove_chars, std::string_view(), output); } template <typename Str> @@ -214,8 +215,8 @@ TrimPositions positions, Str* output) { // Find the edges of leading/trailing whitespace as desired. Need to use - // a StringPiece version of input to be able to call find* on it with the - // StringPiece version of trim_chars (normally the trim_chars will be a + // a std::string_view version of input to be able to call find* on it with the + // std::string_view version of trim_chars (normally the trim_chars will be a // constant so avoid making a copy). std::basic_string_view<typename Str::value_type> input_piece(input); const size_t last_char = input.length() - 1; @@ -245,14 +246,14 @@ ((last_good_char == last_char) ? TRIM_NONE : TRIM_TRAILING)); } -bool TrimString(const string16& input, - StringPiece16 trim_chars, - string16* output) { +bool TrimString(const std::u16string& input, + std::u16string_view trim_chars, + std::u16string* output) { return TrimStringT(input, trim_chars, TRIM_ALL, output) != TRIM_NONE; } bool TrimString(const std::string& input, - StringPiece trim_chars, + std::string_view trim_chars, std::string* output) { return TrimStringT(input, trim_chars, TRIM_ALL, output) != TRIM_NONE; } @@ -273,15 +274,15 @@ return input.substr(begin, end - begin); } -StringPiece16 TrimString(StringPiece16 input, - StringPiece16 trim_chars, - TrimPositions positions) { +std::u16string_view TrimString(std::u16string_view input, + std::u16string_view trim_chars, + TrimPositions positions) { return TrimStringPieceT(input, trim_chars, positions); } -StringPiece TrimString(StringPiece input, - StringPiece trim_chars, - TrimPositions positions) { +std::string_view TrimString(std::string_view input, + std::string_view trim_chars, + TrimPositions positions) { return TrimStringPieceT(input, trim_chars, positions); } @@ -321,24 +322,29 @@ output->clear(); } -TrimPositions TrimWhitespace(const string16& input, +TrimPositions TrimWhitespace(const std::u16string& input, TrimPositions positions, - string16* output) { - return TrimStringT(input, StringPiece16(kWhitespaceUTF16), positions, output); + std::u16string* output) { + return TrimStringT(input, std::u16string_view(kWhitespaceUTF16), positions, + output); } -StringPiece16 TrimWhitespace(StringPiece16 input, TrimPositions positions) { - return TrimStringPieceT(input, StringPiece16(kWhitespaceUTF16), positions); +std::u16string_view TrimWhitespace(std::u16string_view input, + TrimPositions positions) { + return TrimStringPieceT(input, std::u16string_view(kWhitespaceUTF16), + positions); } TrimPositions TrimWhitespaceASCII(const std::string& input, TrimPositions positions, std::string* output) { - return TrimStringT(input, StringPiece(kWhitespaceASCII), positions, output); + return TrimStringT(input, std::string_view(kWhitespaceASCII), positions, + output); } -StringPiece TrimWhitespaceASCII(StringPiece input, TrimPositions positions) { - return TrimStringPieceT(input, StringPiece(kWhitespaceASCII), positions); +std::string_view TrimWhitespaceASCII(std::string_view input, + TrimPositions positions) { + return TrimStringPieceT(input, std::string_view(kWhitespaceASCII), positions); } template <typename STR> @@ -382,8 +388,8 @@ return result; } -string16 CollapseWhitespace(const string16& text, - bool trim_sequences_with_line_breaks) { +std::u16string CollapseWhitespace(const std::u16string& text, + bool trim_sequences_with_line_breaks) { return CollapseWhitespaceT(text, trim_sequences_with_line_breaks); } @@ -392,12 +398,13 @@ return CollapseWhitespaceT(text, trim_sequences_with_line_breaks); } -bool ContainsOnlyChars(StringPiece input, StringPiece characters) { - return input.find_first_not_of(characters) == StringPiece::npos; +bool ContainsOnlyChars(std::string_view input, std::string_view characters) { + return input.find_first_not_of(characters) == std::string_view::npos; } -bool ContainsOnlyChars(StringPiece16 input, StringPiece16 characters) { - return input.find_first_not_of(characters) == StringPiece16::npos; +bool ContainsOnlyChars(std::u16string_view input, + std::u16string_view characters) { + return input.find_first_not_of(characters) == std::u16string_view::npos; } template <class Char> @@ -430,15 +437,15 @@ return !(all_char_bits & non_ascii_bit_mask); } -bool IsStringASCII(StringPiece str) { +bool IsStringASCII(std::string_view str) { return DoIsStringASCII(str.data(), str.length()); } -bool IsStringASCII(StringPiece16 str) { +bool IsStringASCII(std::u16string_view str) { return DoIsStringASCII(str.data(), str.length()); } -bool IsStringUTF8(StringPiece str) { +bool IsStringUTF8(std::string_view str) { const char* src = str.data(); int32_t src_len = static_cast<int32_t>(str.length()); int32_t char_index = 0; @@ -453,8 +460,8 @@ } // Implementation note: Normally this function will be called with a hardcoded -// constant for the lowercase_ascii parameter. Constructing a StringPiece from -// a C constant requires running strlen, so the result will be two passes +// constant for the lowercase_ascii parameter. Constructing a std::string_view +// from a C constant requires running strlen, so the result will be two passes // through the buffers, one to file the length of lowercase_ascii, and one to // compare each letter. // @@ -466,11 +473,11 @@ // // The hardcoded strings are typically very short so it doesn't matter, and the // string piece gives additional flexibility for the caller (doesn't have to be -// null terminated) so we choose the StringPiece route. +// null terminated) so we choose the std::string_view route. template <typename Str> static inline bool DoLowerCaseEqualsASCII( std::basic_string_view<typename Str::value_type> str, - StringPiece lowercase_ascii) { + std::string_view lowercase_ascii) { if (str.size() != lowercase_ascii.size()) return false; for (size_t i = 0; i < str.size(); i++) { @@ -480,15 +487,17 @@ return true; } -bool LowerCaseEqualsASCII(StringPiece str, StringPiece lowercase_ascii) { +bool LowerCaseEqualsASCII(std::string_view str, + std::string_view lowercase_ascii) { return DoLowerCaseEqualsASCII<std::string>(str, lowercase_ascii); } -bool LowerCaseEqualsASCII(StringPiece16 str, StringPiece lowercase_ascii) { - return DoLowerCaseEqualsASCII<string16>(str, lowercase_ascii); +bool LowerCaseEqualsASCII(std::u16string_view str, + std::string_view lowercase_ascii) { + return DoLowerCaseEqualsASCII<std::u16string>(str, lowercase_ascii); } -bool EqualsASCII(StringPiece16 str, StringPiece ascii) { +bool EqualsASCII(std::u16string_view str, std::string_view ascii) { if (str.length() != ascii.length()) return false; return std::equal(ascii.begin(), ascii.end(), str.begin()); @@ -517,14 +526,14 @@ } } -bool StartsWith(StringPiece str, - StringPiece search_for, +bool StartsWith(std::string_view str, + std::string_view search_for, CompareCase case_sensitivity) { return StartsWithT(str, search_for, case_sensitivity); } -bool StartsWith(StringPiece16 str, - StringPiece16 search_for, +bool StartsWith(std::u16string_view str, + std::u16string_view search_for, CompareCase case_sensitivity) { return StartsWithT(str, search_for, case_sensitivity); } @@ -554,16 +563,16 @@ } } -bool EndsWith(StringPiece str, - StringPiece search_for, +bool EndsWith(std::string_view str, + std::string_view search_for, CompareCase case_sensitivity) { return EndsWithT<std::string>(str, search_for, case_sensitivity); } -bool EndsWith(StringPiece16 str, - StringPiece16 search_for, +bool EndsWith(std::u16string_view str, + std::u16string_view search_for, CompareCase case_sensitivity) { - return EndsWithT<string16>(str, search_for, case_sensitivity); + return EndsWithT<std::u16string>(str, search_for, case_sensitivity); } char HexDigitToInt(char16_t c) { @@ -589,7 +598,7 @@ static const char* const kByteStringsUnlocalized[] = {" B", " kB", " MB", " GB", " TB", " PB"}; -string16 FormatBytesUnlocalized(int64_t bytes) { +std::u16string FormatBytesUnlocalized(int64_t bytes) { double unit_amount = static_cast<double>(bytes); size_t dimension = 0; const int kKilo = 1024; @@ -800,37 +809,37 @@ ReplaceType::REPLACE_ALL); } -void ReplaceFirstSubstringAfterOffset(string16* str, +void ReplaceFirstSubstringAfterOffset(std::u16string* str, size_t start_offset, - StringPiece16 find_this, - StringPiece16 replace_with) { + std::u16string_view find_this, + std::u16string_view replace_with) { DoReplaceMatchesAfterOffset(str, start_offset, - SubstringMatcher<string16>{find_this}, + SubstringMatcher<std::u16string>{find_this}, replace_with, ReplaceType::REPLACE_FIRST); } void ReplaceFirstSubstringAfterOffset(std::string* str, size_t start_offset, - StringPiece find_this, - StringPiece replace_with) { + std::string_view find_this, + std::string_view replace_with) { DoReplaceMatchesAfterOffset(str, start_offset, SubstringMatcher<std::string>{find_this}, replace_with, ReplaceType::REPLACE_FIRST); } -void ReplaceSubstringsAfterOffset(string16* str, +void ReplaceSubstringsAfterOffset(std::u16string* str, size_t start_offset, - StringPiece16 find_this, - StringPiece16 replace_with) { + std::u16string_view find_this, + std::u16string_view replace_with) { DoReplaceMatchesAfterOffset(str, start_offset, - SubstringMatcher<string16>{find_this}, + SubstringMatcher<std::u16string>{find_this}, replace_with, ReplaceType::REPLACE_ALL); } void ReplaceSubstringsAfterOffset(std::string* str, size_t start_offset, - StringPiece find_this, - StringPiece replace_with) { + std::string_view find_this, + std::string_view replace_with) { DoReplaceMatchesAfterOffset(str, start_offset, SubstringMatcher<std::string>{find_this}, replace_with, ReplaceType::REPLACE_ALL); @@ -849,7 +858,7 @@ return WriteIntoT(str, length_with_null); } -char16* WriteInto(string16* str, size_t length_with_null) { +char16_t* WriteInto(std::u16string* str, size_t length_with_null) { return WriteIntoT(str, length_with_null); } @@ -892,12 +901,12 @@ } std::string JoinString(const std::vector<std::string>& parts, - StringPiece separator) { + std::string_view separator) { return JoinStringT(parts, separator); } -string16 JoinString(const std::vector<string16>& parts, - StringPiece16 separator) { +std::u16string JoinString(const std::vector<std::u16string>& parts, + std::u16string_view separator) { return JoinStringT(parts, separator); } @@ -906,23 +915,23 @@ #pragma optimize("", on) #endif -std::string JoinString(const std::vector<StringPiece>& parts, - StringPiece separator) { +std::string JoinString(const std::vector<std::string_view>& parts, + std::string_view separator) { return JoinStringT(parts, separator); } -string16 JoinString(const std::vector<StringPiece16>& parts, - StringPiece16 separator) { +std::u16string JoinString(const std::vector<std::u16string_view>& parts, + std::u16string_view separator) { return JoinStringT(parts, separator); } -std::string JoinString(std::initializer_list<StringPiece> parts, - StringPiece separator) { +std::string JoinString(std::initializer_list<std::string_view> parts, + std::string_view separator) { return JoinStringT(parts, separator); } -string16 JoinString(std::initializer_list<StringPiece16> parts, - StringPiece16 separator) { +std::u16string JoinString(std::initializer_list<std::u16string_view> parts, + std::u16string_view separator) { return JoinStringT(parts, separator); } @@ -981,25 +990,27 @@ return formatted; } -string16 ReplaceStringPlaceholders(const string16& format_string, - const std::vector<string16>& subst, - std::vector<size_t>* offsets) { +std::u16string ReplaceStringPlaceholders( + const std::u16string& format_string, + const std::vector<std::u16string>& subst, + std::vector<size_t>* offsets) { return DoReplaceStringPlaceholders(format_string, subst, offsets); } -std::string ReplaceStringPlaceholders(StringPiece format_string, +std::string ReplaceStringPlaceholders(std::string_view format_string, const std::vector<std::string>& subst, std::vector<size_t>* offsets) { return DoReplaceStringPlaceholders(format_string, subst, offsets); } -string16 ReplaceStringPlaceholders(const string16& format_string, - const string16& a, - size_t* offset) { +std::u16string ReplaceStringPlaceholders(const std::u16string& format_string, + const std::u16string& a, + size_t* offset) { std::vector<size_t> offsets; - std::vector<string16> subst; + std::vector<std::u16string> subst; subst.push_back(a); - string16 result = ReplaceStringPlaceholders(format_string, subst, &offsets); + std::u16string result = + ReplaceStringPlaceholders(format_string, subst, &offsets); DCHECK_EQ(1U, offsets.size()); if (offset)
diff --git a/base/strings/string_util.h b/base/strings/string_util.h index 9b3c608..9ed66b2 100644 --- a/base/strings/string_util.h +++ b/base/strings/string_util.h
@@ -14,11 +14,10 @@ #include <initializer_list> #include <string> +#include <string_view> #include <vector> #include "base/compiler_specific.h" -#include "base/strings/string16.h" -#include "base/strings/string_piece.h" // For implicit conversions. #include "util/build_config.h" namespace base { @@ -58,7 +57,7 @@ inline char ToLowerASCII(char c) { return (c >= 'A' && c <= 'Z') ? (c + ('a' - 'A')) : c; } -inline char16 ToLowerASCII(char16 c) { +inline char16_t ToLowerASCII(char16_t c) { return (c >= 'A' && c <= 'Z') ? (c + ('a' - 'A')) : c; } @@ -67,17 +66,17 @@ inline char ToUpperASCII(char c) { return (c >= 'a' && c <= 'z') ? (c + ('A' - 'a')) : c; } -inline char16 ToUpperASCII(char16 c) { +inline char16_t ToUpperASCII(char16_t c) { return (c >= 'a' && c <= 'z') ? (c + ('A' - 'a')) : c; } // Converts the given string to it's ASCII-lowercase equivalent. -std::string ToLowerASCII(StringPiece str); -string16 ToLowerASCII(StringPiece16 str); +std::string ToLowerASCII(std::string_view str); +std::u16string ToLowerASCII(std::u16string_view str); // Converts the given string to it's ASCII-uppercase equivalent. -std::string ToUpperASCII(StringPiece str); -string16 ToUpperASCII(StringPiece16 str); +std::string ToUpperASCII(std::string_view str); +std::u16string ToUpperASCII(std::u16string_view str); // Functor for case-insensitive ASCII comparisons for STL algorithms like // std::search. @@ -102,21 +101,21 @@ // (unlike strcasecmp which can return values greater or less than 1/-1). For // full Unicode support, use base::i18n::ToLower or base::i18h::FoldCase // and then just call the normal string operators on the result. -int CompareCaseInsensitiveASCII(StringPiece a, StringPiece b); -int CompareCaseInsensitiveASCII(StringPiece16 a, StringPiece16 b); +int CompareCaseInsensitiveASCII(std::string_view a, std::string_view b); +int CompareCaseInsensitiveASCII(std::u16string_view a, std::u16string_view b); // Equality for ASCII case-insensitive comparisons. For full Unicode support, // use base::i18n::ToLower or base::i18h::FoldCase and then compare with either // == or !=. -bool EqualsCaseInsensitiveASCII(StringPiece a, StringPiece b); -bool EqualsCaseInsensitiveASCII(StringPiece16 a, StringPiece16 b); +bool EqualsCaseInsensitiveASCII(std::string_view a, std::string_view b); +bool EqualsCaseInsensitiveASCII(std::u16string_view a, std::u16string_view b); // Contains the set of characters representing whitespace in the corresponding // encoding. Null-terminated. The ASCII versions are the whitespaces as defined // by HTML5, and don't include control characters. -extern const char16 kWhitespaceUTF16[]; // Includes Unicode. +extern const char16_t kWhitespaceUTF16[]; // Includes Unicode. extern const char kWhitespaceASCII[]; -extern const char16 kWhitespaceASCIIAs16[]; // No unicode. +extern const char16_t kWhitespaceASCIIAs16[]; // No unicode. // Null-terminated string representing the UTF-8 byte order mark. extern const char kUtf8ByteOrderMark[]; @@ -124,11 +123,11 @@ // Removes characters in |remove_chars| from anywhere in |input|. Returns true // if any characters were removed. |remove_chars| must be null-terminated. // NOTE: Safe to use the same variable for both |input| and |output|. -bool RemoveChars(const string16& input, - StringPiece16 remove_chars, - string16* output); +bool RemoveChars(const std::u16string& input, + std::u16string_view remove_chars, + std::u16string* output); bool RemoveChars(const std::string& input, - StringPiece remove_chars, + std::string_view remove_chars, std::string* output); // Replaces characters in |replace_chars| from anywhere in |input| with @@ -136,12 +135,12 @@ // the |replace_with| string. Returns true if any characters were replaced. // |replace_chars| must be null-terminated. // NOTE: Safe to use the same variable for both |input| and |output|. -bool ReplaceChars(const string16& input, - StringPiece16 replace_chars, - const string16& replace_with, - string16* output); +bool ReplaceChars(const std::u16string& input, + std::u16string_view replace_chars, + const std::u16string& replace_with, + std::u16string* output); bool ReplaceChars(const std::string& input, - StringPiece replace_chars, + std::string_view replace_chars, const std::string& replace_with, std::string* output); @@ -158,21 +157,21 @@ // // It is safe to use the same variable for both |input| and |output| (this is // the normal usage to trim in-place). -bool TrimString(const string16& input, - StringPiece16 trim_chars, - string16* output); +bool TrimString(const std::u16string& input, + std::u16string_view trim_chars, + std::u16string* output); bool TrimString(const std::string& input, - StringPiece trim_chars, + std::string_view trim_chars, std::string* output); -// StringPiece versions of the above. The returned pieces refer to the original -// buffer. -StringPiece16 TrimString(StringPiece16 input, - StringPiece16 trim_chars, - TrimPositions positions); -StringPiece TrimString(StringPiece input, - StringPiece trim_chars, - TrimPositions positions); +// std::string_view versions of the above. The returned pieces refer to the +// original buffer. +std::u16string_view TrimString(std::u16string_view input, + std::u16string_view trim_chars, + TrimPositions positions); +std::string_view TrimString(std::string_view input, + std::string_view trim_chars, + TrimPositions positions); // Truncates a string to the nearest UTF-8 character that will leave // the string less than or equal to the specified byte size. @@ -182,19 +181,21 @@ // Trims any whitespace from either end of the input string. // -// The StringPiece versions return a substring referencing the input buffer. -// The ASCII versions look only for ASCII whitespace. +// The std::string_view versions return a substring referencing the input +// buffer. The ASCII versions look only for ASCII whitespace. // // The std::string versions return where whitespace was found. // NOTE: Safe to use the same variable for both input and output. -TrimPositions TrimWhitespace(const string16& input, +TrimPositions TrimWhitespace(const std::u16string& input, TrimPositions positions, - string16* output); -StringPiece16 TrimWhitespace(StringPiece16 input, TrimPositions positions); + std::u16string* output); +std::u16string_view TrimWhitespace(std::u16string_view input, + TrimPositions positions); TrimPositions TrimWhitespaceASCII(const std::string& input, TrimPositions positions, std::string* output); -StringPiece TrimWhitespaceASCII(StringPiece input, TrimPositions positions); +std::string_view TrimWhitespaceASCII(std::string_view input, + TrimPositions positions); // Searches for CR or LF characters. Removes all contiguous whitespace // strings that contain them. This is useful when trying to deal with text @@ -204,15 +205,16 @@ // (2) If |trim_sequences_with_line_breaks| is true, any other whitespace // sequences containing a CR or LF are trimmed. // (3) All other whitespace sequences are converted to single spaces. -string16 CollapseWhitespace(const string16& text, - bool trim_sequences_with_line_breaks); +std::u16string CollapseWhitespace(const std::u16string& text, + bool trim_sequences_with_line_breaks); std::string CollapseWhitespaceASCII(const std::string& text, bool trim_sequences_with_line_breaks); // Returns true if |input| is empty or contains only characters found in // |characters|. -bool ContainsOnlyChars(StringPiece input, StringPiece characters); -bool ContainsOnlyChars(StringPiece16 input, StringPiece16 characters); +bool ContainsOnlyChars(std::string_view input, std::string_view characters); +bool ContainsOnlyChars(std::u16string_view input, + std::u16string_view characters); // Returns true if the specified string matches the criteria. How can a wide // string be 8-bit or UTF8? It contains only characters that are < 256 (in the @@ -228,19 +230,21 @@ // // IsStringASCII assumes the input is likely all ASCII, and does not leave early // if it is not the case. -bool IsStringUTF8(StringPiece str); -bool IsStringASCII(StringPiece str); -bool IsStringASCII(StringPiece16 str); +bool IsStringUTF8(std::string_view str); +bool IsStringASCII(std::string_view str); +bool IsStringASCII(std::u16string_view str); // Compare the lower-case form of the given string against the given // previously-lower-cased ASCII string (typically a constant). -bool LowerCaseEqualsASCII(StringPiece str, StringPiece lowecase_ascii); -bool LowerCaseEqualsASCII(StringPiece16 str, StringPiece lowecase_ascii); +bool LowerCaseEqualsASCII(std::string_view str, + std::string_view lowecase_ascii); +bool LowerCaseEqualsASCII(std::u16string_view str, + std::string_view lowecase_ascii); // Performs a case-sensitive string compare of the given 16-bit string against // the given 8-bit ASCII string (typically a constant). The behavior is // undefined if the |ascii| string is not ASCII. -bool EqualsASCII(StringPiece16 str, StringPiece ascii); +bool EqualsASCII(std::u16string_view str, std::string_view ascii); // Indicates case sensitivity of comparisons. Only ASCII case insensitivity // is supported. Full Unicode case-insensitive conversions would need to go in @@ -255,17 +259,17 @@ INSENSITIVE_ASCII, }; -bool StartsWith(StringPiece str, - StringPiece search_for, +bool StartsWith(std::string_view str, + std::string_view search_for, CompareCase case_sensitivity); -bool StartsWith(StringPiece16 str, - StringPiece16 search_for, +bool StartsWith(std::u16string_view str, + std::u16string_view search_for, CompareCase case_sensitivity); -bool EndsWith(StringPiece str, - StringPiece search_for, +bool EndsWith(std::string_view str, + std::string_view search_for, CompareCase case_sensitivity); -bool EndsWith(StringPiece16 str, - StringPiece16 search_for, +bool EndsWith(std::u16string_view str, + std::u16string_view search_for, CompareCase case_sensitivity); // Determines the type of ASCII character, independent of locale (the C @@ -311,18 +315,18 @@ // appropriate for use in any UI; use of FormatBytes and friends in ui/base is // highly recommended instead. TODO(avi): Figure out how to get callers to use // FormatBytes instead; remove this. -string16 FormatBytesUnlocalized(int64_t bytes); +std::u16string FormatBytesUnlocalized(int64_t bytes); // Starting at |start_offset| (usually 0), replace the first instance of // |find_this| with |replace_with|. -void ReplaceFirstSubstringAfterOffset(base::string16* str, +void ReplaceFirstSubstringAfterOffset(std::u16string* str, size_t start_offset, - StringPiece16 find_this, - StringPiece16 replace_with); + std::u16string_view find_this, + std::u16string_view replace_with); void ReplaceFirstSubstringAfterOffset(std::string* str, size_t start_offset, - StringPiece find_this, - StringPiece replace_with); + std::string_view find_this, + std::string_view replace_with); // Starting at |start_offset| (usually 0), look through |str| and replace all // instances of |find_this| with |replace_with|. @@ -330,14 +334,14 @@ // This does entire substrings; use std::replace in <algorithm> for single // characters, for example: // std::replace(str.begin(), str.end(), 'a', 'b'); -void ReplaceSubstringsAfterOffset(string16* str, +void ReplaceSubstringsAfterOffset(std::u16string* str, size_t start_offset, - StringPiece16 find_this, - StringPiece16 replace_with); + std::u16string_view find_this, + std::u16string_view replace_with); void ReplaceSubstringsAfterOffset(std::string* str, size_t start_offset, - StringPiece find_this, - StringPiece replace_with); + std::string_view find_this, + std::string_view replace_with); // Reserves enough memory in |str| to accommodate |length_with_null| characters, // sets the size of |str| to |length_with_null - 1| characters, and returns a @@ -360,51 +364,52 @@ // than str.c_str() will get back a string of whatever size |str| had on entry // to this function (probably 0). char* WriteInto(std::string* str, size_t length_with_null); -char16* WriteInto(string16* str, size_t length_with_null); +char16_t* WriteInto(std::u16string* str, size_t length_with_null); // Does the opposite of SplitString()/SplitStringPiece(). Joins a vector or list // of strings into a single string, inserting |separator| (which may be empty) // in between all elements. // -// If possible, callers should build a vector of StringPieces and use the -// StringPiece variant, so that they do not create unnecessary copies of +// If possible, callers should build a vector of std::string_views and use the +// std::string_view variant, so that they do not create unnecessary copies of // strings. For example, instead of using SplitString, modifying the vector, // then using JoinString, use SplitStringPiece followed by JoinString so that no // copies of those strings are created until the final join operation. // // Use StrCat (in base/strings/strcat.h) if you don't need a separator. std::string JoinString(const std::vector<std::string>& parts, - StringPiece separator); -string16 JoinString(const std::vector<string16>& parts, - StringPiece16 separator); -std::string JoinString(const std::vector<StringPiece>& parts, - StringPiece separator); -string16 JoinString(const std::vector<StringPiece16>& parts, - StringPiece16 separator); + std::string_view separator); +std::u16string JoinString(const std::vector<std::u16string>& parts, + std::u16string_view separator); +std::string JoinString(const std::vector<std::string_view>& parts, + std::string_view separator); +std::u16string JoinString(const std::vector<std::u16string_view>& parts, + std::u16string_view separator); // Explicit initializer_list overloads are required to break ambiguity when used // with a literal initializer list (otherwise the compiler would not be able to -// decide between the string and StringPiece overloads). -std::string JoinString(std::initializer_list<StringPiece> parts, - StringPiece separator); -string16 JoinString(std::initializer_list<StringPiece16> parts, - StringPiece16 separator); +// decide between the string and std::string_view overloads). +std::string JoinString(std::initializer_list<std::string_view> parts, + std::string_view separator); +std::u16string JoinString(std::initializer_list<std::u16string_view> parts, + std::u16string_view separator); // Replace $1-$2-$3..$9 in the format string with values from |subst|. // Additionally, any number of consecutive '$' characters is replaced by that // number less one. Eg $$->$, $$$->$$, etc. The offsets parameter here can be // NULL. This only allows you to use up to nine replacements. -string16 ReplaceStringPlaceholders(const string16& format_string, - const std::vector<string16>& subst, - std::vector<size_t>* offsets); +std::u16string ReplaceStringPlaceholders( + const std::u16string& format_string, + const std::vector<std::u16string>& subst, + std::vector<size_t>* offsets); -std::string ReplaceStringPlaceholders(StringPiece format_string, +std::string ReplaceStringPlaceholders(std::string_view format_string, const std::vector<std::string>& subst, std::vector<size_t>* offsets); // Single-string shortcut for ReplaceStringHolders. |offset| may be NULL. -string16 ReplaceStringPlaceholders(const string16& format_string, - const string16& a, - size_t* offset); +std::u16string ReplaceStringPlaceholders(const std::u16string& format_string, + const std::u16string& a, + size_t* offset); } // namespace base
diff --git a/base/strings/string_util_constants.cc b/base/strings/string_util_constants.cc index ed17fcd..de88454 100644 --- a/base/strings/string_util_constants.cc +++ b/base/strings/string_util_constants.cc
@@ -34,7 +34,7 @@ 0x3000, /* IDEOGRAPHIC SPACE */ \ 0 -const char16 kWhitespaceUTF16[] = {WHITESPACE_UNICODE}; +const char16_t kWhitespaceUTF16[] = {WHITESPACE_UNICODE}; const char kWhitespaceASCII[] = {0x09, // CHARACTER TABULATION 0x0A, // LINE FEED (LF) @@ -44,13 +44,13 @@ 0x20, // SPACE 0}; -const char16 kWhitespaceASCIIAs16[] = {0x09, // CHARACTER TABULATION - 0x0A, // LINE FEED (LF) - 0x0B, // LINE TABULATION - 0x0C, // FORM FEED (FF) - 0x0D, // CARRIAGE RETURN (CR) - 0x20, // SPACE - 0}; +const char16_t kWhitespaceASCIIAs16[] = {0x09, // CHARACTER TABULATION + 0x0A, // LINE FEED (LF) + 0x0B, // LINE TABULATION + 0x0C, // FORM FEED (FF) + 0x0D, // CARRIAGE RETURN (CR) + 0x20, // SPACE + 0}; const char kUtf8ByteOrderMark[] = "\xEF\xBB\xBF";
diff --git a/base/strings/utf_offset_string_conversions.cc b/base/strings/utf_offset_string_conversions.cc index 177839a..ee55a24 100644 --- a/base/strings/utf_offset_string_conversions.cc +++ b/base/strings/utf_offset_string_conversions.cc
@@ -8,9 +8,9 @@ #include <algorithm> #include <memory> +#include <string_view> #include "base/logging.h" -#include "base/strings/string_piece.h" #include "base/strings/utf_string_conversion_utils.h" namespace base { @@ -37,7 +37,7 @@ size_t* offset, size_t limit) { DCHECK(offset); - if (*offset == string16::npos) + if (*offset == std::u16string::npos) return; int adjustment = 0; for (Adjustments::const_iterator i = adjustments.begin(); @@ -45,7 +45,7 @@ if (*offset <= i->original_offset) break; if (*offset < (i->original_offset + i->original_length)) { - *offset = string16::npos; + *offset = std::u16string::npos; return; } adjustment += static_cast<int>(i->original_length - i->output_length); @@ -53,7 +53,7 @@ *offset -= adjustment; if (*offset > limit) - *offset = string16::npos; + *offset = std::u16string::npos; } // static @@ -70,7 +70,7 @@ // static void OffsetAdjuster::UnadjustOffset(const Adjustments& adjustments, size_t* offset) { - if (*offset == string16::npos) + if (*offset == std::u16string::npos) return; int adjustment = 0; for (Adjustments::const_iterator i = adjustments.begin(); @@ -79,7 +79,7 @@ break; adjustment += static_cast<int>(i->original_length - i->output_length); if ((*offset + adjustment) < (i->original_offset + i->original_length)) { - *offset = string16::npos; + *offset = std::u16string::npos; return; } } @@ -221,39 +221,39 @@ bool UTF8ToUTF16WithAdjustments( const char* src, size_t src_len, - string16* output, + std::u16string* output, base::OffsetAdjuster::Adjustments* adjustments) { PrepareForUTF16Or32Output(src, src_len, output); return ConvertUnicode(src, src_len, output, adjustments); } -string16 UTF8ToUTF16WithAdjustments( - const base::StringPiece& utf8, +std::u16string UTF8ToUTF16WithAdjustments( + const std::string_view& utf8, base::OffsetAdjuster::Adjustments* adjustments) { - string16 result; + std::u16string result; UTF8ToUTF16WithAdjustments(utf8.data(), utf8.length(), &result, adjustments); return result; } -string16 UTF8ToUTF16AndAdjustOffsets( - const base::StringPiece& utf8, +std::u16string UTF8ToUTF16AndAdjustOffsets( + const std::string_view& utf8, std::vector<size_t>* offsets_for_adjustment) { for (size_t& offset : *offsets_for_adjustment) { if (offset > utf8.length()) - offset = string16::npos; + offset = std::u16string::npos; } OffsetAdjuster::Adjustments adjustments; - string16 result = UTF8ToUTF16WithAdjustments(utf8, &adjustments); + std::u16string result = UTF8ToUTF16WithAdjustments(utf8, &adjustments); OffsetAdjuster::AdjustOffsets(adjustments, offsets_for_adjustment); return result; } std::string UTF16ToUTF8AndAdjustOffsets( - const base::StringPiece16& utf16, + const std::u16string_view& utf16, std::vector<size_t>* offsets_for_adjustment) { for (size_t& offset : *offsets_for_adjustment) { if (offset > utf16.length()) - offset = string16::npos; + offset = std::u16string::npos; } std::string result; PrepareForUTF8Output(utf16.data(), utf16.length(), &result);
diff --git a/base/strings/utf_offset_string_conversions.h b/base/strings/utf_offset_string_conversions.h index b7c4a1b..8d6c5e8 100644 --- a/base/strings/utf_offset_string_conversions.h +++ b/base/strings/utf_offset_string_conversions.h
@@ -8,11 +8,9 @@ #include <stddef.h> #include <string> +#include <string_view> #include <vector> -#include "base/strings/string16.h" -#include "base/strings/string_piece.h" - namespace base { // A helper class and associated data structures to adjust offsets into a @@ -34,7 +32,7 @@ // Adjusts all offsets in |offsets_for_adjustment| to reflect the adjustments // recorded in |adjustments|. Adjusted offsets greater than |limit| will be - // set to string16::npos. + // set to std::u16string::npos. // // Offsets represents insertion/selection points between characters: if |src| // is "abcd", then 0 is before 'a', 2 is between 'b' and 'c', and 4 is at the @@ -42,23 +40,24 @@ // exit, each offset will have been modified to point at the same logical // position in the output string. If an offset cannot be successfully // adjusted (e.g., because it points into the middle of a multibyte sequence), - // it will be set to string16::npos. + // it will be set to std::u16string::npos. static void AdjustOffsets(const Adjustments& adjustments, std::vector<size_t>* offsets_for_adjustment, - size_t limit = string16::npos); + size_t limit = std::u16string::npos); // Adjusts the single |offset| to reflect the adjustments recorded in // |adjustments|. static void AdjustOffset(const Adjustments& adjustments, size_t* offset, - size_t limit = string16::npos); + size_t limit = std::u16string::npos); // Adjusts all offsets in |offsets_for_unadjustment| to reflect the reverse // of the adjustments recorded in |adjustments|. In other words, the offsets // provided represent offsets into an adjusted string and the caller wants // to know the offsets they correspond to in the original string. If an // offset cannot be successfully unadjusted (e.g., because it points into - // the middle of a multibyte sequence), it will be set to string16::npos. + // the middle of a multibyte sequence), it will be set to + // std::u16string::npos. static void UnadjustOffsets(const Adjustments& adjustments, std::vector<size_t>* offsets_for_unadjustment); @@ -91,19 +90,20 @@ // It may be NULL. bool UTF8ToUTF16WithAdjustments(const char* src, size_t src_len, - string16* output, + std::u16string* output, base::OffsetAdjuster::Adjustments* adjustments); -string16 UTF8ToUTF16WithAdjustments( - const base::StringPiece& utf8, +std::u16string UTF8ToUTF16WithAdjustments( + const std::string_view& utf8, base::OffsetAdjuster::Adjustments* adjustments); // As above, but instead internally examines the adjustments and applies them // to |offsets_for_adjustment|. Input offsets greater than the length of the -// input string will be set to string16::npos. See comments by AdjustOffsets(). -string16 UTF8ToUTF16AndAdjustOffsets( - const base::StringPiece& utf8, +// input string will be set to std::u16string::npos. See comments by +// AdjustOffsets(). +std::u16string UTF8ToUTF16AndAdjustOffsets( + const std::string_view& utf8, std::vector<size_t>* offsets_for_adjustment); std::string UTF16ToUTF8AndAdjustOffsets( - const base::StringPiece16& utf16, + const std::u16string_view& utf16, std::vector<size_t>* offsets_for_adjustment); } // namespace base
diff --git a/base/strings/utf_string_conversion_utils.cc b/base/strings/utf_string_conversion_utils.cc index 838471c..32aa3e3 100644 --- a/base/strings/utf_string_conversion_utils.cc +++ b/base/strings/utf_string_conversion_utils.cc
@@ -75,10 +75,10 @@ return char_offset - original_char_offset; } -size_t WriteUnicodeCharacter(uint32_t code_point, string16* output) { +size_t WriteUnicodeCharacter(uint32_t code_point, std::u16string* output) { if (CBU16_LENGTH(code_point) == 1) { // Thie code point is in the Basic Multilingual Plane (BMP). - output->push_back(static_cast<char16>(code_point)); + output->push_back(static_cast<char16_t>(code_point)); return 1; } // Non-BMP characters use a double-character encoding. @@ -127,6 +127,6 @@ } // Instantiate versions we know callers will need. -template void PrepareForUTF16Or32Output(const char*, size_t, string16*); +template void PrepareForUTF16Or32Output(const char*, size_t, std::u16string*); } // namespace base
diff --git a/base/strings/utf_string_conversion_utils.h b/base/strings/utf_string_conversion_utils.h index 3f14808..e24a7db 100644 --- a/base/strings/utf_string_conversion_utils.h +++ b/base/strings/utf_string_conversion_utils.h
@@ -11,7 +11,7 @@ #include <stddef.h> #include <stdint.h> -#include "base/strings/string16.h" +#include <string> namespace base { @@ -60,7 +60,7 @@ // Appends the given code point as a UTF-16 character to the given 16-bit // string. Returns the number of 16-bit values written. -size_t WriteUnicodeCharacter(uint32_t code_point, string16* output); +size_t WriteUnicodeCharacter(uint32_t code_point, std::u16string* output); // Generalized Unicode converter -----------------------------------------------
diff --git a/base/strings/utf_string_conversions.cc b/base/strings/utf_string_conversions.cc index 15f12f6..4b4e420 100644 --- a/base/strings/utf_string_conversions.cc +++ b/base/strings/utf_string_conversions.cc
@@ -6,7 +6,8 @@ #include <stdint.h> -#include "base/strings/string_piece.h" +#include <string_view> + #include "base/strings/string_util.h" #include "base/strings/utf_string_conversion_utils.h" #include "base/third_party/icu/icu_utf.h" @@ -32,7 +33,7 @@ }; template <> -struct SizeCoefficient<char16, char> { +struct SizeCoefficient<char16_t, char> { // One UTF-16 codeunit corresponds to at most 3 codeunits in UTF-8. static constexpr int value = 3; }; @@ -49,7 +50,7 @@ CBU8_APPEND_UNSAFE(out, *size, code_point); } -void UnicodeAppendUnsafe(char16* out, int32_t* size, uint32_t code_point) { +void UnicodeAppendUnsafe(char16_t* out, int32_t* size, uint32_t code_point) { CBU16_APPEND_UNSAFE(out, *size, code_point); } @@ -80,13 +81,13 @@ } template <typename DestChar> -bool DoUTFConversion(const char16* src, +bool DoUTFConversion(const char16_t* src, int32_t src_len, DestChar* dest, int32_t* dest_len) { bool success = true; - auto ConvertSingleChar = [&success](char16 in) -> int32_t { + auto ConvertSingleChar = [&success](char16_t in) -> int32_t { if (!CBU16_IS_SINGLE(in) || !IsValidCodepoint(in)) { success = false; return kErrorCodePoint; @@ -155,23 +156,23 @@ // UTF16 <-> UTF8 -------------------------------------------------------------- -bool UTF8ToUTF16(const char* src, size_t src_len, string16* output) { - return UTFConversion(StringPiece(src, src_len), output); +bool UTF8ToUTF16(const char* src, size_t src_len, std::u16string* output) { + return UTFConversion(std::string_view(src, src_len), output); } -string16 UTF8ToUTF16(StringPiece utf8) { - string16 ret; +std::u16string UTF8ToUTF16(std::string_view utf8) { + std::u16string ret; // Ignore the success flag of this call, it will do the best it can for // invalid input, which is what we want here. UTF8ToUTF16(utf8.data(), utf8.size(), &ret); return ret; } -bool UTF16ToUTF8(const char16* src, size_t src_len, std::string* output) { - return UTFConversion(StringPiece16(src, src_len), output); +bool UTF16ToUTF8(const char16_t* src, size_t src_len, std::string* output) { + return UTFConversion(std::u16string_view(src, src_len), output); } -std::string UTF16ToUTF8(StringPiece16 utf16) { +std::string UTF16ToUTF8(std::u16string_view utf16) { std::string ret; // Ignore the success flag of this call, it will do the best it can for // invalid input, which is what we want here. @@ -181,12 +182,12 @@ // ASCII <-> UTF-16 ----------------------------------------------------------- -string16 ASCIIToUTF16(StringPiece ascii) { +std::u16string ASCIIToUTF16(std::string_view ascii) { DCHECK(IsStringASCII(ascii)) << ascii; - return string16(ascii.begin(), ascii.end()); + return std::u16string(ascii.begin(), ascii.end()); } -std::string UTF16ToASCII(StringPiece16 utf16) { +std::string UTF16ToASCII(std::u16string_view utf16) { DCHECK(IsStringASCII(utf16)) << UTF16ToUTF8(utf16); return std::string(utf16.begin(), utf16.end()); }
diff --git a/base/strings/utf_string_conversions.h b/base/strings/utf_string_conversions.h index c4c2b11..116e6a5 100644 --- a/base/strings/utf_string_conversions.h +++ b/base/strings/utf_string_conversions.h
@@ -8,24 +8,22 @@ #include <stddef.h> #include <string> - -#include "base/strings/string16.h" -#include "base/strings/string_piece.h" +#include <string_view> namespace base { -bool UTF8ToUTF16(const char* src, size_t src_len, string16* output); -string16 UTF8ToUTF16(StringPiece utf8); -bool UTF16ToUTF8(const char16* src, size_t src_len, std::string* output); -std::string UTF16ToUTF8(StringPiece16 utf16); +bool UTF8ToUTF16(const char* src, size_t src_len, std::u16string* output); +std::u16string UTF8ToUTF16(std::string_view utf8); +bool UTF16ToUTF8(const char16_t* src, size_t src_len, std::string* output); +std::string UTF16ToUTF8(std::u16string_view utf16); // This converts an ASCII string, typically a hardcoded constant, to a UTF16 // string. -string16 ASCIIToUTF16(StringPiece ascii); +std::u16string ASCIIToUTF16(std::string_view ascii); // Converts to 7-bit ASCII by truncating. The result must be known to be ASCII // beforehand. -std::string UTF16ToASCII(StringPiece16 utf16); +std::string UTF16ToASCII(std::u16string_view utf16); } // namespace base
diff --git a/base/values.cc b/base/values.cc index 0b348b7..9c34803 100644 --- a/base/values.cc +++ b/base/values.cc
@@ -130,16 +130,18 @@ Value::Value(const char* in_string) : Value(std::string(in_string)) {} -Value::Value(StringPiece in_string) : Value(std::string(in_string)) {} +Value::Value(std::string_view in_string) : Value(std::string(in_string)) {} Value::Value(std::string&& in_string) noexcept : type_(Type::STRING), string_value_(std::move(in_string)) { DCHECK(IsStringUTF8(string_value_)); } -Value::Value(const char16* in_string16) : Value(StringPiece16(in_string16)) {} +Value::Value(const char16_t* in_string16) + : Value(std::u16string_view(in_string16)) {} -Value::Value(StringPiece16 in_string16) : Value(UTF16ToUTF8(in_string16)) {} +Value::Value(std::u16string_view in_string16) + : Value(UTF16ToUTF8(in_string16)) {} Value::Value(const BlobStorage& in_blob) : type_(Type::BINARY), binary_value_(in_blob) {} @@ -237,11 +239,11 @@ return list_; } -Value* Value::FindKey(StringPiece key) { +Value* Value::FindKey(std::string_view key) { return const_cast<Value*>(static_cast<const Value*>(this)->FindKey(key)); } -const Value* Value::FindKey(StringPiece key) const { +const Value* Value::FindKey(std::string_view key) const { CHECK(is_dict()); auto found = dict_.find(key); if (found == dict_.end()) @@ -249,28 +251,28 @@ return found->second.get(); } -Value* Value::FindKeyOfType(StringPiece key, Type type) { +Value* Value::FindKeyOfType(std::string_view key, Type type) { return const_cast<Value*>( static_cast<const Value*>(this)->FindKeyOfType(key, type)); } -const Value* Value::FindKeyOfType(StringPiece key, Type type) const { +const Value* Value::FindKeyOfType(std::string_view key, Type type) const { const Value* result = FindKey(key); if (!result || result->type() != type) return nullptr; return result; } -bool Value::RemoveKey(StringPiece key) { +bool Value::RemoveKey(std::string_view key) { CHECK(is_dict()); // NOTE: Can't directly return dict_->erase(key) due to MSVC warning C4800. return dict_.erase(key) != 0; } -Value* Value::SetKey(StringPiece key, Value value) { +Value* Value::SetKey(std::string_view key, Value value) { CHECK(is_dict()); // NOTE: We can't use |insert_or_assign| here, as only |try_emplace| does - // an explicit conversion from StringPiece to std::string if necessary. + // an explicit conversion from std::string_view to std::string if necessary. auto val_ptr = std::make_unique<Value>(std::move(value)); auto result = dict_.try_emplace(key, std::move(val_ptr)); if (!result.second) { @@ -289,49 +291,50 @@ } Value* Value::SetKey(const char* key, Value value) { - return SetKey(StringPiece(key), std::move(value)); + return SetKey(std::string_view(key), std::move(value)); } -Value* Value::FindPath(std::initializer_list<StringPiece> path) { +Value* Value::FindPath(std::initializer_list<std::string_view> path) { return const_cast<Value*>(const_cast<const Value*>(this)->FindPath(path)); } -Value* Value::FindPath(span<const StringPiece> path) { +Value* Value::FindPath(span<const std::string_view> path) { return const_cast<Value*>(const_cast<const Value*>(this)->FindPath(path)); } -const Value* Value::FindPath(std::initializer_list<StringPiece> path) const { +const Value* Value::FindPath( + std::initializer_list<std::string_view> path) const { DCHECK_GE(path.size(), 2u) << "Use FindKey() for a path of length 1."; return FindPath(make_span(path.begin(), path.size())); } -const Value* Value::FindPath(span<const StringPiece> path) const { +const Value* Value::FindPath(span<const std::string_view> path) const { const Value* cur = this; - for (const StringPiece component : path) { + for (const std::string_view component : path) { if (!cur->is_dict() || (cur = cur->FindKey(component)) == nullptr) return nullptr; } return cur; } -Value* Value::FindPathOfType(std::initializer_list<StringPiece> path, +Value* Value::FindPathOfType(std::initializer_list<std::string_view> path, Type type) { return const_cast<Value*>( const_cast<const Value*>(this)->FindPathOfType(path, type)); } -Value* Value::FindPathOfType(span<const StringPiece> path, Type type) { +Value* Value::FindPathOfType(span<const std::string_view> path, Type type) { return const_cast<Value*>( const_cast<const Value*>(this)->FindPathOfType(path, type)); } -const Value* Value::FindPathOfType(std::initializer_list<StringPiece> path, +const Value* Value::FindPathOfType(std::initializer_list<std::string_view> path, Type type) const { DCHECK_GE(path.size(), 2u) << "Use FindKeyOfType() for a path of length 1."; return FindPathOfType(make_span(path.begin(), path.size()), type); } -const Value* Value::FindPathOfType(span<const StringPiece> path, +const Value* Value::FindPathOfType(span<const std::string_view> path, Type type) const { const Value* result = FindPath(path); if (!result || result->type() != type) @@ -339,24 +342,25 @@ return result; } -Value* Value::SetPath(std::initializer_list<StringPiece> path, Value value) { +Value* Value::SetPath(std::initializer_list<std::string_view> path, + Value value) { DCHECK_GE(path.size(), 2u) << "Use SetKey() for a path of length 1."; return SetPath(make_span(path.begin(), path.size()), std::move(value)); } -Value* Value::SetPath(span<const StringPiece> path, Value value) { +Value* Value::SetPath(span<const std::string_view> path, Value value) { DCHECK_NE(path.begin(), path.end()); // Can't be empty path. // Walk/construct intermediate dictionaries. The last element requires // special handling so skip it in this loop. Value* cur = this; - const StringPiece* cur_path = path.begin(); + const std::string_view* cur_path = path.begin(); for (; (cur_path + 1) < path.end(); ++cur_path) { if (!cur->is_dict()) return nullptr; // Use lower_bound to avoid doing the search twice for missing keys. - const StringPiece path_component = *cur_path; + const std::string_view path_component = *cur_path; auto found = cur->dict_.lower_bound(path_component); if (found == cur->dict_.end() || found->first != path_component) { // No key found, insert one. @@ -374,12 +378,12 @@ return cur->SetKey(*cur_path, std::move(value)); } -bool Value::RemovePath(std::initializer_list<StringPiece> path) { +bool Value::RemovePath(std::initializer_list<std::string_view> path) { DCHECK_GE(path.size(), 2u) << "Use RemoveKey() for a path of length 1."; return RemovePath(make_span(path.begin(), path.size())); } -bool Value::RemovePath(span<const StringPiece> path) { +bool Value::RemovePath(span<const std::string_view> path) { if (!is_dict() || path.empty()) return false; @@ -441,7 +445,7 @@ return is_string(); } -bool Value::GetAsString(string16* out_value) const { +bool Value::GetAsString(std::u16string* out_value) const { if (out_value && is_string()) { *out_value = UTF8ToUTF16(string_value_); return true; @@ -457,7 +461,7 @@ return is_string(); } -bool Value::GetAsString(StringPiece* out_value) const { +bool Value::GetAsString(std::string_view* out_value) const { if (out_value && is_string()) { *out_value = string_value_; return true; @@ -660,7 +664,7 @@ DictionaryValue::DictionaryValue(DictStorage&& in_dict) noexcept : Value(std::move(in_dict)) {} -bool DictionaryValue::HasKey(StringPiece key) const { +bool DictionaryValue::HasKey(std::string_view key) const { DCHECK(IsStringUTF8(key)); auto current_entry = dict_.find(key); DCHECK((current_entry == dict_.end()) || current_entry->second); @@ -671,17 +675,18 @@ dict_.clear(); } -Value* DictionaryValue::Set(StringPiece path, std::unique_ptr<Value> in_value) { +Value* DictionaryValue::Set(std::string_view path, + std::unique_ptr<Value> in_value) { DCHECK(IsStringUTF8(path)); DCHECK(in_value); - StringPiece current_path(path); + std::string_view current_path(path); Value* current_dictionary = this; for (size_t delimiter_position = current_path.find('.'); - delimiter_position != StringPiece::npos; + delimiter_position != std::string_view::npos; delimiter_position = current_path.find('.')) { // Assume that we're indexing into a dictionary. - StringPiece key = current_path.substr(0, delimiter_position); + std::string_view key = current_path.substr(0, delimiter_position); Value* child_dictionary = current_dictionary->FindKeyOfType(key, Type::DICTIONARY); if (!child_dictionary) { @@ -697,38 +702,40 @@ ->SetWithoutPathExpansion(current_path, std::move(in_value)); } -Value* DictionaryValue::SetBoolean(StringPiece path, bool in_value) { +Value* DictionaryValue::SetBoolean(std::string_view path, bool in_value) { return Set(path, std::make_unique<Value>(in_value)); } -Value* DictionaryValue::SetInteger(StringPiece path, int in_value) { +Value* DictionaryValue::SetInteger(std::string_view path, int in_value) { return Set(path, std::make_unique<Value>(in_value)); } -Value* DictionaryValue::SetString(StringPiece path, StringPiece in_value) { +Value* DictionaryValue::SetString(std::string_view path, + std::string_view in_value) { return Set(path, std::make_unique<Value>(in_value)); } -Value* DictionaryValue::SetString(StringPiece path, const string16& in_value) { +Value* DictionaryValue::SetString(std::string_view path, + const std::u16string& in_value) { return Set(path, std::make_unique<Value>(in_value)); } DictionaryValue* DictionaryValue::SetDictionary( - StringPiece path, + std::string_view path, std::unique_ptr<DictionaryValue> in_value) { return static_cast<DictionaryValue*>(Set(path, std::move(in_value))); } -ListValue* DictionaryValue::SetList(StringPiece path, +ListValue* DictionaryValue::SetList(std::string_view path, std::unique_ptr<ListValue> in_value) { return static_cast<ListValue*>(Set(path, std::move(in_value))); } Value* DictionaryValue::SetWithoutPathExpansion( - StringPiece key, + std::string_view key, std::unique_ptr<Value> in_value) { // NOTE: We can't use |insert_or_assign| here, as only |try_emplace| does - // an explicit conversion from StringPiece to std::string if necessary. + // an explicit conversion from std::string_view to std::string if necessary. auto result = dict_.try_emplace(key, std::move(in_value)); if (!result.second) { // in_value is guaranteed to be still intact at this point. @@ -737,9 +744,10 @@ return result.first->second.get(); } -bool DictionaryValue::Get(StringPiece path, const Value** out_value) const { +bool DictionaryValue::Get(std::string_view path, + const Value** out_value) const { DCHECK(IsStringUTF8(path)); - StringPiece current_path(path); + std::string_view current_path(path); const DictionaryValue* current_dictionary = this; for (size_t delimiter_position = current_path.find('.'); delimiter_position != std::string::npos; @@ -757,12 +765,13 @@ return current_dictionary->GetWithoutPathExpansion(current_path, out_value); } -bool DictionaryValue::Get(StringPiece path, Value** out_value) { +bool DictionaryValue::Get(std::string_view path, Value** out_value) { return static_cast<const DictionaryValue&>(*this).Get( path, const_cast<const Value**>(out_value)); } -bool DictionaryValue::GetBoolean(StringPiece path, bool* bool_value) const { +bool DictionaryValue::GetBoolean(std::string_view path, + bool* bool_value) const { const Value* value; if (!Get(path, &value)) return false; @@ -770,7 +779,7 @@ return value->GetAsBoolean(bool_value); } -bool DictionaryValue::GetInteger(StringPiece path, int* out_value) const { +bool DictionaryValue::GetInteger(std::string_view path, int* out_value) const { const Value* value; if (!Get(path, &value)) return false; @@ -778,7 +787,7 @@ return value->GetAsInteger(out_value); } -bool DictionaryValue::GetString(StringPiece path, +bool DictionaryValue::GetString(std::string_view path, std::string* out_value) const { const Value* value; if (!Get(path, &value)) @@ -787,7 +796,8 @@ return value->GetAsString(out_value); } -bool DictionaryValue::GetString(StringPiece path, string16* out_value) const { +bool DictionaryValue::GetString(std::string_view path, + std::u16string* out_value) const { const Value* value; if (!Get(path, &value)) return false; @@ -795,7 +805,7 @@ return value->GetAsString(out_value); } -bool DictionaryValue::GetStringASCII(StringPiece path, +bool DictionaryValue::GetStringASCII(std::string_view path, std::string* out_value) const { std::string out; if (!GetString(path, &out)) @@ -810,7 +820,7 @@ return true; } -bool DictionaryValue::GetBinary(StringPiece path, +bool DictionaryValue::GetBinary(std::string_view path, const Value** out_value) const { const Value* value; bool result = Get(path, &value); @@ -823,12 +833,12 @@ return true; } -bool DictionaryValue::GetBinary(StringPiece path, Value** out_value) { +bool DictionaryValue::GetBinary(std::string_view path, Value** out_value) { return static_cast<const DictionaryValue&>(*this).GetBinary( path, const_cast<const Value**>(out_value)); } -bool DictionaryValue::GetDictionary(StringPiece path, +bool DictionaryValue::GetDictionary(std::string_view path, const DictionaryValue** out_value) const { const Value* value; bool result = Get(path, &value); @@ -841,13 +851,13 @@ return true; } -bool DictionaryValue::GetDictionary(StringPiece path, +bool DictionaryValue::GetDictionary(std::string_view path, DictionaryValue** out_value) { return static_cast<const DictionaryValue&>(*this).GetDictionary( path, const_cast<const DictionaryValue**>(out_value)); } -bool DictionaryValue::GetList(StringPiece path, +bool DictionaryValue::GetList(std::string_view path, const ListValue** out_value) const { const Value* value; bool result = Get(path, &value); @@ -860,12 +870,12 @@ return true; } -bool DictionaryValue::GetList(StringPiece path, ListValue** out_value) { +bool DictionaryValue::GetList(std::string_view path, ListValue** out_value) { return static_cast<const DictionaryValue&>(*this).GetList( path, const_cast<const ListValue**>(out_value)); } -bool DictionaryValue::GetWithoutPathExpansion(StringPiece key, +bool DictionaryValue::GetWithoutPathExpansion(std::string_view key, const Value** out_value) const { DCHECK(IsStringUTF8(key)); auto entry_iterator = dict_.find(key); @@ -877,13 +887,13 @@ return true; } -bool DictionaryValue::GetWithoutPathExpansion(StringPiece key, +bool DictionaryValue::GetWithoutPathExpansion(std::string_view key, Value** out_value) { return static_cast<const DictionaryValue&>(*this).GetWithoutPathExpansion( key, const_cast<const Value**>(out_value)); } -bool DictionaryValue::GetBooleanWithoutPathExpansion(StringPiece key, +bool DictionaryValue::GetBooleanWithoutPathExpansion(std::string_view key, bool* out_value) const { const Value* value; if (!GetWithoutPathExpansion(key, &value)) @@ -892,7 +902,7 @@ return value->GetAsBoolean(out_value); } -bool DictionaryValue::GetIntegerWithoutPathExpansion(StringPiece key, +bool DictionaryValue::GetIntegerWithoutPathExpansion(std::string_view key, int* out_value) const { const Value* value; if (!GetWithoutPathExpansion(key, &value)) @@ -902,7 +912,7 @@ } bool DictionaryValue::GetStringWithoutPathExpansion( - StringPiece key, + std::string_view key, std::string* out_value) const { const Value* value; if (!GetWithoutPathExpansion(key, &value)) @@ -911,8 +921,9 @@ return value->GetAsString(out_value); } -bool DictionaryValue::GetStringWithoutPathExpansion(StringPiece key, - string16* out_value) const { +bool DictionaryValue::GetStringWithoutPathExpansion( + std::string_view key, + std::u16string* out_value) const { const Value* value; if (!GetWithoutPathExpansion(key, &value)) return false; @@ -921,7 +932,7 @@ } bool DictionaryValue::GetDictionaryWithoutPathExpansion( - StringPiece key, + std::string_view key, const DictionaryValue** out_value) const { const Value* value; bool result = GetWithoutPathExpansion(key, &value); @@ -935,7 +946,7 @@ } bool DictionaryValue::GetDictionaryWithoutPathExpansion( - StringPiece key, + std::string_view key, DictionaryValue** out_value) { const DictionaryValue& const_this = static_cast<const DictionaryValue&>(*this); @@ -944,7 +955,7 @@ } bool DictionaryValue::GetListWithoutPathExpansion( - StringPiece key, + std::string_view key, const ListValue** out_value) const { const Value* value; bool result = GetWithoutPathExpansion(key, &value); @@ -957,19 +968,19 @@ return true; } -bool DictionaryValue::GetListWithoutPathExpansion(StringPiece key, +bool DictionaryValue::GetListWithoutPathExpansion(std::string_view key, ListValue** out_value) { return static_cast<const DictionaryValue&>(*this).GetListWithoutPathExpansion( key, const_cast<const ListValue**>(out_value)); } -bool DictionaryValue::Remove(StringPiece path, +bool DictionaryValue::Remove(std::string_view path, std::unique_ptr<Value>* out_value) { DCHECK(IsStringUTF8(path)); - StringPiece current_path(path); + std::string_view current_path(path); DictionaryValue* current_dictionary = this; size_t delimiter_position = current_path.rfind('.'); - if (delimiter_position != StringPiece::npos) { + if (delimiter_position != std::string_view::npos) { if (!GetDictionary(current_path.substr(0, delimiter_position), ¤t_dictionary)) return false; @@ -981,7 +992,7 @@ } bool DictionaryValue::RemoveWithoutPathExpansion( - StringPiece key, + std::string_view key, std::unique_ptr<Value>* out_value) { DCHECK(IsStringUTF8(key)); auto entry_iterator = dict_.find(key); @@ -994,7 +1005,7 @@ return true; } -bool DictionaryValue::RemovePath(StringPiece path, +bool DictionaryValue::RemovePath(std::string_view path, std::unique_ptr<Value>* out_value) { bool result = false; size_t delimiter_position = path.find('.'); @@ -1002,7 +1013,7 @@ if (delimiter_position == std::string::npos) return RemoveWithoutPathExpansion(path, out_value); - StringPiece subdict_path = path.substr(0, delimiter_position); + std::string_view subdict_path = path.substr(0, delimiter_position); DictionaryValue* subdict = nullptr; if (!GetDictionary(subdict_path, &subdict)) return false; @@ -1135,7 +1146,7 @@ return value->GetAsString(out_value); } -bool ListValue::GetString(size_t index, string16* out_value) const { +bool ListValue::GetString(size_t index, std::u16string* out_value) const { const Value* value; if (!Get(index, &value)) return false; @@ -1222,11 +1233,11 @@ list_.emplace_back(in_value); } -void ListValue::AppendString(StringPiece in_value) { +void ListValue::AppendString(std::string_view in_value) { list_.emplace_back(in_value); } -void ListValue::AppendString(const string16& in_value) { +void ListValue::AppendString(const std::u16string& in_value) { list_.emplace_back(in_value); } @@ -1236,7 +1247,7 @@ list_.emplace_back(in_value); } -void ListValue::AppendStrings(const std::vector<string16>& in_values) { +void ListValue::AppendStrings(const std::vector<std::u16string>& in_values) { list_.reserve(list_.size() + in_values.size()); for (const auto& in_value : in_values) list_.emplace_back(in_value);
diff --git a/base/values.h b/base/values.h index c3ec875..b32c8f9 100644 --- a/base/values.h +++ b/base/values.h
@@ -27,14 +27,13 @@ #include <map> #include <memory> #include <string> +#include <string_view> #include <utility> #include <vector> #include "base/containers/flat_map.h" #include "base/containers/span.h" #include "base/macros.h" -#include "base/strings/string16.h" -#include "base/strings/string_piece.h" #include "base/value_iterators.h" namespace base { @@ -116,15 +115,15 @@ explicit Value(bool in_bool); explicit Value(int in_int); - // Value(const char*) and Value(const char16*) are required despite - // Value(StringPiece) and Value(StringPiece16) because otherwise the - // compiler will choose the Value(bool) constructor for these arguments. + // Value(const char*) and Value(const char16_t*) are required despite + // Value(std::string_view) and Value(std::u16string_view) because otherwise + // the compiler will choose the Value(bool) constructor for these arguments. // Value(std::string&&) allow for efficient move construction. explicit Value(const char* in_string); - explicit Value(StringPiece in_string); + explicit Value(std::string_view in_string); explicit Value(std::string&& in_string) noexcept; - explicit Value(const char16* in_string16); - explicit Value(StringPiece16 in_string16); + explicit Value(const char16_t* in_string16); + explicit Value(std::u16string_view in_string16); explicit Value(const BlobStorage& in_blob); explicit Value(BlobStorage&& in_blob) noexcept; @@ -171,8 +170,8 @@ // // Example: // auto* found = FindKey("foo"); - Value* FindKey(StringPiece key); - const Value* FindKey(StringPiece key) const; + Value* FindKey(std::string_view key); + const Value* FindKey(std::string_view key) const; // |FindKeyOfType| is similar to |FindKey|, but it also requires the found // value to have type |type|. If no type is found, or the found value is of a @@ -183,8 +182,8 @@ // // Example: // auto* found = FindKey("foo", Type::INTEGER); - Value* FindKeyOfType(StringPiece key, Type type); - const Value* FindKeyOfType(StringPiece key, Type type) const; + Value* FindKeyOfType(std::string_view key, Type type); + const Value* FindKeyOfType(std::string_view key, Type type) const; // |SetKey| looks up |key| in the underlying dictionary and sets the mapped // value to |value|. If |key| could not be found, a new element is inserted. @@ -193,7 +192,7 @@ // // Example: // SetKey("foo", std::move(myvalue)); - Value* SetKey(StringPiece key, Value value); + Value* SetKey(std::string_view key, Value value); // This overload results in a performance improvement for std::string&&. Value* SetKey(std::string&& key, Value value); // This overload is necessary to avoid ambiguity for const char* arguments. @@ -207,7 +206,7 @@ // // Example: // bool success = RemoveKey("foo"); - bool RemoveKey(StringPiece key); + bool RemoveKey(std::string_view key); // Searches a hierarchy of dictionary values for a given value. If a path // of dictionaries exist, returns the item at that path. If any of the path @@ -223,25 +222,27 @@ // Example: // auto* found = FindPath({"foo", "bar"}); // - // std::vector<StringPiece> components = ... + // std::vector<std::string_view> components = ... // auto* found = FindPath(components); // // Note: If there is only one component in the path, use FindKey() instead. - Value* FindPath(std::initializer_list<StringPiece> path); - Value* FindPath(span<const StringPiece> path); - const Value* FindPath(std::initializer_list<StringPiece> path) const; - const Value* FindPath(span<const StringPiece> path) const; + Value* FindPath(std::initializer_list<std::string_view> path); + Value* FindPath(span<const std::string_view> path); + const Value* FindPath(std::initializer_list<std::string_view> path) const; + const Value* FindPath(span<const std::string_view> path) const; // Like FindPath() but will only return the value if the leaf Value type // matches the given type. Will return nullptr otherwise. // // Note: If there is only one component in the path, use FindKeyOfType() // instead. - Value* FindPathOfType(std::initializer_list<StringPiece> path, Type type); - Value* FindPathOfType(span<const StringPiece> path, Type type); - const Value* FindPathOfType(std::initializer_list<StringPiece> path, + Value* FindPathOfType(std::initializer_list<std::string_view> path, + Type type); + Value* FindPathOfType(span<const std::string_view> path, Type type); + const Value* FindPathOfType(std::initializer_list<std::string_view> path, Type type) const; - const Value* FindPathOfType(span<const StringPiece> path, Type type) const; + const Value* FindPathOfType(span<const std::string_view> path, + Type type) const; // Sets the given path, expanding and creating dictionary keys as necessary. // @@ -255,12 +256,12 @@ // Example: // value.SetPath({"foo", "bar"}, std::move(myvalue)); // - // std::vector<StringPiece> components = ... + // std::vector<std::string_view> components = ... // value.SetPath(components, std::move(myvalue)); // // Note: If there is only one component in the path, use SetKey() instead. - Value* SetPath(std::initializer_list<StringPiece> path, Value value); - Value* SetPath(span<const StringPiece> path, Value value); + Value* SetPath(std::initializer_list<std::string_view> path, Value value); + Value* SetPath(span<const std::string_view> path, Value value); // Tries to remove a Value at the given path. // @@ -272,12 +273,12 @@ // Example: // bool success = value.RemovePath({"foo", "bar"}); // - // std::vector<StringPiece> components = ... + // std::vector<std::string_view> components = ... // bool success = value.RemovePath(components); // // Note: If there is only one component in the path, use RemoveKey() instead. - bool RemovePath(std::initializer_list<StringPiece> path); - bool RemovePath(span<const StringPiece> path); + bool RemovePath(std::initializer_list<std::string_view> path); + bool RemovePath(span<const std::string_view> path); using dict_iterator_proxy = detail::dict_iterator_proxy; using const_dict_iterator_proxy = detail::const_dict_iterator_proxy; @@ -305,9 +306,9 @@ bool GetAsInteger(int* out_value) const; // DEPRECATED, use GetString() instead. bool GetAsString(std::string* out_value) const; - bool GetAsString(string16* out_value) const; + bool GetAsString(std::u16string* out_value) const; bool GetAsString(const Value** out_value) const; - bool GetAsString(StringPiece* out_value) const; + bool GetAsString(std::string_view* out_value) const; // ListValue::From is the equivalent for std::unique_ptr conversions. // DEPRECATED, use GetList() instead. bool GetAsList(ListValue** out_value); @@ -384,7 +385,7 @@ // Returns true if the current dictionary has a value for the given key. // DEPRECATED, use Value::FindKey(key) instead. - bool HasKey(StringPiece key) const; + bool HasKey(std::string_view key) const; // Returns the number of Values in this dictionary. size_t size() const { return dict_.size(); } @@ -404,28 +405,29 @@ // to the path in that location. |in_value| must be non-null. // Returns a pointer to the inserted value. // DEPRECATED, use Value::SetPath(path, value) instead. - Value* Set(StringPiece path, std::unique_ptr<Value> in_value); + Value* Set(std::string_view path, std::unique_ptr<Value> in_value); // Convenience forms of Set(). These methods will replace any existing // value at that path, even if it has a different type. // DEPRECATED, use Value::SetPath(path, Value(bool)) instead. - Value* SetBoolean(StringPiece path, bool in_value); + Value* SetBoolean(std::string_view path, bool in_value); // DEPRECATED, use Value::SetPath(path, Value(int)) instead. - Value* SetInteger(StringPiece path, int in_value); - // DEPRECATED, use Value::SetPath(path, Value(StringPiece)) instead. - Value* SetString(StringPiece path, StringPiece in_value); + Value* SetInteger(std::string_view path, int in_value); + // DEPRECATED, use Value::SetPath(path, Value(std::string_view)) instead. + Value* SetString(std::string_view path, std::string_view in_value); // DEPRECATED, use Value::SetPath(path, Value(const string& 16)) instead. - Value* SetString(StringPiece path, const string16& in_value); + Value* SetString(std::string_view path, const std::u16string& in_value); // DEPRECATED, use Value::SetPath(path, Value(Type::DICTIONARY)) instead. - DictionaryValue* SetDictionary(StringPiece path, + DictionaryValue* SetDictionary(std::string_view path, std::unique_ptr<DictionaryValue> in_value); // DEPRECATED, use Value::SetPath(path, Value(Type::LIST)) instead. - ListValue* SetList(StringPiece path, std::unique_ptr<ListValue> in_value); + ListValue* SetList(std::string_view path, + std::unique_ptr<ListValue> in_value); // Like Set(), but without special treatment of '.'. This allows e.g. URLs to // be used as paths. // DEPRECATED, use Value::SetKey(key, value) instead. - Value* SetWithoutPathExpansion(StringPiece key, + Value* SetWithoutPathExpansion(std::string_view key, std::unique_ptr<Value> in_value); // Gets the Value associated with the given path starting from this object. @@ -437,65 +439,69 @@ // Note that the dictionary always owns the value that's returned. // |out_value| is optional and will only be set if non-NULL. // DEPRECATED, use Value::FindPath(path) instead. - bool Get(StringPiece path, const Value** out_value) const; + bool Get(std::string_view path, const Value** out_value) const; // DEPRECATED, use Value::FindPath(path) instead. - bool Get(StringPiece path, Value** out_value); + bool Get(std::string_view path, Value** out_value); // These are convenience forms of Get(). The value will be retrieved // and the return value will be true if the path is valid and the value at // the end of the path can be returned in the form specified. // |out_value| is optional and will only be set if non-NULL. // DEPRECATED, use Value::FindPath(path) and Value::GetBool() instead. - bool GetBoolean(StringPiece path, bool* out_value) const; + bool GetBoolean(std::string_view path, bool* out_value) const; // DEPRECATED, use Value::FindPath(path) and Value::GetInt() instead. - bool GetInteger(StringPiece path, int* out_value) const; + bool GetInteger(std::string_view path, int* out_value) const; // DEPRECATED, use Value::FindPath(path) and Value::GetString() instead. - bool GetString(StringPiece path, std::string* out_value) const; + bool GetString(std::string_view path, std::string* out_value) const; // DEPRECATED, use Value::FindPath(path) and Value::GetString() instead. - bool GetString(StringPiece path, string16* out_value) const; + bool GetString(std::string_view path, std::u16string* out_value) const; // DEPRECATED, use Value::FindPath(path) and Value::GetString() instead. - bool GetStringASCII(StringPiece path, std::string* out_value) const; + bool GetStringASCII(std::string_view path, std::string* out_value) const; // DEPRECATED, use Value::FindPath(path) and Value::GetBlob() instead. - bool GetBinary(StringPiece path, const Value** out_value) const; + bool GetBinary(std::string_view path, const Value** out_value) const; // DEPRECATED, use Value::FindPath(path) and Value::GetBlob() instead. - bool GetBinary(StringPiece path, Value** out_value); + bool GetBinary(std::string_view path, Value** out_value); // DEPRECATED, use Value::FindPath(path) and Value's Dictionary API instead. - bool GetDictionary(StringPiece path, const DictionaryValue** out_value) const; + bool GetDictionary(std::string_view path, + const DictionaryValue** out_value) const; // DEPRECATED, use Value::FindPath(path) and Value's Dictionary API instead. - bool GetDictionary(StringPiece path, DictionaryValue** out_value); + bool GetDictionary(std::string_view path, DictionaryValue** out_value); // DEPRECATED, use Value::FindPath(path) and Value::GetList() instead. - bool GetList(StringPiece path, const ListValue** out_value) const; + bool GetList(std::string_view path, const ListValue** out_value) const; // DEPRECATED, use Value::FindPath(path) and Value::GetList() instead. - bool GetList(StringPiece path, ListValue** out_value); + bool GetList(std::string_view path, ListValue** out_value); // Like Get(), but without special treatment of '.'. This allows e.g. URLs to // be used as paths. // DEPRECATED, use Value::FindKey(key) instead. - bool GetWithoutPathExpansion(StringPiece key, const Value** out_value) const; + bool GetWithoutPathExpansion(std::string_view key, + const Value** out_value) const; // DEPRECATED, use Value::FindKey(key) instead. - bool GetWithoutPathExpansion(StringPiece key, Value** out_value); + bool GetWithoutPathExpansion(std::string_view key, Value** out_value); // DEPRECATED, use Value::FindKey(key) and Value::GetBool() instead. - bool GetBooleanWithoutPathExpansion(StringPiece key, bool* out_value) const; + bool GetBooleanWithoutPathExpansion(std::string_view key, + bool* out_value) const; // DEPRECATED, use Value::FindKey(key) and Value::GetInt() instead. - bool GetIntegerWithoutPathExpansion(StringPiece key, int* out_value) const; + bool GetIntegerWithoutPathExpansion(std::string_view key, + int* out_value) const; // DEPRECATED, use Value::FindKey(key) and Value::GetString() instead. - bool GetStringWithoutPathExpansion(StringPiece key, + bool GetStringWithoutPathExpansion(std::string_view key, std::string* out_value) const; // DEPRECATED, use Value::FindKey(key) and Value::GetString() instead. - bool GetStringWithoutPathExpansion(StringPiece key, - string16* out_value) const; + bool GetStringWithoutPathExpansion(std::string_view key, + std::u16string* out_value) const; // DEPRECATED, use Value::FindKey(key) and Value's Dictionary API instead. bool GetDictionaryWithoutPathExpansion( - StringPiece key, + std::string_view key, const DictionaryValue** out_value) const; // DEPRECATED, use Value::FindKey(key) and Value's Dictionary API instead. - bool GetDictionaryWithoutPathExpansion(StringPiece key, + bool GetDictionaryWithoutPathExpansion(std::string_view key, DictionaryValue** out_value); // DEPRECATED, use Value::FindKey(key) and Value::GetList() instead. - bool GetListWithoutPathExpansion(StringPiece key, + bool GetListWithoutPathExpansion(std::string_view key, const ListValue** out_value) const; // DEPRECATED, use Value::FindKey(key) and Value::GetList() instead. - bool GetListWithoutPathExpansion(StringPiece key, ListValue** out_value); + bool GetListWithoutPathExpansion(std::string_view key, ListValue** out_value); // Removes the Value with the specified path from this dictionary (or one // of its child dictionaries, if the path is more than just a local key). @@ -504,18 +510,18 @@ // This method returns true if |path| is a valid path; otherwise it will // return false and the DictionaryValue object will be unchanged. // DEPRECATED, use Value::RemovePath(path) instead. - bool Remove(StringPiece path, std::unique_ptr<Value>* out_value); + bool Remove(std::string_view path, std::unique_ptr<Value>* out_value); // Like Remove(), but without special treatment of '.'. This allows e.g. URLs // to be used as paths. // DEPRECATED, use Value::RemoveKey(key) instead. - bool RemoveWithoutPathExpansion(StringPiece key, + bool RemoveWithoutPathExpansion(std::string_view key, std::unique_ptr<Value>* out_value); // Removes a path, clearing out all dictionaries on |path| that remain empty // after removing the value at |path|. // DEPRECATED, use Value::RemovePath(path) instead. - bool RemovePath(StringPiece path, std::unique_ptr<Value>* out_value); + bool RemovePath(std::string_view path, std::unique_ptr<Value>* out_value); using Value::RemovePath; // DictionaryValue::RemovePath shadows otherwise. @@ -625,7 +631,7 @@ bool GetInteger(size_t index, int* out_value) const; // DEPRECATED, use GetList()::operator[]::GetString() instead. bool GetString(size_t index, std::string* out_value) const; - bool GetString(size_t index, string16* out_value) const; + bool GetString(size_t index, std::u16string* out_value) const; bool GetDictionary(size_t index, const DictionaryValue** out_value) const; bool GetDictionary(size_t index, DictionaryValue** out_value); @@ -664,11 +670,11 @@ // DEPRECATED, use GetList()::emplace_back() instead. void AppendBoolean(bool in_value); void AppendInteger(int in_value); - void AppendString(StringPiece in_value); - void AppendString(const string16& in_value); + void AppendString(std::string_view in_value); + void AppendString(const std::u16string& in_value); // DEPRECATED, use GetList()::emplace_back() in a loop instead. void AppendStrings(const std::vector<std::string>& in_values); - void AppendStrings(const std::vector<string16>& in_values); + void AppendStrings(const std::vector<std::u16string>& in_values); // Appends a Value if it's not already present. Returns true if successful, // or false if the value was already
diff --git a/tools/gn/args.cc b/tools/gn/args.cc index 802c373..e14adf6 100644 --- a/tools/gn/args.cc +++ b/tools/gn/args.cc
@@ -108,8 +108,8 @@ void Args::AddArgOverride(const char* name, const Value& value) { std::lock_guard<std::mutex> lock(lock_); - overrides_[base::StringPiece(name)] = value; - all_overrides_[base::StringPiece(name)] = value; + overrides_[std::string_view(name)] = value; + all_overrides_[std::string_view(name)] = value; } void Args::AddArgOverrides(const Scope::KeyValueMap& overrides) { @@ -131,7 +131,7 @@ std::lock_guard<std::mutex> lock(lock_); Scope::KeyValueMap::const_iterator found = - all_overrides_.find(base::StringPiece(name)); + all_overrides_.find(std::string_view(name)); if (found == all_overrides_.end()) return nullptr; return &found->second; @@ -240,7 +240,7 @@ // Some assignments in args.gn had no effect. Show an error for the first // unused assignment. - base::StringPiece name = unused_overrides.begin()->first; + std::string_view name = unused_overrides.begin()->first; const Value& value = unused_overrides.begin()->second; std::string err_help( @@ -250,12 +250,12 @@ "To view all possible args, run \"gn args --list <out_dir>\""); // Use all declare_args for a spelling suggestion. - std::vector<base::StringPiece> candidates; + std::vector<std::string_view> candidates; for (const auto& map_pair : declared_arguments_per_toolchain_) { for (const auto& declared_arg : map_pair.second) candidates.push_back(declared_arg.first); } - base::StringPiece suggestion = SpellcheckString(name, candidates); + std::string_view suggestion = SpellcheckString(name, candidates); if (!suggestion.empty()) err_help = "Did you mean \"" + suggestion + "\"?\n\n" + err_help;
diff --git a/tools/gn/args.h b/tools/gn/args.h index 4a4bc7c..3921e23 100644 --- a/tools/gn/args.h +++ b/tools/gn/args.h
@@ -37,7 +37,7 @@ bool has_override; // True indicates override_value is valid. Value override_value; // From .gn or the current build's "gn args". }; - using ValueWithOverrideMap = std::map<base::StringPiece, ValueWithOverride>; + using ValueWithOverrideMap = std::map<std::string_view, ValueWithOverride>; Args(); Args(const Args& other);
diff --git a/tools/gn/bundle_data.cc b/tools/gn/bundle_data.cc index 9de0e8c..60500c6 100644 --- a/tools/gn/bundle_data.cc +++ b/tools/gn/bundle_data.cc
@@ -16,14 +16,14 @@ namespace { // Return directory of |path| without the trailing directory separator. -base::StringPiece FindDirNoTrailingSeparator(base::StringPiece path) { - base::StringPiece::size_type pos = path.find_last_of("/\\"); - if (pos == base::StringPiece::npos) - return base::StringPiece(); - return base::StringPiece(path.data(), pos); +std::string_view FindDirNoTrailingSeparator(std::string_view path) { + std::string_view::size_type pos = path.find_last_of("/\\"); + if (pos == std::string_view::npos) + return std::string_view(); + return std::string_view(path.data(), pos); } -bool IsSourceFileFromAssetsCatalog(base::StringPiece source, +bool IsSourceFileFromAssetsCatalog(std::string_view source, SourceFile* asset_catalog) { // Check whether |source| matches one of the following pattern: // .*\.xcassets/Contents.json @@ -31,7 +31,7 @@ // .*\.xcassets/[^/]*\.imageset/[^/]* // .*\.xcassets/[^/]*\.launchimage/[^/]* bool is_file_from_asset_catalog = false; - base::StringPiece dir = FindDirNoTrailingSeparator(source); + std::string_view dir = FindDirNoTrailingSeparator(source); if (base::EndsWith(source, "/Contents.json", base::CompareCase::SENSITIVE) && base::EndsWith(dir, ".xcassets", base::CompareCase::SENSITIVE)) { is_file_from_asset_catalog = true;
diff --git a/tools/gn/c_include_iterator.cc b/tools/gn/c_include_iterator.cc index 540d118..077609f 100644 --- a/tools/gn/c_include_iterator.cc +++ b/tools/gn/c_include_iterator.cc
@@ -21,7 +21,7 @@ // Returns a new string piece referencing the same buffer as the argument, but // with leading space trimmed. This only checks for space and tab characters // since we're dealing with lines in C source files. -base::StringPiece TrimLeadingWhitespace(const base::StringPiece& str) { +std::string_view TrimLeadingWhitespace(const std::string_view& str) { size_t new_begin = 0; while (new_begin < str.size() && (str[new_begin] == ' ' || str[new_begin] == '\t')) @@ -40,7 +40,7 @@ // // We assume the line has leading whitespace trimmed. We also assume that empty // lines have already been filtered out. -bool ShouldCountTowardNonIncludeLines(const base::StringPiece& line) { +bool ShouldCountTowardNonIncludeLines(const std::string_view& line) { if (base::StartsWith(line, "//", base::CompareCase::SENSITIVE)) return false; // Don't count comments. if (base::StartsWith(line, "/*", base::CompareCase::SENSITIVE) || @@ -59,15 +59,15 @@ // // The 1-based character number on the line that the include was found at // will be filled into *begin_char. -IncludeType ExtractInclude(const base::StringPiece& line, - base::StringPiece* path, +IncludeType ExtractInclude(const std::string_view& line, + std::string_view* path, int* begin_char) { static const char kInclude[] = "include"; static const size_t kIncludeLen = arraysize(kInclude) - 1; // No null. static const char kImport[] = "import"; static const size_t kImportLen = arraysize(kImport) - 1; // No null. - base::StringPiece trimmed = TrimLeadingWhitespace(line); + std::string_view trimmed = TrimLeadingWhitespace(line); if (trimmed.empty()) return INCLUDE_NONE; @@ -76,11 +76,11 @@ trimmed = TrimLeadingWhitespace(trimmed.substr(1)); - base::StringPiece contents; - if (base::StartsWith(trimmed, base::StringPiece(kInclude, kIncludeLen), + std::string_view contents; + if (base::StartsWith(trimmed, std::string_view(kInclude, kIncludeLen), base::CompareCase::SENSITIVE)) contents = TrimLeadingWhitespace(trimmed.substr(kIncludeLen)); - else if (base::StartsWith(trimmed, base::StringPiece(kImport, kImportLen), + else if (base::StartsWith(trimmed, std::string_view(kImport, kImportLen), base::CompareCase::SENSITIVE)) contents = TrimLeadingWhitespace(trimmed.substr(kImportLen)); @@ -101,7 +101,7 @@ // Count everything to next "/> as the contents. size_t terminator_index = contents.find(terminating_char, 1); - if (terminator_index == base::StringPiece::npos) + if (terminator_index == std::string_view::npos) return INCLUDE_NONE; *path = contents.substr(1, terminator_index - 1); @@ -111,8 +111,8 @@ } // Returns true if this line has a "nogncheck" comment associated with it. -bool HasNoCheckAnnotation(const base::StringPiece& line) { - return line.find("nogncheck") != base::StringPiece::npos; +bool HasNoCheckAnnotation(const std::string_view& line) { + return line.find("nogncheck") != std::string_view::npos; } } // namespace @@ -124,13 +124,13 @@ CIncludeIterator::~CIncludeIterator() = default; -bool CIncludeIterator::GetNextIncludeString(base::StringPiece* out, +bool CIncludeIterator::GetNextIncludeString(std::string_view* out, LocationRange* location) { - base::StringPiece line; + std::string_view line; int cur_line_number = 0; while (lines_since_last_include_ <= kMaxNonIncludeLines && GetNextLine(&line, &cur_line_number)) { - base::StringPiece include_contents; + std::string_view include_contents; int begin_char; IncludeType type = ExtractInclude(line, &include_contents, &begin_char); if (type == INCLUDE_USER && !HasNoCheckAnnotation(line)) { @@ -153,7 +153,7 @@ return false; } -bool CIncludeIterator::GetNextLine(base::StringPiece* line, int* line_number) { +bool CIncludeIterator::GetNextLine(std::string_view* line, int* line_number) { if (offset_ == file_.size()) return false;
diff --git a/tools/gn/c_include_iterator.h b/tools/gn/c_include_iterator.h index 86a0954..0c379e1 100644 --- a/tools/gn/c_include_iterator.h +++ b/tools/gn/c_include_iterator.h
@@ -7,8 +7,9 @@ #include <stddef.h> +#include <string_view> + #include "base/macros.h" -#include "base/strings/string_piece.h" class InputFile; class LocationRange; @@ -26,7 +27,7 @@ // Fills in the string with the contents of the next include, and the // location with where it came from, and returns true, or returns false if // there are no more includes. - bool GetNextIncludeString(base::StringPiece* out, LocationRange* location); + bool GetNextIncludeString(std::string_view* out, LocationRange* location); // Maximum numbef of non-includes we'll tolerate before giving up. This does // not count comments or preprocessor. @@ -35,12 +36,12 @@ private: // Returns false on EOF, otherwise fills in the given line and the one-based // line number into *line_number; - bool GetNextLine(base::StringPiece* line, int* line_number); + bool GetNextLine(std::string_view* line, int* line_number); const InputFile* input_file_; // This just points into input_file_.contents() for convenience. - base::StringPiece file_; + std::string_view file_; // 0-based offset into the file. size_t offset_ = 0;
diff --git a/tools/gn/c_include_iterator_unittest.cc b/tools/gn/c_include_iterator_unittest.cc index aa1f99a..de9b14a 100644 --- a/tools/gn/c_include_iterator_unittest.cc +++ b/tools/gn/c_include_iterator_unittest.cc
@@ -44,7 +44,7 @@ CIncludeIterator iter(&file); - base::StringPiece contents; + std::string_view contents; LocationRange range; EXPECT_TRUE(iter.GetNextIncludeString(&contents, &range)); EXPECT_EQ("foo/bar.h", contents); @@ -77,7 +77,7 @@ InputFile file(SourceFile("//foo.cc")); file.SetContents(buffer); - base::StringPiece contents; + std::string_view contents; LocationRange range; CIncludeIterator iter(&file); @@ -99,7 +99,7 @@ InputFile file(SourceFile("//foo.cc")); file.SetContents(buffer); - base::StringPiece contents; + std::string_view contents; LocationRange range; CIncludeIterator iter(&file); @@ -126,7 +126,7 @@ InputFile file(SourceFile("//foo.cc")); file.SetContents(buffer); - base::StringPiece contents; + std::string_view contents; LocationRange range; CIncludeIterator iter(&file); @@ -152,7 +152,7 @@ InputFile file(SourceFile("//foo.cc")); file.SetContents(buffer); - base::StringPiece contents; + std::string_view contents; LocationRange range; CIncludeIterator iter(&file); @@ -167,7 +167,7 @@ InputFile file(SourceFile("//foo.cc")); file.SetContents(buffer); - base::StringPiece contents; + std::string_view contents; LocationRange range; CIncludeIterator iter(&file);
diff --git a/tools/gn/command_args.cc b/tools/gn/command_args.cc index 26b8bd6..41f9f5b 100644 --- a/tools/gn/command_args.cc +++ b/tools/gn/command_args.cc
@@ -40,7 +40,7 @@ const char kSwitchOverridesOnly[] = "overrides-only"; const char kSwitchJson[] = "json"; -bool DoesLineBeginWithComment(const base::StringPiece& line) { +bool DoesLineBeginWithComment(const std::string_view& line) { // Skip whitespace. size_t i = 0; while (i < line.size() && base::IsAsciiWhitespace(line[i])) @@ -67,7 +67,7 @@ // Assumes DoesLineBeginWithComment(), this strips the # character from the // beginning and normalizes preceding whitespace. -std::string StripHashFromLine(const base::StringPiece& line, bool pad) { +std::string StripHashFromLine(const std::string_view& line, bool pad) { // Replace the # sign and everything before it with 3 spaces, so that a // normal comment that has a space after the # will be indented 4 spaces // (which makes our formatting come out nicely). If the comment is indented @@ -104,8 +104,8 @@ line_off -= 2; // Back up to end of previous line. size_t previous_line_offset = BackUpToLineBegin(data, line_off); - base::StringPiece line(&data[previous_line_offset], - line_off - previous_line_offset + 1); + std::string_view line(&data[previous_line_offset], + line_off - previous_line_offset + 1); if (!DoesLineBeginWithComment(line)) break; @@ -120,7 +120,7 @@ // is a bit different. // // The default value also contains the docstring. -void PrintDefaultValueInfo(base::StringPiece name, const Value& value) { +void PrintDefaultValueInfo(std::string_view name, const Value& value) { OutputString(value.ToString(true) + "\n"); if (value.origin()) { int line_no; @@ -137,7 +137,7 @@ } // Override value is null if there is no override. -void PrintArgHelp(const base::StringPiece& name, +void PrintArgHelp(const std::string_view& name, const Args::ValueWithOverride& val) { OutputString(std::string(name), DECORATION_YELLOW); OutputString("\n"); @@ -163,7 +163,7 @@ } void BuildArgJson(base::Value& dict, - const base::StringPiece& name, + const std::string_view& name, const Args::ValueWithOverride& arg, bool short_only) { assert(dict.is_dict());
diff --git a/tools/gn/command_clean.cc b/tools/gn/command_clean.cc index 32aaf77..d2822fc 100644 --- a/tools/gn/command_clean.cc +++ b/tools/gn/command_clean.cc
@@ -27,7 +27,7 @@ if (!base::ReadFileToString(build_ninja_file, &file_contents)) return std::string(); - std::vector<base::StringPiece> lines = base::SplitStringPiece( + std::vector<std::string_view> lines = base::SplitStringPiece( file_contents, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); std::string result;
diff --git a/tools/gn/command_format.cc b/tools/gn/command_format.cc index a8604a5..15689ad 100644 --- a/tools/gn/command_format.cc +++ b/tools/gn/command_format.cc
@@ -127,7 +127,7 @@ }; // Add to output. - void Print(base::StringPiece str); + void Print(std::string_view str); // Add the current margin (as spaces) to the output. void PrintMargin(); @@ -238,7 +238,7 @@ std::vector<IndentState> stack_; // Gives the precedence for operators in a BinaryOpNode. - std::map<base::StringPiece, Precedence> precedence_; + std::map<std::string_view, Precedence> precedence_; DISALLOW_COPY_AND_ASSIGN(Printer); }; @@ -264,7 +264,7 @@ Printer::~Printer() = default; -void Printer::Print(base::StringPiece str) { +void Printer::Print(std::string_view str) { output_.append(str); } @@ -323,7 +323,7 @@ // This is somewhat arbitrary, but we include the 'deps'- and 'sources'-like // things, but not flags things. if (binop->op().value() == "=" && ident && list) { - const base::StringPiece lhs = ident->value().value(); + const std::string_view lhs = ident->value().value(); if (lhs == "data" || lhs == "datadeps" || lhs == "data_deps" || lhs == "deps" || lhs == "inputs" || lhs == "outputs" || lhs == "public" || lhs == "public_deps" || lhs == "sources") { @@ -347,7 +347,7 @@ if ((binop->op().value() == "=" || binop->op().value() == "+=" || binop->op().value() == "-=") && ident && list) { - const base::StringPiece lhs = ident->value().value(); + const std::string_view lhs = ident->value().value(); if (lhs == "public" || lhs == "sources") const_cast<ListNode*>(list)->SortAsStringsList(); else if (lhs == "deps" || lhs == "public_deps") @@ -389,14 +389,14 @@ const std::unique_ptr<PARSENODE>& b) const { const auto& a_args = a->AsFunctionCall()->args()->contents(); const auto& b_args = b->AsFunctionCall()->args()->contents(); - base::StringPiece a_name; - base::StringPiece b_name; + std::string_view a_name; + std::string_view b_name; if (!a_args.empty()) a_name = a_args[0]->AsLiteral()->value().value(); if (!b_args.empty()) b_name = b_args[0]->AsLiteral()->value().value(); - auto is_absolute = [](base::StringPiece import) { + auto is_absolute = [](std::string_view import) { return import.size() >= 3 && import[0] == '"' && import[1] == '/' && import[2] == '/'; };
diff --git a/tools/gn/command_help.cc b/tools/gn/command_help.cc index 987f506..86ca088 100644 --- a/tools/gn/command_help.cc +++ b/tools/gn/command_help.cc
@@ -215,7 +215,7 @@ bool PrintHelpOnSwitch(const std::string& what) { const switches::SwitchInfoMap& all = switches::GetSwitches(); switches::SwitchInfoMap::const_iterator found = - all.find(base::StringPiece(what)); + all.find(std::string_view(what)); if (found == all.end()) return false; PrintLongHelp(found->second.long_help); @@ -280,7 +280,7 @@ what = args[0]; } - std::vector<base::StringPiece> all_help_topics; + std::vector<std::string_view> all_help_topics; // Special-case ambiguous topics. if (what == "args") { @@ -361,7 +361,7 @@ // No help on this. Err(Location(), "No help on \"" + what + "\".").PrintToStdout(); - base::StringPiece suggestion = SpellcheckString(what, all_help_topics); + std::string_view suggestion = SpellcheckString(what, all_help_topics); if (suggestion.empty()) { OutputString("Run `gn help` for a list of available topics.\n", DECORATION_NONE);
diff --git a/tools/gn/commands.h b/tools/gn/commands.h index d6b6728..f57f740 100644 --- a/tools/gn/commands.h +++ b/tools/gn/commands.h
@@ -8,9 +8,9 @@ #include <map> #include <set> #include <string> +#include <string_view> #include <vector> -#include "base/strings/string_piece.h" #include "base/values.h" #include "tools/gn/target.h" #include "tools/gn/unique_vector.h" @@ -102,7 +102,7 @@ CommandRunner runner; }; -typedef std::map<base::StringPiece, CommandInfo> CommandInfoMap; +typedef std::map<std::string_view, CommandInfo> CommandInfoMap; const CommandInfoMap& GetCommands(); @@ -145,7 +145,8 @@ bool CheckPublicHeaders(const BuildSettings* build_settings, const std::vector<const Target*>& all_targets, const std::vector<const Target*>& to_check, - bool force_check, bool check_generated); + bool force_check, + bool check_generated); // Filters the given list of targets by the given pattern list. void FilterTargetsByPatterns(const std::vector<const Target*>& input,
diff --git a/tools/gn/create_bundle_target_generator.cc b/tools/gn/create_bundle_target_generator.cc index 2c5a3af..be60f50 100644 --- a/tools/gn/create_bundle_target_generator.cc +++ b/tools/gn/create_bundle_target_generator.cc
@@ -73,7 +73,7 @@ bool CreateBundleTargetGenerator::FillBundleDir( const SourceDir& bundle_root_dir, - const base::StringPiece& name, + const std::string_view& name, SourceDir* bundle_dir) { // All bundle_foo_dir properties are optional. They are only required if they // are used in an expansion. The check is performed there.
diff --git a/tools/gn/create_bundle_target_generator.h b/tools/gn/create_bundle_target_generator.h index a7f1edc..63b85fa 100644 --- a/tools/gn/create_bundle_target_generator.h +++ b/tools/gn/create_bundle_target_generator.h
@@ -24,7 +24,7 @@ private: bool FillBundleDir(const SourceDir& bundle_root_dir, - const base::StringPiece& name, + const std::string_view& name, SourceDir* bundle_dir); bool FillXcodeExtraAttributes();
diff --git a/tools/gn/err.cc b/tools/gn/err.cc index 4f60964..4d3cbce 100644 --- a/tools/gn/err.cc +++ b/tools/gn/err.cc
@@ -17,7 +17,7 @@ namespace { -std::string GetNthLine(const base::StringPiece& data, int n) { +std::string GetNthLine(const std::string_view& data, int n) { size_t line_off = Tokenizer::ByteOffsetOfNthLine(data, n); size_t end = line_off + 1; while (end < data.size() && !Tokenizer::IsNewline(data, end))
diff --git a/tools/gn/escape.cc b/tools/gn/escape.cc index d5e33c0..ef4dcfa 100644 --- a/tools/gn/escape.cc +++ b/tools/gn/escape.cc
@@ -62,7 +62,7 @@ return ch == '$' || ch == ' ' || ch == ':'; } -size_t EscapeStringToString_Ninja(const base::StringPiece& str, +size_t EscapeStringToString_Ninja(const std::string_view& str, const EscapeOptions& options, char* dest, bool* needed_quoting) { @@ -75,7 +75,7 @@ return i; } -size_t EscapeStringToString_Depfile(const base::StringPiece& str, +size_t EscapeStringToString_Depfile(const std::string_view& str, const EscapeOptions& options, char* dest, bool* needed_quoting) { @@ -93,7 +93,7 @@ return i; } -size_t EscapeStringToString_NinjaPreformatted(const base::StringPiece& str, +size_t EscapeStringToString_NinjaPreformatted(const std::string_view& str, char* dest) { // Only Ninja-escape $. size_t i = 0; @@ -113,7 +113,7 @@ // See: // http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx // http://blogs.msdn.com/b/oldnewthing/archive/2010/09/17/10063629.aspx -size_t EscapeStringToString_WindowsNinjaFork(const base::StringPiece& str, +size_t EscapeStringToString_WindowsNinjaFork(const std::string_view& str, const EscapeOptions& options, char* dest, bool* needed_quoting) { @@ -165,7 +165,7 @@ return i; } -size_t EscapeStringToString_PosixNinjaFork(const base::StringPiece& str, +size_t EscapeStringToString_PosixNinjaFork(const std::string_view& str, const EscapeOptions& options, char* dest, bool* needed_quoting) { @@ -196,7 +196,7 @@ } // Escapes |str| into |dest| and returns the number of characters written. -size_t EscapeStringToString(const base::StringPiece& str, +size_t EscapeStringToString(const std::string_view& str, const EscapeOptions& options, char* dest, bool* needed_quoting) { @@ -237,7 +237,7 @@ } // namespace -std::string EscapeString(const base::StringPiece& str, +std::string EscapeString(const std::string_view& str, const EscapeOptions& options, bool* needed_quoting) { StackOrHeapBuffer dest(str.size() * kMaxEscapedCharsPerChar); @@ -246,7 +246,7 @@ } void EscapeStringToStream(std::ostream& out, - const base::StringPiece& str, + const std::string_view& str, const EscapeOptions& options) { StackOrHeapBuffer dest(str.size() * kMaxEscapedCharsPerChar); out.write(dest, EscapeStringToString(str, options, dest, nullptr));
diff --git a/tools/gn/escape.h b/tools/gn/escape.h index af5f8b8..36a9c5c 100644 --- a/tools/gn/escape.h +++ b/tools/gn/escape.h
@@ -6,8 +6,7 @@ #define TOOLS_GN_ESCAPE_H_ #include <iosfwd> - -#include "base/strings/string_piece.h" +#include <string_view> enum EscapingMode { // No escaping. @@ -64,14 +63,14 @@ // (if inhibit_quoting was set) quoted will be written to it. This value should // be initialized to false by the caller and will be written to only if it's // true (the common use-case is for chaining calls). -std::string EscapeString(const base::StringPiece& str, +std::string EscapeString(const std::string_view& str, const EscapeOptions& options, bool* needed_quoting); // Same as EscapeString but writes the results to the given stream, saving a // copy. void EscapeStringToStream(std::ostream& out, - const base::StringPiece& str, + const std::string_view& str, const EscapeOptions& options); #endif // TOOLS_GN_ESCAPE_H_
diff --git a/tools/gn/exec_process.cc b/tools/gn/exec_process.cc index 2496405..e266d90 100644 --- a/tools/gn/exec_process.cc +++ b/tools/gn/exec_process.cc
@@ -42,7 +42,7 @@ std_err, exit_code); } -bool ExecProcess(const base::string16& cmdline_str, +bool ExecProcess(const std::u16string& cmdline_str, const base::FilePath& startup_dir, std::string* std_out, std::string* std_err, @@ -94,7 +94,7 @@ start_info.hStdError = GetStdHandle(STD_ERROR_HANDLE); start_info.dwFlags |= STARTF_USESTDHANDLES; - base::string16 cmdline_writable = cmdline_str; + std::u16string cmdline_writable = cmdline_str; // Create the child process. PROCESS_INFORMATION temp_process_info = {};
diff --git a/tools/gn/exec_process.h b/tools/gn/exec_process.h index 278d539..91ee876 100644 --- a/tools/gn/exec_process.h +++ b/tools/gn/exec_process.h
@@ -7,7 +7,6 @@ #include <string> -#include "base/strings/string16.h" #include "util/build_config.h" namespace base { @@ -24,7 +23,7 @@ int* exit_code); #if defined(OS_WIN) -bool ExecProcess(const base::string16& cmdline_str, +bool ExecProcess(const std::u16string& cmdline_str, const base::FilePath& startup_dir, std::string* std_out, std::string* std_err,
diff --git a/tools/gn/filesystem_utils.cc b/tools/gn/filesystem_utils.cc index ea4dfb8..43efcc3 100644 --- a/tools/gn/filesystem_utils.cc +++ b/tools/gn/filesystem_utils.cc
@@ -81,8 +81,8 @@ // Attempts to do a case and slash-insensitive comparison of two 8-bit Windows // paths. -bool AreAbsoluteWindowsPathsEqual(const base::StringPiece& a, - const base::StringPiece& b) { +bool AreAbsoluteWindowsPathsEqual(const std::string_view& a, + const std::string_view& b) { if (a.size() != b.size()) return false; @@ -95,7 +95,7 @@ return true; } -bool DoesBeginWindowsDriveLetter(const base::StringPiece& path) { +bool DoesBeginWindowsDriveLetter(const std::string_view& path) { if (path.size() < 3) return false; @@ -200,7 +200,7 @@ } } -size_t AbsPathLenWithNoTrailingSlash(const base::StringPiece& path) { +size_t AbsPathLenWithNoTrailingSlash(const std::string_view& path) { size_t len = path.size(); #if defined(OS_WIN) size_t min_len = 3; @@ -222,7 +222,7 @@ #endif } -base::FilePath UTF8ToFilePath(const base::StringPiece& sp) { +base::FilePath UTF8ToFilePath(const std::string_view& sp) { #if defined(OS_WIN) return base::FilePath(base::UTF8ToUTF16(sp)); #else @@ -240,12 +240,12 @@ return std::string::npos; } -base::StringPiece FindExtension(const std::string* path) { +std::string_view FindExtension(const std::string* path) { size_t extension_offset = FindExtensionOffset(*path); if (extension_offset == std::string::npos) - return base::StringPiece(); - return base::StringPiece(&path->data()[extension_offset], - path->size() - extension_offset); + return std::string_view(); + return std::string_view(&path->data()[extension_offset], + path->size() - extension_offset); } size_t FindFilenameOffset(const std::string& path) { @@ -256,17 +256,17 @@ return 0; // No filename found means everything was the filename. } -base::StringPiece FindFilename(const std::string* path) { +std::string_view FindFilename(const std::string* path) { size_t filename_offset = FindFilenameOffset(*path); if (filename_offset == 0) - return base::StringPiece(*path); // Everything is the file name. - return base::StringPiece(&(*path).data()[filename_offset], - path->size() - filename_offset); + return std::string_view(*path); // Everything is the file name. + return std::string_view(&(*path).data()[filename_offset], + path->size() - filename_offset); } -base::StringPiece FindFilenameNoExtension(const std::string* path) { +std::string_view FindFilenameNoExtension(const std::string* path) { if (path->empty()) - return base::StringPiece(); + return std::string_view(); size_t filename_offset = FindFilenameOffset(*path); size_t extension_offset = FindExtensionOffset(*path); @@ -276,7 +276,7 @@ else name_len = extension_offset - filename_offset - 1; - return base::StringPiece(&(*path).data()[filename_offset], name_len); + return std::string_view(&(*path).data()[filename_offset], name_len); } void RemoveFilename(std::string* path) { @@ -287,18 +287,18 @@ return !s.empty() && IsSlash(s[s.size() - 1]); } -base::StringPiece FindDir(const std::string* path) { +std::string_view FindDir(const std::string* path) { size_t filename_offset = FindFilenameOffset(*path); if (filename_offset == 0u) - return base::StringPiece(); - return base::StringPiece(path->data(), filename_offset); + return std::string_view(); + return std::string_view(path->data(), filename_offset); } -base::StringPiece FindLastDirComponent(const SourceDir& dir) { +std::string_view FindLastDirComponent(const SourceDir& dir) { const std::string& dir_string = dir.value(); if (dir_string.empty()) - return base::StringPiece(); + return std::string_view(); int cur = static_cast<int>(dir_string.size()) - 1; DCHECK(dir_string[cur] == '/'); int end = cur; @@ -306,9 +306,9 @@ for (; cur >= 0; cur--) { if (dir_string[cur] == '/') - return base::StringPiece(&dir_string[cur + 1], end - cur - 1); + return std::string_view(&dir_string[cur + 1], end - cur - 1); } - return base::StringPiece(&dir_string[0], end); + return std::string_view(&dir_string[0], end); } bool IsStringInOutputDir(const SourceDir& output_dir, const std::string& str) { @@ -334,7 +334,7 @@ return false; } -bool IsPathAbsolute(const base::StringPiece& path) { +bool IsPathAbsolute(const std::string_view& path) { if (path.empty()) return false; @@ -355,12 +355,12 @@ return true; } -bool IsPathSourceAbsolute(const base::StringPiece& path) { +bool IsPathSourceAbsolute(const std::string_view& path) { return (path.size() >= 2 && path[0] == '/' && path[1] == '/'); } -bool MakeAbsolutePathRelativeIfPossible(const base::StringPiece& source_root, - const base::StringPiece& path, +bool MakeAbsolutePathRelativeIfPossible(const std::string_view& source_root, + const std::string_view& path, std::string* dest) { DCHECK(IsPathAbsolute(source_root)); DCHECK(IsPathAbsolute(path)); @@ -504,7 +504,7 @@ return base::FilePath(base::JoinString(relative_components, separator)); } -void NormalizePath(std::string* path, const base::StringPiece& source_root) { +void NormalizePath(std::string* path, const std::string_view& source_root) { char* pathbuf = path->empty() ? nullptr : &(*path)[0]; // top_index is the first character we can modify in the path. Anything @@ -702,7 +702,7 @@ std::string RebasePath(const std::string& input, const SourceDir& dest_dir, - const base::StringPiece& source_root) { + const std::string_view& source_root) { std::string ret; DCHECK(source_root.empty() || !base::EndsWith(source_root, "/", base::CompareCase::SENSITIVE)); @@ -784,7 +784,7 @@ std::string ResolveRelative(const StringType& input, const std::string& value, bool as_file, - const base::StringPiece& source_root) { + const std::string_view& source_root) { std::string result; if (input.size() >= 2 && input[0] == '/' && input[1] == '/') { @@ -846,15 +846,15 @@ } // Explicit template instantiation -template std::string ResolveRelative(const base::StringPiece& input, +template std::string ResolveRelative(const std::string_view& input, const std::string& value, bool as_file, - const base::StringPiece& source_root); + const std::string_view& source_root); template std::string ResolveRelative(const std::string& input, const std::string& value, bool as_file, - const base::StringPiece& source_root); + const std::string_view& source_root); std::string DirectoryWithNoLastSlash(const SourceDir& dir) { std::string ret;
diff --git a/tools/gn/filesystem_utils.h b/tools/gn/filesystem_utils.h index 220c4f8..f25e702 100644 --- a/tools/gn/filesystem_utils.h +++ b/tools/gn/filesystem_utils.h
@@ -8,9 +8,9 @@ #include <stddef.h> #include <string> +#include <string_view> #include "base/files/file_path.h" -#include "base/strings/string_piece.h" #include "tools/gn/settings.h" #include "tools/gn/target.h" @@ -20,7 +20,7 @@ inline std::string FilePathToUTF8(const base::FilePath& path) { return FilePathToUTF8(path.value()); } -base::FilePath UTF8ToFilePath(const base::StringPiece& sp); +base::FilePath UTF8ToFilePath(const std::string_view& sp); // Extensions ----------------------------------------------------------------- @@ -31,7 +31,7 @@ // Returns a string piece pointing into the input string identifying the // extension. Note that the input pointer must outlive the output. -base::StringPiece FindExtension(const std::string* path); +std::string_view FindExtension(const std::string* path); // Filename parts ------------------------------------------------------------- @@ -43,10 +43,10 @@ // Returns a string piece pointing into the input string identifying the // file name (following the last slash, including the extension). Note that the // input pointer must outlive the output. -base::StringPiece FindFilename(const std::string* path); +std::string_view FindFilename(const std::string* path); // Like FindFilename but does not include the extension. -base::StringPiece FindFilenameNoExtension(const std::string* path); +std::string_view FindFilenameNoExtension(const std::string* path); // Removes everything after the last slash. The last slash, if any, will be // preserved. @@ -67,11 +67,11 @@ // Returns a string piece pointing into the input string identifying the // directory name of the given path, including the last slash. Note that the // input pointer must outlive the output. -base::StringPiece FindDir(const std::string* path); +std::string_view FindDir(const std::string* path); // Returns the substring identifying the last component of the dir, or the // empty substring if none. For example "//foo/bar/" -> "bar". -base::StringPiece FindLastDirComponent(const SourceDir& dir); +std::string_view FindLastDirComponent(const SourceDir& dir); // Returns true if the given string is in the given output dir. This is pretty // stupid and doesn't handle "." and "..", etc., it is designed for a sanity @@ -96,12 +96,12 @@ // Returns true if the input string is absolute. Double-slashes at the // beginning are treated as source-relative paths. On Windows, this handles // paths of both the native format: "C:/foo" and ours "/C:/foo" -bool IsPathAbsolute(const base::StringPiece& path); +bool IsPathAbsolute(const std::string_view& path); // Returns true if the input string is source-absolute. Source-absolute // paths begin with two forward slashes and resolve as if they are // relative to the source root. -bool IsPathSourceAbsolute(const base::StringPiece& path); +bool IsPathSourceAbsolute(const std::string_view& path); // Given an absolute path, checks to see if is it is inside the source root. // If it is, fills a source-absolute path into the given output and returns @@ -112,8 +112,8 @@ // ("/C:/"). The source root can end with a slash or not. // // Note that this does not attempt to normalize slashes in the output. -bool MakeAbsolutePathRelativeIfPossible(const base::StringPiece& source_root, - const base::StringPiece& path, +bool MakeAbsolutePathRelativeIfPossible(const std::string_view& source_root, + const std::string_view& path, std::string* dest); // Given two absolute paths |base| and |target|, returns a relative path to @@ -134,7 +134,7 @@ // a leading slash. Otherwise, |path| will retain its relativity. |source_root| // must not end with a slash. void NormalizePath(std::string* path, - const base::StringPiece& source_root = base::StringPiece()); + const std::string_view& source_root = std::string_view()); // Converts slashes to backslashes for Windows. Keeps the string unchanged // for other systems. @@ -150,7 +150,7 @@ std::string RebasePath( const std::string& input, const SourceDir& dest_dir, - const base::StringPiece& source_root = base::StringPiece()); + const std::string_view& source_root = std::string_view()); // Resolves a file or dir name (parameter input) relative to // value directory. Will return an empty SourceDir/File on error @@ -169,7 +169,7 @@ std::string ResolveRelative(const StringType& input, const std::string& value, bool as_file, - const base::StringPiece& source_root); + const std::string_view& source_root); // Resolves source file or directory relative to some given source root. Returns // an empty file path on error.
diff --git a/tools/gn/filesystem_utils_unittest.cc b/tools/gn/filesystem_utils_unittest.cc index 2f8df44..da1d4b1 100644 --- a/tools/gn/filesystem_utils_unittest.cc +++ b/tools/gn/filesystem_utils_unittest.cc
@@ -424,7 +424,7 @@ } TEST(FilesystemUtils, RebasePath) { - base::StringPiece source_root("/source/root"); + std::string_view source_root("/source/root"); // Degenerate case. EXPECT_EQ(".", RebasePath("//", SourceDir("//"), source_root)); @@ -468,84 +468,84 @@ // Check when only |input| is system-absolute EXPECT_EQ("foo", RebasePath("/source/root/foo", SourceDir("//"), - base::StringPiece("/source/root"))); + std::string_view("/source/root"))); EXPECT_EQ("foo/", RebasePath("/source/root/foo/", SourceDir("//"), - base::StringPiece("/source/root"))); + std::string_view("/source/root"))); EXPECT_EQ("../../builddir/Out/Debug", RebasePath("/builddir/Out/Debug", SourceDir("//"), - base::StringPiece("/source/root"))); + std::string_view("/source/root"))); EXPECT_EQ("../../../builddir/Out/Debug", RebasePath("/builddir/Out/Debug", SourceDir("//"), - base::StringPiece("/source/root/foo"))); + std::string_view("/source/root/foo"))); EXPECT_EQ("../../../builddir/Out/Debug/", RebasePath("/builddir/Out/Debug/", SourceDir("//"), - base::StringPiece("/source/root/foo"))); + std::string_view("/source/root/foo"))); EXPECT_EQ("../../path/to/foo", RebasePath("/path/to/foo", SourceDir("//"), - base::StringPiece("/source/root"))); + std::string_view("/source/root"))); EXPECT_EQ("../../../path/to/foo", RebasePath("/path/to/foo", SourceDir("//a"), - base::StringPiece("/source/root"))); + std::string_view("/source/root"))); EXPECT_EQ("../../../../path/to/foo", RebasePath("/path/to/foo", SourceDir("//a/b"), - base::StringPiece("/source/root"))); + std::string_view("/source/root"))); // Check when only |dest_dir| is system-absolute. EXPECT_EQ(".", RebasePath("//", SourceDir("/source/root"), - base::StringPiece("/source/root"))); + std::string_view("/source/root"))); EXPECT_EQ("foo", RebasePath("//foo", SourceDir("/source/root"), - base::StringPiece("/source/root"))); + std::string_view("/source/root"))); EXPECT_EQ("../foo", RebasePath("//foo", SourceDir("/source/root/bar"), - base::StringPiece("/source/root"))); + std::string_view("/source/root"))); EXPECT_EQ("../../../source/root/foo", RebasePath("//foo", SourceDir("/other/source/root"), - base::StringPiece("/source/root"))); + std::string_view("/source/root"))); EXPECT_EQ("../../../../source/root/foo", RebasePath("//foo", SourceDir("/other/source/root/bar"), - base::StringPiece("/source/root"))); + std::string_view("/source/root"))); // Check when |input| and |dest_dir| are both system-absolute. Also, // in this case |source_root| is never used so set it to a dummy // value. EXPECT_EQ("foo", RebasePath("/source/root/foo", SourceDir("/source/root"), - base::StringPiece("/x/y/z"))); + std::string_view("/x/y/z"))); EXPECT_EQ("foo/", RebasePath("/source/root/foo/", SourceDir("/source/root"), - base::StringPiece("/x/y/z"))); + std::string_view("/x/y/z"))); EXPECT_EQ("../../builddir/Out/Debug", RebasePath("/builddir/Out/Debug", SourceDir("/source/root"), - base::StringPiece("/x/y/z"))); + std::string_view("/x/y/z"))); EXPECT_EQ("../../../builddir/Out/Debug", RebasePath("/builddir/Out/Debug", SourceDir("/source/root/foo"), - base::StringPiece("/source/root/foo"))); + std::string_view("/source/root/foo"))); EXPECT_EQ("../../../builddir/Out/Debug/", RebasePath("/builddir/Out/Debug/", SourceDir("/source/root/foo"), - base::StringPiece("/source/root/foo"))); + std::string_view("/source/root/foo"))); EXPECT_EQ("../../path/to/foo", RebasePath("/path/to/foo", SourceDir("/source/root"), - base::StringPiece("/x/y/z"))); + std::string_view("/x/y/z"))); EXPECT_EQ("../../../path/to/foo", RebasePath("/path/to/foo", SourceDir("/source/root/a"), - base::StringPiece("/x/y/z"))); + std::string_view("/x/y/z"))); EXPECT_EQ("../../../../path/to/foo", RebasePath("/path/to/foo", SourceDir("/source/root/a/b"), - base::StringPiece("/x/y/z"))); + std::string_view("/x/y/z"))); #if defined(OS_WIN) // Test corrections while rebasing Windows-style absolute paths. EXPECT_EQ("../../../../path/to/foo", RebasePath("C:/path/to/foo", SourceDir("//a/b"), - base::StringPiece("/C:/source/root"))); + std::string_view("/C:/source/root"))); EXPECT_EQ("../../../../path/to/foo", RebasePath("/C:/path/to/foo", SourceDir("//a/b"), - base::StringPiece("C:/source/root"))); + std::string_view("C:/source/root"))); EXPECT_EQ("../../../../path/to/foo", RebasePath("/C:/path/to/foo", SourceDir("//a/b"), - base::StringPiece("/c:/source/root"))); + std::string_view("/c:/source/root"))); EXPECT_EQ("../../../../path/to/foo", RebasePath("/c:/path/to/foo", SourceDir("//a/b"), - base::StringPiece("c:/source/root"))); + std::string_view("c:/source/root"))); EXPECT_EQ("../../../../path/to/foo", RebasePath("/c:/path/to/foo", SourceDir("//a/b"), - base::StringPiece("C:/source/root"))); + std::string_view("C:/source/root"))); #endif }
diff --git a/tools/gn/function_foreach.cc b/tools/gn/function_foreach.cc index 24ffaab..ec9070f 100644 --- a/tools/gn/function_foreach.cc +++ b/tools/gn/function_foreach.cc
@@ -62,7 +62,7 @@ Err(args_vector[0].get(), "Expected an identifier for the loop var."); return Value(); } - base::StringPiece loop_var(identifier->value().value()); + std::string_view loop_var(identifier->value().value()); // Extract the list to iterate over. Always copy in case the code changes // the list variable inside the loop.
diff --git a/tools/gn/function_forward_variables_from.cc b/tools/gn/function_forward_variables_from.cc index 875af91..0366381 100644 --- a/tools/gn/function_forward_variables_from.cc +++ b/tools/gn/function_forward_variables_from.cc
@@ -43,9 +43,10 @@ if (value) { // Use the storage key for the original value rather than the string in // "cur" because "cur" is a temporary that will be deleted, and Scopes - // expect a persistent StringPiece (it won't copy). Not doing this will - // lead the scope's key to point to invalid memory after this returns. - base::StringPiece storage_key = source->GetStorageKey(cur.string_value()); + // expect a persistent std::string_view (it won't copy). Not doing this + // will lead the scope's key to point to invalid memory after this + // returns. + std::string_view storage_key = source->GetStorageKey(cur.string_value()); if (storage_key.empty()) { // Programmatic value, don't allow copying. *err =
diff --git a/tools/gn/function_get_path_info.cc b/tools/gn/function_get_path_info.cc index b392490..6e87a57 100644 --- a/tools/gn/function_get_path_info.cc +++ b/tools/gn/function_get_path_info.cc
@@ -77,7 +77,7 @@ return std::string(FindExtension(&input_string)); } case WHAT_DIR: { - base::StringPiece dir_incl_slash = FindDir(&input_string); + std::string_view dir_incl_slash = FindDir(&input_string); if (dir_incl_slash.empty()) return std::string("."); // Trim slash since this function doesn't return trailing slashes. The
diff --git a/tools/gn/functions.cc b/tools/gn/functions.cc index c0a64ac..74b48bc 100644 --- a/tools/gn/functions.cc +++ b/tools/gn/functions.cc
@@ -135,7 +135,7 @@ // Set the target name variable to the current target, and mark it used // because we don't want to issue an error if the script ignores it. - const base::StringPiece target_name(variables::kTargetName); + const std::string_view target_name(variables::kTargetName); block_scope->SetValue(target_name, Value(function, args[0].string_value()), function); block_scope->MarkUsed(target_name);
diff --git a/tools/gn/functions.h b/tools/gn/functions.h index 9dc2cdc..4119571 100644 --- a/tools/gn/functions.h +++ b/tools/gn/functions.h
@@ -7,10 +7,9 @@ #include <map> #include <string> +#include <string_view> #include <vector> -#include "base/strings/string_piece.h" - class Err; class BlockNode; class FunctionCallNode; @@ -433,7 +432,7 @@ bool is_target; }; -typedef std::map<base::StringPiece, FunctionInfo> FunctionInfoMap; +typedef std::map<std::string_view, FunctionInfo> FunctionInfoMap; // Returns the mapping of all built-in functions. const FunctionInfoMap& GetFunctions();
diff --git a/tools/gn/generated_file_target_generator.cc b/tools/gn/generated_file_target_generator.cc index 023e5d4..35e0db4 100644 --- a/tools/gn/generated_file_target_generator.cc +++ b/tools/gn/generated_file_target_generator.cc
@@ -68,7 +68,7 @@ } bool GeneratedFileTargetGenerator::IsMetadataCollectionTarget( - const base::StringPiece& variable, + const std::string_view& variable, const ParseNode* origin) { if (contents_defined_) { *err_ =
diff --git a/tools/gn/generated_file_target_generator.h b/tools/gn/generated_file_target_generator.h index 206555f..cdcea14 100644 --- a/tools/gn/generated_file_target_generator.h +++ b/tools/gn/generated_file_target_generator.h
@@ -35,7 +35,7 @@ // it is okay to set metadata collection variables on this target. // // Should be called before FillContents(). - bool IsMetadataCollectionTarget(const base::StringPiece& variable, + bool IsMetadataCollectionTarget(const std::string_view& variable, const ParseNode* origin); bool contents_defined_ = false;
diff --git a/tools/gn/header_checker.cc b/tools/gn/header_checker.cc index 14784b7..f4af9d8 100644 --- a/tools/gn/header_checker.cc +++ b/tools/gn/header_checker.cc
@@ -244,7 +244,7 @@ } SourceFile HeaderChecker::SourceFileForInclude( - const base::StringPiece& relative_file_path, + const std::string_view& relative_file_path, const std::vector<SourceDir>& include_dirs, const InputFile& source_file, const LocationRange& range, @@ -308,7 +308,7 @@ size_t error_count_before = errors->size(); CIncludeIterator iter(&input_file); - base::StringPiece current_include; + std::string_view current_include; LocationRange range; std::set<std::pair<const Target*, const Target*>> no_dependency_cache;
diff --git a/tools/gn/header_checker.h b/tools/gn/header_checker.h index 3932001..8e73c19 100644 --- a/tools/gn/header_checker.h +++ b/tools/gn/header_checker.h
@@ -9,13 +9,13 @@ #include <map> #include <mutex> #include <set> +#include <string_view> #include <vector> #include "base/atomic_ref_count.h" #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/strings/string_piece.h" #include "tools/gn/err.h" #include "tools/gn/source_dir.h" @@ -112,7 +112,7 @@ bool IsFileInOuputDir(const SourceFile& file) const; // Resolves the contents of an include to a SourceFile. - SourceFile SourceFileForInclude(const base::StringPiece& relative_file_path, + SourceFile SourceFileForInclude(const std::string_view& relative_file_path, const std::vector<SourceDir>& include_dirs, const InputFile& source_file, const LocationRange& range,
diff --git a/tools/gn/input_conversion.cc b/tools/gn/input_conversion.cc index 270d437..d2acb71 100644 --- a/tools/gn/input_conversion.cc +++ b/tools/gn/input_conversion.cc
@@ -107,7 +107,7 @@ return ret; } -bool IsIdentifier(const base::StringPiece& buffer) { +bool IsIdentifier(const std::string_view& buffer) { DCHECK(buffer.size() > 0); if (!Tokenizer::IsIdentifierFirstChar(buffer[0])) return false; @@ -146,14 +146,13 @@ } // Search for the key in the input file. We know it's present because // it was parsed by the JSON reader, but we need its location to - // construct a StringPiece that can be used as key in the Scope. + // construct a std::string_view that can be used as key in the Scope. size_t off = input_file->contents().find("\"" + it.first + "\""); if (off == std::string::npos) { *err = Err(origin, "Invalid encoding \"" + it.first + "\"."); return Value(); } - base::StringPiece key(&input_file->contents()[off + 1], - it.first.size()); + std::string_view key(&input_file->contents()[off + 1], it.first.size()); scope->SetValue(key, std::move(parsed_value), origin); } return Value(origin, std::move(scope));
diff --git a/tools/gn/label.cc b/tools/gn/label.cc index 22b6f81..e5a1148 100644 --- a/tools/gn/label.cc +++ b/tools/gn/label.cc
@@ -29,7 +29,7 @@ // used. The value is used only for generating error messages. bool ComputeBuildLocationFromDep(const Value& input_value, const SourceDir& current_dir, - const base::StringPiece& input, + const std::string_view& input, SourceDir* result, Err* err) { // No rule, use the current location. @@ -48,7 +48,7 @@ // error messages. bool ComputeTargetNameFromDep(const Value& input_value, const SourceDir& computed_location, - const base::StringPiece& input, + const std::string_view& input, std::string* result, Err* err) { if (!input.empty()) { @@ -88,13 +88,14 @@ bool Resolve(const SourceDir& current_dir, const Label& current_toolchain, const Value& original_value, - const base::StringPiece& input, + const std::string_view& input, SourceDir* out_dir, std::string* out_name, SourceDir* out_toolchain_dir, std::string* out_toolchain_name, Err* err) { - // To workaround the problem that StringPiece operator[] doesn't return a ref. + // To workaround the problem that std::string_view operator[] doesn't return a + // ref. const char* input_str = input.data(); size_t offset = 0; #if defined(OS_WIN) @@ -110,19 +111,19 @@ } #endif size_t path_separator = input.find_first_of(":(", offset); - base::StringPiece location_piece; - base::StringPiece name_piece; - base::StringPiece toolchain_piece; + std::string_view location_piece; + std::string_view name_piece; + std::string_view toolchain_piece; if (path_separator == std::string::npos) { location_piece = input; // Leave name & toolchain piece null. } else { - location_piece = base::StringPiece(&input_str[0], path_separator); + location_piece = std::string_view(&input_str[0], path_separator); size_t toolchain_separator = input.find('(', path_separator); if (toolchain_separator == std::string::npos) { - name_piece = base::StringPiece(&input_str[path_separator + 1], - input.size() - path_separator - 1); + name_piece = std::string_view(&input_str[path_separator + 1], + input.size() - path_separator - 1); // Leave location piece null. } else if (!out_toolchain_dir) { // Toolchain specified but not allows in this context. @@ -135,9 +136,8 @@ // Name piece is everything between the two separators. Note that the // separators may be the same (e.g. "//foo(bar)" which means empty name. if (toolchain_separator > path_separator) { - name_piece = - base::StringPiece(&input_str[path_separator + 1], - toolchain_separator - path_separator - 1); + name_piece = std::string_view(&input_str[path_separator + 1], + toolchain_separator - path_separator - 1); } // Toolchain name should end in a ) and this should be the end of the @@ -151,8 +151,8 @@ // Subtract off the two parens to just get the toolchain name. toolchain_piece = - base::StringPiece(&input_str[toolchain_separator + 1], - input.size() - toolchain_separator - 2); + std::string_view(&input_str[toolchain_separator + 1], + input.size() - toolchain_separator - 2); } } @@ -251,15 +251,15 @@ )*"; Label::Label(const SourceDir& dir, - const base::StringPiece& name, + const std::string_view& name, const SourceDir& toolchain_dir, - const base::StringPiece& toolchain_name) + const std::string_view& toolchain_name) : dir_(dir), toolchain_dir_(toolchain_dir) { name_.assign(name.data(), name.size()); toolchain_name_.assign(toolchain_name.data(), toolchain_name.size()); } -Label::Label(const SourceDir& dir, const base::StringPiece& name) : dir_(dir) { +Label::Label(const SourceDir& dir, const std::string_view& name) : dir_(dir) { name_.assign(name.data(), name.size()); }
diff --git a/tools/gn/label.h b/tools/gn/label.h index 44f6e40..9fd245f 100644 --- a/tools/gn/label.h +++ b/tools/gn/label.h
@@ -24,12 +24,12 @@ // Makes a label given an already-separated out path and name. // See also Resolve(). Label(const SourceDir& dir, - const base::StringPiece& name, + const std::string_view& name, const SourceDir& toolchain_dir, - const base::StringPiece& toolchain_name); + const std::string_view& toolchain_name); // Makes a label with an empty toolchain. - Label(const SourceDir& dir, const base::StringPiece& name); + Label(const SourceDir& dir, const std::string_view& name); // Resolves a string from a build file that may be relative to the // current directory into a fully qualified label. On failure returns an
diff --git a/tools/gn/label_pattern.cc b/tools/gn/label_pattern.cc index bed4d86..b69cfe4 100644 --- a/tools/gn/label_pattern.cc +++ b/tools/gn/label_pattern.cc
@@ -53,7 +53,7 @@ LabelPattern::LabelPattern(Type type, const SourceDir& dir, - const base::StringPiece& name, + const std::string_view& name, const Label& toolchain_label) : toolchain_(toolchain_label), type_(type), dir_(dir), name_(name) {} @@ -68,7 +68,7 @@ if (!value.VerifyTypeIs(Value::STRING, err)) return LabelPattern(); - base::StringPiece str(value.string_value()); + std::string_view str(value.string_value()); if (str.empty()) { *err = Err(value, "Label pattern must not be empty."); return LabelPattern(); @@ -120,8 +120,8 @@ } // Extract path and name. - base::StringPiece path; - base::StringPiece name; + std::string_view path; + std::string_view name; size_t offset = 0; #if defined(OS_WIN) if (IsPathAbsolute(str)) { @@ -136,7 +136,7 @@ #endif size_t colon = str.find(':', offset); if (colon == std::string::npos) { - path = base::StringPiece(str); + path = std::string_view(str); } else { path = str.substr(0, colon); name = str.substr(colon + 1); @@ -173,7 +173,7 @@ // Resolve the part of the path that's not the wildcard. if (!path.empty()) { // The non-wildcard stuff better not have a wildcard. - if (path.find('*') != base::StringPiece::npos) { + if (path.find('*') != std::string_view::npos) { *err = Err(value, "Label patterns only support wildcard suffixes.", "The pattern contained a '*' that wasn't at the end."); return LabelPattern(); @@ -207,7 +207,7 @@ } // When we're doing wildcard matching, the name is always empty. - return LabelPattern(type, dir, base::StringPiece(), toolchain_label); + return LabelPattern(type, dir, std::string_view(), toolchain_label); } bool LabelPattern::HasWildcard(const std::string& str) {
diff --git a/tools/gn/label_pattern.h b/tools/gn/label_pattern.h index 231fd6d..675d328 100644 --- a/tools/gn/label_pattern.h +++ b/tools/gn/label_pattern.h
@@ -5,7 +5,8 @@ #ifndef TOOLS_GN_LABEL_PATTERN_H_ #define TOOLS_GN_LABEL_PATTERN_H_ -#include "base/strings/string_piece.h" +#include <string_view> + #include "tools/gn/label.h" #include "tools/gn/source_dir.h" @@ -29,7 +30,7 @@ LabelPattern(); LabelPattern(Type type, const SourceDir& dir, - const base::StringPiece& name, + const std::string_view& name, const Label& toolchain_label); LabelPattern(const LabelPattern& other); ~LabelPattern();
diff --git a/tools/gn/lib_file.cc b/tools/gn/lib_file.cc index 81e54fb..50295ac 100644 --- a/tools/gn/lib_file.cc +++ b/tools/gn/lib_file.cc
@@ -8,7 +8,7 @@ LibFile::LibFile(const SourceFile& source_file) : source_file_(source_file) {} -LibFile::LibFile(const base::StringPiece& lib_name) +LibFile::LibFile(const std::string_view& lib_name) : name_(lib_name.data(), lib_name.size()) { DCHECK(!lib_name.empty()); }
diff --git a/tools/gn/lib_file.h b/tools/gn/lib_file.h index 58621eb..b971ad6 100644 --- a/tools/gn/lib_file.h +++ b/tools/gn/lib_file.h
@@ -9,8 +9,8 @@ #include <algorithm> #include <string> +#include <string_view> -#include "base/strings/string_piece.h" #include "tools/gn/source_file.h" // Represents an entry in "libs" list. Can be either a path (a SourceFile) or @@ -19,7 +19,7 @@ public: LibFile() = default; - explicit LibFile(const base::StringPiece& lib_name); + explicit LibFile(const std::string_view& lib_name); explicit LibFile(const SourceFile& source_file); bool is_source_file() const { return name_.empty(); }
diff --git a/tools/gn/metadata_unittest.cc b/tools/gn/metadata_unittest.cc index 901e539..683e65f 100644 --- a/tools/gn/metadata_unittest.cc +++ b/tools/gn/metadata_unittest.cc
@@ -17,8 +17,8 @@ b_expected.list_value().push_back(Value(nullptr, true)); Metadata::Contents contents; - contents.insert(std::pair<base::StringPiece, Value>("a", a_expected)); - contents.insert(std::pair<base::StringPiece, Value>("b", b_expected)); + contents.insert(std::pair<std::string_view, Value>("a", a_expected)); + contents.insert(std::pair<std::string_view, Value>("b", b_expected)); metadata.set_contents(std::move(contents)); @@ -41,7 +41,7 @@ a_expected.list_value().push_back(Value(nullptr, "bar.h")); metadata.contents().insert( - std::pair<base::StringPiece, Value>("a", a_expected)); + std::pair<std::string_view, Value>("a", a_expected)); std::vector<std::string> data_keys; data_keys.emplace_back("a"); @@ -75,7 +75,7 @@ a_expected.list_value().push_back(Value(nullptr, "foo/bar.h")); metadata.contents().insert( - std::pair<base::StringPiece, Value>("a", a_expected)); + std::pair<std::string_view, Value>("a", a_expected)); std::vector<std::string> data_keys; data_keys.emplace_back("a"); @@ -117,7 +117,7 @@ inner_scope.SetScopeValue(std::move(scope)); a.list_value().push_back(inner_scope); - metadata.contents().insert(std::pair<base::StringPiece, Value>("a", a)); + metadata.contents().insert(std::pair<std::string_view, Value>("a", a)); std::vector<std::string> data_keys; data_keys.emplace_back("a"); std::vector<std::string> walk_keys; @@ -162,7 +162,7 @@ a_expected.list_value().push_back(Value(nullptr, "//target")); metadata.contents().insert( - std::pair<base::StringPiece, Value>("a", a_expected)); + std::pair<std::string_view, Value>("a", a_expected)); std::vector<std::string> data_keys; std::vector<std::string> walk_keys; @@ -213,7 +213,7 @@ a_expected.list_value().push_back(Value(nullptr, "//target")); metadata.contents().insert( - std::pair<base::StringPiece, Value>("a", a_expected)); + std::pair<std::string_view, Value>("a", a_expected)); std::vector<std::string> data_keys; std::vector<std::string> walk_keys;
diff --git a/tools/gn/metadata_walk_unittest.cc b/tools/gn/metadata_walk_unittest.cc index a18a07e..04f7cd1 100644 --- a/tools/gn/metadata_walk_unittest.cc +++ b/tools/gn/metadata_walk_unittest.cc
@@ -17,12 +17,12 @@ Value a_expected(nullptr, Value::LIST); a_expected.list_value().push_back(Value(nullptr, "foo")); one.metadata().contents().insert( - std::pair<base::StringPiece, Value>("a", a_expected)); + std::pair<std::string_view, Value>("a", a_expected)); Value b_expected(nullptr, Value::LIST); b_expected.list_value().push_back(Value(nullptr, true)); one.metadata().contents().insert( - std::pair<base::StringPiece, Value>("b", b_expected)); + std::pair<std::string_view, Value>("b", b_expected)); one.metadata().set_source_dir(SourceDir("/usr/home/files/")); @@ -30,12 +30,12 @@ Value a_2_expected(nullptr, Value::LIST); a_2_expected.list_value().push_back(Value(nullptr, "bar")); two.metadata().contents().insert( - std::pair<base::StringPiece, Value>("a", a_2_expected)); + std::pair<std::string_view, Value>("a", a_2_expected)); Value b_2_expected(nullptr, Value::LIST); b_2_expected.list_value().push_back(Value(nullptr, false)); two.metadata().contents().insert( - std::pair<base::StringPiece, Value>("b", b_2_expected)); + std::pair<std::string_view, Value>("b", b_2_expected)); two.metadata().set_source_dir(SourceDir("/usr/home/files/inner")); @@ -75,18 +75,18 @@ Value a_expected(nullptr, Value::LIST); a_expected.list_value().push_back(Value(nullptr, "foo")); one.metadata().contents().insert( - std::pair<base::StringPiece, Value>("a", a_expected)); + std::pair<std::string_view, Value>("a", a_expected)); Value b_expected(nullptr, Value::LIST); b_expected.list_value().push_back(Value(nullptr, true)); one.metadata().contents().insert( - std::pair<base::StringPiece, Value>("b", b_expected)); + std::pair<std::string_view, Value>("b", b_expected)); TestTarget two(setup, "//foo:two", Target::SOURCE_SET); Value a_2_expected(nullptr, Value::LIST); a_2_expected.list_value().push_back(Value(nullptr, "bar")); two.metadata().contents().insert( - std::pair<base::StringPiece, Value>("a", a_2_expected)); + std::pair<std::string_view, Value>("a", a_2_expected)); one.public_deps().push_back(LabelTargetPair(&two)); @@ -124,25 +124,25 @@ Value a_expected(nullptr, Value::LIST); a_expected.list_value().push_back(Value(nullptr, "foo")); one.metadata().contents().insert( - std::pair<base::StringPiece, Value>("a", a_expected)); + std::pair<std::string_view, Value>("a", a_expected)); Value walk_expected(nullptr, Value::LIST); walk_expected.list_value().push_back( Value(nullptr, "//foo:two(//toolchain:default)")); one.metadata().contents().insert( - std::pair<base::StringPiece, Value>("walk", walk_expected)); + std::pair<std::string_view, Value>("walk", walk_expected)); TestTarget two(setup, "//foo:two", Target::SOURCE_SET); Value a_2_expected(nullptr, Value::LIST); a_2_expected.list_value().push_back(Value(nullptr, "bar")); two.metadata().contents().insert( - std::pair<base::StringPiece, Value>("a", a_2_expected)); + std::pair<std::string_view, Value>("a", a_2_expected)); TestTarget three(setup, "//foo:three", Target::SOURCE_SET); Value a_3_expected(nullptr, Value::LIST); a_3_expected.list_value().push_back(Value(nullptr, "baz")); three.metadata().contents().insert( - std::pair<base::StringPiece, Value>("a", a_3_expected)); + std::pair<std::string_view, Value>("a", a_3_expected)); one.public_deps().push_back(LabelTargetPair(&two)); one.public_deps().push_back(LabelTargetPair(&three)); @@ -180,12 +180,12 @@ Value a_expected(nullptr, Value::LIST); a_expected.list_value().push_back(Value(nullptr, "foo")); one.metadata().contents().insert( - std::pair<base::StringPiece, Value>("a", a_expected)); + std::pair<std::string_view, Value>("a", a_expected)); Value walk_expected(nullptr, Value::LIST); walk_expected.list_value().push_back(Value(nullptr, "//foo:missing")); one.metadata().contents().insert( - std::pair<base::StringPiece, Value>("walk", walk_expected)); + std::pair<std::string_view, Value>("walk", walk_expected)); UniqueVector<const Target*> targets; targets.push_back(&one);
diff --git a/tools/gn/operators.cc b/tools/gn/operators.cc index 24b17c0..ab77782 100644 --- a/tools/gn/operators.cc +++ b/tools/gn/operators.cc
@@ -101,7 +101,7 @@ } // Known to be an accessor. - base::StringPiece base_str = dest_accessor->base().value(); + std::string_view base_str = dest_accessor->base().value(); Value* base = exec_scope->GetMutableValue(base_str, Scope::SEARCH_CURRENT, false); if (!base) {
diff --git a/tools/gn/output_conversion_unittest.cc b/tools/gn/output_conversion_unittest.cc index 2e4146d..ad6ea80 100644 --- a/tools/gn/output_conversion_unittest.cc +++ b/tools/gn/output_conversion_unittest.cc
@@ -100,7 +100,7 @@ // Add some values to the scope. Value value(nullptr, "hello"); new_scope->SetValue("v", value, nullptr); - base::StringPiece private_var_name("_private"); + std::string_view private_var_name("_private"); new_scope->SetValue(private_var_name, value, nullptr); std::ostringstream result; @@ -164,7 +164,7 @@ // Add some values to the scope. Value value(nullptr, "hello"); new_scope->SetValue("v", value, nullptr); - base::StringPiece private_var_name("_private"); + std::string_view private_var_name("_private"); new_scope->SetValue(private_var_name, value, nullptr); std::ostringstream result;
diff --git a/tools/gn/parse_tree.cc b/tools/gn/parse_tree.cc index 337b3b2..b49fae7 100644 --- a/tools/gn/parse_tree.cc +++ b/tools/gn/parse_tree.cc
@@ -36,7 +36,7 @@ DEPS_CATEGORY_OTHER, }; -DepsCategory GetDepsCategory(base::StringPiece deps) { +DepsCategory GetDepsCategory(std::string_view deps) { if (deps.length() < 2 || deps[0] != '"' || deps[deps.size() - 1] != '"') return DEPS_CATEGORY_OTHER; @@ -49,19 +49,19 @@ return DEPS_CATEGORY_RELATIVE; } -std::tuple<base::StringPiece, base::StringPiece> SplitAtFirst( - base::StringPiece str, +std::tuple<std::string_view, std::string_view> SplitAtFirst( + std::string_view str, char c) { if (!base::StartsWith(str, "\"", base::CompareCase::SENSITIVE) || !base::EndsWith(str, "\"", base::CompareCase::SENSITIVE)) - return std::make_tuple(str, base::StringPiece()); + return std::make_tuple(str, std::string_view()); str = str.substr(1, str.length() - 2); size_t index_of_first = str.find(c); return std::make_tuple(str.substr(0, index_of_first), - index_of_first != base::StringPiece::npos + index_of_first != std::string_view::npos ? str.substr(index_of_first + 1) - : base::StringPiece()); + : std::string_view()); } bool IsSortRangeSeparator(const ParseNode* node, const ParseNode* prev) { @@ -74,7 +74,7 @@ static_cast<int>(node->comments()->before().size() + 1))); } -base::StringPiece GetStringRepresentation(const ParseNode* node) { +std::string_view GetStringRepresentation(const ParseNode* node) { DCHECK(node->AsLiteral() || node->AsIdentifier() || node->AsAccessor()); if (node->AsLiteral()) return node->AsLiteral()->value().value(); @@ -82,7 +82,7 @@ return node->AsIdentifier()->value().value(); else if (node->AsAccessor()) return node->AsAccessor()->base().value(); - return base::StringPiece(); + return std::string_view(); } } // namespace @@ -148,7 +148,7 @@ } base::Value ParseNode::CreateJSONNode(const char* type, - const base::StringPiece& value) const { + const std::string_view& value) const { base::Value dict(base::Value::Type::DICTIONARY); dict.SetKey(kJsonNodeType, base::Value(type)); dict.SetKey(kJsonNodeValue, base::Value(value)); @@ -712,8 +712,8 @@ void ListNode::SortAsStringsList() { // Sorts alphabetically. SortList([](const ParseNode* a, const ParseNode* b) { - base::StringPiece astr = GetStringRepresentation(a); - base::StringPiece bstr = GetStringRepresentation(b); + std::string_view astr = GetStringRepresentation(a); + std::string_view bstr = GetStringRepresentation(b); return astr < bstr; }); } @@ -722,8 +722,8 @@ // Sorts first relative targets, then absolute, each group is sorted // alphabetically. SortList([](const ParseNode* a, const ParseNode* b) { - base::StringPiece astr = GetStringRepresentation(a); - base::StringPiece bstr = GetStringRepresentation(b); + std::string_view astr = GetStringRepresentation(a); + std::string_view bstr = GetStringRepresentation(b); return std::make_pair(GetDepsCategory(astr), SplitAtFirst(astr, ':')) < std::make_pair(GetDepsCategory(bstr), SplitAtFirst(bstr, ':')); }); @@ -807,7 +807,7 @@ case Token::FALSE_TOKEN: return Value(this, false); case Token::INTEGER: { - base::StringPiece s = value_.value(); + std::string_view s = value_.value(); if ((base::StartsWith(s, "0", base::CompareCase::SENSITIVE) && s.size() > 1) || base::StartsWith(s, "-0", base::CompareCase::SENSITIVE)) {
diff --git a/tools/gn/parse_tree.h b/tools/gn/parse_tree.h index 6c61b72..82a5071 100644 --- a/tools/gn/parse_tree.h +++ b/tools/gn/parse_tree.h
@@ -112,8 +112,8 @@ // Helper functions for GetJSONNode. Creates and fills a Value object with // given type (and value). base::Value CreateJSONNode(const char* type) const; - base::Value CreateJSONNode(const char* type, const base::StringPiece& value) - const; + base::Value CreateJSONNode(const char* type, + const std::string_view& value) const; private: // Helper function for CreateJSONNode.
diff --git a/tools/gn/parser.cc b/tools/gn/parser.cc index ea498a4..b65a5de 100644 --- a/tools/gn/parser.cc +++ b/tools/gn/parser.cc
@@ -290,7 +290,7 @@ }; Parser::Parser(const std::vector<Token>& tokens, Err* err) - : invalid_token_(Location(), Token::INVALID, base::StringPiece()), + : invalid_token_(Location(), Token::INVALID, std::string_view()), err_(err), cur_(0) { for (const auto& token : tokens) {
diff --git a/tools/gn/path_output.cc b/tools/gn/path_output.cc index 0f57997..8da480a 100644 --- a/tools/gn/path_output.cc +++ b/tools/gn/path_output.cc
@@ -11,7 +11,7 @@ #include "util/build_config.h" PathOutput::PathOutput(const SourceDir& current_dir, - const base::StringPiece& source_root, + const std::string_view& source_root, EscapingMode escaping) : current_dir_(current_dir) { inverse_current_dir_ = RebasePath("//", current_dir, source_root); @@ -65,7 +65,7 @@ } else { // DIR_NO_LAST_SLASH mode, just trim the last char. WritePathStr(out, - base::StringPiece(dir.value().data(), dir.value().size() - 1)); + std::string_view(dir.value().data(), dir.value().size() - 1)); } } @@ -104,8 +104,7 @@ file.value()[file.value().size() - 1] == '/') { // Trim trailing slash. EscapeStringToStream( - out, - base::StringPiece(file.value().data(), file.value().size() - 1), + out, std::string_view(file.value().data(), file.value().size() - 1), options_); } else { // Doesn't end with a slash, write the whole thing. @@ -122,7 +121,7 @@ } void PathOutput::WriteSourceRelativeString(std::ostream& out, - const base::StringPiece& str) const { + const std::string_view& str) const { if (options_.mode == ESCAPE_NINJA_COMMAND) { // Shell escaping needs an intermediate string since it may end up // quoting the whole thing. @@ -133,7 +132,7 @@ intermediate.append(str.data(), str.size()); EscapeStringToStream( - out, base::StringPiece(intermediate.c_str(), intermediate.size()), + out, std::string_view(intermediate.c_str(), intermediate.size()), options_); } else { // Ninja (and none) escaping can avoid the intermediate string and @@ -144,11 +143,11 @@ } void PathOutput::WritePathStr(std::ostream& out, - const base::StringPiece& str) const { + const std::string_view& str) const { DCHECK(str.size() > 0 && str[0] == '/'); if (str.substr(0, current_dir_.value().size()) == - base::StringPiece(current_dir_.value())) { + std::string_view(current_dir_.value())) { // The current dir is a prefix of the output file, so we can strip the // prefix and write out the result. EscapeStringToStream(out, str.substr(current_dir_.value().size()),
diff --git a/tools/gn/path_output.h b/tools/gn/path_output.h index 1d98a2c..21c4cc4 100644 --- a/tools/gn/path_output.h +++ b/tools/gn/path_output.h
@@ -7,9 +7,9 @@ #include <iosfwd> #include <string> +#include <string_view> #include "base/macros.h" -#include "base/strings/string_piece.h" #include "tools/gn/escape.h" #include "tools/gn/source_dir.h" #include "tools/gn/unique_vector.h" @@ -35,7 +35,7 @@ }; PathOutput(const SourceDir& current_dir, - const base::StringPiece& source_root, + const std::string_view& source_root, EscapingMode escaping); ~PathOutput(); @@ -71,13 +71,13 @@ // Backend for WriteFile and WriteDir. This appends the given file or // directory string to the file. - void WritePathStr(std::ostream& out, const base::StringPiece& str) const; + void WritePathStr(std::ostream& out, const std::string_view& str) const; private: // Takes the given string and writes it out, appending to the inverse // current dir. This assumes leading slashes have been trimmed. void WriteSourceRelativeString(std::ostream& out, - const base::StringPiece& str) const; + const std::string_view& str) const; SourceDir current_dir_;
diff --git a/tools/gn/path_output_unittest.cc b/tools/gn/path_output_unittest.cc index 8857fd9..190647a 100644 --- a/tools/gn/path_output_unittest.cc +++ b/tools/gn/path_output_unittest.cc
@@ -14,7 +14,7 @@ TEST(PathOutput, Basic) { SourceDir build_dir("//out/Debug/"); - base::StringPiece source_root("/source/root"); + std::string_view source_root("/source/root"); PathOutput writer(build_dir, source_root, ESCAPE_NONE); { // Normal source-root path. @@ -56,7 +56,7 @@ // Same as basic but the output dir is the root. TEST(PathOutput, BasicInRoot) { SourceDir build_dir("//"); - base::StringPiece source_root("/source/root"); + std::string_view source_root("/source/root"); PathOutput writer(build_dir, source_root, ESCAPE_NONE); { // Normal source-root path. @@ -74,7 +74,7 @@ TEST(PathOutput, NinjaEscaping) { SourceDir build_dir("//out/Debug/"); - base::StringPiece source_root("/source/root"); + std::string_view source_root("/source/root"); PathOutput writer(build_dir, source_root, ESCAPE_NINJA); { // Spaces and $ in filenames. @@ -92,7 +92,7 @@ TEST(PathOutput, NinjaForkEscaping) { SourceDir build_dir("//out/Debug/"); - base::StringPiece source_root("/source/root"); + std::string_view source_root("/source/root"); PathOutput writer(build_dir, source_root, ESCAPE_NINJA_COMMAND); // Spaces in filenames should get quoted on Windows. @@ -145,7 +145,7 @@ TEST(PathOutput, InhibitQuoting) { SourceDir build_dir("//out/Debug/"); - base::StringPiece source_root("/source/root"); + std::string_view source_root("/source/root"); PathOutput writer(build_dir, source_root, ESCAPE_NINJA_COMMAND); writer.set_inhibit_quoting(true); @@ -169,7 +169,7 @@ TEST(PathOutput, WriteDir) { { SourceDir build_dir("//out/Debug/"); - base::StringPiece source_root("/source/root"); + std::string_view source_root("/source/root"); PathOutput writer(build_dir, source_root, ESCAPE_NINJA); { std::ostringstream out; @@ -259,7 +259,7 @@ } { // Empty build dir writer. - base::StringPiece source_root("/source/root"); + std::string_view source_root("/source/root"); PathOutput root_writer(SourceDir("//"), source_root, ESCAPE_NINJA); { std::ostringstream out;
diff --git a/tools/gn/scope.cc b/tools/gn/scope.cc index 40d4a86..793f1a8 100644 --- a/tools/gn/scope.cc +++ b/tools/gn/scope.cc
@@ -21,7 +21,7 @@ // Returns true if this variable name should be considered private. Private // values start with an underscore, and are not imported from "gni" files // when processing an import. -bool IsPrivateVar(const base::StringPiece& name) { +bool IsPrivateVar(const std::string_view& name) { return name.empty() || name[0] == '_'; } @@ -74,13 +74,13 @@ return !values_.empty(); } -const Value* Scope::GetValue(const base::StringPiece& ident, +const Value* Scope::GetValue(const std::string_view& ident, bool counts_as_used) { const Scope* found_in_scope = nullptr; return GetValueWithScope(ident, counts_as_used, &found_in_scope); } -const Value* Scope::GetValueWithScope(const base::StringPiece& ident, +const Value* Scope::GetValueWithScope(const std::string_view& ident, bool counts_as_used, const Scope** found_in_scope) { // First check for programmatically-provided values. @@ -110,7 +110,7 @@ return nullptr; } -Value* Scope::GetMutableValue(const base::StringPiece& ident, +Value* Scope::GetMutableValue(const std::string_view& ident, SearchNested search_mode, bool counts_as_used) { // Don't do programmatic values, which are not mutable. @@ -129,7 +129,7 @@ return nullptr; } -base::StringPiece Scope::GetStorageKey(const base::StringPiece& ident) const { +std::string_view Scope::GetStorageKey(const std::string_view& ident) const { RecordMap::const_iterator found = values_.find(ident); if (found != values_.end()) return found->first; @@ -137,15 +137,15 @@ // Search in parent scope. if (containing()) return containing()->GetStorageKey(ident); - return base::StringPiece(); + return std::string_view(); } -const Value* Scope::GetValue(const base::StringPiece& ident) const { +const Value* Scope::GetValue(const std::string_view& ident) const { const Scope* found_in_scope = nullptr; return GetValueWithScope(ident, &found_in_scope); } -const Value* Scope::GetValueWithScope(const base::StringPiece& ident, +const Value* Scope::GetValueWithScope(const std::string_view& ident, const Scope** found_in_scope) const { RecordMap::const_iterator found = values_.find(ident); if (found != values_.end()) { @@ -157,7 +157,7 @@ return nullptr; } -Value* Scope::SetValue(const base::StringPiece& ident, +Value* Scope::SetValue(const std::string_view& ident, Value v, const ParseNode* set_node) { Record& r = values_[ident]; // Clears any existing value. @@ -166,7 +166,7 @@ return &r.value; } -void Scope::RemoveIdentifier(const base::StringPiece& ident) { +void Scope::RemoveIdentifier(const std::string_view& ident) { RecordMap::iterator found = values_.find(ident); if (found != values_.end()) values_.erase(found); @@ -177,7 +177,7 @@ // currently backed by several different vendor-specific implementations and // I'm not sure if all of them support mutating while iterating. Since this // is not perf-critical, do the safe thing. - std::vector<base::StringPiece> to_remove; + std::vector<std::string_view> to_remove; for (const auto& cur : values_) { if (IsPrivateVar(cur.first)) to_remove.push_back(cur.first); @@ -203,7 +203,7 @@ return nullptr; } -void Scope::MarkUsed(const base::StringPiece& ident) { +void Scope::MarkUsed(const std::string_view& ident) { RecordMap::iterator found = values_.find(ident); if (found == values_.end()) { NOTREACHED(); @@ -227,7 +227,7 @@ } } -void Scope::MarkUnused(const base::StringPiece& ident) { +void Scope::MarkUnused(const std::string_view& ident) { RecordMap::iterator found = values_.find(ident); if (found == values_.end()) { NOTREACHED(); @@ -236,7 +236,7 @@ found->second.used = false; } -bool Scope::IsSetButUnused(const base::StringPiece& ident) const { +bool Scope::IsSetButUnused(const std::string_view& ident) const { RecordMap::const_iterator found = values_.find(ident); if (found != values_.end()) { if (!found->second.used) { @@ -298,7 +298,7 @@ Err* err) const { // Values. for (const auto& pair : values_) { - const base::StringPiece& current_name = pair.first; + const std::string_view& current_name = pair.first; if (options.skip_private_vars && IsPrivateVar(current_name)) continue; // Skip this private var. if (!options.excluded_values.empty() &&
diff --git a/tools/gn/scope.h b/tools/gn/scope.h index f7d70ca..962f5c3 100644 --- a/tools/gn/scope.h +++ b/tools/gn/scope.h
@@ -38,7 +38,7 @@ // variables. So you should use a non-const containing scope whenever possible. class Scope { public: - using KeyValueMap = std::map<base::StringPiece, Value>; + using KeyValueMap = std::map<std::string_view, Value>; // Holds an owning list of Items. using ItemVector = std::vector<std::unique_ptr<Item>>; @@ -59,7 +59,7 @@ // Returns a non-null value if the given value can be programmatically // generated, or NULL if there is none. virtual const Value* GetProgrammaticValue( - const base::StringPiece& ident) = 0; + const std::string_view& ident) = 0; protected: Scope* scope_; @@ -135,11 +135,11 @@ // found_in_scope is set to the scope that contains the definition of the // ident. If the value was provided programmatically (like host_cpu), // found_in_scope will be set to null. - const Value* GetValue(const base::StringPiece& ident, bool counts_as_used); - const Value* GetValue(const base::StringPiece& ident) const; - const Value* GetValueWithScope(const base::StringPiece& ident, + const Value* GetValue(const std::string_view& ident, bool counts_as_used); + const Value* GetValue(const std::string_view& ident) const; + const Value* GetValueWithScope(const std::string_view& ident, const Scope** found_in_scope) const; - const Value* GetValueWithScope(const base::StringPiece& ident, + const Value* GetValueWithScope(const std::string_view& ident, bool counts_as_used, const Scope** found_in_scope); @@ -165,28 +165,28 @@ // } // The 6 should get set on the nested scope rather than modify the value // in the outer one. - Value* GetMutableValue(const base::StringPiece& ident, + Value* GetMutableValue(const std::string_view& ident, SearchNested search_mode, bool counts_as_used); - // Returns the StringPiece used to identify the value. This string piece + // Returns the std::string_view used to identify the value. This string piece // will have the same contents as "ident" passed in, but may point to a - // different underlying buffer. This is useful because this StringPiece is - // static and won't be deleted for the life of the program, so it can be used - // as keys in places that may outlive a temporary. It will return an empty - // string for programmatic and nonexistant values. - base::StringPiece GetStorageKey(const base::StringPiece& ident) const; + // different underlying buffer. This is useful because this std::string_view + // is static and won't be deleted for the life of the program, so it can be + // used as keys in places that may outlive a temporary. It will return an + // empty string for programmatic and nonexistant values. + std::string_view GetStorageKey(const std::string_view& ident) const; // The set_node indicates the statement that caused the set, for displaying // errors later. Returns a pointer to the value in the current scope (a copy // is made for storage). - Value* SetValue(const base::StringPiece& ident, + Value* SetValue(const std::string_view& ident, Value v, const ParseNode* set_node); // Removes the value with the given identifier if it exists on the current // scope. This does not search recursive scopes. Does nothing if not found. - void RemoveIdentifier(const base::StringPiece& ident); + void RemoveIdentifier(const std::string_view& ident); // Removes from this scope all identifiers and templates that are considered // private. @@ -200,17 +200,17 @@ const Template* GetTemplate(const std::string& name) const; // Marks the given identifier as (un)used in the current scope. - void MarkUsed(const base::StringPiece& ident); + void MarkUsed(const std::string_view& ident); void MarkAllUsed(); void MarkAllUsed(const std::set<std::string>& excluded_values); - void MarkUnused(const base::StringPiece& ident); + void MarkUnused(const std::string_view& ident); // Checks to see if the scope has a var set that hasn't been used. This is // called before replacing the var with a different one. It does not check // containing scopes. // // If the identifier is present but hasnn't been used, return true. - bool IsSetButUnused(const base::StringPiece& ident) const; + bool IsSetButUnused(const std::string_view& ident) const; // Checks the scope to see if any values were set but not used, and fills in // the error and returns false if they were. @@ -338,7 +338,7 @@ Value value; }; - using RecordMap = std::unordered_map<base::StringPiece, Record>; + using RecordMap = std::unordered_map<std::string_view, Record>; void AddProvider(ProgrammaticProvider* p); void RemoveProvider(ProgrammaticProvider* p);
diff --git a/tools/gn/scope_per_file_provider.cc b/tools/gn/scope_per_file_provider.cc index d7d11af..1adfa84 100644 --- a/tools/gn/scope_per_file_provider.cc +++ b/tools/gn/scope_per_file_provider.cc
@@ -18,7 +18,7 @@ ScopePerFileProvider::~ScopePerFileProvider() = default; const Value* ScopePerFileProvider::GetProgrammaticValue( - const base::StringPiece& ident) { + const std::string_view& ident) { if (ident == variables::kCurrentToolchain) return GetCurrentToolchain(); if (ident == variables::kDefaultToolchain)
diff --git a/tools/gn/scope_per_file_provider.h b/tools/gn/scope_per_file_provider.h index ac0d872..c7a76c0 100644 --- a/tools/gn/scope_per_file_provider.h +++ b/tools/gn/scope_per_file_provider.h
@@ -21,7 +21,7 @@ ~ScopePerFileProvider() override; // ProgrammaticProvider implementation. - const Value* GetProgrammaticValue(const base::StringPiece& ident) override; + const Value* GetProgrammaticValue(const std::string_view& ident) override; private: const Value* GetCurrentToolchain();
diff --git a/tools/gn/scope_unittest.cc b/tools/gn/scope_unittest.cc index 681d6c8..f54c666 100644 --- a/tools/gn/scope_unittest.cc +++ b/tools/gn/scope_unittest.cc
@@ -57,7 +57,7 @@ // Add some values to the scope. Value old_value(&assignment, "hello"); setup.scope()->SetValue("v", old_value, &assignment); - base::StringPiece private_var_name("_private"); + std::string_view private_var_name("_private"); setup.scope()->SetValue(private_var_name, old_value, &assignment); // Add some templates to the scope.
diff --git a/tools/gn/setup.cc b/tools/gn/setup.cc index 1b2ad55..16e09fe 100644 --- a/tools/gn/setup.cc +++ b/tools/gn/setup.cc
@@ -193,7 +193,7 @@ #if defined(OS_WIN) -std::u16string SysMultiByteTo16(base::StringPiece mb) { +std::u16string SysMultiByteTo16(std::string_view mb) { if (mb.empty()) return std::u16string(); @@ -222,7 +222,7 @@ // quote the first argument in addition (to allow for spaces in the Python // path, you need *another* set of quotes around that, likewise, we need // two quotes at the end. - base::string16 command = u"cmd.exe /c \"\""; + std::u16string command = u"cmd.exe /c \"\""; command.append(bat_path.value()); command.append(u"\" -c \"import sys; print sys.executable\"\""); @@ -245,11 +245,11 @@ return base::FilePath(); } -const base::char16 kPythonExeName[] = u"python.exe"; -const base::char16 kPythonBatName[] = u"python.bat"; +const char16_t kPythonExeName[] = u"python.exe"; +const char16_t kPythonBatName[] = u"python.bat"; base::FilePath FindWindowsPython() { - base::char16 current_directory[MAX_PATH]; + char16_t current_directory[MAX_PATH]; ::GetCurrentDirectory(MAX_PATH, reinterpret_cast<LPWSTR>(current_directory)); // First search for python.exe in the current directory. @@ -259,12 +259,12 @@ return cur_dir_candidate_exe; // Get the path. - const base::char16 kPathEnvVarName[] = u"Path"; + const char16_t kPathEnvVarName[] = u"Path"; DWORD path_length = ::GetEnvironmentVariable( reinterpret_cast<LPCWSTR>(kPathEnvVarName), nullptr, 0); if (path_length == 0) return base::FilePath(); - std::unique_ptr<base::char16[]> full_path(new base::char16[path_length]); + std::unique_ptr<char16_t[]> full_path(new char16_t[path_length]); DWORD actual_path_length = ::GetEnvironmentVariable( reinterpret_cast<LPCWSTR>(kPathEnvVarName), reinterpret_cast<LPWSTR>(full_path.get()), path_length); @@ -272,7 +272,7 @@ // Search for python.exe in the path. for (const auto& component : base::SplitStringPiece( - base::StringPiece16(full_path.get(), path_length), u";", + std::u16string_view(full_path.get(), path_length), u";", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) { base::FilePath candidate_exe = base::FilePath(component).Append(kPythonExeName);
diff --git a/tools/gn/source_dir.cc b/tools/gn/source_dir.cc index 7def4b2..e8c4ae9 100644 --- a/tools/gn/source_dir.cc +++ b/tools/gn/source_dir.cc
@@ -77,7 +77,7 @@ const Value& blame_input_value, const StringType& input_value, Err* err, - const base::StringPiece& source_root) const { + const std::string_view& source_root) const { if (!ValidateResolveInput<StringType>(as_file, blame_input_value, input_value, err)) { return std::string(); @@ -88,7 +88,7 @@ SourceFile SourceDir::ResolveRelativeFile( const Value& p, Err* err, - const base::StringPiece& source_root) const { + const std::string_view& source_root) const { SourceFile ret; if (!p.VerifyTypeIs(Value::STRING, err)) @@ -105,7 +105,7 @@ std::string SourceDir::ResolveRelativeAs(bool as_file, const Value& v, Err* err, - const base::StringPiece& source_root, + const std::string_view& source_root, const std::string* v_value) const { if (!v.VerifyTypeIs(Value::STRING, err)) return std::string(); @@ -123,7 +123,7 @@ SourceDir SourceDir::ResolveRelativeDir( const Value& v, Err* err, - const base::StringPiece& source_root) const { + const std::string_view& source_root) const { if (!v.VerifyTypeIs(Value::STRING, err)) return SourceDir(); @@ -140,11 +140,11 @@ const Value& blame_input_value, const std::string& input_value, Err* err, - const base::StringPiece& source_root) const; + const std::string_view& source_root) const; template std::string SourceDir::ResolveRelativeAs( bool as_file, const Value& blame_input_value, - const base::StringPiece& input_value, + const std::string_view& input_value, Err* err, - const base::StringPiece& source_root) const; + const std::string_view& source_root) const;
diff --git a/tools/gn/source_dir.h b/tools/gn/source_dir.h index 8b6dcc9..ed4b1e3 100644 --- a/tools/gn/source_dir.h +++ b/tools/gn/source_dir.h
@@ -9,10 +9,10 @@ #include <algorithm> #include <string> +#include <string_view> #include "base/files/file_path.h" #include "base/logging.h" -#include "base/strings/string_piece.h" class Err; class SourceFile; @@ -47,7 +47,7 @@ bool as_file, const Value& v, Err* err, - const base::StringPiece& source_root = base::StringPiece(), + const std::string_view& source_root = std::string_view(), const std::string* v_value = nullptr) const; // Like ResolveRelativeAs above, but allows to produce result @@ -58,13 +58,13 @@ const Value& blame_input_value, const StringType& input_value, Err* err, - const base::StringPiece& source_root = base::StringPiece()) const; + const std::string_view& source_root = std::string_view()) const; // Wrapper for ResolveRelativeAs. SourceFile ResolveRelativeFile( const Value& p, Err* err, - const base::StringPiece& source_root = base::StringPiece()) const; + const std::string_view& source_root = std::string_view()) const; // Wrapper for ResolveRelativeAs. template <typename StringType> @@ -72,7 +72,7 @@ const Value& blame_input_value, const StringType& input_value, Err* err, - const base::StringPiece& source_root = base::StringPiece()) const { + const std::string_view& source_root = std::string_view()) const { SourceDir ret; ret.value_ = ResolveRelativeAs<StringType>(false, blame_input_value, input_value, err, source_root); @@ -84,7 +84,7 @@ SourceDir ResolveRelativeDir( const Value& v, Err* err, - const base::StringPiece& source_root = base::StringPiece()) const; + const std::string_view& source_root = std::string_view()) const; // Resolves this source file relative to some given source root. Returns // an empty file path on error. @@ -110,19 +110,19 @@ // // This function asserts that the directory is actually source-absolute. The // return value points into our buffer. - base::StringPiece SourceAbsoluteWithOneSlash() const { + std::string_view SourceAbsoluteWithOneSlash() const { CHECK(is_source_absolute()); - return base::StringPiece(&value_[1], value_.size() - 1); + return std::string_view(&value_[1], value_.size() - 1); } // Returns a path that does not end with a slash. // // This function simply returns the reference to the value if the path is a // root, e.g. "/" or "//". - base::StringPiece SourceWithNoTrailingSlash() const { + std::string_view SourceWithNoTrailingSlash() const { if (value_.size() > 2) - return base::StringPiece(&value_[0], value_.size() - 1); - return base::StringPiece(value_); + return std::string_view(&value_[0], value_.size() - 1); + return std::string_view(value_); } void SwapValue(std::string* v);
diff --git a/tools/gn/source_dir_unittest.cc b/tools/gn/source_dir_unittest.cc index d5ada23..20c60b7 100644 --- a/tools/gn/source_dir_unittest.cc +++ b/tools/gn/source_dir_unittest.cc
@@ -13,9 +13,9 @@ Err err; SourceDir base("//base/"); #if defined(OS_WIN) - base::StringPiece source_root("C:/source/root"); + std::string_view source_root("C:/source/root"); #else - base::StringPiece source_root("/source/root"); + std::string_view source_root("/source/root"); #endif // Empty input is an error. @@ -116,9 +116,9 @@ Err err; SourceDir base("//base/"); #if defined(OS_WIN) - base::StringPiece source_root("C:/source/root"); + std::string_view source_root("C:/source/root"); #else - base::StringPiece source_root("/source/root"); + std::string_view source_root("/source/root"); #endif // Empty input is an error.
diff --git a/tools/gn/source_file.cc b/tools/gn/source_file.cc index ce24207..d3ea1cc 100644 --- a/tools/gn/source_file.cc +++ b/tools/gn/source_file.cc
@@ -22,7 +22,7 @@ } SourceFile::Type GetSourceFileType(const std::string& file) { - base::StringPiece extension = FindExtension(&file); + std::string_view extension = FindExtension(&file); if (extension == "cc" || extension == "cpp" || extension == "cxx") return SourceFile::SOURCE_CPP; if (extension == "h" || extension == "hpp" || extension == "hxx" ||
diff --git a/tools/gn/source_file.h b/tools/gn/source_file.h index 081cda6..392cdd4 100644 --- a/tools/gn/source_file.h +++ b/tools/gn/source_file.h
@@ -9,10 +9,10 @@ #include <algorithm> #include <string> +#include <string_view> #include "base/files/file_path.h" #include "base/logging.h" -#include "base/strings/string_piece.h" class SourceDir; @@ -78,9 +78,9 @@ // // This function asserts that the file is actually source-absolute. The // return value points into our buffer. - base::StringPiece SourceAbsoluteWithOneSlash() const { + std::string_view SourceAbsoluteWithOneSlash() const { CHECK(is_source_absolute()); - return base::StringPiece(&value_[1], value_.size() - 1); + return std::string_view(&value_[1], value_.size() - 1); } bool operator==(const SourceFile& other) const {
diff --git a/tools/gn/standard_out.cc b/tools/gn/standard_out.cc index 3056418..003c8ee 100644 --- a/tools/gn/standard_out.cc +++ b/tools/gn/standard_out.cc
@@ -6,11 +6,11 @@ #include <stddef.h> +#include <string_view> #include <vector> #include "base/command_line.h" #include "base/logging.h" -#include "base/strings/string_piece.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "tools/gn/switches.h" @@ -78,8 +78,8 @@ #endif // !defined(OS_WIN) void OutputMarkdownDec(TextDecoration dec) { -// The markdown rendering turns "dim" text to italics and any -// other colored text to bold. + // The markdown rendering turns "dim" text to italics and any + // other colored text to bold. #if defined(OS_WIN) DWORD written = 0;
diff --git a/tools/gn/string_utils.cc b/tools/gn/string_utils.cc index 89fc4b0..ab0aea8 100644 --- a/tools/gn/string_utils.cc +++ b/tools/gn/string_utils.cc
@@ -117,7 +117,7 @@ size_t end_offset, std::string* output, Err* err) { - base::StringPiece identifier(&input[begin_offset], end_offset - begin_offset); + std::string_view identifier(&input[begin_offset], end_offset - begin_offset); const Value* value = scope->GetValue(identifier, true); if (!value) { // We assume the input points inside the token. @@ -225,7 +225,7 @@ return false; } int value = 0; - if (!base::HexStringToInt(base::StringPiece(&input[*i + 2], 2), &value)) { + if (!base::HexStringToInt(std::string_view(&input[*i + 2], 2), &value)) { *err = ErrInsideStringToken(token, dollars_index, *i - dollars_index + 1, "Could not convert hex value."); return false; @@ -287,8 +287,8 @@ return true; } -size_t EditDistance(const base::StringPiece& s1, - const base::StringPiece& s2, +size_t EditDistance(const std::string_view& s1, + const std::string_view& s2, size_t max_edit_distance) { // The algorithm implemented below is the "classic" // dynamic-programming algorithm for computing the Levenshtein @@ -329,14 +329,13 @@ return row[n]; } -base::StringPiece SpellcheckString( - const base::StringPiece& text, - const std::vector<base::StringPiece>& words) { +std::string_view SpellcheckString(const std::string_view& text, + const std::vector<std::string_view>& words) { const size_t kMaxValidEditDistance = 3u; size_t min_distance = kMaxValidEditDistance + 1u; - base::StringPiece result; - for (base::StringPiece word : words) { + std::string_view result; + for (std::string_view word : words) { size_t distance = EditDistance(word, text, kMaxValidEditDistance); if (distance < min_distance) { min_distance = distance;
diff --git a/tools/gn/string_utils.h b/tools/gn/string_utils.h index c77daca..3d4e056 100644 --- a/tools/gn/string_utils.h +++ b/tools/gn/string_utils.h
@@ -6,16 +6,15 @@ #define TOOLS_GN_STRING_UTILS_H_ #include <string> +#include <string_view> #include <vector> -#include "base/strings/string_piece.h" - class Err; class Scope; class Token; class Value; -inline std::string operator+(const std::string& a, const base::StringPiece& b) { +inline std::string operator+(const std::string& a, const std::string_view& b) { std::string ret; ret.reserve(a.size() + b.size()); ret.assign(a); @@ -23,7 +22,7 @@ return ret; } -inline std::string operator+(const base::StringPiece& a, const std::string& b) { +inline std::string operator+(const std::string_view& a, const std::string& b) { std::string ret; ret.reserve(a.size() + b.size()); ret.assign(a.data(), a.size()); @@ -41,14 +40,14 @@ // Returns the minimum number of inserts, deleted, and replacements of // characters needed to transform s1 to s2, or max_edit_distance + 1 if // transforming s1 into s2 isn't possible in at most max_edit_distance steps. -size_t EditDistance(const base::StringPiece& s1, - const base::StringPiece& s2, +size_t EditDistance(const std::string_view& s1, + const std::string_view& s2, size_t max_edit_distance); // Given a string |text| and a vector of correctly-spelled strings |words|, // returns the first string in |words| closest to |text|, or an empty -// StringPiece if none of the strings in |words| is close. -base::StringPiece SpellcheckString(const base::StringPiece& text, - const std::vector<base::StringPiece>& words); +// std::string_view if none of the strings in |words| is close. +std::string_view SpellcheckString(const std::string_view& text, + const std::vector<std::string_view>& words); #endif // TOOLS_GN_STRING_UTILS_H_
diff --git a/tools/gn/string_utils_unittest.cc b/tools/gn/string_utils_unittest.cc index bf10dd4..4c5cd81 100644 --- a/tools/gn/string_utils_unittest.cc +++ b/tools/gn/string_utils_unittest.cc
@@ -144,7 +144,7 @@ } TEST(StringUtils, SpellcheckString) { - std::vector<base::StringPiece> words; + std::vector<std::string_view> words; words.push_back("your"); words.push_back("bravado"); words.push_back("won\'t");
diff --git a/tools/gn/switches.h b/tools/gn/switches.h index d1abb1f..9f0ddf0 100644 --- a/tools/gn/switches.h +++ b/tools/gn/switches.h
@@ -6,8 +6,7 @@ #define TOOLS_GN_SWITCHES_H_ #include <map> - -#include "base/strings/string_piece.h" +#include <string_view> namespace switches { @@ -19,7 +18,7 @@ const char* long_help; }; -typedef std::map<base::StringPiece, SwitchInfo> SwitchInfoMap; +typedef std::map<std::string_view, SwitchInfo> SwitchInfoMap; // Returns the mapping of all global switches. const SwitchInfoMap& GetSwitches();
diff --git a/tools/gn/target_unittest.cc b/tools/gn/target_unittest.cc index f117846..24f4822 100644 --- a/tools/gn/target_unittest.cc +++ b/tools/gn/target_unittest.cc
@@ -1108,12 +1108,12 @@ Value a_expected(nullptr, Value::LIST); a_expected.list_value().push_back(Value(nullptr, "foo")); one.metadata().contents().insert( - std::pair<base::StringPiece, Value>("a", a_expected)); + std::pair<std::string_view, Value>("a", a_expected)); Value b_expected(nullptr, Value::LIST); b_expected.list_value().push_back(Value(nullptr, true)); one.metadata().contents().insert( - std::pair<base::StringPiece, Value>("b", b_expected)); + std::pair<std::string_view, Value>("b", b_expected)); one.metadata().set_source_dir(SourceDir("/usr/home/files/")); @@ -1143,18 +1143,18 @@ Value a_expected(nullptr, Value::LIST); a_expected.list_value().push_back(Value(nullptr, "foo")); one.metadata().contents().insert( - std::pair<base::StringPiece, Value>("a", a_expected)); + std::pair<std::string_view, Value>("a", a_expected)); Value b_expected(nullptr, Value::LIST); b_expected.list_value().push_back(Value(nullptr, true)); one.metadata().contents().insert( - std::pair<base::StringPiece, Value>("b", b_expected)); + std::pair<std::string_view, Value>("b", b_expected)); TestTarget two(setup, "//foo:two", Target::SOURCE_SET); Value a_2_expected(nullptr, Value::LIST); a_2_expected.list_value().push_back(Value(nullptr, "bar")); two.metadata().contents().insert( - std::pair<base::StringPiece, Value>("a", a_2_expected)); + std::pair<std::string_view, Value>("a", a_2_expected)); one.public_deps().push_back(LabelTargetPair(&two)); @@ -1185,25 +1185,25 @@ Value a_expected(nullptr, Value::LIST); a_expected.list_value().push_back(Value(nullptr, "foo")); one.metadata().contents().insert( - std::pair<base::StringPiece, Value>("a", a_expected)); + std::pair<std::string_view, Value>("a", a_expected)); Value walk_expected(nullptr, Value::LIST); walk_expected.list_value().push_back( Value(nullptr, "//foo:two(//toolchain:default)")); one.metadata().contents().insert( - std::pair<base::StringPiece, Value>("walk", walk_expected)); + std::pair<std::string_view, Value>("walk", walk_expected)); TestTarget two(setup, "//foo:two", Target::SOURCE_SET); Value a_2_expected(nullptr, Value::LIST); a_2_expected.list_value().push_back(Value(nullptr, "bar")); two.metadata().contents().insert( - std::pair<base::StringPiece, Value>("a", a_2_expected)); + std::pair<std::string_view, Value>("a", a_2_expected)); TestTarget three(setup, "//foo:three", Target::SOURCE_SET); Value a_3_expected(nullptr, Value::LIST); a_3_expected.list_value().push_back(Value(nullptr, "baz")); three.metadata().contents().insert( - std::pair<base::StringPiece, Value>("a", a_3_expected)); + std::pair<std::string_view, Value>("a", a_3_expected)); one.public_deps().push_back(LabelTargetPair(&two)); one.public_deps().push_back(LabelTargetPair(&three)); @@ -1234,12 +1234,12 @@ Value a_expected(nullptr, Value::LIST); a_expected.list_value().push_back(Value(nullptr, "foo")); one.metadata().contents().insert( - std::pair<base::StringPiece, Value>("a", a_expected)); + std::pair<std::string_view, Value>("a", a_expected)); Value walk_expected(nullptr, Value::LIST); walk_expected.list_value().push_back(Value(nullptr, "//foo:missing")); one.metadata().contents().insert( - std::pair<base::StringPiece, Value>("walk", walk_expected)); + std::pair<std::string_view, Value>("walk", walk_expected)); std::vector<std::string> data_keys; data_keys.push_back("a");
diff --git a/tools/gn/template.cc b/tools/gn/template.cc index 2b40fb3..625cf5e 100644 --- a/tools/gn/template.cc +++ b/tools/gn/template.cc
@@ -83,7 +83,7 @@ invoker_value->SetScopeValue(std::move(invocation_scope)); template_scope.set_source_dir(scope->GetSourceDir()); - const base::StringPiece target_name(variables::kTargetName); + const std::string_view target_name(variables::kTargetName); template_scope.SetValue( target_name, Value(invocation, args[0].string_value()), invocation);
diff --git a/tools/gn/token.cc b/tools/gn/token.cc index 3c016fd..7951571 100644 --- a/tools/gn/token.cc +++ b/tools/gn/token.cc
@@ -8,7 +8,7 @@ Token::Token() : type_(INVALID), value_() {} -Token::Token(const Location& location, Type t, const base::StringPiece& v) +Token::Token(const Location& location, Type t, const std::string_view& v) : type_(t), value_(v), location_(location) {} Token::Token(const Token& other) = default;
diff --git a/tools/gn/token.h b/tools/gn/token.h index 126201c..46eb78e 100644 --- a/tools/gn/token.h +++ b/tools/gn/token.h
@@ -5,7 +5,8 @@ #ifndef TOOLS_GN_TOKEN_H_ #define TOOLS_GN_TOKEN_H_ -#include "base/strings/string_piece.h" +#include <string_view> + #include "tools/gn/location.h" class Token { @@ -57,11 +58,11 @@ }; Token(); - Token(const Location& location, Type t, const base::StringPiece& v); + Token(const Location& location, Type t, const std::string_view& v); Token(const Token& other); Type type() const { return type_; } - const base::StringPiece& value() const { return value_; } + const std::string_view& value() const { return value_; } const Location& location() const { return location_; } void set_location(Location location) { location_ = location; } LocationRange range() const { @@ -78,7 +79,7 @@ private: Type type_; - base::StringPiece value_; + std::string_view value_; Location location_; };
diff --git a/tools/gn/tokenizer.cc b/tools/gn/tokenizer.cc index 09f0b4b..73a1491 100644 --- a/tools/gn/tokenizer.cc +++ b/tools/gn/tokenizer.cc
@@ -32,7 +32,7 @@ return c == '(' || c == ')' || c == '[' || c == ']' || c == '{' || c == '}'; } -Token::Type GetSpecificOperatorType(base::StringPiece value) { +Token::Type GetSpecificOperatorType(std::string_view value) { if (value == "=") return Token::EQUAL; if (value == "+") @@ -98,8 +98,8 @@ break; size_t token_end = cur_; - base::StringPiece token_value(&input_.data()[token_begin], - token_end - token_begin); + std::string_view token_value(&input_.data()[token_begin], + token_end - token_begin); if (type == Token::UNCLASSIFIED_OPERATOR) { type = GetSpecificOperatorType(token_value); @@ -148,7 +148,7 @@ } // static -size_t Tokenizer::ByteOffsetOfNthLine(const base::StringPiece& buf, int n) { +size_t Tokenizer::ByteOffsetOfNthLine(const std::string_view& buf, int n) { DCHECK_GT(n, 0); if (n == 1) @@ -168,7 +168,7 @@ } // static -bool Tokenizer::IsNewline(const base::StringPiece& buffer, size_t offset) { +bool Tokenizer::IsNewline(const std::string_view& buffer, size_t offset) { DCHECK(offset < buffer.size()); // We may need more logic here to handle different line ending styles. return buffer[offset] == '\n';
diff --git a/tools/gn/tokenizer.h b/tools/gn/tokenizer.h index 7b66ac0..41451ee 100644 --- a/tools/gn/tokenizer.h +++ b/tools/gn/tokenizer.h
@@ -7,10 +7,10 @@ #include <stddef.h> +#include <string_view> #include <vector> #include "base/macros.h" -#include "base/strings/string_piece.h" #include "tools/gn/err.h" #include "tools/gn/token.h" @@ -27,11 +27,11 @@ // // This is a helper function for error output so that the tokenizer's // notion of lines can be used elsewhere. - static size_t ByteOffsetOfNthLine(const base::StringPiece& buf, int n); + static size_t ByteOffsetOfNthLine(const std::string_view& buf, int n); // Returns true if the given offset of the string piece counts as a newline. // The offset must be in the buffer. - static bool IsNewline(const base::StringPiece& buffer, size_t offset); + static bool IsNewline(const std::string_view& buffer, size_t offset); static bool IsIdentifierFirstChar(char c); @@ -77,7 +77,7 @@ std::vector<Token> tokens_; const InputFile* input_file_; - const base::StringPiece input_; + const std::string_view input_; Err* err_; size_t cur_ = 0; // Byte offset into input buffer.
diff --git a/tools/gn/toolchain.h b/tools/gn/toolchain.h index afab7f3..fbeda8f 100644 --- a/tools/gn/toolchain.h +++ b/tools/gn/toolchain.h
@@ -6,9 +6,9 @@ #define TOOLS_GN_TOOLCHAIN_H_ #include <memory> +#include <string_view> #include "base/logging.h" -#include "base/strings/string_piece.h" #include "tools/gn/item.h" #include "tools/gn/label_ptr.h" #include "tools/gn/scope.h"
diff --git a/tools/gn/variables.h b/tools/gn/variables.h index 09f2c18..60769d4 100644 --- a/tools/gn/variables.h +++ b/tools/gn/variables.h
@@ -6,8 +6,7 @@ #define TOOLS_GN_VARIABLES_H_ #include <map> - -#include "base/strings/string_piece.h" +#include <string_view> namespace variables { @@ -337,7 +336,7 @@ const char* help; }; -typedef std::map<base::StringPiece, VariableInfo> VariableInfoMap; +typedef std::map<std::string_view, VariableInfo> VariableInfoMap; // Returns the built-in readonly variables. // Note: this is used only for help so this getter is not threadsafe.
diff --git a/tools/gn/visibility.cc b/tools/gn/visibility.cc index 75039e9..babbacc 100644 --- a/tools/gn/visibility.cc +++ b/tools/gn/visibility.cc
@@ -5,8 +5,8 @@ #include "tools/gn/visibility.h" #include <memory> +#include <string_view> -#include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "base/values.h" #include "tools/gn/err.h"
diff --git a/tools/gn/visual_studio_writer.cc b/tools/gn/visual_studio_writer.cc index 217075b..0a4c6a5 100644 --- a/tools/gn/visual_studio_writer.cc +++ b/tools/gn/visual_studio_writer.cc
@@ -98,16 +98,16 @@ std::string kits_path; #if defined(OS_WIN) - const base::char16* const subkeys[] = { + const char16_t* const subkeys[] = { u"SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", u"SOFTWARE\\Wow6432Node\\Microsoft\\Windows Kits\\Installed Roots"}; - base::string16 value_name = + std::u16string value_name = base::ASCIIToUTF16("KitsRoot") + base::ASCIIToUTF16(kWindowsKitsVersion); - for (const base::char16* subkey : subkeys) { + for (const char16_t* subkey : subkeys) { base::win::RegKey key(HKEY_LOCAL_MACHINE, subkey, KEY_READ); - base::string16 value; + std::u16string value; if (key.ReadValue(value_name.c_str(), &value) == ERROR_SUCCESS) { kits_path = base::UTF16ToUTF8(value); break; @@ -175,13 +175,13 @@ // Returns a string piece pointing into the input string identifying the parent // directory path, excluding the last slash. Note that the input pointer must // outlive the output. -base::StringPiece FindParentDir(const std::string* path) { +std::string_view FindParentDir(const std::string* path) { DCHECK(path && !path->empty()); for (int i = static_cast<int>(path->size()) - 2; i >= 0; --i) { if (IsSlash((*path)[i])) - return base::StringPiece(path->data(), i); + return std::string_view(path->data(), i); } - return base::StringPiece(); + return std::string_view(); } bool FilterTargets(const BuildSettings* build_settings, @@ -697,7 +697,7 @@ filter_path_output.WriteFile(target_relative_out, *file_and_type.file); std::string target_relative_path = target_relative_out.str(); ConvertPathToSystem(&target_relative_path); - base::StringPiece filter_path = FindParentDir(&target_relative_path); + std::string_view filter_path = FindParentDir(&target_relative_path); if (!filter_path.empty()) { std::string filter_path_str(filter_path); @@ -806,9 +806,9 @@ root_folder_path_.clear(); // Get all project directories. Create solution folder for each directory. - std::map<base::StringPiece, SolutionEntry*> processed_paths; + std::map<std::string_view, SolutionEntry*> processed_paths; for (const std::unique_ptr<SolutionProject>& project : projects_) { - base::StringPiece folder_path = project->label_dir_path; + std::string_view folder_path = project->label_dir_path; if (IsSlash(folder_path[folder_path.size() - 1])) folder_path = folder_path.substr(0, folder_path.size() - 1); auto it = processed_paths.find(folder_path); @@ -856,7 +856,7 @@ continue; SolutionEntry* folder = solution_folder.get(); - base::StringPiece parent_path; + std::string_view parent_path; while ((parent_path = FindParentDir(&folder->path)) != root_folder_path_) { auto it = processed_paths.find(parent_path); if (it != processed_paths.end()) {
diff --git a/tools/gn/xcode_object.cc b/tools/gn/xcode_object.cc index 248661a..7509547 100644 --- a/tools/gn/xcode_object.cc +++ b/tools/gn/xcode_object.cc
@@ -140,7 +140,7 @@ {"y", "sourcecode.yacc"}, }; -const char* GetSourceType(const base::StringPiece& ext) { +const char* GetSourceType(const std::string_view& ext) { for (size_t i = 0; i < arraysize(kSourceTypeForExt); ++i) { if (kSourceTypeForExt[i].ext == ext) return kSourceTypeForExt[i].source_type; @@ -149,11 +149,11 @@ return "text"; } -bool HasExplicitFileType(const base::StringPiece& ext) { +bool HasExplicitFileType(const std::string_view& ext) { return ext == "dart"; } -bool IsSourceFileForIndexing(const base::StringPiece& ext) { +bool IsSourceFileForIndexing(const std::string_view& ext) { return ext == "c" || ext == "cc" || ext == "cpp" || ext == "cxx" || ext == "m" || ext == "mm"; } @@ -467,7 +467,7 @@ PrintProperty(out, rules, "explicitFileType", type_); PrintProperty(out, rules, "includeInIndex", 0u); } else { - base::StringPiece ext = FindExtension(&name_); + std::string_view ext = FindExtension(&name_); if (HasExplicitFileType(ext)) PrintProperty(out, rules, "explicitFileType", GetSourceType(ext)); else @@ -547,7 +547,7 @@ } PBXGroup* group = nullptr; - base::StringPiece component(navigator_path.data(), sep); + std::string_view component(navigator_path.data(), sep); for (const auto& child : children_) { if (child->Class() != PBXGroupClass) continue; @@ -692,7 +692,7 @@ PBXNativeTarget* target) { PBXFileReference* file_reference = sources_->AddSourceFile(navigator_path, source_path); - base::StringPiece ext = FindExtension(&source_path); + std::string_view ext = FindExtension(&source_path); if (!IsSourceFileForIndexing(ext)) return; @@ -736,7 +736,7 @@ const std::string& output_type, const std::string& shell_script, const PBXAttributes& extra_attributes) { - base::StringPiece ext = FindExtension(&output_name); + std::string_view ext = FindExtension(&output_name); PBXFileReference* product = static_cast<PBXFileReference*>( products_->AddChild(std::make_unique<PBXFileReference>( std::string(), output_name,
diff --git a/tools/gn/xml_element_writer.cc b/tools/gn/xml_element_writer.cc index 360d8af..f94878c 100644 --- a/tools/gn/xml_element_writer.cc +++ b/tools/gn/xml_element_writer.cc
@@ -8,13 +8,13 @@ XmlAttributes::XmlAttributes() = default; -XmlAttributes::XmlAttributes(const base::StringPiece& attr_key, - const base::StringPiece& attr_value) { +XmlAttributes::XmlAttributes(const std::string_view& attr_key, + const std::string_view& attr_value) { add(attr_key, attr_value); } -XmlAttributes& XmlAttributes::add(const base::StringPiece& attr_key, - const base::StringPiece& attr_value) { +XmlAttributes& XmlAttributes::add(const std::string_view& attr_key, + const std::string_view& attr_value) { push_back(std::make_pair(attr_key, attr_value)); return *this; } @@ -50,7 +50,7 @@ } } -void XmlElementWriter::Text(const base::StringPiece& content) { +void XmlElementWriter::Text(const std::string_view& content) { StartContent(false); out_ << content; }
diff --git a/tools/gn/xml_element_writer.h b/tools/gn/xml_element_writer.h index 1f68a7d..b276052 100644 --- a/tools/gn/xml_element_writer.h +++ b/tools/gn/xml_element_writer.h
@@ -8,22 +8,22 @@ #include <memory> #include <ostream> #include <string> +#include <string_view> #include <utility> #include <vector> #include "base/macros.h" -#include "base/strings/string_piece.h" // Vector of XML attribute key-value pairs. class XmlAttributes - : public std::vector<std::pair<base::StringPiece, base::StringPiece>> { + : public std::vector<std::pair<std::string_view, std::string_view>> { public: XmlAttributes(); - XmlAttributes(const base::StringPiece& attr_key, - const base::StringPiece& attr_value); + XmlAttributes(const std::string_view& attr_key, + const std::string_view& attr_value); - XmlAttributes& add(const base::StringPiece& attr_key, - const base::StringPiece& attr_value); + XmlAttributes& add(const std::string_view& attr_key, + const std::string_view& attr_value); }; // Helper class for writing XML elements. New XML element is started in @@ -54,7 +54,7 @@ ~XmlElementWriter(); // Writes arbitrary XML element text. - void Text(const base::StringPiece& content); + void Text(const std::string_view& content); // Starts new XML sub-element. Caller must ensure that parent element outlives // its children.