diff options
author | 2022-11-02 17:49:49 -0700 | |
---|---|---|
committer | 2022-11-29 21:46:02 -0800 | |
commit | a577514789fc241abe15f793a66f19d6431f7769 (patch) | |
tree | 662d9566d115f8bf76444ba8cbc18385255e53ab | |
parent | 0eef7918aab2a7582b019d88967e8437b101991c (diff) |
Make StringPiece to be std::string_view alias
Bug: 237583012
Test: build + boot + UTs
Change-Id: I849831f4466d3b9c7ec842b75256e7fcba77a0c0
126 files changed, 832 insertions, 1174 deletions
diff --git a/cmds/idmap2/include/idmap2/BinaryStreamVisitor.h b/cmds/idmap2/include/idmap2/BinaryStreamVisitor.h index 5e189f2c1340..7b38bd11d847 100644 --- a/cmds/idmap2/include/idmap2/BinaryStreamVisitor.h +++ b/cmds/idmap2/include/idmap2/BinaryStreamVisitor.h @@ -39,7 +39,7 @@ class BinaryStreamVisitor : public Visitor { void Write8(uint8_t value); void Write16(uint16_t value); void Write32(uint32_t value); - void WriteString(const StringPiece& value); + void WriteString(StringPiece value); std::ostream& stream_; }; diff --git a/cmds/idmap2/libidmap2/BinaryStreamVisitor.cpp b/cmds/idmap2/libidmap2/BinaryStreamVisitor.cpp index 4b271a1ff96f..89769246434a 100644 --- a/cmds/idmap2/libidmap2/BinaryStreamVisitor.cpp +++ b/cmds/idmap2/libidmap2/BinaryStreamVisitor.cpp @@ -38,7 +38,7 @@ void BinaryStreamVisitor::Write32(uint32_t value) { stream_.write(reinterpret_cast<char*>(&x), sizeof(uint32_t)); } -void BinaryStreamVisitor::WriteString(const StringPiece& value) { +void BinaryStreamVisitor::WriteString(StringPiece value) { // pad with null to nearest word boundary; size_t padding_size = CalculatePadding(value.size()); Write32(value.size()); diff --git a/cmds/idmap2/libidmap2/FabricatedOverlay.cpp b/cmds/idmap2/libidmap2/FabricatedOverlay.cpp index d517e29f3369..dd5be21cd164 100644 --- a/cmds/idmap2/libidmap2/FabricatedOverlay.cpp +++ b/cmds/idmap2/libidmap2/FabricatedOverlay.cpp @@ -101,10 +101,10 @@ FabricatedOverlay::Builder& FabricatedOverlay::Builder::SetResourceValue( } Result<FabricatedOverlay> FabricatedOverlay::Builder::Build() { - using ConfigMap = std::map<std::string, TargetValue>; - using EntryMap = std::map<std::string, ConfigMap>; - using TypeMap = std::map<std::string, EntryMap>; - using PackageMap = std::map<std::string, TypeMap>; + using ConfigMap = std::map<std::string, TargetValue, std::less<>>; + using EntryMap = std::map<std::string, ConfigMap, std::less<>>; + using TypeMap = std::map<std::string, EntryMap, std::less<>>; + using PackageMap = std::map<std::string, TypeMap, std::less<>>; PackageMap package_map; android::StringPool string_pool; for (const auto& res_entry : entries_) { @@ -116,8 +116,7 @@ Result<FabricatedOverlay> FabricatedOverlay::Builder::Build() { return Error("failed to parse resource name '%s'", res_entry.resource_name.c_str()); } - std::string package_name = - package_substr.empty() ? target_package_name_ : package_substr.to_string(); + std::string_view package_name = package_substr.empty() ? target_package_name_ : package_substr; if (type_name.empty()) { return Error("resource name '%s' missing type name", res_entry.resource_name.c_str()); } @@ -133,17 +132,14 @@ Result<FabricatedOverlay> FabricatedOverlay::Builder::Build() { .first; } - auto type = package->second.find(type_name.to_string()); + auto type = package->second.find(type_name); if (type == package->second.end()) { - type = - package->second - .insert(std::make_pair(type_name.to_string(), EntryMap())) - .first; + type = package->second.insert(std::make_pair(type_name, EntryMap())).first; } - auto entry = type->second.find(entry_name.to_string()); + auto entry = type->second.find(entry_name); if (entry == type->second.end()) { - entry = type->second.insert(std::make_pair(entry_name.to_string(), ConfigMap())).first; + entry = type->second.insert(std::make_pair(entry_name, ConfigMap())).first; } auto value = entry->second.find(res_entry.configuration); diff --git a/cmds/idmap2/libidmap2/Idmap.cpp b/cmds/idmap2/libidmap2/Idmap.cpp index 813dff1c141c..7c0b937122c7 100644 --- a/cmds/idmap2/libidmap2/Idmap.cpp +++ b/cmds/idmap2/libidmap2/Idmap.cpp @@ -317,7 +317,7 @@ Result<std::unique_ptr<const IdmapData>> IdmapData::FromResourceMapping( } std::unique_ptr<IdmapData> data(new IdmapData()); - data->string_pool_data_ = resource_mapping.GetStringPoolData().to_string(); + data->string_pool_data_ = std::string(resource_mapping.GetStringPoolData()); uint32_t inline_value_count = 0; std::set<std::string> config_set; for (const auto& mapping : resource_mapping.GetTargetToOverlayMap()) { diff --git a/cmds/idmap2/libidmap2/PolicyUtils.cpp b/cmds/idmap2/libidmap2/PolicyUtils.cpp index 4e3f54d2583e..76c70cab6296 100644 --- a/cmds/idmap2/libidmap2/PolicyUtils.cpp +++ b/cmds/idmap2/libidmap2/PolicyUtils.cpp @@ -53,7 +53,7 @@ std::vector<std::string> BitmaskToPolicies(const PolicyBitmask& bitmask) { for (const auto& policy : kPolicyStringToFlag) { if ((bitmask & policy.second) != 0) { - policies.emplace_back(policy.first.to_string()); + policies.emplace_back(policy.first); } } diff --git a/core/jni/android_content_res_ApkAssets.cpp b/core/jni/android_content_res_ApkAssets.cpp index a8d72316036e..5a78412ac277 100644 --- a/core/jni/android_content_res_ApkAssets.cpp +++ b/core/jni/android_content_res_ApkAssets.cpp @@ -96,7 +96,7 @@ class LoaderAssetsProvider : public AssetsProvider { } bool ForEachFile(const std::string& /* root_path */, - const std::function<void(const StringPiece&, FileType)>& /* f */) const { + const std::function<void(StringPiece, FileType)>& /* f */) const { return true; } diff --git a/libs/androidfw/AssetManager2.cpp b/libs/androidfw/AssetManager2.cpp index 3fa369d7ff4a..27fb94408966 100644 --- a/libs/androidfw/AssetManager2.cpp +++ b/libs/androidfw/AssetManager2.cpp @@ -317,7 +317,7 @@ const std::unordered_map<std::string, std::string>* return &loaded_package->GetOverlayableMap(); } -bool AssetManager2::GetOverlayablesToString(const android::StringPiece& package_name, +bool AssetManager2::GetOverlayablesToString(android::StringPiece package_name, std::string* out) const { uint8_t package_id = 0U; for (const auto& apk_assets : apk_assets_) { @@ -492,7 +492,7 @@ std::unique_ptr<AssetDir> AssetManager2::OpenDir(const std::string& dirname) con continue; } - auto func = [&](const StringPiece& name, FileType type) { + auto func = [&](StringPiece name, FileType type) { AssetDir::FileInfo info; info.setFileName(String8(name.data(), name.size())); info.setFileType(type); @@ -1271,7 +1271,7 @@ base::expected<const ResolvedBag*, NullOrIOError> AssetManager2::GetBag( return result; } -static bool Utf8ToUtf16(const StringPiece& str, std::u16string* out) { +static bool Utf8ToUtf16(StringPiece str, std::u16string* out) { ssize_t len = utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(str.data()), str.size(), false); if (len < 0) { diff --git a/libs/androidfw/AssetsProvider.cpp b/libs/androidfw/AssetsProvider.cpp index bce34d37c90b..289d7e660402 100644 --- a/libs/androidfw/AssetsProvider.cpp +++ b/libs/androidfw/AssetsProvider.cpp @@ -211,8 +211,7 @@ std::unique_ptr<Asset> ZipAssetsProvider::OpenInternal(const std::string& path, } bool ZipAssetsProvider::ForEachFile(const std::string& root_path, - const std::function<void(const StringPiece&, FileType)>& f) - const { + const std::function<void(StringPiece, FileType)>& f) const { std::string root_path_full = root_path; if (root_path_full.back() != '/') { root_path_full += '/'; @@ -238,8 +237,7 @@ bool ZipAssetsProvider::ForEachFile(const std::string& root_path, if (!leaf_file_path.empty()) { auto iter = std::find(leaf_file_path.begin(), leaf_file_path.end(), '/'); if (iter != leaf_file_path.end()) { - std::string dir = - leaf_file_path.substr(0, std::distance(leaf_file_path.begin(), iter)).to_string(); + std::string dir(leaf_file_path.substr(0, std::distance(leaf_file_path.begin(), iter))); dirs.insert(std::move(dir)); } else { f(leaf_file_path, kFileTypeRegular); @@ -324,8 +322,7 @@ std::unique_ptr<Asset> DirectoryAssetsProvider::OpenInternal(const std::string& bool DirectoryAssetsProvider::ForEachFile( const std::string& /* root_path */, - const std::function<void(const StringPiece&, FileType)>& /* f */) - const { + const std::function<void(StringPiece, FileType)>& /* f */) const { return true; } @@ -373,8 +370,7 @@ std::unique_ptr<Asset> MultiAssetsProvider::OpenInternal(const std::string& path } bool MultiAssetsProvider::ForEachFile(const std::string& root_path, - const std::function<void(const StringPiece&, FileType)>& f) - const { + const std::function<void(StringPiece, FileType)>& f) const { return primary_->ForEachFile(root_path, f) && secondary_->ForEachFile(root_path, f); } @@ -412,7 +408,7 @@ std::unique_ptr<Asset> EmptyAssetsProvider::OpenInternal(const std::string& /* p bool EmptyAssetsProvider::ForEachFile( const std::string& /* root_path */, - const std::function<void(const StringPiece&, FileType)>& /* f */) const { + const std::function<void(StringPiece, FileType)>& /* f */) const { return true; } diff --git a/libs/androidfw/ConfigDescription.cpp b/libs/androidfw/ConfigDescription.cpp index 19ead9583eb2..93a7d173cb97 100644 --- a/libs/androidfw/ConfigDescription.cpp +++ b/libs/androidfw/ConfigDescription.cpp @@ -637,7 +637,7 @@ static bool parseVersion(const char* name, ResTable_config* out) { return true; } -bool ConfigDescription::Parse(const StringPiece& str, ConfigDescription* out) { +bool ConfigDescription::Parse(StringPiece str, ConfigDescription* out) { std::vector<std::string> parts = util::SplitAndLowercase(str, '-'); ConfigDescription config; diff --git a/libs/androidfw/Idmap.cpp b/libs/androidfw/Idmap.cpp index e122d4844ee9..f3d244342b55 100644 --- a/libs/androidfw/Idmap.cpp +++ b/libs/androidfw/Idmap.cpp @@ -274,8 +274,7 @@ LoadedIdmap::LoadedIdmap(std::string&& idmap_path, target_apk_path_(target_apk_path), idmap_last_mod_time_(getFileModDate(idmap_path_.data())) {} -std::unique_ptr<LoadedIdmap> LoadedIdmap::Load(const StringPiece& idmap_path, - const StringPiece& idmap_data) { +std::unique_ptr<LoadedIdmap> LoadedIdmap::Load(StringPiece idmap_path, StringPiece idmap_data) { ATRACE_CALL(); size_t data_size = idmap_data.size(); auto data_ptr = reinterpret_cast<const uint8_t*>(idmap_data.data()); @@ -365,7 +364,7 @@ std::unique_ptr<LoadedIdmap> LoadedIdmap::Load(const StringPiece& idmap_path, // Can't use make_unique because LoadedIdmap constructor is private. return std::unique_ptr<LoadedIdmap>( - new LoadedIdmap(idmap_path.to_string(), header, data_header, target_entries, + new LoadedIdmap(std::string(idmap_path), header, data_header, target_entries, target_inline_entries, target_inline_entry_values, configurations, overlay_entries, std::move(idmap_string_pool), *target_path, *overlay_path)); } diff --git a/libs/androidfw/Locale.cpp b/libs/androidfw/Locale.cpp index d87a3ce72177..272a988ec55a 100644 --- a/libs/androidfw/Locale.cpp +++ b/libs/androidfw/Locale.cpp @@ -66,7 +66,7 @@ static inline bool is_number(const std::string& str) { return std::all_of(std::begin(str), std::end(str), ::isdigit); } -bool LocaleValue::InitFromFilterString(const StringPiece& str) { +bool LocaleValue::InitFromFilterString(StringPiece str) { // A locale (as specified in the filter) is an underscore separated name such // as "en_US", "en_Latn_US", or "en_US_POSIX". std::vector<std::string> parts = util::SplitAndLowercase(str, '_'); @@ -132,11 +132,11 @@ bool LocaleValue::InitFromFilterString(const StringPiece& str) { return true; } -bool LocaleValue::InitFromBcp47Tag(const StringPiece& bcp47tag) { +bool LocaleValue::InitFromBcp47Tag(StringPiece bcp47tag) { return InitFromBcp47TagImpl(bcp47tag, '-'); } -bool LocaleValue::InitFromBcp47TagImpl(const StringPiece& bcp47tag, const char separator) { +bool LocaleValue::InitFromBcp47TagImpl(StringPiece bcp47tag, const char separator) { std::vector<std::string> subtags = util::SplitAndLowercase(bcp47tag, separator); if (subtags.size() == 1) { set_language(subtags[0].c_str()); diff --git a/libs/androidfw/ResourceUtils.cpp b/libs/androidfw/ResourceUtils.cpp index 87fb2c038c9f..ccb61561578f 100644 --- a/libs/androidfw/ResourceUtils.cpp +++ b/libs/androidfw/ResourceUtils.cpp @@ -18,7 +18,7 @@ namespace android { -bool ExtractResourceName(const StringPiece& str, StringPiece* out_package, StringPiece* out_type, +bool ExtractResourceName(StringPiece str, StringPiece* out_package, StringPiece* out_type, StringPiece* out_entry) { *out_package = ""; *out_type = ""; @@ -33,16 +33,16 @@ bool ExtractResourceName(const StringPiece& str, StringPiece* out_package, Strin while (current != end) { if (out_type->size() == 0 && *current == '/') { has_type_separator = true; - out_type->assign(start, current - start); + *out_type = StringPiece(start, current - start); start = current + 1; } else if (out_package->size() == 0 && *current == ':') { has_package_separator = true; - out_package->assign(start, current - start); + *out_package = StringPiece(start, current - start); start = current + 1; } current++; } - out_entry->assign(start, end - start); + *out_entry = StringPiece(start, end - start); return !(has_package_separator && out_package->empty()) && !(has_type_separator && out_type->empty()); @@ -50,7 +50,7 @@ bool ExtractResourceName(const StringPiece& str, StringPiece* out_package, Strin base::expected<AssetManager2::ResourceName, NullOrIOError> ToResourceName( const StringPoolRef& type_string_ref, const StringPoolRef& entry_string_ref, - const StringPiece& package_name) { + StringPiece package_name) { AssetManager2::ResourceName name{ .package = package_name.data(), .package_len = package_name.size(), diff --git a/libs/androidfw/StringPool.cpp b/libs/androidfw/StringPool.cpp index b59e906f6281..1cb8df311c89 100644 --- a/libs/androidfw/StringPool.cpp +++ b/libs/androidfw/StringPool.cpp @@ -161,16 +161,15 @@ const StringPool::Context& StringPool::StyleRef::GetContext() const { return entry_->context; } -StringPool::Ref StringPool::MakeRef(const StringPiece& str) { +StringPool::Ref StringPool::MakeRef(StringPiece str) { return MakeRefImpl(str, Context{}, true); } -StringPool::Ref StringPool::MakeRef(const StringPiece& str, const Context& context) { +StringPool::Ref StringPool::MakeRef(StringPiece str, const Context& context) { return MakeRefImpl(str, context, true); } -StringPool::Ref StringPool::MakeRefImpl(const StringPiece& str, const Context& context, - bool unique) { +StringPool::Ref StringPool::MakeRefImpl(StringPiece str, const Context& context, bool unique) { if (unique) { auto range = indexed_strings_.equal_range(str); for (auto iter = range.first; iter != range.second; ++iter) { @@ -181,7 +180,7 @@ StringPool::Ref StringPool::MakeRefImpl(const StringPiece& str, const Context& c } std::unique_ptr<Entry> entry(new Entry()); - entry->value = str.to_string(); + entry->value = std::string(str); entry->context = context; entry->index_ = strings_.size(); entry->ref_ = 0; diff --git a/libs/androidfw/Util.cpp b/libs/androidfw/Util.cpp index 52ad0dce8187..be55fe8b4bb6 100644 --- a/libs/androidfw/Util.cpp +++ b/libs/androidfw/Util.cpp @@ -42,7 +42,7 @@ void ReadUtf16StringFromDevice(const uint16_t* src, size_t len, std::string* out } } -std::u16string Utf8ToUtf16(const StringPiece& utf8) { +std::u16string Utf8ToUtf16(StringPiece utf8) { ssize_t utf16_length = utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(utf8.data()), utf8.length()); if (utf16_length <= 0) { @@ -56,7 +56,7 @@ std::u16string Utf8ToUtf16(const StringPiece& utf8) { return utf16; } -std::string Utf16ToUtf8(const StringPiece16& utf16) { +std::string Utf16ToUtf8(StringPiece16 utf16) { ssize_t utf8_length = utf16_to_utf8_length(utf16.data(), utf16.length()); if (utf8_length <= 0) { return {}; @@ -68,7 +68,7 @@ std::string Utf16ToUtf8(const StringPiece16& utf16) { return utf8; } -std::string Utf8ToModifiedUtf8(const std::string& utf8) { +std::string Utf8ToModifiedUtf8(std::string_view utf8) { // Java uses Modified UTF-8 which only supports the 1, 2, and 3 byte formats of UTF-8. To encode // 4 byte UTF-8 codepoints, Modified UTF-8 allows the use of surrogate pairs in the same format // of CESU-8 surrogate pairs. Calculate the size of the utf8 string with all 4 byte UTF-8 @@ -86,7 +86,7 @@ std::string Utf8ToModifiedUtf8(const std::string& utf8) { // Early out if no 4 byte codepoints are found if (size == modified_size) { - return utf8; + return std::string(utf8); } std::string output; @@ -115,7 +115,7 @@ std::string Utf8ToModifiedUtf8(const std::string& utf8) { return output; } -std::string ModifiedUtf8ToUtf8(const std::string& modified_utf8) { +std::string ModifiedUtf8ToUtf8(std::string_view modified_utf8) { // The UTF-8 representation will have a byte length less than or equal to the Modified UTF-8 // representation. std::string output; @@ -170,30 +170,28 @@ std::string ModifiedUtf8ToUtf8(const std::string& modified_utf8) { return output; } -static std::vector<std::string> SplitAndTransform( - const StringPiece& str, char sep, const std::function<char(char)>& f) { +template <class Func> +static std::vector<std::string> SplitAndTransform(StringPiece str, char sep, Func&& f) { std::vector<std::string> parts; const StringPiece::const_iterator end = std::end(str); StringPiece::const_iterator start = std::begin(str); StringPiece::const_iterator current; do { current = std::find(start, end, sep); - parts.emplace_back(str.substr(start, current).to_string()); - if (f) { - std::string& part = parts.back(); - std::transform(part.begin(), part.end(), part.begin(), f); - } + parts.emplace_back(StringPiece(start, current - start)); + std::string& part = parts.back(); + std::transform(part.begin(), part.end(), part.begin(), f); start = current + 1; } while (current != end); return parts; } -std::vector<std::string> SplitAndLowercase(const StringPiece& str, char sep) { - return SplitAndTransform(str, sep, ::tolower); +std::vector<std::string> SplitAndLowercase(StringPiece str, char sep) { + return SplitAndTransform(str, sep, [](char c) { return ::tolower(c); }); } std::unique_ptr<uint8_t[]> Copy(const BigBuffer& buffer) { - std::unique_ptr<uint8_t[]> data = std::unique_ptr<uint8_t[]>(new uint8_t[buffer.size()]); + auto data = std::unique_ptr<uint8_t[]>(new uint8_t[buffer.size()]); uint8_t* p = data.get(); for (const auto& block : buffer) { memcpy(p, block.buffer.get(), block.size); @@ -211,7 +209,7 @@ StringPiece16 GetString16(const android::ResStringPool& pool, size_t idx) { std::string GetString(const android::ResStringPool& pool, size_t idx) { if (auto str = pool.string8At(idx); str.ok()) { - return ModifiedUtf8ToUtf8(str->to_string()); + return ModifiedUtf8ToUtf8(*str); } return Utf16ToUtf8(GetString16(pool, idx)); } diff --git a/libs/androidfw/include/androidfw/AssetManager2.h b/libs/androidfw/include/androidfw/AssetManager2.h index 1bde792da2ba..e9aaedc229d6 100644 --- a/libs/androidfw/include/androidfw/AssetManager2.h +++ b/libs/androidfw/include/androidfw/AssetManager2.h @@ -124,8 +124,7 @@ class AssetManager2 { uint8_t GetAssignedPackageId(const LoadedPackage* package) const; // Returns a string representation of the overlayable API of a package. - bool GetOverlayablesToString(const android::StringPiece& package_name, - std::string* out) const; + bool GetOverlayablesToString(android::StringPiece package_name, std::string* out) const; const std::unordered_map<std::string, std::string>* GetOverlayableMapForPackage( uint32_t package_id) const; diff --git a/libs/androidfw/include/androidfw/AssetsProvider.h b/libs/androidfw/include/androidfw/AssetsProvider.h index 966ec74c1786..13cbe3bab84c 100644 --- a/libs/androidfw/include/androidfw/AssetsProvider.h +++ b/libs/androidfw/include/androidfw/AssetsProvider.h @@ -46,7 +46,7 @@ struct AssetsProvider { // Iterate over all files and directories provided by the interface. The order of iteration is // stable. virtual bool ForEachFile(const std::string& path, - const std::function<void(const StringPiece&, FileType)>& f) const = 0; + const std::function<void(StringPiece, FileType)>& f) const = 0; // Retrieves the path to the contents of the AssetsProvider on disk. The path could represent an // APk, a directory, or some other file type. @@ -90,7 +90,7 @@ struct ZipAssetsProvider : public AssetsProvider { off64_t len = kUnknownLength); bool ForEachFile(const std::string& root_path, - const std::function<void(const StringPiece&, FileType)>& f) const override; + const std::function<void(StringPiece, FileType)>& f) const override; WARN_UNUSED std::optional<std::string_view> GetPath() const override; WARN_UNUSED const std::string& GetDebugName() const override; @@ -132,7 +132,7 @@ struct DirectoryAssetsProvider : public AssetsProvider { static std::unique_ptr<DirectoryAssetsProvider> Create(std::string root_dir); bool ForEachFile(const std::string& path, - const std::function<void(const StringPiece&, FileType)>& f) const override; + const std::function<void(StringPiece, FileType)>& f) const override; WARN_UNUSED std::optional<std::string_view> GetPath() const override; WARN_UNUSED const std::string& GetDebugName() const override; @@ -157,7 +157,7 @@ struct MultiAssetsProvider : public AssetsProvider { std::unique_ptr<AssetsProvider>&& secondary); bool ForEachFile(const std::string& root_path, - const std::function<void(const StringPiece&, FileType)>& f) const override; + const std::function<void(StringPiece, FileType)>& f) const override; WARN_UNUSED std::optional<std::string_view> GetPath() const override; WARN_UNUSED const std::string& GetDebugName() const override; @@ -184,7 +184,7 @@ struct EmptyAssetsProvider : public AssetsProvider { static std::unique_ptr<AssetsProvider> Create(const std::string& path); bool ForEachFile(const std::string& path, - const std::function<void(const StringPiece&, FileType)>& f) const override; + const std::function<void(StringPiece, FileType)>& f) const override; WARN_UNUSED std::optional<std::string_view> GetPath() const override; WARN_UNUSED const std::string& GetDebugName() const override; diff --git a/libs/androidfw/include/androidfw/ConfigDescription.h b/libs/androidfw/include/androidfw/ConfigDescription.h index 61d10cd4e55b..71087cdfb6fa 100644 --- a/libs/androidfw/include/androidfw/ConfigDescription.h +++ b/libs/androidfw/include/androidfw/ConfigDescription.h @@ -72,7 +72,7 @@ struct ConfigDescription : public ResTable_config { * The resulting configuration has the appropriate sdkVersion defined * for backwards compatibility. */ - static bool Parse(const android::StringPiece& str, ConfigDescription* out = nullptr); + static bool Parse(android::StringPiece str, ConfigDescription* out = nullptr); /** * If the configuration uses an axis that was added after diff --git a/libs/androidfw/include/androidfw/IDiagnostics.h b/libs/androidfw/include/androidfw/IDiagnostics.h index 273b05ac7689..4d5844eaa069 100644 --- a/libs/androidfw/include/androidfw/IDiagnostics.h +++ b/libs/androidfw/include/androidfw/IDiagnostics.h @@ -35,7 +35,7 @@ struct DiagMessage { public: DiagMessage() = default; - explicit DiagMessage(const android::StringPiece& src) : source_(src) { + explicit DiagMessage(android::StringPiece src) : source_(src) { } explicit DiagMessage(const Source& src) : source_(src) { @@ -61,7 +61,7 @@ struct DiagMessage { template <> inline DiagMessage& DiagMessage::operator<<(const ::std::u16string& value) { - message_ << android::StringPiece16(value); + message_ << value; return *this; } diff --git a/libs/androidfw/include/androidfw/Idmap.h b/libs/androidfw/include/androidfw/Idmap.h index a1cbbbf2271b..f173e6ef9c16 100644 --- a/libs/androidfw/include/androidfw/Idmap.h +++ b/libs/androidfw/include/androidfw/Idmap.h @@ -157,8 +157,7 @@ class IdmapResMap { class LoadedIdmap { public: // Loads an IDMAP from a chunk of memory. Returns nullptr if the IDMAP data was malformed. - static std::unique_ptr<LoadedIdmap> Load(const StringPiece& idmap_path, - const StringPiece& idmap_data); + static std::unique_ptr<LoadedIdmap> Load(StringPiece idmap_path, StringPiece idmap_data); // Returns the path to the IDMAP. std::string_view IdmapPath() const { diff --git a/libs/androidfw/include/androidfw/Locale.h b/libs/androidfw/include/androidfw/Locale.h index 484ed79a8efd..8934bed098fe 100644 --- a/libs/androidfw/include/androidfw/Locale.h +++ b/libs/androidfw/include/androidfw/Locale.h @@ -39,10 +39,10 @@ struct LocaleValue { /** * Initialize this LocaleValue from a config string. */ - bool InitFromFilterString(const android::StringPiece& config); + bool InitFromFilterString(android::StringPiece config); // Initializes this LocaleValue from a BCP-47 locale tag. - bool InitFromBcp47Tag(const android::StringPiece& bcp47tag); + bool InitFromBcp47Tag(android::StringPiece bcp47tag); /** * Initialize this LocaleValue from parts of a vector. @@ -70,7 +70,7 @@ struct LocaleValue { inline bool operator>(const LocaleValue& o) const; private: - bool InitFromBcp47TagImpl(const android::StringPiece& bcp47tag, const char separator); + bool InitFromBcp47TagImpl(android::StringPiece bcp47tag, const char separator); void set_language(const char* language); void set_region(const char* language); diff --git a/libs/androidfw/include/androidfw/ResourceUtils.h b/libs/androidfw/include/androidfw/ResourceUtils.h index bd1c44033b88..2d90a526dfbe 100644 --- a/libs/androidfw/include/androidfw/ResourceUtils.h +++ b/libs/androidfw/include/androidfw/ResourceUtils.h @@ -25,14 +25,14 @@ namespace android { // Extracts the package, type, and name from a string of the format: [[package:]type/]name // Validation must be performed on each extracted piece. // Returns false if there was a syntax error. -bool ExtractResourceName(const StringPiece& str, StringPiece* out_package, StringPiece* out_type, +bool ExtractResourceName(StringPiece str, StringPiece* out_package, StringPiece* out_type, StringPiece* out_entry); // Convert a type_string_ref, entry_string_ref, and package to AssetManager2::ResourceName. // Useful for getting resource name without re-running AssetManager2::FindEntry searches. base::expected<AssetManager2::ResourceName, NullOrIOError> ToResourceName( const StringPoolRef& type_string_ref, const StringPoolRef& entry_string_ref, - const StringPiece& package_name); + StringPiece package_name); // Formats a ResourceName to "package:type/entry_name". std::string ToFormattedResourceString(const AssetManager2::ResourceName& resource_name); diff --git a/libs/androidfw/include/androidfw/Source.h b/libs/androidfw/include/androidfw/Source.h index 0421a91d3eba..ddc9ba421101 100644 --- a/libs/androidfw/include/androidfw/Source.h +++ b/libs/androidfw/include/androidfw/Source.h @@ -34,15 +34,14 @@ struct Source { Source() = default; - inline Source(const android::StringPiece& path) : path(path.to_string()) { // NOLINT(implicit) + inline Source(android::StringPiece path) : path(path) { // NOLINT(implicit) } - inline Source(const android::StringPiece& path, const android::StringPiece& archive) - : path(path.to_string()), archive(archive.to_string()) { + inline Source(android::StringPiece path, android::StringPiece archive) + : path(path), archive(archive) { } - inline Source(const android::StringPiece& path, size_t line) - : path(path.to_string()), line(line) { + inline Source(android::StringPiece path, size_t line) : path(path), line(line) { } inline Source WithLine(size_t line) const { diff --git a/libs/androidfw/include/androidfw/StringPiece.h b/libs/androidfw/include/androidfw/StringPiece.h index fac2fa4fa575..f6cc64edfb5a 100644 --- a/libs/androidfw/include/androidfw/StringPiece.h +++ b/libs/androidfw/include/androidfw/StringPiece.h @@ -19,307 +19,37 @@ #include <ostream> #include <string> +#include <string_view> -#include "utils/JenkinsHash.h" #include "utils/Unicode.h" namespace android { -// Read only wrapper around basic C strings. Prevents excessive copying. -// StringPiece does not own the data it is wrapping. The lifetime of the underlying -// data must outlive this StringPiece. -// -// WARNING: When creating from std::basic_string<>, moving the original -// std::basic_string<> will invalidate the data held in a BasicStringPiece<>. -// BasicStringPiece<> should only be used transitively. -// -// NOTE: When creating an std::pair<StringPiece, T> using std::make_pair(), -// passing an std::string will first copy the string, then create a StringPiece -// on the copy, which is then immediately destroyed. -// Instead, create a StringPiece explicitly: -// -// std::string my_string = "foo"; -// std::make_pair<StringPiece, T>(StringPiece(my_string), ...); -template <typename TChar> -class BasicStringPiece { - public: - using const_iterator = const TChar*; - using difference_type = size_t; - using size_type = size_t; - - // End of string marker. - constexpr static const size_t npos = static_cast<size_t>(-1); - - BasicStringPiece(); - BasicStringPiece(const BasicStringPiece<TChar>& str); - BasicStringPiece(const std::basic_string<TChar>& str); // NOLINT(google-explicit-constructor) - BasicStringPiece(const TChar* str); // NOLINT(google-explicit-constructor) - BasicStringPiece(const TChar* str, size_t len); - - BasicStringPiece<TChar>& operator=(const BasicStringPiece<TChar>& rhs); - BasicStringPiece<TChar>& assign(const TChar* str, size_t len); - - BasicStringPiece<TChar> substr(size_t start, size_t len = npos) const; - BasicStringPiece<TChar> substr(BasicStringPiece<TChar>::const_iterator begin, - BasicStringPiece<TChar>::const_iterator end) const; - - const TChar* data() const; - size_t length() const; - size_t size() const; - bool empty() const; - std::basic_string<TChar> to_string() const; - - bool contains(const BasicStringPiece<TChar>& rhs) const; - int compare(const BasicStringPiece<TChar>& rhs) const; - bool operator<(const BasicStringPiece<TChar>& rhs) const; - bool operator>(const BasicStringPiece<TChar>& rhs) const; - bool operator==(const BasicStringPiece<TChar>& rhs) const; - bool operator!=(const BasicStringPiece<TChar>& rhs) const; - - const_iterator begin() const; - const_iterator end() const; - - private: - const TChar* data_; - size_t length_; -}; +template <class T> +using BasicStringPiece = std::basic_string_view<T>; using StringPiece = BasicStringPiece<char>; using StringPiece16 = BasicStringPiece<char16_t>; -// -// BasicStringPiece implementation. -// - -template <typename TChar> -constexpr const size_t BasicStringPiece<TChar>::npos; - -template <typename TChar> -inline BasicStringPiece<TChar>::BasicStringPiece() : data_(nullptr), length_(0) {} - -template <typename TChar> -inline BasicStringPiece<TChar>::BasicStringPiece(const BasicStringPiece<TChar>& str) - : data_(str.data_), length_(str.length_) {} - -template <typename TChar> -inline BasicStringPiece<TChar>::BasicStringPiece(const std::basic_string<TChar>& str) - : data_(str.data()), length_(str.length()) {} - -template <> -inline BasicStringPiece<char>::BasicStringPiece(const char* str) - : data_(str), length_(str != nullptr ? strlen(str) : 0) {} - -template <> -inline BasicStringPiece<char16_t>::BasicStringPiece(const char16_t* str) - : data_(str), length_(str != nullptr ? strlen16(str) : 0) {} - -template <typename TChar> -inline BasicStringPiece<TChar>::BasicStringPiece(const TChar* str, size_t len) - : data_(str), length_(len) {} - -template <typename TChar> -inline BasicStringPiece<TChar>& BasicStringPiece<TChar>::operator=( - const BasicStringPiece<TChar>& rhs) { - data_ = rhs.data_; - length_ = rhs.length_; - return *this; -} - -template <typename TChar> -inline BasicStringPiece<TChar>& BasicStringPiece<TChar>::assign(const TChar* str, size_t len) { - data_ = str; - length_ = len; - return *this; -} - -template <typename TChar> -inline BasicStringPiece<TChar> BasicStringPiece<TChar>::substr(size_t start, size_t len) const { - if (len == npos) { - len = length_ - start; - } - - if (start > length_ || start + len > length_) { - return BasicStringPiece<TChar>(); - } - return BasicStringPiece<TChar>(data_ + start, len); -} - -template <typename TChar> -inline BasicStringPiece<TChar> BasicStringPiece<TChar>::substr( - BasicStringPiece<TChar>::const_iterator begin, - BasicStringPiece<TChar>::const_iterator end) const { - return BasicStringPiece<TChar>(begin, end - begin); -} - -template <typename TChar> -inline const TChar* BasicStringPiece<TChar>::data() const { - return data_; -} - -template <typename TChar> -inline size_t BasicStringPiece<TChar>::length() const { - return length_; -} - -template <typename TChar> -inline size_t BasicStringPiece<TChar>::size() const { - return length_; -} - -template <typename TChar> -inline bool BasicStringPiece<TChar>::empty() const { - return length_ == 0; -} - -template <typename TChar> -inline std::basic_string<TChar> BasicStringPiece<TChar>::to_string() const { - return std::basic_string<TChar>(data_, length_); -} - -template <> -inline bool BasicStringPiece<char>::contains(const BasicStringPiece<char>& rhs) const { - if (!data_ || !rhs.data_) { - return false; - } - if (rhs.length_ > length_) { - return false; - } - return strstr(data_, rhs.data_) != nullptr; -} - -template <> -inline int BasicStringPiece<char>::compare(const BasicStringPiece<char>& rhs) const { - const char nullStr = '\0'; - const char* b1 = data_ != nullptr ? data_ : &nullStr; - const char* e1 = b1 + length_; - const char* b2 = rhs.data_ != nullptr ? rhs.data_ : &nullStr; - const char* e2 = b2 + rhs.length_; - - while (b1 < e1 && b2 < e2) { - const int d = static_cast<int>(*b1++) - static_cast<int>(*b2++); - if (d) { - return d; - } - } - return static_cast<int>(length_ - rhs.length_); -} - -inline ::std::ostream& operator<<(::std::ostream& out, const BasicStringPiece<char16_t>& str) { - const ssize_t result_len = utf16_to_utf8_length(str.data(), str.size()); - if (result_len < 0) { - // Empty string. - return out; - } - - std::string result; - result.resize(static_cast<size_t>(result_len)); - utf16_to_utf8(str.data(), str.length(), &*result.begin(), static_cast<size_t>(result_len) + 1); - return out << result; -} - -template <> -inline bool BasicStringPiece<char16_t>::contains(const BasicStringPiece<char16_t>& rhs) const { - if (!data_ || !rhs.data_) { - return false; - } - if (rhs.length_ > length_) { - return false; - } - return strstr16(data_, rhs.data_) != nullptr; -} - -template <> -inline int BasicStringPiece<char16_t>::compare(const BasicStringPiece<char16_t>& rhs) const { - const char16_t nullStr = u'\0'; - const char16_t* b1 = data_ != nullptr ? data_ : &nullStr; - const char16_t* b2 = rhs.data_ != nullptr ? rhs.data_ : &nullStr; - return strzcmp16(b1, length_, b2, rhs.length_); -} - -template <typename TChar> -inline bool BasicStringPiece<TChar>::operator<(const BasicStringPiece<TChar>& rhs) const { - return compare(rhs) < 0; -} - -template <typename TChar> -inline bool BasicStringPiece<TChar>::operator>(const BasicStringPiece<TChar>& rhs) const { - return compare(rhs) > 0; -} - -template <typename TChar> -inline bool BasicStringPiece<TChar>::operator==(const BasicStringPiece<TChar>& rhs) const { - return compare(rhs) == 0; -} - -template <typename TChar> -inline bool BasicStringPiece<TChar>::operator!=(const BasicStringPiece<TChar>& rhs) const { - return compare(rhs) != 0; -} - -template <typename TChar> -inline typename BasicStringPiece<TChar>::const_iterator BasicStringPiece<TChar>::begin() const { - return data_; -} - -template <typename TChar> -inline typename BasicStringPiece<TChar>::const_iterator BasicStringPiece<TChar>::end() const { - return data_ + length_; -} - -template <typename TChar> -inline bool operator==(const TChar* lhs, const BasicStringPiece<TChar>& rhs) { - return BasicStringPiece<TChar>(lhs) == rhs; -} - -template <typename TChar> -inline bool operator!=(const TChar* lhs, const BasicStringPiece<TChar>& rhs) { - return BasicStringPiece<TChar>(lhs) != rhs; -} - -inline ::std::ostream& operator<<(::std::ostream& out, const BasicStringPiece<char>& str) { - return out.write(str.data(), str.size()); -} - -template <typename TChar> -inline ::std::basic_string<TChar>& operator+=(::std::basic_string<TChar>& lhs, - const BasicStringPiece<TChar>& rhs) { - return lhs.append(rhs.data(), rhs.size()); -} - -template <typename TChar> -inline bool operator==(const ::std::basic_string<TChar>& lhs, const BasicStringPiece<TChar>& rhs) { - return BasicStringPiece<TChar>(lhs) == rhs; -} - -template <typename TChar> -inline bool operator!=(const ::std::basic_string<TChar>& lhs, const BasicStringPiece<TChar>& rhs) { - return BasicStringPiece<TChar>(lhs) != rhs; -} - } // namespace android -inline ::std::ostream& operator<<(::std::ostream& out, const std::u16string& str) { +namespace std { + +inline ::std::ostream& operator<<(::std::ostream& out, ::std::u16string_view str) { ssize_t utf8_len = utf16_to_utf8_length(str.data(), str.size()); if (utf8_len < 0) { - return out << "???"; + return out; // empty } std::string utf8; utf8.resize(static_cast<size_t>(utf8_len)); - utf16_to_utf8(str.data(), str.size(), &*utf8.begin(), utf8_len + 1); + utf16_to_utf8(str.data(), str.size(), utf8.data(), utf8_len + 1); return out << utf8; } -namespace std { - -template <typename TChar> -struct hash<android::BasicStringPiece<TChar>> { - size_t operator()(const android::BasicStringPiece<TChar>& str) const { - uint32_t hashCode = android::JenkinsHashMixBytes( - 0, reinterpret_cast<const uint8_t*>(str.data()), sizeof(TChar) * str.size()); - return static_cast<size_t>(hashCode); - } -}; +inline ::std::ostream& operator<<(::std::ostream& out, const ::std::u16string& str) { + return out << std::u16string_view(str); +} } // namespace std diff --git a/libs/androidfw/include/androidfw/StringPool.h b/libs/androidfw/include/androidfw/StringPool.h index 25174d8fe3c8..0190ab57bf23 100644 --- a/libs/androidfw/include/androidfw/StringPool.h +++ b/libs/androidfw/include/androidfw/StringPool.h @@ -167,11 +167,11 @@ class StringPool { // Adds a string to the pool, unless it already exists. Returns a reference to the string in the // pool. - Ref MakeRef(const android::StringPiece& str); + Ref MakeRef(android::StringPiece str); // Adds a string to the pool, unless it already exists, with a context object that can be used // when sorting the string pool. Returns a reference to the string in the pool. - Ref MakeRef(const android::StringPiece& str, const Context& context); + Ref MakeRef(android::StringPiece str, const Context& context); // Adds a string from another string pool. Returns a reference to the string in the string pool. Ref MakeRef(const Ref& ref); @@ -215,7 +215,7 @@ class StringPool { static bool Flatten(BigBuffer* out, const StringPool& pool, bool utf8, IDiagnostics* diag); - Ref MakeRefImpl(const android::StringPiece& str, const Context& context, bool unique); + Ref MakeRefImpl(android::StringPiece str, const Context& context, bool unique); void ReAssignIndices(); std::vector<std::unique_ptr<Entry>> strings_; diff --git a/libs/androidfw/include/androidfw/Util.h b/libs/androidfw/include/androidfw/Util.h index 1bbc7f5716bc..ae7c65f2d4e1 100644 --- a/libs/androidfw/include/androidfw/Util.h +++ b/libs/androidfw/include/androidfw/Util.h @@ -123,16 +123,16 @@ class unique_cptr { void ReadUtf16StringFromDevice(const uint16_t* src, size_t len, std::string* out); // Converts a UTF-8 string to a UTF-16 string. -std::u16string Utf8ToUtf16(const StringPiece& utf8); +std::u16string Utf8ToUtf16(StringPiece utf8); // Converts a UTF-16 string to a UTF-8 string. -std::string Utf16ToUtf8(const StringPiece16& utf16); +std::string Utf16ToUtf8(StringPiece16 utf16); // Converts a UTF8 string into Modified UTF8 -std::string Utf8ToModifiedUtf8(const std::string& utf8); +std::string Utf8ToModifiedUtf8(std::string_view utf8); // Converts a Modified UTF8 string into a UTF8 string -std::string ModifiedUtf8ToUtf8(const std::string& modified_utf8); +std::string ModifiedUtf8ToUtf8(std::string_view modified_utf8); inline uint16_t HostToDevice16(uint16_t value) { return htods(value); @@ -150,7 +150,7 @@ inline uint32_t DeviceToHost32(uint32_t value) { return dtohl(value); } -std::vector<std::string> SplitAndLowercase(const android::StringPiece& str, char sep); +std::vector<std::string> SplitAndLowercase(android::StringPiece str, char sep); template <typename T> inline bool IsFourByteAligned(const incfs::map_ptr<T>& data) { diff --git a/libs/androidfw/tests/AttributeResolution_bench.cpp b/libs/androidfw/tests/AttributeResolution_bench.cpp index ddd8ab820cb1..1c89c61c8f78 100644 --- a/libs/androidfw/tests/AttributeResolution_bench.cpp +++ b/libs/androidfw/tests/AttributeResolution_bench.cpp @@ -120,8 +120,8 @@ static void BM_ApplyStyleFramework(benchmark::State& state) { return; } - std::unique_ptr<Asset> asset = assetmanager.OpenNonAsset(layout_path->to_string(), value->cookie, - Asset::ACCESS_BUFFER); + std::unique_ptr<Asset> asset = + assetmanager.OpenNonAsset(std::string(*layout_path), value->cookie, Asset::ACCESS_BUFFER); if (asset == nullptr) { state.SkipWithError("failed to load layout"); return; diff --git a/libs/androidfw/tests/ConfigDescription_test.cpp b/libs/androidfw/tests/ConfigDescription_test.cpp index ce7f8054e2ca..8fed0a4d22fc 100644 --- a/libs/androidfw/tests/ConfigDescription_test.cpp +++ b/libs/androidfw/tests/ConfigDescription_test.cpp @@ -25,8 +25,8 @@ namespace android { -static ::testing::AssertionResult TestParse( - const StringPiece& input, ConfigDescription* config = nullptr) { +static ::testing::AssertionResult TestParse(StringPiece input, + ConfigDescription* config = nullptr) { if (ConfigDescription::Parse(input, config)) { return ::testing::AssertionSuccess() << input << " was successfully parsed"; } @@ -138,7 +138,7 @@ TEST(ConfigDescriptionTest, ParseVrAttribute) { EXPECT_EQ(std::string("vrheadset-v26"), config.toString().string()); } -static inline ConfigDescription ParseConfigOrDie(const android::StringPiece& str) { +static inline ConfigDescription ParseConfigOrDie(android::StringPiece str) { ConfigDescription config; CHECK(ConfigDescription::Parse(str, &config)) << "invalid configuration: " << str; return config; diff --git a/libs/androidfw/tests/StringPiece_test.cpp b/libs/androidfw/tests/StringPiece_test.cpp index 316a5c1bf40e..822e527253df 100644 --- a/libs/androidfw/tests/StringPiece_test.cpp +++ b/libs/androidfw/tests/StringPiece_test.cpp @@ -60,36 +60,4 @@ TEST(StringPieceTest, PiecesHaveCorrectSortOrderUtf8) { EXPECT_TRUE(StringPiece(car) > banana); } -TEST(StringPieceTest, ContainsOtherStringPiece) { - StringPiece text("I am a leaf on the wind."); - StringPiece start_needle("I am"); - StringPiece end_needle("wind."); - StringPiece middle_needle("leaf"); - StringPiece empty_needle(""); - StringPiece missing_needle("soar"); - StringPiece long_needle("This string is longer than the text."); - - EXPECT_TRUE(text.contains(start_needle)); - EXPECT_TRUE(text.contains(end_needle)); - EXPECT_TRUE(text.contains(middle_needle)); - EXPECT_TRUE(text.contains(empty_needle)); - EXPECT_FALSE(text.contains(missing_needle)); - EXPECT_FALSE(text.contains(long_needle)); - - StringPiece16 text16(u"I am a leaf on the wind."); - StringPiece16 start_needle16(u"I am"); - StringPiece16 end_needle16(u"wind."); - StringPiece16 middle_needle16(u"leaf"); - StringPiece16 empty_needle16(u""); - StringPiece16 missing_needle16(u"soar"); - StringPiece16 long_needle16(u"This string is longer than the text."); - - EXPECT_TRUE(text16.contains(start_needle16)); - EXPECT_TRUE(text16.contains(end_needle16)); - EXPECT_TRUE(text16.contains(middle_needle16)); - EXPECT_TRUE(text16.contains(empty_needle16)); - EXPECT_FALSE(text16.contains(missing_needle16)); - EXPECT_FALSE(text16.contains(long_needle16)); -} - } // namespace android diff --git a/libs/androidfw/tests/StringPool_test.cpp b/libs/androidfw/tests/StringPool_test.cpp index 047d45785409..0e0acae165d9 100644 --- a/libs/androidfw/tests/StringPool_test.cpp +++ b/libs/androidfw/tests/StringPool_test.cpp @@ -321,15 +321,15 @@ TEST(StringPoolTest, ModifiedUTF8) { ASSERT_EQ(test.setTo(data.get(), buffer.size()), NO_ERROR); auto str = test.string8At(0); ASSERT_TRUE(str.has_value()); - EXPECT_THAT(str->to_string(), Eq("\xED\xA0\x81\xED\xB0\x80")); + EXPECT_THAT(*str, Eq("\xED\xA0\x81\xED\xB0\x80")); str = test.string8At(1); ASSERT_TRUE(str.has_value()); - EXPECT_THAT(str->to_string(), Eq("foo \xED\xA0\x81\xED\xB0\xB7 bar")); + EXPECT_THAT(*str, Eq("foo \xED\xA0\x81\xED\xB0\xB7 bar")); str = test.string8At(2); ASSERT_TRUE(str.has_value()); - EXPECT_THAT(str->to_string(), Eq("\xED\xA0\x81\xED\xB0\x80\xED\xA0\x81\xED\xB0\xB7")); + EXPECT_THAT(*str, Eq("\xED\xA0\x81\xED\xB0\x80\xED\xA0\x81\xED\xB0\xB7")); // Check that retrieving the strings returns the original UTF-8 character bytes EXPECT_THAT(android::util::GetString(test, 0), Eq("\xF0\x90\x90\x80")); diff --git a/startop/view_compiler/apk_layout_compiler.cc b/startop/view_compiler/apk_layout_compiler.cc index 5cb0c171e06f..1d3b648175cc 100644 --- a/startop/view_compiler/apk_layout_compiler.cc +++ b/startop/view_compiler/apk_layout_compiler.cc @@ -100,56 +100,60 @@ void CompileApkAssetsLayouts(const std::unique_ptr<android::ApkAssets>& assets, dex_file.MakeClass(StringPrintf("%s.CompiledView", package_name.c_str()))}; std::vector<dex::MethodBuilder> methods; - assets->GetAssetsProvider()->ForEachFile("res/", [&](const android::StringPiece& s, - android::FileType) { - if (s == "layout") { - auto path = StringPrintf("res/%s/", s.to_string().c_str()); - assets->GetAssetsProvider()->ForEachFile(path, [&](const android::StringPiece& layout_file, - android::FileType) { - auto layout_path = StringPrintf("%s%s", path.c_str(), layout_file.to_string().c_str()); - android::ApkAssetsCookie cookie = android::kInvalidCookie; - auto asset = resources.OpenNonAsset(layout_path, android::Asset::ACCESS_RANDOM, &cookie); - CHECK(asset); - CHECK(android::kInvalidCookie != cookie); - const auto dynamic_ref_table = resources.GetDynamicRefTableForCookie(cookie); - CHECK(nullptr != dynamic_ref_table); - android::ResXMLTree xml_tree{dynamic_ref_table}; - xml_tree.setTo(asset->getBuffer(/*wordAligned=*/true), - asset->getLength(), - /*copy_data=*/true); - android::ResXMLParser parser{xml_tree}; - parser.restart(); - if (CanCompileLayout(&parser)) { - parser.restart(); - const std::string layout_name = startop::util::FindLayoutNameFromFilename(layout_path); - ResXmlVisitorAdapter adapter{&parser}; - switch (target) { - case CompilationTarget::kDex: { - methods.push_back(compiled_view.CreateMethod( - layout_name, - dex::Prototype{dex::TypeDescriptor::FromClassname("android.view.View"), - dex::TypeDescriptor::FromClassname("android.content.Context"), - dex::TypeDescriptor::Int()})); - DexViewBuilder builder(&methods.back()); - builder.Start(); - LayoutCompilerVisitor visitor{&builder}; - adapter.Accept(&visitor); - builder.Finish(); - methods.back().Encode(); - break; - } - case CompilationTarget::kJavaLanguage: { - JavaLangViewBuilder builder{package_name, layout_name, target_out}; - builder.Start(); - LayoutCompilerVisitor visitor{&builder}; - adapter.Accept(&visitor); - builder.Finish(); - break; - } - } - } - }); - } + assets->GetAssetsProvider()->ForEachFile("res/", [&](android::StringPiece s, android::FileType) { + if (s == "layout") { + auto path = StringPrintf("res/%.*s/", (int)s.size(), s.data()); + assets->GetAssetsProvider() + ->ForEachFile(path, [&](android::StringPiece layout_file, android::FileType) { + auto layout_path = StringPrintf("%s%.*s", path.c_str(), + (int)layout_file.size(), layout_file.data()); + android::ApkAssetsCookie cookie = android::kInvalidCookie; + auto asset = resources.OpenNonAsset(layout_path, + android::Asset::ACCESS_RANDOM, &cookie); + CHECK(asset); + CHECK(android::kInvalidCookie != cookie); + const auto dynamic_ref_table = resources.GetDynamicRefTableForCookie(cookie); + CHECK(nullptr != dynamic_ref_table); + android::ResXMLTree xml_tree{dynamic_ref_table}; + xml_tree.setTo(asset->getBuffer(/*wordAligned=*/true), asset->getLength(), + /*copy_data=*/true); + android::ResXMLParser parser{xml_tree}; + parser.restart(); + if (CanCompileLayout(&parser)) { + parser.restart(); + const std::string layout_name = + startop::util::FindLayoutNameFromFilename(layout_path); + ResXmlVisitorAdapter adapter{&parser}; + switch (target) { + case CompilationTarget::kDex: { + methods.push_back(compiled_view.CreateMethod( + layout_name, + dex::Prototype{dex::TypeDescriptor::FromClassname( + "android.view.View"), + dex::TypeDescriptor::FromClassname( + "android.content.Context"), + dex::TypeDescriptor::Int()})); + DexViewBuilder builder(&methods.back()); + builder.Start(); + LayoutCompilerVisitor visitor{&builder}; + adapter.Accept(&visitor); + builder.Finish(); + methods.back().Encode(); + break; + } + case CompilationTarget::kJavaLanguage: { + JavaLangViewBuilder builder{package_name, layout_name, + target_out}; + builder.Start(); + LayoutCompilerVisitor visitor{&builder}; + adapter.Accept(&visitor); + builder.Finish(); + break; + } + } + } + }); + } }); if (target == CompilationTarget::kDex) { diff --git a/tools/aapt2/LoadedApk.cpp b/tools/aapt2/LoadedApk.cpp index 9b9cde2f37da..6b1fd9ff11eb 100644 --- a/tools/aapt2/LoadedApk.cpp +++ b/tools/aapt2/LoadedApk.cpp @@ -72,7 +72,7 @@ static ApkFormat DetermineApkFormat(io::IFileCollection* apk) { } } -std::unique_ptr<LoadedApk> LoadedApk::LoadApkFromPath(const StringPiece& path, +std::unique_ptr<LoadedApk> LoadedApk::LoadApkFromPath(StringPiece path, android::IDiagnostics* diag) { android::Source source(path); std::string error; diff --git a/tools/aapt2/LoadedApk.h b/tools/aapt2/LoadedApk.h index a4aff3f8376a..4cd7eae0a5e2 100644 --- a/tools/aapt2/LoadedApk.h +++ b/tools/aapt2/LoadedApk.h @@ -45,7 +45,7 @@ class LoadedApk { virtual ~LoadedApk() = default; // Loads both binary and proto APKs from disk. - static std::unique_ptr<LoadedApk> LoadApkFromPath(const ::android::StringPiece& path, + static std::unique_ptr<LoadedApk> LoadApkFromPath(android::StringPiece path, android::IDiagnostics* diag); // Loads a proto APK from the given file collection. diff --git a/tools/aapt2/NameMangler.h b/tools/aapt2/NameMangler.h index 0b4905253d20..0b08c3276cb5 100644 --- a/tools/aapt2/NameMangler.h +++ b/tools/aapt2/NameMangler.h @@ -36,7 +36,7 @@ struct NameManglerPolicy { * We must know which references to mangle, and which to keep (android vs. * com.android.support). */ - std::set<std::string> packages_to_mangle; + std::set<std::string, std::less<>> packages_to_mangle; }; class NameMangler { @@ -54,7 +54,7 @@ class NameMangler { mangled_entry_name); } - bool ShouldMangle(const std::string& package) const { + bool ShouldMangle(std::string_view package) const { if (package.empty() || policy_.target_package_name == package) { return false; } @@ -68,8 +68,8 @@ class NameMangler { * The mangled name should contain symbols that are illegal to define in XML, * so that there will never be name mangling collisions. */ - static std::string MangleEntry(const std::string& package, const std::string& name) { - return package + "$" + name; + static std::string MangleEntry(std::string_view package, std::string_view name) { + return (std::string(package) += '$') += name; } /** diff --git a/tools/aapt2/Resource.cpp b/tools/aapt2/Resource.cpp index df8c3b9956d0..cfcb2bb4f99d 100644 --- a/tools/aapt2/Resource.cpp +++ b/tools/aapt2/Resource.cpp @@ -138,11 +138,11 @@ ResourceNamedTypeRef ResourceNamedTypeWithDefaultName(ResourceType t) { return {to_string(t), t}; } -std::optional<ResourceNamedTypeRef> ParseResourceNamedType(const android::StringPiece& s) { +std::optional<ResourceNamedTypeRef> ParseResourceNamedType(android::StringPiece s) { auto dot = std::find(s.begin(), s.end(), '.'); const ResourceType* parsedType; if (dot != s.end() && dot != std::prev(s.end())) { - parsedType = ParseResourceType(s.substr(s.begin(), dot)); + parsedType = ParseResourceType(android::StringPiece(s.begin(), dot - s.begin())); } else { parsedType = ParseResourceType(s); } @@ -152,7 +152,7 @@ std::optional<ResourceNamedTypeRef> ParseResourceNamedType(const android::String return ResourceNamedTypeRef(s, *parsedType); } -const ResourceType* ParseResourceType(const StringPiece& str) { +const ResourceType* ParseResourceType(StringPiece str) { auto iter = sResourceTypeMap.find(str); if (iter == std::end(sResourceTypeMap)) { return nullptr; diff --git a/tools/aapt2/Resource.h b/tools/aapt2/Resource.h index 9cfaf4742ca5..7ba3277d2093 100644 --- a/tools/aapt2/Resource.h +++ b/tools/aapt2/Resource.h @@ -74,7 +74,7 @@ android::StringPiece to_string(ResourceType type); /** * Returns a pointer to a valid ResourceType, or nullptr if the string was invalid. */ -const ResourceType* ParseResourceType(const android::StringPiece& str); +const ResourceType* ParseResourceType(android::StringPiece str); /** * Pair of type name as in ResourceTable and actual resource type. @@ -87,7 +87,7 @@ struct ResourceNamedType { ResourceType type = ResourceType::kRaw; ResourceNamedType() = default; - ResourceNamedType(const android::StringPiece& n, ResourceType t); + ResourceNamedType(android::StringPiece n, ResourceType t); int compare(const ResourceNamedType& other) const; @@ -108,19 +108,19 @@ struct ResourceNamedTypeRef { ResourceNamedTypeRef(const ResourceNamedTypeRef&) = default; ResourceNamedTypeRef(ResourceNamedTypeRef&&) = default; ResourceNamedTypeRef(const ResourceNamedType& rhs); // NOLINT(google-explicit-constructor) - ResourceNamedTypeRef(const android::StringPiece& n, ResourceType t); + ResourceNamedTypeRef(android::StringPiece n, ResourceType t); ResourceNamedTypeRef& operator=(const ResourceNamedTypeRef& rhs) = default; ResourceNamedTypeRef& operator=(ResourceNamedTypeRef&& rhs) = default; ResourceNamedTypeRef& operator=(const ResourceNamedType& rhs); ResourceNamedType ToResourceNamedType() const; - std::string to_string() const; + std::string_view to_string() const; }; ResourceNamedTypeRef ResourceNamedTypeWithDefaultName(ResourceType t); -std::optional<ResourceNamedTypeRef> ParseResourceNamedType(const android::StringPiece& s); +std::optional<ResourceNamedTypeRef> ParseResourceNamedType(android::StringPiece s); /** * A resource's name. This can uniquely identify @@ -132,9 +132,8 @@ struct ResourceName { std::string entry; ResourceName() = default; - ResourceName(const android::StringPiece& p, const ResourceNamedTypeRef& t, - const android::StringPiece& e); - ResourceName(const android::StringPiece& p, ResourceType t, const android::StringPiece& e); + ResourceName(android::StringPiece p, const ResourceNamedTypeRef& t, android::StringPiece e); + ResourceName(android::StringPiece p, ResourceType t, android::StringPiece e); int compare(const ResourceName& other) const; @@ -157,9 +156,8 @@ struct ResourceNameRef { ResourceNameRef(const ResourceNameRef&) = default; ResourceNameRef(ResourceNameRef&&) = default; ResourceNameRef(const ResourceName& rhs); // NOLINT(google-explicit-constructor) - ResourceNameRef(const android::StringPiece& p, const ResourceNamedTypeRef& t, - const android::StringPiece& e); - ResourceNameRef(const android::StringPiece& p, ResourceType t, const android::StringPiece& e); + ResourceNameRef(android::StringPiece p, const ResourceNamedTypeRef& t, android::StringPiece e); + ResourceNameRef(android::StringPiece p, ResourceType t, android::StringPiece e); ResourceNameRef& operator=(const ResourceNameRef& rhs) = default; ResourceNameRef& operator=(ResourceNameRef&& rhs) = default; ResourceNameRef& operator=(const ResourceName& rhs); @@ -346,8 +344,8 @@ inline ::std::ostream& operator<<(::std::ostream& out, const ResourceType& val) // // ResourceNamedType implementation. // -inline ResourceNamedType::ResourceNamedType(const android::StringPiece& n, ResourceType t) - : name(n.to_string()), type(t) { +inline ResourceNamedType::ResourceNamedType(android::StringPiece n, ResourceType t) + : name(n), type(t) { } inline int ResourceNamedType::compare(const ResourceNamedType& other) const { @@ -380,7 +378,7 @@ inline ::std::ostream& operator<<(::std::ostream& out, const ResourceNamedType& // // ResourceNamedTypeRef implementation. // -inline ResourceNamedTypeRef::ResourceNamedTypeRef(const android::StringPiece& n, ResourceType t) +inline ResourceNamedTypeRef::ResourceNamedTypeRef(android::StringPiece n, ResourceType t) : name(n), type(t) { } @@ -398,8 +396,8 @@ inline ResourceNamedType ResourceNamedTypeRef::ToResourceNamedType() const { return ResourceNamedType(name, type); } -inline std::string ResourceNamedTypeRef::to_string() const { - return name.to_string(); +inline std::string_view ResourceNamedTypeRef::to_string() const { + return name; } inline bool operator<(const ResourceNamedTypeRef& lhs, const ResourceNamedTypeRef& rhs) { @@ -422,13 +420,12 @@ inline ::std::ostream& operator<<(::std::ostream& out, const ResourceNamedTypeRe // ResourceName implementation. // -inline ResourceName::ResourceName(const android::StringPiece& p, const ResourceNamedTypeRef& t, - const android::StringPiece& e) - : package(p.to_string()), type(t.ToResourceNamedType()), entry(e.to_string()) { +inline ResourceName::ResourceName(android::StringPiece p, const ResourceNamedTypeRef& t, + android::StringPiece e) + : package(p), type(t.ToResourceNamedType()), entry(e) { } -inline ResourceName::ResourceName(const android::StringPiece& p, ResourceType t, - const android::StringPiece& e) +inline ResourceName::ResourceName(android::StringPiece p, ResourceType t, android::StringPiece e) : ResourceName(p, ResourceNamedTypeWithDefaultName(t), e) { } @@ -471,14 +468,13 @@ inline ::std::ostream& operator<<(::std::ostream& out, const ResourceName& name) inline ResourceNameRef::ResourceNameRef(const ResourceName& rhs) : package(rhs.package), type(rhs.type), entry(rhs.entry) {} -inline ResourceNameRef::ResourceNameRef(const android::StringPiece& p, - const ResourceNamedTypeRef& t, - const android::StringPiece& e) +inline ResourceNameRef::ResourceNameRef(android::StringPiece p, const ResourceNamedTypeRef& t, + android::StringPiece e) : package(p), type(t), entry(e) { } -inline ResourceNameRef::ResourceNameRef(const android::StringPiece& p, ResourceType t, - const android::StringPiece& e) +inline ResourceNameRef::ResourceNameRef(android::StringPiece p, ResourceType t, + android::StringPiece e) : ResourceNameRef(p, ResourceNamedTypeWithDefaultName(t), e) { } diff --git a/tools/aapt2/ResourceParser.cpp b/tools/aapt2/ResourceParser.cpp index 19fd306d5a42..fa9a98f136cb 100644 --- a/tools/aapt2/ResourceParser.cpp +++ b/tools/aapt2/ResourceParser.cpp @@ -50,11 +50,11 @@ constexpr const char* kStagingPublicGroupFinalTag = "staging-public-group-final" constexpr const char* sXliffNamespaceUri = "urn:oasis:names:tc:xliff:document:1.2"; // Returns true if the element is <skip> or <eat-comment> and can be safely ignored. -static bool ShouldIgnoreElement(const StringPiece& ns, const StringPiece& name) { +static bool ShouldIgnoreElement(StringPiece ns, StringPiece name) { return ns.empty() && (name == "skip" || name == "eat-comment"); } -static uint32_t ParseFormatTypeNoEnumsOrFlags(const StringPiece& piece) { +static uint32_t ParseFormatTypeNoEnumsOrFlags(StringPiece piece) { if (piece == "reference") { return android::ResTable_map::TYPE_REFERENCE; } else if (piece == "string") { @@ -75,7 +75,7 @@ static uint32_t ParseFormatTypeNoEnumsOrFlags(const StringPiece& piece) { return 0; } -static uint32_t ParseFormatType(const StringPiece& piece) { +static uint32_t ParseFormatType(StringPiece piece) { if (piece == "enum") { return android::ResTable_map::TYPE_ENUM; } else if (piece == "flags") { @@ -84,9 +84,9 @@ static uint32_t ParseFormatType(const StringPiece& piece) { return ParseFormatTypeNoEnumsOrFlags(piece); } -static uint32_t ParseFormatAttribute(const StringPiece& str) { +static uint32_t ParseFormatAttribute(StringPiece str) { uint32_t mask = 0; - for (const StringPiece& part : util::Tokenize(str, '|')) { + for (StringPiece part : util::Tokenize(str, '|')) { StringPiece trimmed_part = util::TrimWhitespace(part); uint32_t type = ParseFormatType(trimmed_part); if (type == 0) { @@ -122,7 +122,7 @@ static bool AddResourcesToTable(ResourceTable* table, android::IDiagnostics* dia StringPiece trimmed_comment = util::TrimWhitespace(res->comment); if (trimmed_comment.size() != res->comment.size()) { // Only if there was a change do we re-assign. - res->comment = trimmed_comment.to_string(); + res->comment = std::string(trimmed_comment); } NewResourceBuilder res_builder(res->name); @@ -362,7 +362,7 @@ bool ResourceParser::FlattenXmlSubtree( // Trim leading whitespace. StringPiece trimmed = util::TrimLeadingWhitespace(first_segment->data); if (trimmed.size() != first_segment->data.size()) { - first_segment->data = trimmed.to_string(); + first_segment->data = std::string(trimmed); } } @@ -370,7 +370,7 @@ bool ResourceParser::FlattenXmlSubtree( // Trim trailing whitespace. StringPiece trimmed = util::TrimTrailingWhitespace(last_segment->data); if (trimmed.size() != last_segment->data.size()) { - last_segment->data = trimmed.to_string(); + last_segment->data = std::string(trimmed); } } } @@ -466,7 +466,7 @@ bool ResourceParser::ParseResources(xml::XmlPullParser* parser) { // Extract the product name if it exists. if (std::optional<StringPiece> maybe_product = xml::FindNonEmptyAttribute(parser, "product")) { - parsed_resource.product = maybe_product.value().to_string(); + parsed_resource.product = std::string(maybe_product.value()); } // Parse the resource regardless of product. @@ -559,7 +559,7 @@ bool ResourceParser::ParseResource(xml::XmlPullParser* parser, // Items have their type encoded in the type attribute. if (std::optional<StringPiece> maybe_type = xml::FindNonEmptyAttribute(parser, "type")) { - resource_type = maybe_type.value().to_string(); + resource_type = std::string(maybe_type.value()); } else { diag_->Error(android::DiagMessage(source_.WithLine(parser->line_number())) << "<item> must have a 'type' attribute"); @@ -582,7 +582,7 @@ bool ResourceParser::ParseResource(xml::XmlPullParser* parser, // Bags have their type encoded in the type attribute. if (std::optional<StringPiece> maybe_type = xml::FindNonEmptyAttribute(parser, "type")) { - resource_type = maybe_type.value().to_string(); + resource_type = std::string(maybe_type.value()); } else { diag_->Error(android::DiagMessage(source_.WithLine(parser->line_number())) << "<bag> must have a 'type' attribute"); @@ -603,7 +603,7 @@ bool ResourceParser::ParseResource(xml::XmlPullParser* parser, out_resource->name.type = ResourceNamedTypeWithDefaultName(ResourceType::kId).ToResourceNamedType(); - out_resource->name.entry = maybe_name.value().to_string(); + out_resource->name.entry = std::string(maybe_name.value()); // Ids either represent a unique resource id or reference another resource id auto item = ParseItem(parser, out_resource, resource_format); @@ -640,7 +640,7 @@ bool ResourceParser::ParseResource(xml::XmlPullParser* parser, out_resource->name.type = ResourceNamedTypeWithDefaultName(ResourceType::kMacro).ToResourceNamedType(); - out_resource->name.entry = maybe_name.value().to_string(); + out_resource->name.entry = std::string(maybe_name.value()); return ParseMacro(parser, out_resource); } @@ -657,7 +657,7 @@ bool ResourceParser::ParseResource(xml::XmlPullParser* parser, out_resource->name.type = ResourceNamedTypeWithDefaultName(item_iter->second.type).ToResourceNamedType(); - out_resource->name.entry = maybe_name.value().to_string(); + out_resource->name.entry = std::string(maybe_name.value()); // Only use the implied format of the type when there is no explicit format. if (resource_format == 0u) { @@ -684,7 +684,7 @@ bool ResourceParser::ParseResource(xml::XmlPullParser* parser, return false; } - out_resource->name.entry = maybe_name.value().to_string(); + out_resource->name.entry = std::string(maybe_name.value()); } // Call the associated parse method. The type will be filled in by the @@ -708,7 +708,7 @@ bool ResourceParser::ParseResource(xml::XmlPullParser* parser, } out_resource->name.type = parsed_type->ToResourceNamedType(); - out_resource->name.entry = maybe_name.value().to_string(); + out_resource->name.entry = std::string(maybe_name.value()); out_resource->value = ParseXml(parser, android::ResTable_map::TYPE_REFERENCE, kNoRawString); if (!out_resource->value) { diag_->Error(android::DiagMessage(out_resource->source) @@ -1005,7 +1005,7 @@ bool static ParseGroupImpl(xml::XmlPullParser* parser, ParsedResource* out_resou const size_t depth = parser->depth(); while (xml::XmlPullParser::NextChildNode(parser, depth)) { if (parser->event() == xml::XmlPullParser::Event::kComment) { - comment = util::TrimWhitespace(parser->comment()).to_string(); + comment = std::string(util::TrimWhitespace(parser->comment())); continue; } else if (parser->event() != xml::XmlPullParser::Event::kStartElement) { // Skip text. @@ -1045,7 +1045,7 @@ bool static ParseGroupImpl(xml::XmlPullParser* parser, ParsedResource* out_resou } ParsedResource& entry_res = out_resource->child_resources.emplace_back(ParsedResource{ - .name = ResourceName{{}, parsed_type, maybe_name.value().to_string()}, + .name = ResourceName{{}, parsed_type, std::string(maybe_name.value())}, .source = item_source, .comment = std::move(comment), }); @@ -1231,7 +1231,7 @@ bool ResourceParser::ParseOverlayable(xml::XmlPullParser* parser, ParsedResource ParsedResource child_resource{}; child_resource.name.type = type->ToResourceNamedType(); - child_resource.name.entry = item_name.value().to_string(); + child_resource.name.entry = std::string(item_name.value()); child_resource.overlayable_item = overlayable_item; out_resource->child_resources.push_back(std::move(child_resource)); @@ -1246,7 +1246,7 @@ bool ResourceParser::ParseOverlayable(xml::XmlPullParser* parser, ParsedResource xml::FindNonEmptyAttribute(parser, "type")) { // Parse the polices separated by vertical bar characters to allow for specifying multiple // policies. Items within the policy tag will have the specified policy. - for (const StringPiece& part : util::Tokenize(maybe_type.value(), '|')) { + for (StringPiece part : util::Tokenize(maybe_type.value(), '|')) { StringPiece trimmed_part = util::TrimWhitespace(part); const auto policy = std::find_if(kPolicyStringToFlag.begin(), kPolicyStringToFlag.end(), @@ -1377,7 +1377,7 @@ bool ResourceParser::ParseAttrImpl(xml::XmlPullParser* parser, const size_t depth = parser->depth(); while (xml::XmlPullParser::NextChildNode(parser, depth)) { if (parser->event() == xml::XmlPullParser::Event::kComment) { - comment = util::TrimWhitespace(parser->comment()).to_string(); + comment = std::string(util::TrimWhitespace(parser->comment())); continue; } else if (parser->event() != xml::XmlPullParser::Event::kStartElement) { // Skip text. @@ -1457,7 +1457,7 @@ bool ResourceParser::ParseAttrImpl(xml::XmlPullParser* parser, } std::optional<Attribute::Symbol> ResourceParser::ParseEnumOrFlagItem(xml::XmlPullParser* parser, - const StringPiece& tag) { + StringPiece tag) { const android::Source source = source_.WithLine(parser->line_number()); std::optional<StringPiece> maybe_name = xml::FindNonEmptyAttribute(parser, "name"); @@ -1764,7 +1764,7 @@ bool ResourceParser::ParseDeclareStyleable(xml::XmlPullParser* parser, const size_t depth = parser->depth(); while (xml::XmlPullParser::NextChildNode(parser, depth)) { if (parser->event() == xml::XmlPullParser::Event::kComment) { - comment = util::TrimWhitespace(parser->comment()).to_string(); + comment = std::string(util::TrimWhitespace(parser->comment())); continue; } else if (parser->event() != xml::XmlPullParser::Event::kStartElement) { // Ignore text. diff --git a/tools/aapt2/ResourceParser.h b/tools/aapt2/ResourceParser.h index 396ce9767fe9..012a056dccf3 100644 --- a/tools/aapt2/ResourceParser.h +++ b/tools/aapt2/ResourceParser.h @@ -122,7 +122,7 @@ class ResourceParser { bool ParseAttr(xml::XmlPullParser* parser, ParsedResource* out_resource); bool ParseAttrImpl(xml::XmlPullParser* parser, ParsedResource* out_resource, bool weak); std::optional<Attribute::Symbol> ParseEnumOrFlagItem(xml::XmlPullParser* parser, - const android::StringPiece& tag); + android::StringPiece tag); bool ParseStyle(ResourceType type, xml::XmlPullParser* parser, ParsedResource* out_resource); bool ParseStyleItem(xml::XmlPullParser* parser, Style* style); bool ParseDeclareStyleable(xml::XmlPullParser* parser, ParsedResource* out_resource); diff --git a/tools/aapt2/ResourceParser_test.cpp b/tools/aapt2/ResourceParser_test.cpp index fe7eb96ffe16..b59b16574c42 100644 --- a/tools/aapt2/ResourceParser_test.cpp +++ b/tools/aapt2/ResourceParser_test.cpp @@ -65,11 +65,11 @@ class ResourceParserTest : public ::testing::Test { context_ = test::ContextBuilder().Build(); } - ::testing::AssertionResult TestParse(const StringPiece& str) { + ::testing::AssertionResult TestParse(StringPiece str) { return TestParse(str, ConfigDescription{}); } - ::testing::AssertionResult TestParse(const StringPiece& str, const ConfigDescription& config) { + ::testing::AssertionResult TestParse(StringPiece str, const ConfigDescription& config) { ResourceParserOptions parserOptions; ResourceParser parser(context_->GetDiagnostics(), &table_, android::Source{"test"}, config, parserOptions); diff --git a/tools/aapt2/ResourceTable.cpp b/tools/aapt2/ResourceTable.cpp index cb4811445ed1..a3b0b45df5c3 100644 --- a/tools/aapt2/ResourceTable.cpp +++ b/tools/aapt2/ResourceTable.cpp @@ -49,21 +49,21 @@ bool less_than_type(const std::unique_ptr<ResourceTableType>& lhs, } template <typename T> -bool less_than_struct_with_name(const std::unique_ptr<T>& lhs, const StringPiece& rhs) { +bool less_than_struct_with_name(const std::unique_ptr<T>& lhs, StringPiece rhs) { return lhs->name.compare(0, lhs->name.size(), rhs.data(), rhs.size()) < 0; } template <typename T> -bool greater_than_struct_with_name(const StringPiece& lhs, const std::unique_ptr<T>& rhs) { +bool greater_than_struct_with_name(StringPiece lhs, const std::unique_ptr<T>& rhs) { return rhs->name.compare(0, rhs->name.size(), lhs.data(), lhs.size()) > 0; } template <typename T> struct NameEqualRange { - bool operator()(const std::unique_ptr<T>& lhs, const StringPiece& rhs) const { + bool operator()(const std::unique_ptr<T>& lhs, StringPiece rhs) const { return less_than_struct_with_name<T>(lhs, rhs); } - bool operator()(const StringPiece& lhs, const std::unique_ptr<T>& rhs) const { + bool operator()(StringPiece lhs, const std::unique_ptr<T>& rhs) const { return greater_than_struct_with_name<T>(lhs, rhs); } }; @@ -78,7 +78,7 @@ bool less_than_struct_with_name_and_id(const T& lhs, } template <typename T, typename Func, typename Elements> -T* FindElementsRunAction(const android::StringPiece& name, Elements& entries, Func action) { +T* FindElementsRunAction(android::StringPiece name, Elements& entries, Func action) { const auto iter = std::lower_bound(entries.begin(), entries.end(), name, less_than_struct_with_name<T>); const bool found = iter != entries.end() && name == (*iter)->name; @@ -87,7 +87,7 @@ T* FindElementsRunAction(const android::StringPiece& name, Elements& entries, Fu struct ConfigKey { const ConfigDescription* config; - const StringPiece& product; + StringPiece product; }; template <typename T> @@ -104,12 +104,12 @@ bool lt_config_key_ref(const T& lhs, const ConfigKey& rhs) { ResourceTable::ResourceTable(ResourceTable::Validation validation) : validation_(validation) { } -ResourceTablePackage* ResourceTable::FindPackage(const android::StringPiece& name) const { +ResourceTablePackage* ResourceTable::FindPackage(android::StringPiece name) const { return FindElementsRunAction<ResourceTablePackage>( name, packages, [&](bool found, auto& iter) { return found ? iter->get() : nullptr; }); } -ResourceTablePackage* ResourceTable::FindOrCreatePackage(const android::StringPiece& name) { +ResourceTablePackage* ResourceTable::FindOrCreatePackage(android::StringPiece name) { return FindElementsRunAction<ResourceTablePackage>(name, packages, [&](bool found, auto& iter) { return found ? iter->get() : packages.emplace(iter, new ResourceTablePackage(name))->get(); }); @@ -139,18 +139,18 @@ ResourceTableType* ResourceTablePackage::FindOrCreateType(const ResourceNamedTyp }); } -ResourceEntry* ResourceTableType::CreateEntry(const android::StringPiece& name) { +ResourceEntry* ResourceTableType::CreateEntry(android::StringPiece name) { return FindElementsRunAction<ResourceEntry>(name, entries, [&](bool found, auto& iter) { return entries.emplace(iter, new ResourceEntry(name))->get(); }); } -ResourceEntry* ResourceTableType::FindEntry(const android::StringPiece& name) const { +ResourceEntry* ResourceTableType::FindEntry(android::StringPiece name) const { return FindElementsRunAction<ResourceEntry>( name, entries, [&](bool found, auto& iter) { return found ? iter->get() : nullptr; }); } -ResourceEntry* ResourceTableType::FindOrCreateEntry(const android::StringPiece& name) { +ResourceEntry* ResourceTableType::FindOrCreateEntry(android::StringPiece name) { return FindElementsRunAction<ResourceEntry>(name, entries, [&](bool found, auto& iter) { return found ? iter->get() : entries.emplace(iter, new ResourceEntry(name))->get(); }); @@ -183,7 +183,7 @@ const ResourceConfigValue* ResourceEntry::FindValue(const android::ConfigDescrip } ResourceConfigValue* ResourceEntry::FindOrCreateValue(const ConfigDescription& config, - const StringPiece& product) { + StringPiece product) { auto iter = std::lower_bound(values.begin(), values.end(), ConfigKey{&config, product}, lt_config_key_ref<std::unique_ptr<ResourceConfigValue>>); if (iter != values.end()) { diff --git a/tools/aapt2/ResourceTable.h b/tools/aapt2/ResourceTable.h index f49ce8147f71..bb286a8abdaa 100644 --- a/tools/aapt2/ResourceTable.h +++ b/tools/aapt2/ResourceTable.h @@ -71,12 +71,11 @@ struct StagedId { struct Overlayable { Overlayable() = default; - Overlayable(const android::StringPiece& name, const android::StringPiece& actor) - : name(name.to_string()), actor(actor.to_string()) {} - Overlayable(const android::StringPiece& name, const android::StringPiece& actor, - const android::Source& source) - : name(name.to_string()), actor(actor.to_string()), source(source) { - } + Overlayable(android::StringPiece name, android::StringPiece actor) : name(name), actor(actor) { + } + Overlayable(android::StringPiece name, android::StringPiece actor, const android::Source& source) + : name(name), actor(actor), source(source) { + } static const char* kActorScheme; std::string name; @@ -105,8 +104,9 @@ class ResourceConfigValue { // The actual Value. std::unique_ptr<Value> value; - ResourceConfigValue(const android::ConfigDescription& config, const android::StringPiece& product) - : config(config), product(product.to_string()) {} + ResourceConfigValue(const android::ConfigDescription& config, android::StringPiece product) + : config(config), product(product) { + } private: DISALLOW_COPY_AND_ASSIGN(ResourceConfigValue); @@ -136,7 +136,8 @@ class ResourceEntry { // The resource's values for each configuration. std::vector<std::unique_ptr<ResourceConfigValue>> values; - explicit ResourceEntry(const android::StringPiece& name) : name(name.to_string()) {} + explicit ResourceEntry(android::StringPiece name) : name(name) { + } ResourceConfigValue* FindValue(const android::ConfigDescription& config, android::StringPiece product = {}); @@ -144,7 +145,7 @@ class ResourceEntry { android::StringPiece product = {}) const; ResourceConfigValue* FindOrCreateValue(const android::ConfigDescription& config, - const android::StringPiece& product); + android::StringPiece product); std::vector<ResourceConfigValue*> FindAllValues(const android::ConfigDescription& config); template <typename Func> @@ -180,9 +181,9 @@ class ResourceTableType { : named_type(type.ToResourceNamedType()) { } - ResourceEntry* CreateEntry(const android::StringPiece& name); - ResourceEntry* FindEntry(const android::StringPiece& name) const; - ResourceEntry* FindOrCreateEntry(const android::StringPiece& name); + ResourceEntry* CreateEntry(android::StringPiece name); + ResourceEntry* FindEntry(android::StringPiece name) const; + ResourceEntry* FindOrCreateEntry(android::StringPiece name); private: DISALLOW_COPY_AND_ASSIGN(ResourceTableType); @@ -194,7 +195,7 @@ class ResourceTablePackage { std::vector<std::unique_ptr<ResourceTableType>> types; - explicit ResourceTablePackage(const android::StringPiece& name) : name(name.to_string()) { + explicit ResourceTablePackage(android::StringPiece name) : name(name) { } ResourceTablePackage() = default; @@ -319,8 +320,8 @@ class ResourceTable { // Returns the package struct with the given name, or nullptr if such a package does not // exist. The empty string is a valid package and typically is used to represent the // 'current' package before it is known to the ResourceTable. - ResourceTablePackage* FindPackage(const android::StringPiece& name) const; - ResourceTablePackage* FindOrCreatePackage(const android::StringPiece& name); + ResourceTablePackage* FindPackage(android::StringPiece name) const; + ResourceTablePackage* FindOrCreatePackage(android::StringPiece name); std::unique_ptr<ResourceTable> Clone() const; diff --git a/tools/aapt2/ResourceTable_test.cpp b/tools/aapt2/ResourceTable_test.cpp index 0cf84736a081..54b98d13aa0a 100644 --- a/tools/aapt2/ResourceTable_test.cpp +++ b/tools/aapt2/ResourceTable_test.cpp @@ -187,7 +187,7 @@ static StringPiece LevelToString(Visibility::Level level) { static ::testing::AssertionResult VisibilityOfResource(const ResourceTable& table, const ResourceNameRef& name, Visibility::Level level, - const StringPiece& comment) { + StringPiece comment) { std::optional<ResourceTable::SearchResult> result = table.FindResource(name); if (!result) { return ::testing::AssertionFailure() << "no resource '" << name << "' found in table"; diff --git a/tools/aapt2/ResourceUtils.cpp b/tools/aapt2/ResourceUtils.cpp index 41c7435b534d..5a118a902963 100644 --- a/tools/aapt2/ResourceUtils.cpp +++ b/tools/aapt2/ResourceUtils.cpp @@ -109,8 +109,7 @@ std::optional<ResourceName> ToResourceName(const android::AssetManager2::Resourc return name_out; } -bool ParseResourceName(const StringPiece& str, ResourceNameRef* out_ref, - bool* out_private) { +bool ParseResourceName(StringPiece str, ResourceNameRef* out_ref, bool* out_private) { if (str.empty()) { return false; } @@ -151,8 +150,8 @@ bool ParseResourceName(const StringPiece& str, ResourceNameRef* out_ref, return true; } -bool ParseReference(const StringPiece& str, ResourceNameRef* out_ref, - bool* out_create, bool* out_private) { +bool ParseReference(StringPiece str, ResourceNameRef* out_ref, bool* out_create, + bool* out_private) { StringPiece trimmed_str(util::TrimWhitespace(str)); if (trimmed_str.empty()) { return false; @@ -198,11 +197,11 @@ bool ParseReference(const StringPiece& str, ResourceNameRef* out_ref, return false; } -bool IsReference(const StringPiece& str) { +bool IsReference(StringPiece str) { return ParseReference(str, nullptr, nullptr, nullptr); } -bool ParseAttributeReference(const StringPiece& str, ResourceNameRef* out_ref) { +bool ParseAttributeReference(StringPiece str, ResourceNameRef* out_ref) { StringPiece trimmed_str(util::TrimWhitespace(str)); if (trimmed_str.empty()) { return false; @@ -235,7 +234,7 @@ bool ParseAttributeReference(const StringPiece& str, ResourceNameRef* out_ref) { return false; } -bool IsAttributeReference(const StringPiece& str) { +bool IsAttributeReference(StringPiece str) { return ParseAttributeReference(str, nullptr); } @@ -247,7 +246,7 @@ bool IsAttributeReference(const StringPiece& str) { * <[*]package>:[style/]<entry> * [[*]package:style/]<entry> */ -std::optional<Reference> ParseStyleParentReference(const StringPiece& str, std::string* out_error) { +std::optional<Reference> ParseStyleParentReference(StringPiece str, std::string* out_error) { if (str.empty()) { return {}; } @@ -296,7 +295,7 @@ std::optional<Reference> ParseStyleParentReference(const StringPiece& str, std:: return result; } -std::optional<Reference> ParseXmlAttributeName(const StringPiece& str) { +std::optional<Reference> ParseXmlAttributeName(StringPiece str) { StringPiece trimmed_str = util::TrimWhitespace(str); const char* start = trimmed_str.data(); const char* const end = start + trimmed_str.size(); @@ -325,8 +324,7 @@ std::optional<Reference> ParseXmlAttributeName(const StringPiece& str) { return std::optional<Reference>(std::move(ref)); } -std::unique_ptr<Reference> TryParseReference(const StringPiece& str, - bool* out_create) { +std::unique_ptr<Reference> TryParseReference(StringPiece str, bool* out_create) { ResourceNameRef ref; bool private_ref = false; if (ParseReference(str, &ref, out_create, &private_ref)) { @@ -344,7 +342,7 @@ std::unique_ptr<Reference> TryParseReference(const StringPiece& str, return {}; } -std::unique_ptr<Item> TryParseNullOrEmpty(const StringPiece& str) { +std::unique_ptr<Item> TryParseNullOrEmpty(StringPiece str) { const StringPiece trimmed_str(util::TrimWhitespace(str)); if (trimmed_str == "@null") { return MakeNull(); @@ -365,8 +363,7 @@ std::unique_ptr<BinaryPrimitive> MakeEmpty() { android::Res_value::DATA_NULL_EMPTY); } -std::unique_ptr<BinaryPrimitive> TryParseEnumSymbol(const Attribute* enum_attr, - const StringPiece& str) { +std::unique_ptr<BinaryPrimitive> TryParseEnumSymbol(const Attribute* enum_attr, StringPiece str) { StringPiece trimmed_str(util::TrimWhitespace(str)); for (const Attribute::Symbol& symbol : enum_attr->symbols) { // Enum symbols are stored as @package:id/symbol resources, @@ -382,8 +379,7 @@ std::unique_ptr<BinaryPrimitive> TryParseEnumSymbol(const Attribute* enum_attr, return {}; } -std::unique_ptr<BinaryPrimitive> TryParseFlagSymbol(const Attribute* flag_attr, - const StringPiece& str) { +std::unique_ptr<BinaryPrimitive> TryParseFlagSymbol(const Attribute* flag_attr, StringPiece str) { android::Res_value flags = {}; flags.dataType = android::Res_value::TYPE_INT_HEX; flags.data = 0u; @@ -393,7 +389,7 @@ std::unique_ptr<BinaryPrimitive> TryParseFlagSymbol(const Attribute* flag_attr, return util::make_unique<BinaryPrimitive>(flags); } - for (const StringPiece& part : util::Tokenize(str, '|')) { + for (StringPiece part : util::Tokenize(str, '|')) { StringPiece trimmed_part = util::TrimWhitespace(part); bool flag_set = false; @@ -429,7 +425,7 @@ static uint32_t ParseHex(char c, bool* out_error) { } } -std::unique_ptr<BinaryPrimitive> TryParseColor(const StringPiece& str) { +std::unique_ptr<BinaryPrimitive> TryParseColor(StringPiece str) { StringPiece color_str(util::TrimWhitespace(str)); const char* start = color_str.data(); const size_t len = color_str.size(); @@ -484,7 +480,7 @@ std::unique_ptr<BinaryPrimitive> TryParseColor(const StringPiece& str) { : util::make_unique<BinaryPrimitive>(value); } -std::optional<bool> ParseBool(const StringPiece& str) { +std::optional<bool> ParseBool(StringPiece str) { StringPiece trimmed_str(util::TrimWhitespace(str)); if (trimmed_str == "true" || trimmed_str == "TRUE" || trimmed_str == "True") { return std::optional<bool>(true); @@ -495,7 +491,7 @@ std::optional<bool> ParseBool(const StringPiece& str) { return {}; } -std::optional<uint32_t> ParseInt(const StringPiece& str) { +std::optional<uint32_t> ParseInt(StringPiece str) { std::u16string str16 = android::util::Utf8ToUtf16(str); android::Res_value value; if (android::ResTable::stringToInt(str16.data(), str16.size(), &value)) { @@ -504,7 +500,7 @@ std::optional<uint32_t> ParseInt(const StringPiece& str) { return {}; } -std::optional<ResourceId> ParseResourceId(const StringPiece& str) { +std::optional<ResourceId> ParseResourceId(StringPiece str) { StringPiece trimmed_str(util::TrimWhitespace(str)); std::u16string str16 = android::util::Utf8ToUtf16(trimmed_str); @@ -520,7 +516,7 @@ std::optional<ResourceId> ParseResourceId(const StringPiece& str) { return {}; } -std::optional<int> ParseSdkVersion(const StringPiece& str) { +std::optional<int> ParseSdkVersion(StringPiece str) { StringPiece trimmed_str(util::TrimWhitespace(str)); std::u16string str16 = android::util::Utf8ToUtf16(trimmed_str); @@ -539,14 +535,14 @@ std::optional<int> ParseSdkVersion(const StringPiece& str) { const StringPiece::const_iterator begin = std::begin(trimmed_str); const StringPiece::const_iterator end = std::end(trimmed_str); const StringPiece::const_iterator codename_end = std::find(begin, end, '.'); - entry = GetDevelopmentSdkCodeNameVersion(trimmed_str.substr(begin, codename_end)); + entry = GetDevelopmentSdkCodeNameVersion(StringPiece(begin, codename_end - begin)); if (entry) { return entry.value(); } return {}; } -std::unique_ptr<BinaryPrimitive> TryParseBool(const StringPiece& str) { +std::unique_ptr<BinaryPrimitive> TryParseBool(StringPiece str) { if (std::optional<bool> maybe_result = ParseBool(str)) { const uint32_t data = maybe_result.value() ? 0xffffffffu : 0u; return util::make_unique<BinaryPrimitive>(android::Res_value::TYPE_INT_BOOLEAN, data); @@ -559,7 +555,7 @@ std::unique_ptr<BinaryPrimitive> MakeBool(bool val) { val ? 0xffffffffu : 0u); } -std::unique_ptr<BinaryPrimitive> TryParseInt(const StringPiece& str) { +std::unique_ptr<BinaryPrimitive> TryParseInt(StringPiece str) { std::u16string str16 = android::util::Utf8ToUtf16(util::TrimWhitespace(str)); android::Res_value value; if (!android::ResTable::stringToInt(str16.data(), str16.size(), &value)) { @@ -572,7 +568,7 @@ std::unique_ptr<BinaryPrimitive> MakeInt(uint32_t val) { return util::make_unique<BinaryPrimitive>(android::Res_value::TYPE_INT_DEC, val); } -std::unique_ptr<BinaryPrimitive> TryParseFloat(const StringPiece& str) { +std::unique_ptr<BinaryPrimitive> TryParseFloat(StringPiece str) { std::u16string str16 = android::util::Utf8ToUtf16(util::TrimWhitespace(str)); android::Res_value value; if (!android::ResTable::stringToFloat(str16.data(), str16.size(), &value)) { @@ -623,7 +619,7 @@ uint32_t AndroidTypeToAttributeTypeMask(uint16_t type) { } std::unique_ptr<Item> TryParseItemForAttribute( - const StringPiece& value, uint32_t type_mask, + StringPiece value, uint32_t type_mask, const std::function<bool(const ResourceName&)>& on_create_reference) { using android::ResTable_map; @@ -687,7 +683,7 @@ std::unique_ptr<Item> TryParseItemForAttribute( * allows. */ std::unique_ptr<Item> TryParseItemForAttribute( - const StringPiece& str, const Attribute* attr, + StringPiece str, const Attribute* attr, const std::function<bool(const ResourceName&)>& on_create_reference) { using android::ResTable_map; diff --git a/tools/aapt2/ResourceUtils.h b/tools/aapt2/ResourceUtils.h index 22cf3459809d..f30f4acfec7a 100644 --- a/tools/aapt2/ResourceUtils.h +++ b/tools/aapt2/ResourceUtils.h @@ -38,7 +38,7 @@ namespace ResourceUtils { * `out_resource` set to the parsed resource name and `out_private` set to true * if a '*' prefix was present. */ -bool ParseResourceName(const android::StringPiece& str, ResourceNameRef* out_resource, +bool ParseResourceName(android::StringPiece str, ResourceNameRef* out_resource, bool* out_private = nullptr); /* @@ -49,27 +49,27 @@ bool ParseResourceName(const android::StringPiece& str, ResourceNameRef* out_res * If '+' was present in the reference, `out_create` is set to true. * If '*' was present in the reference, `out_private` is set to true. */ -bool ParseReference(const android::StringPiece& str, ResourceNameRef* out_reference, +bool ParseReference(android::StringPiece str, ResourceNameRef* out_reference, bool* out_create = nullptr, bool* out_private = nullptr); /* * Returns true if the string is in the form of a resource reference * (@[+][package:]type/name). */ -bool IsReference(const android::StringPiece& str); +bool IsReference(android::StringPiece str); /* * Returns true if the string was parsed as an attribute reference * (?[package:][type/]name), * with `out_reference` set to the parsed reference. */ -bool ParseAttributeReference(const android::StringPiece& str, ResourceNameRef* out_reference); +bool ParseAttributeReference(android::StringPiece str, ResourceNameRef* out_reference); /** * Returns true if the string is in the form of an attribute * reference(?[package:][type/]name). */ -bool IsAttributeReference(const android::StringPiece& str); +bool IsAttributeReference(android::StringPiece str); /** * Convert an android::ResTable::resource_name to an aapt::ResourceName struct. @@ -85,22 +85,22 @@ std::optional<ResourceName> ToResourceName(const android::AssetManager2::Resourc * Returns a boolean value if the string is equal to TRUE, true, True, FALSE, * false, or False. */ -std::optional<bool> ParseBool(const android::StringPiece& str); +std::optional<bool> ParseBool(android::StringPiece str); /** * Returns a uint32_t if the string is an integer. */ -std::optional<uint32_t> ParseInt(const android::StringPiece& str); +std::optional<uint32_t> ParseInt(android::StringPiece str); /** * Returns an ID if it the string represented a valid ID. */ -std::optional<ResourceId> ParseResourceId(const android::StringPiece& str); +std::optional<ResourceId> ParseResourceId(android::StringPiece str); /** * Parses an SDK version, which can be an integer, or a letter from A-Z. */ -std::optional<int> ParseSdkVersion(const android::StringPiece& str); +std::optional<int> ParseSdkVersion(android::StringPiece str); /* * Returns a Reference, or None Maybe instance if the string `str` was parsed as @@ -113,7 +113,7 @@ std::optional<int> ParseSdkVersion(const android::StringPiece& str); * ?[package:]style/<entry> or * <package>:[style/]<entry> */ -std::optional<Reference> ParseStyleParentReference(const android::StringPiece& str, +std::optional<Reference> ParseStyleParentReference(android::StringPiece str, std::string* out_error); /* @@ -123,7 +123,7 @@ std::optional<Reference> ParseStyleParentReference(const android::StringPiece& s * * package:entry */ -std::optional<Reference> ParseXmlAttributeName(const android::StringPiece& str); +std::optional<Reference> ParseXmlAttributeName(android::StringPiece str); /* * Returns a Reference object if the string was parsed as a resource or @@ -132,14 +132,13 @@ std::optional<Reference> ParseXmlAttributeName(const android::StringPiece& str); * if * the '+' was present in the string. */ -std::unique_ptr<Reference> TryParseReference(const android::StringPiece& str, - bool* out_create = nullptr); +std::unique_ptr<Reference> TryParseReference(android::StringPiece str, bool* out_create = nullptr); /* * Returns a BinaryPrimitve object representing @null or @empty if the string * was parsed as one. */ -std::unique_ptr<Item> TryParseNullOrEmpty(const android::StringPiece& str); +std::unique_ptr<Item> TryParseNullOrEmpty(android::StringPiece str); // Returns a Reference representing @null. // Due to runtime compatibility issues, this is encoded as a reference with ID 0. @@ -154,13 +153,13 @@ std::unique_ptr<BinaryPrimitive> MakeEmpty(); * Returns a BinaryPrimitve object representing a color if the string was parsed * as one. */ -std::unique_ptr<BinaryPrimitive> TryParseColor(const android::StringPiece& str); +std::unique_ptr<BinaryPrimitive> TryParseColor(android::StringPiece str); /* * Returns a BinaryPrimitve object representing a boolean if the string was * parsed as one. */ -std::unique_ptr<BinaryPrimitive> TryParseBool(const android::StringPiece& str); +std::unique_ptr<BinaryPrimitive> TryParseBool(android::StringPiece str); // Returns a boolean BinaryPrimitive. std::unique_ptr<BinaryPrimitive> MakeBool(bool val); @@ -169,7 +168,7 @@ std::unique_ptr<BinaryPrimitive> MakeBool(bool val); * Returns a BinaryPrimitve object representing an integer if the string was * parsed as one. */ -std::unique_ptr<BinaryPrimitive> TryParseInt(const android::StringPiece& str); +std::unique_ptr<BinaryPrimitive> TryParseInt(android::StringPiece str); // Returns an integer BinaryPrimitive. std::unique_ptr<BinaryPrimitive> MakeInt(uint32_t value); @@ -178,21 +177,21 @@ std::unique_ptr<BinaryPrimitive> MakeInt(uint32_t value); * Returns a BinaryPrimitve object representing a floating point number * (float, dimension, etc) if the string was parsed as one. */ -std::unique_ptr<BinaryPrimitive> TryParseFloat(const android::StringPiece& str); +std::unique_ptr<BinaryPrimitive> TryParseFloat(android::StringPiece str); /* * Returns a BinaryPrimitve object representing an enum symbol if the string was * parsed as one. */ std::unique_ptr<BinaryPrimitive> TryParseEnumSymbol(const Attribute* enum_attr, - const android::StringPiece& str); + android::StringPiece str); /* * Returns a BinaryPrimitve object representing a flag symbol if the string was * parsed as one. */ std::unique_ptr<BinaryPrimitive> TryParseFlagSymbol(const Attribute* enum_attr, - const android::StringPiece& str); + android::StringPiece str); /* * Try to convert a string to an Item for the given attribute. The attribute * will @@ -201,11 +200,11 @@ std::unique_ptr<BinaryPrimitive> TryParseFlagSymbol(const Attribute* enum_attr, * reference to an ID that must be created (@+id/foo). */ std::unique_ptr<Item> TryParseItemForAttribute( - const android::StringPiece& value, const Attribute* attr, + android::StringPiece value, const Attribute* attr, const std::function<bool(const ResourceName&)>& on_create_reference = {}); std::unique_ptr<Item> TryParseItemForAttribute( - const android::StringPiece& value, uint32_t type_mask, + android::StringPiece value, uint32_t type_mask, const std::function<bool(const ResourceName&)>& on_create_reference = {}); uint32_t AndroidTypeToAttributeTypeMask(uint16_t type); diff --git a/tools/aapt2/ResourceValues.cpp b/tools/aapt2/ResourceValues.cpp index c4d54be01efe..a5754e0d168f 100644 --- a/tools/aapt2/ResourceValues.cpp +++ b/tools/aapt2/ResourceValues.cpp @@ -206,7 +206,7 @@ void Reference::PrettyPrint(Printer* printer) const { PrettyPrintReferenceImpl(*this, true /*print_package*/, printer); } -void Reference::PrettyPrint(const StringPiece& package, Printer* printer) const { +void Reference::PrettyPrint(StringPiece package, Printer* printer) const { const bool print_package = name ? package != name.value().package : true; PrettyPrintReferenceImpl(*this, print_package, printer); } diff --git a/tools/aapt2/ResourceValues.h b/tools/aapt2/ResourceValues.h index f5167a1ac8e6..6f9dccbd3bcc 100644 --- a/tools/aapt2/ResourceValues.h +++ b/tools/aapt2/ResourceValues.h @@ -83,8 +83,8 @@ class Value { return comment_; } - void SetComment(const android::StringPiece& str) { - comment_ = str.to_string(); + void SetComment(android::StringPiece str) { + comment_.assign(str); } void SetComment(std::string&& str) { @@ -176,7 +176,7 @@ struct Reference : public TransformableItem<Reference, BaseItem<Reference>> { void PrettyPrint(text::Printer* printer) const override; // Prints the reference without a package name if the package name matches the one given. - void PrettyPrint(const android::StringPiece& package, text::Printer* printer) const; + void PrettyPrint(android::StringPiece package, text::Printer* printer) const; }; bool operator<(const Reference&, const Reference&); diff --git a/tools/aapt2/SdkConstants.cpp b/tools/aapt2/SdkConstants.cpp index 34e8edb0a47f..a7c5479b56fd 100644 --- a/tools/aapt2/SdkConstants.cpp +++ b/tools/aapt2/SdkConstants.cpp @@ -77,7 +77,7 @@ ApiVersion FindAttributeSdkLevel(const ResourceId& id) { return iter->second; } -std::optional<ApiVersion> GetDevelopmentSdkCodeNameVersion(const StringPiece& code_name) { +std::optional<ApiVersion> GetDevelopmentSdkCodeNameVersion(StringPiece code_name) { return (sDevelopmentSdkCodeNames.find(code_name) == sDevelopmentSdkCodeNames.end()) ? std::optional<ApiVersion>() : sDevelopmentSdkLevel; diff --git a/tools/aapt2/SdkConstants.h b/tools/aapt2/SdkConstants.h index 0bd61c04f2b2..40bcef787815 100644 --- a/tools/aapt2/SdkConstants.h +++ b/tools/aapt2/SdkConstants.h @@ -63,7 +63,7 @@ enum : ApiVersion { }; ApiVersion FindAttributeSdkLevel(const ResourceId& id); -std::optional<ApiVersion> GetDevelopmentSdkCodeNameVersion(const android::StringPiece& code_name); +std::optional<ApiVersion> GetDevelopmentSdkCodeNameVersion(android::StringPiece code_name); } // namespace aapt diff --git a/tools/aapt2/cmd/ApkInfo.cpp b/tools/aapt2/cmd/ApkInfo.cpp index 697b110443fd..3c0831c7ec0d 100644 --- a/tools/aapt2/cmd/ApkInfo.cpp +++ b/tools/aapt2/cmd/ApkInfo.cpp @@ -64,7 +64,7 @@ int ApkInfoCommand::Action(const std::vector<std::string>& args) { Usage(&std::cerr); return 1; } - const StringPiece& path = args[0]; + StringPiece path = args[0]; std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(path, diag_); if (!apk) { return 1; diff --git a/tools/aapt2/cmd/Command.cpp b/tools/aapt2/cmd/Command.cpp index b1452fad0e8f..514651e92c27 100644 --- a/tools/aapt2/cmd/Command.cpp +++ b/tools/aapt2/cmd/Command.cpp @@ -33,7 +33,7 @@ using android::StringPiece; namespace aapt { -std::string GetSafePath(const StringPiece& arg) { +std::string GetSafePath(StringPiece arg) { #ifdef _WIN32 // If the path exceeds the maximum path length for Windows, encode the path using the // extended-length prefix @@ -47,63 +47,62 @@ std::string GetSafePath(const StringPiece& arg) { return path8; #else - return arg.to_string(); + return std::string(arg); #endif } -void Command::AddRequiredFlag(const StringPiece& name, const StringPiece& description, - std::string* value, uint32_t flags) { - auto func = [value, flags](const StringPiece& arg) -> bool { - *value = (flags & Command::kPath) ? GetSafePath(arg) : arg.to_string(); +void Command::AddRequiredFlag(StringPiece name, StringPiece description, std::string* value, + uint32_t flags) { + auto func = [value, flags](StringPiece arg) -> bool { + *value = (flags & Command::kPath) ? GetSafePath(arg) : std::string(arg); return true; }; flags_.emplace_back(Flag(name, description, /* required */ true, /* num_args */ 1, func)); } -void Command::AddRequiredFlagList(const StringPiece& name, const StringPiece& description, +void Command::AddRequiredFlagList(StringPiece name, StringPiece description, std::vector<std::string>* value, uint32_t flags) { - auto func = [value, flags](const StringPiece& arg) -> bool { - value->push_back((flags & Command::kPath) ? GetSafePath(arg) : arg.to_string()); + auto func = [value, flags](StringPiece arg) -> bool { + value->push_back((flags & Command::kPath) ? GetSafePath(arg) : std::string(arg)); return true; }; flags_.emplace_back(Flag(name, description, /* required */ true, /* num_args */ 1, func)); } -void Command::AddOptionalFlag(const StringPiece& name, const StringPiece& description, +void Command::AddOptionalFlag(StringPiece name, StringPiece description, std::optional<std::string>* value, uint32_t flags) { - auto func = [value, flags](const StringPiece& arg) -> bool { - *value = (flags & Command::kPath) ? GetSafePath(arg) : arg.to_string(); + auto func = [value, flags](StringPiece arg) -> bool { + *value = (flags & Command::kPath) ? GetSafePath(arg) : std::string(arg); return true; }; flags_.emplace_back(Flag(name, description, /* required */ false, /* num_args */ 1, func)); } -void Command::AddOptionalFlagList(const StringPiece& name, const StringPiece& description, +void Command::AddOptionalFlagList(StringPiece name, StringPiece description, std::vector<std::string>* value, uint32_t flags) { - auto func = [value, flags](const StringPiece& arg) -> bool { - value->push_back((flags & Command::kPath) ? GetSafePath(arg) : arg.to_string()); + auto func = [value, flags](StringPiece arg) -> bool { + value->push_back((flags & Command::kPath) ? GetSafePath(arg) : std::string(arg)); return true; }; flags_.emplace_back(Flag(name, description, /* required */ false, /* num_args */ 1, func)); } -void Command::AddOptionalFlagList(const StringPiece& name, const StringPiece& description, +void Command::AddOptionalFlagList(StringPiece name, StringPiece description, std::unordered_set<std::string>* value) { - auto func = [value](const StringPiece& arg) -> bool { - value->insert(arg.to_string()); + auto func = [value](StringPiece arg) -> bool { + value->emplace(arg); return true; }; flags_.emplace_back(Flag(name, description, /* required */ false, /* num_args */ 1, func)); } -void Command::AddOptionalSwitch(const StringPiece& name, const StringPiece& description, - bool* value) { - auto func = [value](const StringPiece& arg) -> bool { +void Command::AddOptionalSwitch(StringPiece name, StringPiece description, bool* value) { + auto func = [value](StringPiece arg) -> bool { *value = true; return true; }; @@ -120,8 +119,8 @@ void Command::AddOptionalSubcommand(std::unique_ptr<Command>&& subcommand, bool } } -void Command::SetDescription(const StringPiece& description) { - description_ = description.to_string(); +void Command::SetDescription(StringPiece description) { + description_ = std::string(description); } void Command::Usage(std::ostream* out) { @@ -183,7 +182,7 @@ int Command::Execute(const std::vector<StringPiece>& args, std::ostream* out_err std::vector<std::string> file_args; for (size_t i = 0; i < args.size(); i++) { - const StringPiece& arg = args[i]; + StringPiece arg = args[i]; if (*(arg.data()) != '-') { // Continue parsing as the subcommand if the first argument matches one of the subcommands if (i == 0) { diff --git a/tools/aapt2/cmd/Command.h b/tools/aapt2/cmd/Command.h index 8678cda59856..1416e980ed19 100644 --- a/tools/aapt2/cmd/Command.h +++ b/tools/aapt2/cmd/Command.h @@ -30,13 +30,10 @@ namespace aapt { class Command { public: - explicit Command(const android::StringPiece& name) - : name_(name.to_string()), full_subcommand_name_(name.to_string()){}; + explicit Command(android::StringPiece name) : name_(name), full_subcommand_name_(name){}; - explicit Command(const android::StringPiece& name, const android::StringPiece& short_name) - : name_(name.to_string()), - short_name_(short_name.to_string()), - full_subcommand_name_(name.to_string()){}; + explicit Command(android::StringPiece name, android::StringPiece short_name) + : name_(name), short_name_(short_name), full_subcommand_name_(name){}; Command(Command&&) = default; Command& operator=(Command&&) = default; @@ -52,30 +49,26 @@ class Command { kPath = 1 << 0, }; - void AddRequiredFlag(const android::StringPiece& name, const android::StringPiece& description, + void AddRequiredFlag(android::StringPiece name, android::StringPiece description, std::string* value, uint32_t flags = 0); - void AddRequiredFlagList(const android::StringPiece& name, - const android::StringPiece& description, std::vector<std::string>* value, - uint32_t flags = 0); + void AddRequiredFlagList(android::StringPiece name, android::StringPiece description, + std::vector<std::string>* value, uint32_t flags = 0); - void AddOptionalFlag(const android::StringPiece& name, const android::StringPiece& description, + void AddOptionalFlag(android::StringPiece name, android::StringPiece description, std::optional<std::string>* value, uint32_t flags = 0); - void AddOptionalFlagList(const android::StringPiece& name, - const android::StringPiece& description, std::vector<std::string>* value, - uint32_t flags = 0); + void AddOptionalFlagList(android::StringPiece name, android::StringPiece description, + std::vector<std::string>* value, uint32_t flags = 0); - void AddOptionalFlagList(const android::StringPiece& name, - const android::StringPiece& description, + void AddOptionalFlagList(android::StringPiece name, android::StringPiece description, std::unordered_set<std::string>* value); - void AddOptionalSwitch(const android::StringPiece& name, const android::StringPiece& description, - bool* value); + void AddOptionalSwitch(android::StringPiece name, android::StringPiece description, bool* value); void AddOptionalSubcommand(std::unique_ptr<Command>&& subcommand, bool experimental = false); - void SetDescription(const android::StringPiece& name); + void SetDescription(android::StringPiece name); // Prints the help menu of the command. void Usage(std::ostream* out); @@ -90,17 +83,21 @@ class Command { private: struct Flag { - explicit Flag(const android::StringPiece& name, const android::StringPiece& description, + explicit Flag(android::StringPiece name, android::StringPiece description, const bool is_required, const size_t num_args, - std::function<bool(const android::StringPiece& value)>&& action) - : name(name.to_string()), description(description.to_string()), is_required(is_required), - num_args(num_args), action(std::move(action)) {} + std::function<bool(android::StringPiece value)>&& action) + : name(name), + description(description), + is_required(is_required), + num_args(num_args), + action(std::move(action)) { + } const std::string name; const std::string description; const bool is_required; const size_t num_args; - const std::function<bool(const android::StringPiece& value)> action; + const std::function<bool(android::StringPiece value)> action; bool found = false; }; diff --git a/tools/aapt2/cmd/Compile.cpp b/tools/aapt2/cmd/Compile.cpp index 0409f7391f79..03f9715fb265 100644 --- a/tools/aapt2/cmd/Compile.cpp +++ b/tools/aapt2/cmd/Compile.cpp @@ -125,8 +125,12 @@ static std::optional<ResourcePathData> ExtractResourcePathData(const std::string const android::Source res_path = options.source_path ? StringPiece(options.source_path.value()) : StringPiece(path); - return ResourcePathData{res_path, dir_str.to_string(), name.to_string(), - extension.to_string(), config_str.to_string(), config}; + return ResourcePathData{res_path, + std::string(dir_str), + std::string(name), + std::string(extension), + std::string(config_str), + config}; } static std::string BuildIntermediateContainerFilename(const ResourcePathData& data) { @@ -279,7 +283,7 @@ static bool CompileTable(IAaptContext* context, const CompileOptions& options, return true; } -static bool WriteHeaderAndDataToWriter(const StringPiece& output_path, const ResourceFile& file, +static bool WriteHeaderAndDataToWriter(StringPiece output_path, const ResourceFile& file, io::KnownSizeInputStream* in, IArchiveWriter* writer, android::IDiagnostics* diag) { TRACE_CALL(); @@ -311,7 +315,7 @@ static bool WriteHeaderAndDataToWriter(const StringPiece& output_path, const Res return true; } -static bool FlattenXmlToOutStream(const StringPiece& output_path, const xml::XmlResource& xmlres, +static bool FlattenXmlToOutStream(StringPiece output_path, const xml::XmlResource& xmlres, ContainerWriter* container_writer, android::IDiagnostics* diag) { pb::internal::CompiledFile pb_compiled_file; SerializeCompiledFileToPb(xmlres.file, &pb_compiled_file); @@ -538,7 +542,7 @@ static bool CompilePng(IAaptContext* context, const CompileOptions& options, if (context->IsVerbose()) { // For debugging only, use the legacy PNG cruncher and compare the resulting file sizes. // This will help catch exotic cases where the new code may generate larger PNGs. - std::stringstream legacy_stream(content.to_string()); + std::stringstream legacy_stream{std::string(content)}; android::BigBuffer legacy_buffer(4096); Png png(context->GetDiagnostics()); if (!png.process(path_data.source, &legacy_stream, &legacy_buffer, {})) { diff --git a/tools/aapt2/cmd/Convert.cpp b/tools/aapt2/cmd/Convert.cpp index 52e113e0dbdc..612e3a630013 100644 --- a/tools/aapt2/cmd/Convert.cpp +++ b/tools/aapt2/cmd/Convert.cpp @@ -387,7 +387,7 @@ int ConvertCommand::Action(const std::vector<std::string>& args) { } Context context; - const StringPiece& path = args[0]; + StringPiece path = args[0]; unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(path, context.GetDiagnostics()); if (apk == nullptr) { context.GetDiagnostics()->Error(android::DiagMessage(path) << "failed to load APK"); diff --git a/tools/aapt2/cmd/Diff.cpp b/tools/aapt2/cmd/Diff.cpp index 423e939398d7..5bfc73233bfe 100644 --- a/tools/aapt2/cmd/Diff.cpp +++ b/tools/aapt2/cmd/Diff.cpp @@ -78,7 +78,7 @@ class DiffContext : public IAaptContext { SymbolTable symbol_table_; }; -static void EmitDiffLine(const android::Source& source, const StringPiece& message) { +static void EmitDiffLine(const android::Source& source, StringPiece message) { std::cerr << source << ": " << message << "\n"; } diff --git a/tools/aapt2/cmd/Link.cpp b/tools/aapt2/cmd/Link.cpp index a8d229956b73..97404fc69af2 100644 --- a/tools/aapt2/cmd/Link.cpp +++ b/tools/aapt2/cmd/Link.cpp @@ -126,8 +126,8 @@ class LinkContext : public IAaptContext { return compilation_package_; } - void SetCompilationPackage(const StringPiece& package_name) { - compilation_package_ = package_name.to_string(); + void SetCompilationPackage(StringPiece package_name) { + compilation_package_ = std::string(package_name); } uint8_t GetPackageId() override { @@ -240,9 +240,9 @@ class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate { IAaptContext* context_; }; -static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res, - const StringPiece& path, bool keep_raw_values, bool utf16, - OutputFormat format, IArchiveWriter* writer) { +static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res, StringPiece path, + bool keep_raw_values, bool utf16, OutputFormat format, + IArchiveWriter* writer) { TRACE_CALL(); if (context->IsVerbose()) { context->GetDiagnostics()->Note(android::DiagMessage(path) @@ -262,8 +262,8 @@ static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res, } io::BigBufferInputStream input_stream(&buffer); - return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(), - ArchiveEntry::kCompress, writer); + return io::CopyInputStreamToArchive(context, &input_stream, path, ArchiveEntry::kCompress, + writer); } break; case OutputFormat::kProto: { @@ -272,8 +272,7 @@ static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res, SerializeXmlOptions options; options.remove_empty_text_nodes = (path == kAndroidManifestPath); SerializeXmlResourceToPb(xml_res, &pb_node); - return io::CopyProtoToArchive(context, &pb_node, path.to_string(), ArchiveEntry::kCompress, - writer); + return io::CopyProtoToArchive(context, &pb_node, path, ArchiveEntry::kCompress, writer); } break; } return false; @@ -329,13 +328,13 @@ struct R { }; template <typename T> -uint32_t GetCompressionFlags(const StringPiece& str, T options) { +uint32_t GetCompressionFlags(StringPiece str, T options) { if (options.do_not_compress_anything) { return 0; } - if (options.regex_to_not_compress - && std::regex_search(str.to_string(), options.regex_to_not_compress.value())) { + if (options.regex_to_not_compress && + std::regex_search(str.begin(), str.end(), options.regex_to_not_compress.value())) { return 0; } @@ -1176,7 +1175,7 @@ class Linker { return bcp47tag; } - std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) { + std::unique_ptr<IArchiveWriter> MakeArchiveWriter(StringPiece out) { if (options_.output_to_directory) { return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out); } else { @@ -1212,8 +1211,8 @@ class Linker { return false; } - bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate, - const StringPiece& out_package, const JavaClassGeneratorOptions& java_options, + bool WriteJavaFile(ResourceTable* table, StringPiece package_name_to_generate, + StringPiece out_package, const JavaClassGeneratorOptions& java_options, const std::optional<std::string>& out_text_symbols_path = {}) { if (!options_.generate_java_class_path && !out_text_symbols_path) { return true; @@ -2473,14 +2472,14 @@ int LinkCommand::Action(const std::vector<std::string>& args) { for (std::string& extra_package : extra_java_packages_) { // A given package can actually be a colon separated list of packages. for (StringPiece package : util::Split(extra_package, ':')) { - options_.extra_java_packages.insert(package.to_string()); + options_.extra_java_packages.emplace(package); } } if (product_list_) { for (StringPiece product : util::Tokenize(product_list_.value(), ',')) { if (product != "" && product != "default") { - options_.products.insert(product.to_string()); + options_.products.emplace(product); } } } diff --git a/tools/aapt2/cmd/Optimize.cpp b/tools/aapt2/cmd/Optimize.cpp index 042926c1943a..9c1a2f6854ff 100644 --- a/tools/aapt2/cmd/Optimize.cpp +++ b/tools/aapt2/cmd/Optimize.cpp @@ -370,8 +370,8 @@ int OptimizeCommand::Action(const std::vector<std::string>& args) { if (!kept_artifacts_.empty()) { for (const std::string& artifact_str : kept_artifacts_) { - for (const StringPiece& artifact : util::Tokenize(artifact_str, ',')) { - options_.kept_artifacts.insert(artifact.to_string()); + for (StringPiece artifact : util::Tokenize(artifact_str, ',')) { + options_.kept_artifacts.emplace(artifact); } } } @@ -403,7 +403,7 @@ int OptimizeCommand::Action(const std::vector<std::string>& args) { if (target_densities_) { // Parse the target screen densities. - for (const StringPiece& config_str : util::Tokenize(target_densities_.value(), ',')) { + for (StringPiece config_str : util::Tokenize(target_densities_.value(), ',')) { std::optional<uint16_t> target_density = ParseTargetDensityParameter(config_str, diag); if (!target_density) { return 1; diff --git a/tools/aapt2/cmd/Util.cpp b/tools/aapt2/cmd/Util.cpp index 56e2f5243e96..92849cf02d48 100644 --- a/tools/aapt2/cmd/Util.cpp +++ b/tools/aapt2/cmd/Util.cpp @@ -34,8 +34,7 @@ using ::android::base::StringPrintf; namespace aapt { -std::optional<uint16_t> ParseTargetDensityParameter(const StringPiece& arg, - android::IDiagnostics* diag) { +std::optional<uint16_t> ParseTargetDensityParameter(StringPiece arg, android::IDiagnostics* diag) { ConfigDescription preferred_density_config; if (!ConfigDescription::Parse(arg, &preferred_density_config)) { diag->Error(android::DiagMessage() @@ -55,7 +54,7 @@ std::optional<uint16_t> ParseTargetDensityParameter(const StringPiece& arg, return preferred_density_config.density; } -bool ParseSplitParameter(const StringPiece& arg, android::IDiagnostics* diag, std::string* out_path, +bool ParseSplitParameter(StringPiece arg, android::IDiagnostics* diag, std::string* out_path, SplitConstraints* out_split) { CHECK(diag != nullptr); CHECK(out_path != nullptr); @@ -77,7 +76,7 @@ bool ParseSplitParameter(const StringPiece& arg, android::IDiagnostics* diag, st *out_path = parts[0]; out_split->name = parts[1]; - for (const StringPiece& config_str : util::Tokenize(parts[1], ',')) { + for (StringPiece config_str : util::Tokenize(parts[1], ',')) { ConfigDescription config; if (!ConfigDescription::Parse(config_str, &config)) { diag->Error(android::DiagMessage() @@ -93,7 +92,7 @@ std::unique_ptr<IConfigFilter> ParseConfigFilterParameters(const std::vector<std android::IDiagnostics* diag) { std::unique_ptr<AxisConfigFilter> filter = util::make_unique<AxisConfigFilter>(); for (const std::string& config_arg : args) { - for (const StringPiece& config_str : util::Tokenize(config_arg, ',')) { + for (StringPiece config_str : util::Tokenize(config_arg, ',')) { ConfigDescription config; LocaleValue lv; if (lv.InitFromFilterString(config_str)) { diff --git a/tools/aapt2/cmd/Util.h b/tools/aapt2/cmd/Util.h index 3d4ca245ee28..169d5f92f7dd 100644 --- a/tools/aapt2/cmd/Util.h +++ b/tools/aapt2/cmd/Util.h @@ -34,13 +34,13 @@ namespace aapt { // Parses a configuration density (ex. hdpi, xxhdpi, 234dpi, anydpi, etc). // Returns Nothing and logs a human friendly error message if the string was not legal. -std::optional<uint16_t> ParseTargetDensityParameter(const android::StringPiece& arg, +std::optional<uint16_t> ParseTargetDensityParameter(android::StringPiece arg, android::IDiagnostics* diag); // Parses a string of the form 'path/to/output.apk:<config>[,<config>...]' and fills in // `out_path` with the path and `out_split` with the set of ConfigDescriptions. // Returns false and logs a human friendly error message if the string was not legal. -bool ParseSplitParameter(const android::StringPiece& arg, android::IDiagnostics* diag, +bool ParseSplitParameter(android::StringPiece arg, android::IDiagnostics* diag, std::string* out_path, SplitConstraints* out_split); // Parses a set of config filter strings of the form 'en,fr-rFR' and returns an IConfigFilter. diff --git a/tools/aapt2/compile/NinePatch.cpp b/tools/aapt2/compile/NinePatch.cpp index c931da48c889..4538ecc56e4c 100644 --- a/tools/aapt2/compile/NinePatch.cpp +++ b/tools/aapt2/compile/NinePatch.cpp @@ -218,11 +218,9 @@ inline static uint32_t get_alpha(uint32_t color) { static bool PopulateBounds(const std::vector<Range>& padding, const std::vector<Range>& layout_bounds, - const std::vector<Range>& stretch_regions, - const int32_t length, int32_t* padding_start, - int32_t* padding_end, int32_t* layout_start, - int32_t* layout_end, const StringPiece& edge_name, - std::string* out_err) { + const std::vector<Range>& stretch_regions, const int32_t length, + int32_t* padding_start, int32_t* padding_end, int32_t* layout_start, + int32_t* layout_end, StringPiece edge_name, std::string* out_err) { if (padding.size() > 1) { std::stringstream err_stream; err_stream << "too many padding sections on " << edge_name << " border"; diff --git a/tools/aapt2/compile/Png.h b/tools/aapt2/compile/Png.h index 7f8d923edd03..a8b7dd18f12f 100644 --- a/tools/aapt2/compile/Png.h +++ b/tools/aapt2/compile/Png.h @@ -59,7 +59,7 @@ class Png { */ class PngChunkFilter : public io::InputStream { public: - explicit PngChunkFilter(const android::StringPiece& data); + explicit PngChunkFilter(android::StringPiece data); virtual ~PngChunkFilter() = default; bool Next(const void** buffer, size_t* len) override; diff --git a/tools/aapt2/compile/PngChunkFilter.cpp b/tools/aapt2/compile/PngChunkFilter.cpp index 4db2392b4eab..2e55d0c82b7b 100644 --- a/tools/aapt2/compile/PngChunkFilter.cpp +++ b/tools/aapt2/compile/PngChunkFilter.cpp @@ -70,7 +70,7 @@ static bool IsPngChunkAllowed(uint32_t type) { } } -PngChunkFilter::PngChunkFilter(const StringPiece& data) : data_(data) { +PngChunkFilter::PngChunkFilter(StringPiece data) : data_(data) { if (util::StartsWith(data_, kPngSignature)) { window_start_ = 0; window_end_ = kPngSignatureSize; diff --git a/tools/aapt2/compile/Pseudolocalizer.cpp b/tools/aapt2/compile/Pseudolocalizer.cpp index 3a515fad3202..463ce787dae7 100644 --- a/tools/aapt2/compile/Pseudolocalizer.cpp +++ b/tools/aapt2/compile/Pseudolocalizer.cpp @@ -20,36 +20,42 @@ using android::StringPiece; +using namespace std::literals; + namespace aapt { // String basis to generate expansion -static const std::string kExpansionString = +static constexpr auto kExpansionString = "one two three " "four five six seven eight nine ten eleven twelve thirteen " - "fourteen fiveteen sixteen seventeen nineteen twenty"; + "fourteen fiveteen sixteen seventeen nineteen twenty"sv; // Special unicode characters to override directionality of the words -static const std::string kRlm = "\u200f"; -static const std::string kRlo = "\u202e"; -static const std::string kPdf = "\u202c"; +static constexpr auto kRlm = "\u200f"sv; +static constexpr auto kRlo = "\u202e"sv; +static constexpr auto kPdf = "\u202c"sv; // Placeholder marks -static const std::string kPlaceholderOpen = "\u00bb"; -static const std::string kPlaceholderClose = "\u00ab"; +static constexpr auto kPlaceholderOpen = "\u00bb"sv; +static constexpr auto kPlaceholderClose = "\u00ab"sv; static const char kArgStart = '{'; static const char kArgEnd = '}'; class PseudoMethodNone : public PseudoMethodImpl { public: - std::string Text(const StringPiece& text) override { return text.to_string(); } - std::string Placeholder(const StringPiece& text) override { return text.to_string(); } + std::string Text(StringPiece text) override { + return std::string(text); + } + std::string Placeholder(StringPiece text) override { + return std::string(text); + } }; class PseudoMethodBidi : public PseudoMethodImpl { public: - std::string Text(const StringPiece& text) override; - std::string Placeholder(const StringPiece& text) override; + std::string Text(StringPiece text) override; + std::string Placeholder(StringPiece text) override; }; class PseudoMethodAccent : public PseudoMethodImpl { @@ -57,8 +63,8 @@ class PseudoMethodAccent : public PseudoMethodImpl { PseudoMethodAccent() : depth_(0), word_count_(0), length_(0) {} std::string Start() override; std::string End() override; - std::string Text(const StringPiece& text) override; - std::string Placeholder(const StringPiece& text) override; + std::string Text(StringPiece text) override; + std::string Placeholder(StringPiece text) override; private: size_t depth_; @@ -84,7 +90,7 @@ void Pseudolocalizer::SetMethod(Method method) { } } -std::string Pseudolocalizer::Text(const StringPiece& text) { +std::string Pseudolocalizer::Text(StringPiece text) { std::string out; size_t depth = last_depth_; size_t lastpos, pos; @@ -116,7 +122,7 @@ std::string Pseudolocalizer::Text(const StringPiece& text) { } size_t size = nextpos - lastpos; if (size) { - std::string chunk = text.substr(lastpos, size).to_string(); + std::string chunk(text.substr(lastpos, size)); if (pseudo) { chunk = impl_->Text(chunk); } else if (str[lastpos] == kArgStart && str[nextpos - 1] == kArgEnd) { @@ -301,21 +307,23 @@ static bool IsPossibleNormalPlaceholderEnd(const char c) { } static std::string PseudoGenerateExpansion(const unsigned int length) { - std::string result = kExpansionString; - const char* s = result.data(); + std::string result(kExpansionString); if (result.size() < length) { result += " "; result += PseudoGenerateExpansion(length - result.size()); } else { int ext = 0; // Should contain only whole words, so looking for a space - for (unsigned int i = length + 1; i < result.size(); ++i) { - ++ext; - if (s[i] == ' ') { - break; + { + const char* const s = result.data(); + for (unsigned int i = length + 1; i < result.size(); ++i) { + ++ext; + if (s[i] == ' ') { + break; + } } } - result = result.substr(0, length + ext); + result.resize(length + ext); } return result; } @@ -349,7 +357,7 @@ std::string PseudoMethodAccent::End() { * * Note: This leaves placeholder syntax untouched. */ -std::string PseudoMethodAccent::Text(const StringPiece& source) { +std::string PseudoMethodAccent::Text(StringPiece source) { const char* s = source.data(); std::string result; const size_t I = source.size(); @@ -435,12 +443,12 @@ std::string PseudoMethodAccent::Text(const StringPiece& source) { return result; } -std::string PseudoMethodAccent::Placeholder(const StringPiece& source) { +std::string PseudoMethodAccent::Placeholder(StringPiece source) { // Surround a placeholder with brackets - return kPlaceholderOpen + source.to_string() + kPlaceholderClose; + return (std::string(kPlaceholderOpen) += source) += kPlaceholderClose; } -std::string PseudoMethodBidi::Text(const StringPiece& source) { +std::string PseudoMethodBidi::Text(StringPiece source) { const char* s = source.data(); std::string result; bool lastspace = true; @@ -456,10 +464,10 @@ std::string PseudoMethodBidi::Text(const StringPiece& source) { space = (!escape && isspace(c)) || (escape && (c == 'n' || c == 't')); if (lastspace && !space) { // Word start - result += kRlm + kRlo; + (result += kRlm) += kRlo; } else if (!lastspace && space) { // Word end - result += kPdf + kRlm; + (result += kPdf) += kRlm; } lastspace = space; if (escape) { @@ -470,14 +478,14 @@ std::string PseudoMethodBidi::Text(const StringPiece& source) { } if (!lastspace) { // End of last word - result += kPdf + kRlm; + (result += kPdf) += kRlm; } return result; } -std::string PseudoMethodBidi::Placeholder(const StringPiece& source) { +std::string PseudoMethodBidi::Placeholder(StringPiece source) { // Surround a placeholder with directionality change sequence - return kRlm + kRlo + source.to_string() + kPdf + kRlm; + return (((std::string(kRlm) += kRlo) += source) += kPdf) += kRlm; } } // namespace aapt diff --git a/tools/aapt2/compile/Pseudolocalizer.h b/tools/aapt2/compile/Pseudolocalizer.h index 4dedc700a8e7..2b94bcc87fc9 100644 --- a/tools/aapt2/compile/Pseudolocalizer.h +++ b/tools/aapt2/compile/Pseudolocalizer.h @@ -31,8 +31,8 @@ class PseudoMethodImpl { virtual ~PseudoMethodImpl() {} virtual std::string Start() { return {}; } virtual std::string End() { return {}; } - virtual std::string Text(const android::StringPiece& text) = 0; - virtual std::string Placeholder(const android::StringPiece& text) = 0; + virtual std::string Text(android::StringPiece text) = 0; + virtual std::string Placeholder(android::StringPiece text) = 0; }; class Pseudolocalizer { @@ -47,7 +47,7 @@ class Pseudolocalizer { void SetMethod(Method method); std::string Start() { return impl_->Start(); } std::string End() { return impl_->End(); } - std::string Text(const android::StringPiece& text); + std::string Text(android::StringPiece text); private: std::unique_ptr<PseudoMethodImpl> impl_; diff --git a/tools/aapt2/configuration/ConfigurationParser.cpp b/tools/aapt2/configuration/ConfigurationParser.cpp index 6bba11e26e6a..1b0325325778 100644 --- a/tools/aapt2/configuration/ConfigurationParser.cpp +++ b/tools/aapt2/configuration/ConfigurationParser.cpp @@ -152,7 +152,7 @@ bool CopyXmlReferences(const std::optional<std::string>& name, const Group<T>& g * success, or false if the either the placeholder is not found in the name, or the value is not * present and the placeholder was. */ -bool ReplacePlaceholder(const StringPiece& placeholder, const std::optional<StringPiece>& value, +bool ReplacePlaceholder(StringPiece placeholder, const std::optional<StringPiece>& value, std::string* name, android::IDiagnostics* diag) { size_t offset = name->find(placeholder.data()); bool found = (offset != std::string::npos); @@ -338,17 +338,17 @@ std::optional<PostProcessingConfiguration> ExtractConfiguration(const std::strin return {config}; } -const StringPiece& AbiToString(Abi abi) { +StringPiece AbiToString(Abi abi) { return kAbiToStringMap.at(static_cast<size_t>(abi)); } /** * Returns the common artifact base name from a template string. */ -std::optional<std::string> ToBaseName(std::string result, const StringPiece& apk_name, +std::optional<std::string> ToBaseName(std::string result, StringPiece apk_name, android::IDiagnostics* diag) { const StringPiece ext = file::GetExtension(apk_name); - size_t end_index = apk_name.to_string().rfind(ext.to_string()); + size_t end_index = apk_name.rfind(ext); const std::string base_name = (end_index != std::string::npos) ? std::string{apk_name.begin(), end_index} : ""; @@ -371,17 +371,17 @@ std::optional<std::string> ToBaseName(std::string result, const StringPiece& apk // If no extension is specified, and the name template does not end in the current extension, // add the existing extension. if (!util::EndsWith(result, ext)) { - result.append(ext.to_string()); + result.append(ext); } } return result; } -std::optional<std::string> ConfiguredArtifact::ToArtifactName(const StringPiece& format, - const StringPiece& apk_name, +std::optional<std::string> ConfiguredArtifact::ToArtifactName(StringPiece format, + StringPiece apk_name, android::IDiagnostics* diag) const { - std::optional<std::string> base = ToBaseName(format.to_string(), apk_name, diag); + std::optional<std::string> base = ToBaseName(std::string(format), apk_name, diag); if (!base) { return {}; } @@ -414,7 +414,7 @@ std::optional<std::string> ConfiguredArtifact::ToArtifactName(const StringPiece& return result; } -std::optional<std::string> ConfiguredArtifact::Name(const StringPiece& apk_name, +std::optional<std::string> ConfiguredArtifact::Name(StringPiece apk_name, android::IDiagnostics* diag) const { if (!name) { return {}; @@ -439,7 +439,7 @@ ConfigurationParser::ConfigurationParser(std::string contents, const std::string } std::optional<std::vector<OutputArtifact>> ConfigurationParser::Parse( - const android::StringPiece& apk_path) { + android::StringPiece apk_path) { std::optional<PostProcessingConfiguration> maybe_config = ExtractConfiguration(contents_, config_path_, diag_); if (!maybe_config) { @@ -447,7 +447,7 @@ std::optional<std::vector<OutputArtifact>> ConfigurationParser::Parse( } // Convert from a parsed configuration to a list of artifacts for processing. - const std::string& apk_name = file::GetFilename(apk_path).to_string(); + const std::string apk_name(file::GetFilename(apk_path)); std::vector<OutputArtifact> output_artifacts; PostProcessingConfiguration& config = maybe_config.value(); @@ -519,7 +519,7 @@ bool ArtifactFormatTagHandler(PostProcessingConfiguration* config, Element* root for (auto& node : root_element->children) { xml::Text* t; if ((t = NodeCast<xml::Text>(node.get())) != nullptr) { - config->artifact_format = TrimWhitespace(t->text).to_string(); + config->artifact_format.emplace(TrimWhitespace(t->text)); break; } } @@ -561,7 +561,7 @@ bool AbiGroupTagHandler(PostProcessingConfiguration* config, Element* root_eleme for (auto& node : child->children) { xml::Text* t; if ((t = NodeCast<xml::Text>(node.get())) != nullptr) { - auto abi = kStringToAbiMap.find(TrimWhitespace(t->text).to_string()); + auto abi = kStringToAbiMap.find(TrimWhitespace(t->text)); if (abi != kStringToAbiMap.end()) { group.push_back(abi->second); } else { @@ -622,7 +622,7 @@ bool ScreenDensityGroupTagHandler(PostProcessingConfiguration* config, Element* xml::Text* t; if ((t = NodeCast<xml::Text>(node.get())) != nullptr) { ConfigDescription config_descriptor; - const android::StringPiece& text = TrimWhitespace(t->text); + android::StringPiece text = TrimWhitespace(t->text); bool parsed = ConfigDescription::Parse(text, &config_descriptor); if (parsed && (config_descriptor.CopyWithoutSdkVersion().diff(ConfigDescription::DefaultConfig()) == @@ -688,7 +688,7 @@ bool LocaleGroupTagHandler(PostProcessingConfiguration* config, Element* root_el xml::Text* t; if ((t = NodeCast<xml::Text>(node.get())) != nullptr) { ConfigDescription config_descriptor; - const android::StringPiece& text = TrimWhitespace(t->text); + android::StringPiece text = TrimWhitespace(t->text); bool parsed = ConfigDescription::Parse(text, &config_descriptor); if (parsed && (config_descriptor.CopyWithoutSdkVersion().diff(ConfigDescription::DefaultConfig()) == @@ -806,7 +806,7 @@ bool GlTextureGroupTagHandler(PostProcessingConfiguration* config, Element* root for (auto& node : element->children) { xml::Text* t; if ((t = NodeCast<xml::Text>(node.get())) != nullptr) { - result.texture_paths.push_back(TrimWhitespace(t->text).to_string()); + result.texture_paths.emplace_back(TrimWhitespace(t->text)); } } } @@ -843,7 +843,7 @@ bool DeviceFeatureGroupTagHandler(PostProcessingConfiguration* config, Element* for (auto& node : child->children) { xml::Text* t; if ((t = NodeCast<xml::Text>(node.get())) != nullptr) { - group.push_back(TrimWhitespace(t->text).to_string()); + group.emplace_back(TrimWhitespace(t->text)); break; } } diff --git a/tools/aapt2/configuration/ConfigurationParser.h b/tools/aapt2/configuration/ConfigurationParser.h index 2c8221d5108b..d66f4ab000a3 100644 --- a/tools/aapt2/configuration/ConfigurationParser.h +++ b/tools/aapt2/configuration/ConfigurationParser.h @@ -43,7 +43,7 @@ enum class Abi { }; /** Helper method to convert an ABI to a string representing the path within the APK. */ -const android::StringPiece& AbiToString(Abi abi); +android::StringPiece AbiToString(Abi abi); /** * Represents an individual locale. When a locale is included, it must be @@ -150,8 +150,7 @@ class ConfigurationParser { * Parses the configuration file and returns the results. If the configuration could not be parsed * the result is empty and any errors will be displayed with the provided diagnostics context. */ - std::optional<std::vector<configuration::OutputArtifact>> Parse( - const android::StringPiece& apk_path); + std::optional<std::vector<configuration::OutputArtifact>> Parse(android::StringPiece apk_path); protected: /** diff --git a/tools/aapt2/configuration/ConfigurationParser.internal.h b/tools/aapt2/configuration/ConfigurationParser.internal.h index 3028c3f58e4e..198f730f1e12 100644 --- a/tools/aapt2/configuration/ConfigurationParser.internal.h +++ b/tools/aapt2/configuration/ConfigurationParser.internal.h @@ -138,13 +138,12 @@ struct ConfiguredArtifact { std::optional<std::string> gl_texture_group; /** Convert an artifact name template into a name string based on configuration contents. */ - std::optional<std::string> ToArtifactName(const android::StringPiece& format, - const android::StringPiece& apk_name, + std::optional<std::string> ToArtifactName(android::StringPiece format, + android::StringPiece apk_name, android::IDiagnostics* diag) const; /** Convert an artifact name template into a name string based on configuration contents. */ - std::optional<std::string> Name(const android::StringPiece& apk_name, - android::IDiagnostics* diag) const; + std::optional<std::string> Name(android::StringPiece apk_name, android::IDiagnostics* diag) const; }; /** AAPT2 XML configuration file binary representation. */ diff --git a/tools/aapt2/filter/AbiFilter.cpp b/tools/aapt2/filter/AbiFilter.cpp index 9ace82ad4af7..908b1714bd14 100644 --- a/tools/aapt2/filter/AbiFilter.cpp +++ b/tools/aapt2/filter/AbiFilter.cpp @@ -23,15 +23,15 @@ namespace aapt { std::unique_ptr<AbiFilter> AbiFilter::FromAbiList(const std::vector<configuration::Abi>& abi_list) { - std::unordered_set<std::string> abi_set; + std::unordered_set<std::string_view> abi_set; for (auto& abi : abi_list) { - abi_set.insert(configuration::AbiToString(abi).to_string()); + abi_set.insert(configuration::AbiToString(abi)); } // Make unique by hand as the constructor is private. - return std::unique_ptr<AbiFilter>(new AbiFilter(abi_set)); + return std::unique_ptr<AbiFilter>(new AbiFilter(std::move(abi_set))); } -bool AbiFilter::Keep(const std::string& path) { +bool AbiFilter::Keep(std::string_view path) { // We only care about libraries. if (!util::StartsWith(path, kLibPrefix)) { return true; @@ -44,7 +44,7 @@ bool AbiFilter::Keep(const std::string& path) { } // Strip the lib/ prefix. - const std::string& path_abi = path.substr(kLibPrefixLen, abi_end - kLibPrefixLen); + const auto path_abi = path.substr(kLibPrefixLen, abi_end - kLibPrefixLen); return (abis_.find(path_abi) != abis_.end()); } diff --git a/tools/aapt2/filter/AbiFilter.h b/tools/aapt2/filter/AbiFilter.h index 2832711efb2c..7380f3f479ae 100644 --- a/tools/aapt2/filter/AbiFilter.h +++ b/tools/aapt2/filter/AbiFilter.h @@ -18,7 +18,7 @@ #define AAPT2_ABISPLITTER_H #include <memory> -#include <string> +#include <string_view> #include <unordered_set> #include <vector> @@ -39,16 +39,16 @@ class AbiFilter : public IPathFilter { static std::unique_ptr<AbiFilter> FromAbiList(const std::vector<configuration::Abi>& abi_list); /** Returns true if the path is for a native library in the list of desired ABIs. */ - bool Keep(const std::string& path) override; + bool Keep(std::string_view path) override; private: - explicit AbiFilter(std::unordered_set<std::string> abis) : abis_(std::move(abis)) { + explicit AbiFilter(std::unordered_set<std::string_view> abis) : abis_(std::move(abis)) { } /** The path prefix to where all native libs end up inside an APK file. */ static constexpr const char* kLibPrefix = "lib/"; static constexpr size_t kLibPrefixLen = 4; - const std::unordered_set<std::string> abis_; + const std::unordered_set<std::string_view> abis_; }; } // namespace aapt diff --git a/tools/aapt2/filter/Filter.h b/tools/aapt2/filter/Filter.h index f932f9ccc82e..baf4791f76c8 100644 --- a/tools/aapt2/filter/Filter.h +++ b/tools/aapt2/filter/Filter.h @@ -18,6 +18,7 @@ #define AAPT2_FILTER_H #include <string> +#include <string_view> #include <vector> #include "util/Util.h" @@ -30,7 +31,7 @@ class IPathFilter { virtual ~IPathFilter() = default; /** Returns true if the path should be kept. */ - virtual bool Keep(const std::string& path) = 0; + virtual bool Keep(std::string_view path) = 0; }; /** @@ -42,7 +43,7 @@ class PrefixFilter : public IPathFilter { } /** Returns true if the provided path matches the prefix. */ - bool Keep(const std::string& path) override { + bool Keep(std::string_view path) override { return util::StartsWith(path, prefix_); } @@ -59,7 +60,7 @@ class FilterChain : public IPathFilter { } /** Returns true if all filters keep the path. */ - bool Keep(const std::string& path) override { + bool Keep(std::string_view path) override { for (auto& filter : filters_) { if (!filter->Keep(path)) { return false; diff --git a/tools/aapt2/format/Archive.cpp b/tools/aapt2/format/Archive.cpp index 80c16188aca4..e9a93d8b12ad 100644 --- a/tools/aapt2/format/Archive.cpp +++ b/tools/aapt2/format/Archive.cpp @@ -40,8 +40,8 @@ class DirectoryWriter : public IArchiveWriter { public: DirectoryWriter() = default; - bool Open(const StringPiece& out_dir) { - dir_ = out_dir.to_string(); + bool Open(StringPiece out_dir) { + dir_ = std::string(out_dir); file::FileType type = file::GetFileType(dir_); if (type == file::FileType::kNonExistant) { error_ = "directory does not exist"; @@ -53,14 +53,14 @@ class DirectoryWriter : public IArchiveWriter { return true; } - bool StartEntry(const StringPiece& path, uint32_t flags) override { + bool StartEntry(StringPiece path, uint32_t flags) override { if (file_) { return false; } std::string full_path = dir_; file::AppendPath(&full_path, path); - file::mkdirs(file::GetStem(full_path).to_string()); + file::mkdirs(std::string(file::GetStem(full_path))); file_ = {::android::base::utf8::fopen(full_path.c_str(), "wb"), fclose}; if (!file_) { @@ -91,7 +91,7 @@ class DirectoryWriter : public IArchiveWriter { return true; } - bool WriteFile(const StringPiece& path, uint32_t flags, io::InputStream* in) override { + bool WriteFile(StringPiece path, uint32_t flags, io::InputStream* in) override { if (!StartEntry(path, flags)) { return false; } @@ -132,8 +132,8 @@ class ZipFileWriter : public IArchiveWriter { public: ZipFileWriter() = default; - bool Open(const StringPiece& path) { - file_ = {::android::base::utf8::fopen(path.to_string().c_str(), "w+b"), fclose}; + bool Open(StringPiece path) { + file_ = {::android::base::utf8::fopen(path.data(), "w+b"), fclose}; if (!file_) { error_ = SystemErrorCodeToString(errno); return false; @@ -142,7 +142,7 @@ class ZipFileWriter : public IArchiveWriter { return true; } - bool StartEntry(const StringPiece& path, uint32_t flags) override { + bool StartEntry(StringPiece path, uint32_t flags) override { if (!writer_) { return false; } @@ -182,7 +182,7 @@ class ZipFileWriter : public IArchiveWriter { return true; } - bool WriteFile(const StringPiece& path, uint32_t flags, io::InputStream* in) override { + bool WriteFile(StringPiece path, uint32_t flags, io::InputStream* in) override { while (true) { if (!StartEntry(path, flags)) { return false; @@ -257,7 +257,7 @@ class ZipFileWriter : public IArchiveWriter { } // namespace std::unique_ptr<IArchiveWriter> CreateDirectoryArchiveWriter(android::IDiagnostics* diag, - const StringPiece& path) { + StringPiece path) { std::unique_ptr<DirectoryWriter> writer = util::make_unique<DirectoryWriter>(); if (!writer->Open(path)) { diag->Error(android::DiagMessage(path) << writer->GetError()); @@ -267,7 +267,7 @@ std::unique_ptr<IArchiveWriter> CreateDirectoryArchiveWriter(android::IDiagnosti } std::unique_ptr<IArchiveWriter> CreateZipFileArchiveWriter(android::IDiagnostics* diag, - const StringPiece& path) { + StringPiece path) { std::unique_ptr<ZipFileWriter> writer = util::make_unique<ZipFileWriter>(); if (!writer->Open(path)) { diag->Error(android::DiagMessage(path) << writer->GetError()); diff --git a/tools/aapt2/format/Archive.h b/tools/aapt2/format/Archive.h index 55b0b2f0f017..6cde753a255d 100644 --- a/tools/aapt2/format/Archive.h +++ b/tools/aapt2/format/Archive.h @@ -46,12 +46,12 @@ class IArchiveWriter : public ::google::protobuf::io::CopyingOutputStream { public: virtual ~IArchiveWriter() = default; - virtual bool WriteFile(const android::StringPiece& path, uint32_t flags, io::InputStream* in) = 0; + virtual bool WriteFile(android::StringPiece path, uint32_t flags, io::InputStream* in) = 0; // Starts a new entry and allows caller to write bytes to it sequentially. // Only use StartEntry if code you do not control needs to write to a CopyingOutputStream. // Prefer WriteFile instead of manually calling StartEntry/FinishEntry. - virtual bool StartEntry(const android::StringPiece& path, uint32_t flags) = 0; + virtual bool StartEntry(android::StringPiece path, uint32_t flags) = 0; // Called to finish writing an entry previously started by StartEntry. // Prefer WriteFile instead of manually calling StartEntry/FinishEntry. @@ -70,10 +70,10 @@ class IArchiveWriter : public ::google::protobuf::io::CopyingOutputStream { }; std::unique_ptr<IArchiveWriter> CreateDirectoryArchiveWriter(android::IDiagnostics* diag, - const android::StringPiece& path); + android::StringPiece path); std::unique_ptr<IArchiveWriter> CreateZipFileArchiveWriter(android::IDiagnostics* diag, - const android::StringPiece& path); + android::StringPiece path); } // namespace aapt diff --git a/tools/aapt2/format/Archive_test.cpp b/tools/aapt2/format/Archive_test.cpp index ceed3740f37a..3c44da710d94 100644 --- a/tools/aapt2/format/Archive_test.cpp +++ b/tools/aapt2/format/Archive_test.cpp @@ -50,7 +50,7 @@ std::unique_ptr<IArchiveWriter> MakeDirectoryWriter(const std::string& output_pa } std::unique_ptr<IArchiveWriter> MakeZipFileWriter(const std::string& output_path) { - file::mkdirs(file::GetStem(output_path).to_string()); + file::mkdirs(std::string(file::GetStem(output_path))); std::remove(output_path.c_str()); StdErrDiagnostics diag; diff --git a/tools/aapt2/format/binary/BinaryResourceParser.cpp b/tools/aapt2/format/binary/BinaryResourceParser.cpp index 82918629f1f4..75dcba581c90 100644 --- a/tools/aapt2/format/binary/BinaryResourceParser.cpp +++ b/tools/aapt2/format/binary/BinaryResourceParser.cpp @@ -373,7 +373,7 @@ bool BinaryResourceParser::ParseType(const ResourceTablePackage* package, std::optional<ResourceNamedTypeRef> parsed_type = ParseResourceNamedType(type_str); if (!parsed_type) { diag_->Warn(android::DiagMessage(source_) - << "invalid type name '" << type_str << "' for type with ID " << type->id); + << "invalid type name '" << type_str << "' for type with ID " << int(type->id)); return true; } diff --git a/tools/aapt2/format/binary/TableFlattener_test.cpp b/tools/aapt2/format/binary/TableFlattener_test.cpp index d08b4a3e5deb..0f1168514c4a 100644 --- a/tools/aapt2/format/binary/TableFlattener_test.cpp +++ b/tools/aapt2/format/binary/TableFlattener_test.cpp @@ -84,7 +84,7 @@ class TableFlattenerTest : public ::testing::Test { return ::testing::AssertionSuccess(); } - ::testing::AssertionResult Exists(ResTable* table, const StringPiece& expected_name, + ::testing::AssertionResult Exists(ResTable* table, StringPiece expected_name, const ResourceId& expected_id, const ConfigDescription& expected_config, const uint8_t expected_data_type, const uint32_t expected_data, diff --git a/tools/aapt2/format/binary/XmlFlattener.cpp b/tools/aapt2/format/binary/XmlFlattener.cpp index 983e6467fab0..05f975177cd1 100644 --- a/tools/aapt2/format/binary/XmlFlattener.cpp +++ b/tools/aapt2/format/binary/XmlFlattener.cpp @@ -79,7 +79,7 @@ class XmlFlattenerVisitor : public xml::ConstVisitor { } void Visit(const xml::Text* node) override { - std::string text = util::TrimWhitespace(node->text).to_string(); + std::string text(util::TrimWhitespace(node->text)); // Skip whitespace only text nodes. if (text.empty()) { @@ -88,10 +88,10 @@ class XmlFlattenerVisitor : public xml::ConstVisitor { // Compact leading and trailing whitespace into a single space if (isspace(node->text[0])) { - text = ' ' + text; + text.insert(text.begin(), ' '); } - if (isspace(node->text[node->text.length() - 1])) { - text = text + ' '; + if (isspace(node->text.back())) { + text += ' '; } ChunkWriter writer(buffer_); @@ -165,7 +165,7 @@ class XmlFlattenerVisitor : public xml::ConstVisitor { // We are adding strings to a StringPool whose strings will be sorted and merged with other // string pools. That means we can't encode the ID of a string directly. Instead, we defer the // writing of the ID here, until after the StringPool is merged and sorted. - void AddString(const StringPiece& str, uint32_t priority, android::ResStringPool_ref* dest, + void AddString(StringPiece str, uint32_t priority, android::ResStringPool_ref* dest, bool treat_empty_string_as_null = false) { if (str.empty() && treat_empty_string_as_null) { // Some parts of the runtime treat null differently than empty string. diff --git a/tools/aapt2/format/proto/ProtoSerialize_test.cpp b/tools/aapt2/format/proto/ProtoSerialize_test.cpp index 5adc5e639830..ecfdba83a2e8 100644 --- a/tools/aapt2/format/proto/ProtoSerialize_test.cpp +++ b/tools/aapt2/format/proto/ProtoSerialize_test.cpp @@ -35,7 +35,7 @@ namespace aapt { class MockFileCollection : public io::IFileCollection { public: - MOCK_METHOD1(FindFile, io::IFile*(const StringPiece& path)); + MOCK_METHOD1(FindFile, io::IFile*(StringPiece path)); MOCK_METHOD0(Iterator, std::unique_ptr<io::IFileCollectionIterator>()); MOCK_METHOD0(GetDirSeparator, char()); }; @@ -491,7 +491,7 @@ TEST(ProtoSerializeTest, SerializeAndDeserializePrimitives) { EXPECT_THAT(bp->value.data, Eq(ResourceUtils::MakeEmpty()->value.data)); } -static void ExpectConfigSerializes(const StringPiece& config_str) { +static void ExpectConfigSerializes(StringPiece config_str) { const ConfigDescription expected_config = test::ParseConfigOrDie(config_str); pb::Configuration pb_config; SerializeConfig(expected_config, &pb_config); diff --git a/tools/aapt2/io/File.h b/tools/aapt2/io/File.h index 422658a0309e..08d497def8a4 100644 --- a/tools/aapt2/io/File.h +++ b/tools/aapt2/io/File.h @@ -101,7 +101,7 @@ class IFileCollection { public: virtual ~IFileCollection() = default; - virtual IFile* FindFile(const android::StringPiece& path) = 0; + virtual IFile* FindFile(android::StringPiece path) = 0; virtual std::unique_ptr<IFileCollectionIterator> Iterator() = 0; virtual char GetDirSeparator() = 0; }; diff --git a/tools/aapt2/io/FileSystem.cpp b/tools/aapt2/io/FileSystem.cpp index 3f071af08844..a64982a7fa5c 100644 --- a/tools/aapt2/io/FileSystem.cpp +++ b/tools/aapt2/io/FileSystem.cpp @@ -67,8 +67,8 @@ IFile* FileCollectionIterator::Next() { return result; } -std::unique_ptr<FileCollection> FileCollection::Create(const android::StringPiece& root, - std::string* outError) { +std::unique_ptr<FileCollection> FileCollection::Create(android::StringPiece root, + std::string* outError) { std::unique_ptr<FileCollection> collection = std::unique_ptr<FileCollection>(new FileCollection()); @@ -80,7 +80,7 @@ std::unique_ptr<FileCollection> FileCollection::Create(const android::StringPiec std::vector<std::string> sorted_files; while (struct dirent *entry = readdir(d.get())) { - std::string prefix_path = root.to_string(); + std::string prefix_path(root); file::AppendPath(&prefix_path, entry->d_name); // The directory to iterate over looking for files @@ -117,12 +117,19 @@ std::unique_ptr<FileCollection> FileCollection::Create(const android::StringPiec return collection; } -IFile* FileCollection::InsertFile(const StringPiece& path) { - return (files_[path.to_string()] = util::make_unique<RegularFile>(android::Source(path))).get(); +IFile* FileCollection::InsertFile(StringPiece path) { + auto file = util::make_unique<RegularFile>(android::Source(path)); + auto it = files_.lower_bound(path); + if (it != files_.end() && it->first == path) { + it->second = std::move(file); + } else { + it = files_.emplace_hint(it, path, std::move(file)); + } + return it->second.get(); } -IFile* FileCollection::FindFile(const StringPiece& path) { - auto iter = files_.find(path.to_string()); +IFile* FileCollection::FindFile(StringPiece path) { + auto iter = files_.find(path); if (iter != files_.end()) { return iter->second.get(); } diff --git a/tools/aapt2/io/FileSystem.h b/tools/aapt2/io/FileSystem.h index bc03b9b4391e..0e798fc1b975 100644 --- a/tools/aapt2/io/FileSystem.h +++ b/tools/aapt2/io/FileSystem.h @@ -60,12 +60,11 @@ class FileCollection : public IFileCollection { FileCollection() = default; /** Creates a file collection containing all files contained in the specified root directory. */ - static std::unique_ptr<FileCollection> Create(const android::StringPiece& path, - std::string* outError); + static std::unique_ptr<FileCollection> Create(android::StringPiece path, std::string* outError); // Adds a file located at path. Returns the IFile representation of that file. - IFile* InsertFile(const android::StringPiece& path); - IFile* FindFile(const android::StringPiece& path) override; + IFile* InsertFile(android::StringPiece path); + IFile* FindFile(android::StringPiece path) override; std::unique_ptr<IFileCollectionIterator> Iterator() override; char GetDirSeparator() override; @@ -74,7 +73,7 @@ class FileCollection : public IFileCollection { friend class FileCollectionIterator; - std::map<std::string, std::unique_ptr<IFile>> files_; + std::map<std::string, std::unique_ptr<IFile>, std::less<>> files_; }; } // namespace io diff --git a/tools/aapt2/io/StringStream.cpp b/tools/aapt2/io/StringStream.cpp index 4ca04a8c7477..9c497882b99b 100644 --- a/tools/aapt2/io/StringStream.cpp +++ b/tools/aapt2/io/StringStream.cpp @@ -21,7 +21,7 @@ using ::android::StringPiece; namespace aapt { namespace io { -StringInputStream::StringInputStream(const StringPiece& str) : str_(str), offset_(0u) { +StringInputStream::StringInputStream(StringPiece str) : str_(str), offset_(0u) { } bool StringInputStream::Next(const void** data, size_t* size) { diff --git a/tools/aapt2/io/StringStream.h b/tools/aapt2/io/StringStream.h index f29890ab7ee5..f7bdecca0dee 100644 --- a/tools/aapt2/io/StringStream.h +++ b/tools/aapt2/io/StringStream.h @@ -29,7 +29,7 @@ namespace io { class StringInputStream : public KnownSizeInputStream { public: - explicit StringInputStream(const android::StringPiece& str); + explicit StringInputStream(android::StringPiece str); bool Next(const void** data, size_t* size) override; diff --git a/tools/aapt2/io/Util.cpp b/tools/aapt2/io/Util.cpp index afe54d408361..79d8d527fe8b 100644 --- a/tools/aapt2/io/Util.cpp +++ b/tools/aapt2/io/Util.cpp @@ -26,7 +26,7 @@ using ::google::protobuf::io::ZeroCopyOutputStream; namespace aapt { namespace io { -bool CopyInputStreamToArchive(IAaptContext* context, InputStream* in, const std::string& out_path, +bool CopyInputStreamToArchive(IAaptContext* context, InputStream* in, std::string_view out_path, uint32_t compression_flags, IArchiveWriter* writer) { TRACE_CALL(); if (context->IsVerbose()) { @@ -43,7 +43,7 @@ bool CopyInputStreamToArchive(IAaptContext* context, InputStream* in, const std: return true; } -bool CopyFileToArchive(IAaptContext* context, io::IFile* file, const std::string& out_path, +bool CopyFileToArchive(IAaptContext* context, io::IFile* file, std::string_view out_path, uint32_t compression_flags, IArchiveWriter* writer) { TRACE_CALL(); std::unique_ptr<io::IData> data = file->OpenAsData(); @@ -56,13 +56,13 @@ bool CopyFileToArchive(IAaptContext* context, io::IFile* file, const std::string } bool CopyFileToArchivePreserveCompression(IAaptContext* context, io::IFile* file, - const std::string& out_path, IArchiveWriter* writer) { + std::string_view out_path, IArchiveWriter* writer) { uint32_t compression_flags = file->WasCompressed() ? ArchiveEntry::kCompress : 0u; return CopyFileToArchive(context, file, out_path, compression_flags, writer); } bool CopyProtoToArchive(IAaptContext* context, ::google::protobuf::Message* proto_msg, - const std::string& out_path, uint32_t compression_flags, + std::string_view out_path, uint32_t compression_flags, IArchiveWriter* writer) { TRACE_CALL(); if (context->IsVerbose()) { @@ -110,7 +110,7 @@ bool Copy(OutputStream* out, InputStream* in) { return !in->HadError(); } -bool Copy(OutputStream* out, const StringPiece& in) { +bool Copy(OutputStream* out, StringPiece in) { const char* in_buffer = in.data(); size_t in_len = in.size(); while (in_len != 0) { diff --git a/tools/aapt2/io/Util.h b/tools/aapt2/io/Util.h index 1b48a288d255..685f522a2e71 100644 --- a/tools/aapt2/io/Util.h +++ b/tools/aapt2/io/Util.h @@ -17,12 +17,11 @@ #ifndef AAPT_IO_UTIL_H #define AAPT_IO_UTIL_H -#include <string> - -#include "google/protobuf/message.h" -#include "google/protobuf/io/coded_stream.h" +#include <string_view> #include "format/Archive.h" +#include "google/protobuf/io/coded_stream.h" +#include "google/protobuf/message.h" #include "io/File.h" #include "io/Io.h" #include "process/IResourceTableConsumer.h" @@ -30,23 +29,23 @@ namespace aapt { namespace io { -bool CopyInputStreamToArchive(IAaptContext* context, InputStream* in, const std::string& out_path, +bool CopyInputStreamToArchive(IAaptContext* context, InputStream* in, std::string_view out_path, uint32_t compression_flags, IArchiveWriter* writer); -bool CopyFileToArchive(IAaptContext* context, IFile* file, const std::string& out_path, +bool CopyFileToArchive(IAaptContext* context, IFile* file, std::string_view out_path, uint32_t compression_flags, IArchiveWriter* writer); bool CopyFileToArchivePreserveCompression(IAaptContext* context, IFile* file, - const std::string& out_path, IArchiveWriter* writer); + std::string_view out_path, IArchiveWriter* writer); bool CopyProtoToArchive(IAaptContext* context, ::google::protobuf::Message* proto_msg, - const std::string& out_path, uint32_t compression_flags, + std::string_view out_path, uint32_t compression_flags, IArchiveWriter* writer); // Copies the data from in to out. Returns false if there was an error. // If there was an error, check the individual streams' HadError/GetError methods. bool Copy(OutputStream* out, InputStream* in); -bool Copy(OutputStream* out, const ::android::StringPiece& in); +bool Copy(OutputStream* out, android::StringPiece in); bool Copy(::google::protobuf::io::ZeroCopyOutputStream* out, InputStream* in); class OutputStreamAdaptor : public io::OutputStream { diff --git a/tools/aapt2/io/ZipArchive.cpp b/tools/aapt2/io/ZipArchive.cpp index 400269c41230..4a5385d90d3b 100644 --- a/tools/aapt2/io/ZipArchive.cpp +++ b/tools/aapt2/io/ZipArchive.cpp @@ -91,8 +91,8 @@ IFile* ZipFileCollectionIterator::Next() { ZipFileCollection::ZipFileCollection() : handle_(nullptr) {} -std::unique_ptr<ZipFileCollection> ZipFileCollection::Create( - const StringPiece& path, std::string* out_error) { +std::unique_ptr<ZipFileCollection> ZipFileCollection::Create(StringPiece path, + std::string* out_error) { TRACE_CALL(); constexpr static const int32_t kEmptyArchive = -6; @@ -130,8 +130,8 @@ std::unique_ptr<ZipFileCollection> ZipFileCollection::Create( continue; } - std::unique_ptr<IFile> file = util::make_unique<ZipFile>( - collection->handle_, zip_data, android::Source(zip_entry_path, path.to_string())); + std::unique_ptr<IFile> file = util::make_unique<ZipFile>(collection->handle_, zip_data, + android::Source(zip_entry_path, path)); collection->files_by_name_[zip_entry_path] = file.get(); collection->files_.push_back(std::move(file)); } @@ -144,8 +144,8 @@ std::unique_ptr<ZipFileCollection> ZipFileCollection::Create( return collection; } -IFile* ZipFileCollection::FindFile(const StringPiece& path) { - auto iter = files_by_name_.find(path.to_string()); +IFile* ZipFileCollection::FindFile(StringPiece path) { + auto iter = files_by_name_.find(path); if (iter != files_by_name_.end()) { return iter->second; } diff --git a/tools/aapt2/io/ZipArchive.h b/tools/aapt2/io/ZipArchive.h index 78c9c211ab57..c263aa490d22 100644 --- a/tools/aapt2/io/ZipArchive.h +++ b/tools/aapt2/io/ZipArchive.h @@ -61,10 +61,10 @@ class ZipFileCollectionIterator : public IFileCollectionIterator { // An IFileCollection that represents a ZIP archive and the entries within it. class ZipFileCollection : public IFileCollection { public: - static std::unique_ptr<ZipFileCollection> Create(const android::StringPiece& path, + static std::unique_ptr<ZipFileCollection> Create(android::StringPiece path, std::string* outError); - io::IFile* FindFile(const android::StringPiece& path) override; + io::IFile* FindFile(android::StringPiece path) override; std::unique_ptr<IFileCollectionIterator> Iterator() override; char GetDirSeparator() override; @@ -76,7 +76,7 @@ class ZipFileCollection : public IFileCollection { ZipArchiveHandle handle_; std::vector<std::unique_ptr<IFile>> files_; - std::map<std::string, IFile*> files_by_name_; + std::map<std::string, IFile*, std::less<>> files_by_name_; }; } // namespace io diff --git a/tools/aapt2/java/AnnotationProcessor.cpp b/tools/aapt2/java/AnnotationProcessor.cpp index 482d91aeb491..87da09a7b054 100644 --- a/tools/aapt2/java/AnnotationProcessor.cpp +++ b/tools/aapt2/java/AnnotationProcessor.cpp @@ -30,7 +30,7 @@ using ::android::StringPiece; namespace aapt { -StringPiece AnnotationProcessor::ExtractFirstSentence(const StringPiece& comment) { +StringPiece AnnotationProcessor::ExtractFirstSentence(StringPiece comment) { Utf8Iterator iter(comment); while (iter.HasNext()) { const char32_t codepoint = iter.Next(); @@ -62,7 +62,7 @@ static std::array<AnnotationRule, 2> sAnnotationRules = {{ }}; void AnnotationProcessor::AppendCommentLine(std::string comment) { - static const std::string sDeprecated = "@deprecated"; + static constexpr std::string_view sDeprecated = "@deprecated"; // Treat deprecated specially, since we don't remove it from the source comment. if (comment.find(sDeprecated) != std::string::npos) { @@ -74,7 +74,7 @@ void AnnotationProcessor::AppendCommentLine(std::string comment) { if (idx != std::string::npos) { // Captures all parameters associated with the specified annotation rule // by matching the first pair of parantheses after the rule. - std::regex re(rule.doc_str.to_string() + "\\s*\\((.+)\\)"); + std::regex re(std::string(rule.doc_str) += "\\s*\\((.+)\\)"); std::smatch match_result; const bool is_match = std::regex_search(comment, match_result, re); // We currently only capture and preserve parameters for SystemApi. @@ -97,7 +97,7 @@ void AnnotationProcessor::AppendCommentLine(std::string comment) { // If there was trimming to do, copy the string. if (trimmed.size() != comment.size()) { - comment = trimmed.to_string(); + comment = std::string(trimmed); } if (!has_comments_) { @@ -107,12 +107,12 @@ void AnnotationProcessor::AppendCommentLine(std::string comment) { comment_ << "\n * " << std::move(comment); } -void AnnotationProcessor::AppendComment(const StringPiece& comment) { +void AnnotationProcessor::AppendComment(StringPiece comment) { // We need to process line by line to clean-up whitespace and append prefixes. for (StringPiece line : util::Tokenize(comment, '\n')) { line = util::TrimWhitespace(line); if (!line.empty()) { - AppendCommentLine(line.to_string()); + AppendCommentLine(std::string(line)); } } } @@ -126,7 +126,7 @@ void AnnotationProcessor::AppendNewLine() { void AnnotationProcessor::Print(Printer* printer, bool strip_api_annotations) const { if (has_comments_) { std::string result = comment_.str(); - for (const StringPiece& line : util::Tokenize(result, '\n')) { + for (StringPiece line : util::Tokenize(result, '\n')) { printer->Println(line); } printer->Println(" */"); diff --git a/tools/aapt2/java/AnnotationProcessor.h b/tools/aapt2/java/AnnotationProcessor.h index f217afb16f32..db3437e3b5b1 100644 --- a/tools/aapt2/java/AnnotationProcessor.h +++ b/tools/aapt2/java/AnnotationProcessor.h @@ -56,11 +56,11 @@ class AnnotationProcessor { // Extracts the first sentence of a comment. The algorithm selects the substring starting from // the beginning of the string, and ending at the first '.' character that is followed by a // whitespace character. If these requirements are not met, the whole string is returned. - static android::StringPiece ExtractFirstSentence(const android::StringPiece& comment); + static android::StringPiece ExtractFirstSentence(android::StringPiece comment); // Adds more comments. Resources can have value definitions for various configurations, and // each of the definitions may have comments that need to be processed. - void AppendComment(const android::StringPiece& comment); + void AppendComment(android::StringPiece comment); void AppendNewLine(); diff --git a/tools/aapt2/java/ClassDefinition.cpp b/tools/aapt2/java/ClassDefinition.cpp index 3163497f0da6..98f3bd2018b0 100644 --- a/tools/aapt2/java/ClassDefinition.cpp +++ b/tools/aapt2/java/ClassDefinition.cpp @@ -27,8 +27,8 @@ void ClassMember::Print(bool /*final*/, Printer* printer, bool strip_api_annotat processor_.Print(printer, strip_api_annotations); } -void MethodDefinition::AppendStatement(const StringPiece& statement) { - statements_.push_back(statement.to_string()); +void MethodDefinition::AppendStatement(StringPiece statement) { + statements_.emplace_back(statement); } void MethodDefinition::Print(bool final, Printer* printer, bool) const { @@ -110,8 +110,8 @@ constexpr static const char* sWarningHeader = " * should not be modified by hand.\n" " */\n\n"; -void ClassDefinition::WriteJavaFile(const ClassDefinition* def, const StringPiece& package, - bool final, bool strip_api_annotations, io::OutputStream* out) { +void ClassDefinition::WriteJavaFile(const ClassDefinition* def, StringPiece package, bool final, + bool strip_api_annotations, io::OutputStream* out) { Printer printer(out); printer.Print(sWarningHeader).Print("package ").Print(package).Println(";"); printer.Println(); diff --git a/tools/aapt2/java/ClassDefinition.h b/tools/aapt2/java/ClassDefinition.h index 2acdadb3c034..63c99821a836 100644 --- a/tools/aapt2/java/ClassDefinition.h +++ b/tools/aapt2/java/ClassDefinition.h @@ -59,8 +59,8 @@ class ClassMember { template <typename T> class PrimitiveMember : public ClassMember { public: - PrimitiveMember(const android::StringPiece& name, const T& val, bool staged_api = false) - : name_(name.to_string()), val_(val), staged_api_(staged_api) { + PrimitiveMember(android::StringPiece name, const T& val, bool staged_api = false) + : name_(name), val_(val), staged_api_(staged_api) { } bool empty() const override { @@ -104,8 +104,8 @@ class PrimitiveMember : public ClassMember { template <> class PrimitiveMember<std::string> : public ClassMember { public: - PrimitiveMember(const android::StringPiece& name, const std::string& val, bool staged_api = false) - : name_(name.to_string()), val_(val) { + PrimitiveMember(android::StringPiece name, const std::string& val, bool staged_api = false) + : name_(name), val_(val) { } bool empty() const override { @@ -141,7 +141,8 @@ using StringMember = PrimitiveMember<std::string>; template <typename T, typename StringConverter> class PrimitiveArrayMember : public ClassMember { public: - explicit PrimitiveArrayMember(const android::StringPiece& name) : name_(name.to_string()) {} + explicit PrimitiveArrayMember(android::StringPiece name) : name_(name) { + } void AddElement(const T& val) { elements_.emplace_back(val); @@ -209,12 +210,12 @@ using ResourceArrayMember = PrimitiveArrayMember<std::variant<ResourceId, FieldR class MethodDefinition : public ClassMember { public: // Expected method signature example: 'public static void onResourcesLoaded(int p)'. - explicit MethodDefinition(const android::StringPiece& signature) - : signature_(signature.to_string()) {} + explicit MethodDefinition(android::StringPiece signature) : signature_(signature) { + } // Appends a single statement to the method. It should include no newlines or else // formatting may be broken. - void AppendStatement(const android::StringPiece& statement); + void AppendStatement(android::StringPiece statement); // Not quite the same as a name, but good enough. const std::string& GetName() const override { @@ -239,11 +240,12 @@ enum class ClassQualifier { kNone, kStatic }; class ClassDefinition : public ClassMember { public: - static void WriteJavaFile(const ClassDefinition* def, const android::StringPiece& package, - bool final, bool strip_api_annotations, io::OutputStream* out); + static void WriteJavaFile(const ClassDefinition* def, android::StringPiece package, bool final, + bool strip_api_annotations, io::OutputStream* out); - ClassDefinition(const android::StringPiece& name, ClassQualifier qualifier, bool createIfEmpty) - : name_(name.to_string()), qualifier_(qualifier), create_if_empty_(createIfEmpty) {} + ClassDefinition(android::StringPiece name, ClassQualifier qualifier, bool createIfEmpty) + : name_(name), qualifier_(qualifier), create_if_empty_(createIfEmpty) { + } enum class Result { kAdded, diff --git a/tools/aapt2/java/JavaClassGenerator.cpp b/tools/aapt2/java/JavaClassGenerator.cpp index a25ca22c288d..7665d0e8d9cb 100644 --- a/tools/aapt2/java/JavaClassGenerator.cpp +++ b/tools/aapt2/java/JavaClassGenerator.cpp @@ -57,14 +57,14 @@ static const std::set<StringPiece> sJavaIdentifiers = { "transient", "try", "void", "volatile", "while", "true", "false", "null"}; -static bool IsValidSymbol(const StringPiece& symbol) { +static bool IsValidSymbol(StringPiece symbol) { return sJavaIdentifiers.find(symbol) == sJavaIdentifiers.end(); } // Java symbols can not contain . or -, but those are valid in a resource name. // Replace those with '_'. -std::string JavaClassGenerator::TransformToFieldName(const StringPiece& symbol) { - std::string output = symbol.to_string(); +std::string JavaClassGenerator::TransformToFieldName(StringPiece symbol) { + std::string output(symbol); for (char& c : output) { if (c == '.' || c == '-') { c = '_'; @@ -84,7 +84,7 @@ std::string JavaClassGenerator::TransformToFieldName(const StringPiece& symbol) // Foo_bar static std::string TransformNestedAttr(const ResourceNameRef& attr_name, const std::string& styleable_class_name, - const StringPiece& package_name_to_generate) { + StringPiece package_name_to_generate) { std::string output = styleable_class_name; // We may reference IDs from other packages, so prefix the entry name with @@ -226,16 +226,15 @@ static bool operator<(const StyleableAttr& lhs, const StyleableAttr& rhs) { static FieldReference GetRFieldReference(const ResourceName& name, StringPiece fallback_package_name) { - const std::string package_name = - name.package.empty() ? fallback_package_name.to_string() : name.package; + const std::string_view package_name = name.package.empty() ? fallback_package_name : name.package; const std::string entry = JavaClassGenerator::TransformToFieldName(name.entry); - return FieldReference(StringPrintf("%s.R.%s.%s", package_name.c_str(), - name.type.to_string().data(), entry.c_str())); + return FieldReference( + StringPrintf("%s.R.%s.%s", package_name.data(), name.type.to_string().data(), entry.c_str())); } bool JavaClassGenerator::ProcessStyleable(const ResourceNameRef& name, const ResourceId& id, const Styleable& styleable, - const StringPiece& package_name_to_generate, + StringPiece package_name_to_generate, ClassDefinition* out_class_def, MethodDefinition* out_rewrite_method, Printer* r_txt_printer) { @@ -314,7 +313,8 @@ bool JavaClassGenerator::ProcessStyleable(const ResourceNameRef& name, const Res return true; } const StringPiece attr_comment_line = entry.symbol.value().attribute->GetComment(); - return attr_comment_line.contains("@removed") || attr_comment_line.contains("@hide"); + return attr_comment_line.find("@removed") != std::string::npos || + attr_comment_line.find("@hide") != std::string::npos; }); documentation_attrs.erase(documentation_remove_iter, documentation_attrs.end()); @@ -397,7 +397,7 @@ bool JavaClassGenerator::ProcessStyleable(const ResourceNameRef& name, const Res comment = styleable_attr.symbol.value().attribute->GetComment(); } - if (comment.contains("@removed")) { + if (comment.find("@removed") != std::string::npos) { // Removed attributes are public but hidden from the documentation, so // don't emit them as part of the class documentation. continue; @@ -497,7 +497,7 @@ void JavaClassGenerator::ProcessResource(const ResourceNameRef& name, const Reso } if (out_rewrite_method != nullptr) { - const std::string type_str = name.type.to_string(); + const auto type_str = name.type.to_string(); out_rewrite_method->AppendStatement( StringPrintf("%s.%s = (%s.%s & 0x00ffffff) | packageIdBits;", type_str.data(), field_name.data(), type_str.data(), field_name.data())); @@ -505,8 +505,7 @@ void JavaClassGenerator::ProcessResource(const ResourceNameRef& name, const Reso } std::optional<std::string> JavaClassGenerator::UnmangleResource( - const StringPiece& package_name, const StringPiece& package_name_to_generate, - const ResourceEntry& entry) { + StringPiece package_name, StringPiece package_name_to_generate, const ResourceEntry& entry) { if (SkipSymbol(entry.visibility.level)) { return {}; } @@ -528,7 +527,7 @@ std::optional<std::string> JavaClassGenerator::UnmangleResource( return {std::move(unmangled_name)}; } -bool JavaClassGenerator::ProcessType(const StringPiece& package_name_to_generate, +bool JavaClassGenerator::ProcessType(StringPiece package_name_to_generate, const ResourceTablePackage& package, const ResourceTableType& type, ClassDefinition* out_type_class_def, @@ -577,7 +576,7 @@ bool JavaClassGenerator::ProcessType(const StringPiece& package_name_to_generate return true; } -bool JavaClassGenerator::Generate(const StringPiece& package_name_to_generate, OutputStream* out, +bool JavaClassGenerator::Generate(StringPiece package_name_to_generate, OutputStream* out, OutputStream* out_r_txt) { return Generate(package_name_to_generate, package_name_to_generate, out, out_r_txt); } @@ -591,8 +590,8 @@ static void AppendJavaDocAnnotations(const std::vector<std::string>& annotations } } -bool JavaClassGenerator::Generate(const StringPiece& package_name_to_generate, - const StringPiece& out_package_name, OutputStream* out, +bool JavaClassGenerator::Generate(StringPiece package_name_to_generate, + StringPiece out_package_name, OutputStream* out, OutputStream* out_r_txt) { ClassDefinition r_class("R", ClassQualifier::kNone, true); std::unique_ptr<MethodDefinition> rewrite_method; diff --git a/tools/aapt2/java/JavaClassGenerator.h b/tools/aapt2/java/JavaClassGenerator.h index b45a2f12db35..234df04472ce 100644 --- a/tools/aapt2/java/JavaClassGenerator.h +++ b/tools/aapt2/java/JavaClassGenerator.h @@ -70,16 +70,16 @@ class JavaClassGenerator { // All symbols technically belong to a single package, but linked libraries will // have their names mangled, denoting that they came from a different package. // We need to generate these symbols in a separate file. Returns true on success. - bool Generate(const android::StringPiece& package_name_to_generate, io::OutputStream* out, + bool Generate(android::StringPiece package_name_to_generate, io::OutputStream* out, io::OutputStream* out_r_txt = nullptr); - bool Generate(const android::StringPiece& package_name_to_generate, - const android::StringPiece& output_package_name, io::OutputStream* out, + bool Generate(android::StringPiece package_name_to_generate, + android::StringPiece output_package_name, io::OutputStream* out, io::OutputStream* out_r_txt = nullptr); const std::string& GetError() const; - static std::string TransformToFieldName(const android::StringPiece& symbol); + static std::string TransformToFieldName(android::StringPiece symbol); private: bool SkipSymbol(Visibility::Level state); @@ -87,11 +87,11 @@ class JavaClassGenerator { // Returns the unmangled resource entry name if the unmangled package is the same as // package_name_to_generate. Returns nothing if the resource should be skipped. - std::optional<std::string> UnmangleResource(const android::StringPiece& package_name, - const android::StringPiece& package_name_to_generate, + std::optional<std::string> UnmangleResource(android::StringPiece package_name, + android::StringPiece package_name_to_generate, const ResourceEntry& entry); - bool ProcessType(const android::StringPiece& package_name_to_generate, + bool ProcessType(android::StringPiece package_name_to_generate, const ResourceTablePackage& package, const ResourceTableType& type, ClassDefinition* out_type_class_def, MethodDefinition* out_rewrite_method_def, text::Printer* r_txt_printer); @@ -106,8 +106,7 @@ class JavaClassGenerator { // its package ID if `out_rewrite_method` is not nullptr. // `package_name_to_generate` is the package bool ProcessStyleable(const ResourceNameRef& name, const ResourceId& id, - const Styleable& styleable, - const android::StringPiece& package_name_to_generate, + const Styleable& styleable, android::StringPiece package_name_to_generate, ClassDefinition* out_class_def, MethodDefinition* out_rewrite_method, text::Printer* r_txt_printer); diff --git a/tools/aapt2/link/ManifestFixer.cpp b/tools/aapt2/link/ManifestFixer.cpp index d0850b800e4f..56d90758ee73 100644 --- a/tools/aapt2/link/ManifestFixer.cpp +++ b/tools/aapt2/link/ManifestFixer.cpp @@ -646,8 +646,8 @@ bool ManifestFixer::BuildRules(xml::XmlActionExecutor* executor, android::IDiagn return true; } -static void FullyQualifyClassName(const StringPiece& package, const StringPiece& attr_ns, - const StringPiece& attr_name, xml::Element* el) { +static void FullyQualifyClassName(StringPiece package, StringPiece attr_ns, StringPiece attr_name, + xml::Element* el) { xml::Attribute* attr = el->FindAttribute(attr_ns, attr_name); if (attr != nullptr) { if (std::optional<std::string> new_value = @@ -657,7 +657,7 @@ static void FullyQualifyClassName(const StringPiece& package, const StringPiece& } } -static bool RenameManifestPackage(const StringPiece& package_override, xml::Element* manifest_el) { +static bool RenameManifestPackage(StringPiece package_override, xml::Element* manifest_el) { xml::Attribute* attr = manifest_el->FindAttribute({}, "package"); // We've already verified that the manifest element is present, with a package @@ -665,7 +665,7 @@ static bool RenameManifestPackage(const StringPiece& package_override, xml::Elem CHECK(attr != nullptr); std::string original_package = std::move(attr->value); - attr->value = package_override.to_string(); + attr->value.assign(package_override); xml::Element* application_el = manifest_el->FindChild({}, "application"); if (application_el != nullptr) { diff --git a/tools/aapt2/link/ManifestFixer_test.cpp b/tools/aapt2/link/ManifestFixer_test.cpp index 8d1a647b494d..7180ae6b8bc7 100644 --- a/tools/aapt2/link/ManifestFixer_test.cpp +++ b/tools/aapt2/link/ManifestFixer_test.cpp @@ -61,12 +61,12 @@ struct ManifestFixerTest : public ::testing::Test { .Build(); } - std::unique_ptr<xml::XmlResource> Verify(const StringPiece& str) { + std::unique_ptr<xml::XmlResource> Verify(StringPiece str) { return VerifyWithOptions(str, {}); } - std::unique_ptr<xml::XmlResource> VerifyWithOptions( - const StringPiece& str, const ManifestFixerOptions& options) { + std::unique_ptr<xml::XmlResource> VerifyWithOptions(StringPiece str, + const ManifestFixerOptions& options) { std::unique_ptr<xml::XmlResource> doc = test::BuildXmlDom(str); ManifestFixer fixer(options); if (fixer.Consume(mContext.get(), doc.get())) { diff --git a/tools/aapt2/link/ReferenceLinker.cpp b/tools/aapt2/link/ReferenceLinker.cpp index f2a93a868bb7..9dadfb26a3f8 100644 --- a/tools/aapt2/link/ReferenceLinker.cpp +++ b/tools/aapt2/link/ReferenceLinker.cpp @@ -189,8 +189,7 @@ class EmptyDeclStack : public xml::IPackageDeclStack { public: EmptyDeclStack() = default; - std::optional<xml::ExtractedPackage> TransformPackageAlias( - const StringPiece& alias) const override { + std::optional<xml::ExtractedPackage> TransformPackageAlias(StringPiece alias) const override { if (alias.empty()) { return xml::ExtractedPackage{{}, true /*private*/}; } @@ -206,8 +205,7 @@ struct MacroDeclStack : public xml::IPackageDeclStack { : alias_namespaces_(std::move(namespaces)) { } - std::optional<xml::ExtractedPackage> TransformPackageAlias( - const StringPiece& alias) const override { + std::optional<xml::ExtractedPackage> TransformPackageAlias(StringPiece alias) const override { if (alias.empty()) { return xml::ExtractedPackage{{}, true /*private*/}; } diff --git a/tools/aapt2/link/TableMerger.cpp b/tools/aapt2/link/TableMerger.cpp index c9f0964193d2..67a48283e8b6 100644 --- a/tools/aapt2/link/TableMerger.cpp +++ b/tools/aapt2/link/TableMerger.cpp @@ -66,7 +66,7 @@ bool TableMerger::MergeImpl(const android::Source& src, ResourceTable* table, bo // This will merge and mangle resources from a static library. It is assumed that all FileReferences // have correctly set their io::IFile*. -bool TableMerger::MergeAndMangle(const android::Source& src, const StringPiece& package_name, +bool TableMerger::MergeAndMangle(const android::Source& src, StringPiece package_name, ResourceTable* table) { bool error = false; for (auto& package : table->packages) { @@ -326,8 +326,8 @@ std::unique_ptr<FileReference> TableMerger::CloneAndMangleFile( const std::string& package, const FileReference& file_ref) { StringPiece prefix, entry, suffix; if (util::ExtractResFilePathParts(*file_ref.path, &prefix, &entry, &suffix)) { - std::string mangled_entry = NameMangler::MangleEntry(package, entry.to_string()); - std::string newPath = prefix.to_string() + mangled_entry + suffix.to_string(); + std::string mangled_entry = NameMangler::MangleEntry(package, entry); + std::string newPath = (std::string(prefix) += mangled_entry) += suffix; std::unique_ptr<FileReference> new_file_ref = util::make_unique<FileReference>(main_table_->string_pool.MakeRef(newPath)); new_file_ref->SetComment(file_ref.GetComment()); diff --git a/tools/aapt2/link/TableMerger.h b/tools/aapt2/link/TableMerger.h index 2ba212372966..37daf42f51e5 100644 --- a/tools/aapt2/link/TableMerger.h +++ b/tools/aapt2/link/TableMerger.h @@ -61,7 +61,7 @@ class TableMerger { // References are made to this ResourceTable for efficiency reasons. TableMerger(IAaptContext* context, ResourceTable* out_table, const TableMergerOptions& options); - inline const std::set<std::string>& merged_packages() const { + inline const std::set<std::string, std::less<>>& merged_packages() const { return merged_packages_; } @@ -71,7 +71,7 @@ class TableMerger { // Merges resources from the given package, mangling the name. This is for static libraries. // All FileReference values must have their io::IFile set. - bool MergeAndMangle(const android::Source& src, const android::StringPiece& package, + bool MergeAndMangle(const android::Source& src, android::StringPiece package, ResourceTable* table); // Merges a compiled file that belongs to this same or empty package. @@ -84,7 +84,7 @@ class TableMerger { ResourceTable* main_table_; TableMergerOptions options_; ResourceTablePackage* main_package_; - std::set<std::string> merged_packages_; + std::set<std::string, std::less<>> merged_packages_; bool MergeImpl(const android::Source& src, ResourceTable* src_table, bool overlay, bool allow_new); diff --git a/tools/aapt2/optimize/MultiApkGenerator.cpp b/tools/aapt2/optimize/MultiApkGenerator.cpp index f994e27e4e5b..f01db3ddca2e 100644 --- a/tools/aapt2/optimize/MultiApkGenerator.cpp +++ b/tools/aapt2/optimize/MultiApkGenerator.cpp @@ -113,12 +113,12 @@ class ContextWrapper : public IAaptContext { }; class SignatureFilter : public IPathFilter { - bool Keep(const std::string& path) override { + bool Keep(std::string_view path) override { static std::regex signature_regex(R"regex(^META-INF/.*\.(RSA|DSA|EC|SF)$)regex"); - if (std::regex_search(path, signature_regex)) { + if (std::regex_search(path.begin(), path.end(), signature_regex)) { return false; } - return !(path == "META-INF/MANIFEST.MF"); + return path != "META-INF/MANIFEST.MF"; } }; diff --git a/tools/aapt2/optimize/Obfuscator.cpp b/tools/aapt2/optimize/Obfuscator.cpp index f704f26bfd29..1fdd728928df 100644 --- a/tools/aapt2/optimize/Obfuscator.cpp +++ b/tools/aapt2/optimize/Obfuscator.cpp @@ -35,7 +35,7 @@ namespace aapt { Obfuscator::Obfuscator(std::map<std::string, std::string>& path_map_out) : path_map_(path_map_out) { } -std::string ShortenFileName(const android::StringPiece& file_path, int output_length) { +std::string ShortenFileName(android::StringPiece file_path, int output_length) { std::size_t hash_num = std::hash<android::StringPiece>{}(file_path); std::string result = ""; // Convert to (modified) base64 so that it is a proper file path. @@ -58,9 +58,9 @@ int OptimalShortenedLength(int num_resources) { } } -std::string GetShortenedPath(const android::StringPiece& shortened_filename, - const android::StringPiece& extension, int collision_count) { - std::string shortened_path = "res/" + shortened_filename.to_string(); +std::string GetShortenedPath(android::StringPiece shortened_filename, + android::StringPiece extension, int collision_count) { + std::string shortened_path = std::string("res/") += shortened_filename; if (collision_count > 0) { shortened_path += std::to_string(collision_count); } diff --git a/tools/aapt2/optimize/VersionCollapser_test.cpp b/tools/aapt2/optimize/VersionCollapser_test.cpp index aa0d0c095f57..18dcd6bace77 100644 --- a/tools/aapt2/optimize/VersionCollapser_test.cpp +++ b/tools/aapt2/optimize/VersionCollapser_test.cpp @@ -23,7 +23,7 @@ using android::StringPiece; namespace aapt { static std::unique_ptr<ResourceTable> BuildTableWithConfigs( - const StringPiece& name, std::initializer_list<std::string> list) { + StringPiece name, std::initializer_list<std::string> list) { test::ResourceTableBuilder builder; for (const std::string& item : list) { builder.AddSimple(name, test::ParseConfigOrDie(item)); diff --git a/tools/aapt2/process/SymbolTable.cpp b/tools/aapt2/process/SymbolTable.cpp index 92b45c397eed..bca62da447b0 100644 --- a/tools/aapt2/process/SymbolTable.cpp +++ b/tools/aapt2/process/SymbolTable.cpp @@ -218,7 +218,7 @@ std::unique_ptr<SymbolTable::Symbol> ResourceTableSymbolSource::FindByName( return symbol; } -bool AssetManagerSymbolSource::AddAssetPath(const StringPiece& path) { +bool AssetManagerSymbolSource::AddAssetPath(StringPiece path) { TRACE_CALL(); if (std::unique_ptr<const ApkAssets> apk = ApkAssets::Load(path.data())) { apk_assets_.push_back(std::move(apk)); diff --git a/tools/aapt2/process/SymbolTable.h b/tools/aapt2/process/SymbolTable.h index c17837c224ab..b09ff702ca58 100644 --- a/tools/aapt2/process/SymbolTable.h +++ b/tools/aapt2/process/SymbolTable.h @@ -192,7 +192,7 @@ class AssetManagerSymbolSource : public ISymbolSource { public: AssetManagerSymbolSource() = default; - bool AddAssetPath(const android::StringPiece& path); + bool AddAssetPath(android::StringPiece path); std::map<size_t, std::string> GetAssignedPackageIds() const; bool IsPackageDynamic(uint32_t packageId, const std::string& package_name) const; diff --git a/tools/aapt2/test/Builders.cpp b/tools/aapt2/test/Builders.cpp index 30336e27b907..65f63dc68e54 100644 --- a/tools/aapt2/test/Builders.cpp +++ b/tools/aapt2/test/Builders.cpp @@ -34,61 +34,53 @@ using ::android::StringPiece; namespace aapt { namespace test { -ResourceTableBuilder& ResourceTableBuilder::AddSimple(const StringPiece& name, - const ResourceId& id) { +ResourceTableBuilder& ResourceTableBuilder::AddSimple(StringPiece name, const ResourceId& id) { return AddValue(name, id, util::make_unique<Id>()); } -ResourceTableBuilder& ResourceTableBuilder::AddSimple(const StringPiece& name, +ResourceTableBuilder& ResourceTableBuilder::AddSimple(StringPiece name, const ConfigDescription& config, const ResourceId& id) { return AddValue(name, config, id, util::make_unique<Id>()); } -ResourceTableBuilder& ResourceTableBuilder::AddReference(const StringPiece& name, - const StringPiece& ref) { +ResourceTableBuilder& ResourceTableBuilder::AddReference(StringPiece name, StringPiece ref) { return AddReference(name, {}, ref); } -ResourceTableBuilder& ResourceTableBuilder::AddReference(const StringPiece& name, - const ResourceId& id, - const StringPiece& ref) { +ResourceTableBuilder& ResourceTableBuilder::AddReference(StringPiece name, const ResourceId& id, + StringPiece ref) { return AddValue(name, id, util::make_unique<Reference>(ParseNameOrDie(ref))); } -ResourceTableBuilder& ResourceTableBuilder::AddString(const StringPiece& name, - const StringPiece& str) { +ResourceTableBuilder& ResourceTableBuilder::AddString(StringPiece name, StringPiece str) { return AddString(name, {}, str); } -ResourceTableBuilder& ResourceTableBuilder::AddString(const StringPiece& name, const ResourceId& id, - const StringPiece& str) { +ResourceTableBuilder& ResourceTableBuilder::AddString(StringPiece name, const ResourceId& id, + StringPiece str) { return AddValue(name, id, util::make_unique<String>(table_->string_pool.MakeRef(str))); } -ResourceTableBuilder& ResourceTableBuilder::AddString(const StringPiece& name, const ResourceId& id, +ResourceTableBuilder& ResourceTableBuilder::AddString(StringPiece name, const ResourceId& id, const ConfigDescription& config, - const StringPiece& str) { + StringPiece str) { return AddValue(name, config, id, util::make_unique<String>(table_->string_pool.MakeRef(str))); } -ResourceTableBuilder& ResourceTableBuilder::AddFileReference(const StringPiece& name, - const StringPiece& path, +ResourceTableBuilder& ResourceTableBuilder::AddFileReference(StringPiece name, StringPiece path, io::IFile* file) { return AddFileReference(name, {}, path, file); } -ResourceTableBuilder& ResourceTableBuilder::AddFileReference(const StringPiece& name, - const ResourceId& id, - const StringPiece& path, - io::IFile* file) { +ResourceTableBuilder& ResourceTableBuilder::AddFileReference(StringPiece name, const ResourceId& id, + StringPiece path, io::IFile* file) { auto file_ref = util::make_unique<FileReference>(table_->string_pool.MakeRef(path)); file_ref->file = file; return AddValue(name, id, std::move(file_ref)); } -ResourceTableBuilder& ResourceTableBuilder::AddFileReference(const StringPiece& name, - const StringPiece& path, +ResourceTableBuilder& ResourceTableBuilder::AddFileReference(StringPiece name, StringPiece path, const ConfigDescription& config, io::IFile* file) { auto file_ref = util::make_unique<FileReference>(table_->string_pool.MakeRef(path)); @@ -96,17 +88,17 @@ ResourceTableBuilder& ResourceTableBuilder::AddFileReference(const StringPiece& return AddValue(name, config, {}, std::move(file_ref)); } -ResourceTableBuilder& ResourceTableBuilder::AddValue(const StringPiece& name, +ResourceTableBuilder& ResourceTableBuilder::AddValue(StringPiece name, std::unique_ptr<Value> value) { return AddValue(name, {}, std::move(value)); } -ResourceTableBuilder& ResourceTableBuilder::AddValue(const StringPiece& name, const ResourceId& id, +ResourceTableBuilder& ResourceTableBuilder::AddValue(StringPiece name, const ResourceId& id, std::unique_ptr<Value> value) { return AddValue(name, {}, id, std::move(value)); } -ResourceTableBuilder& ResourceTableBuilder::AddValue(const StringPiece& name, +ResourceTableBuilder& ResourceTableBuilder::AddValue(StringPiece name, const ConfigDescription& config, const ResourceId& id, std::unique_ptr<Value> value) { @@ -121,8 +113,7 @@ ResourceTableBuilder& ResourceTableBuilder::AddValue(const StringPiece& name, return *this; } -ResourceTableBuilder& ResourceTableBuilder::SetSymbolState(const StringPiece& name, - const ResourceId& id, +ResourceTableBuilder& ResourceTableBuilder::SetSymbolState(StringPiece name, const ResourceId& id, Visibility::Level level, bool allow_new) { ResourceName res_name = ParseNameOrDie(name); @@ -136,9 +127,8 @@ ResourceTableBuilder& ResourceTableBuilder::SetSymbolState(const StringPiece& na return *this; } -ResourceTableBuilder& ResourceTableBuilder::SetOverlayable(const StringPiece& name, +ResourceTableBuilder& ResourceTableBuilder::SetOverlayable(StringPiece name, const OverlayableItem& overlayable) { - ResourceName res_name = ParseNameOrDie(name); CHECK(table_->AddResource( NewResourceBuilder(res_name).SetOverlayable(overlayable).SetAllowMangled(true).Build(), @@ -159,8 +149,7 @@ std::unique_ptr<ResourceTable> ResourceTableBuilder::Build() { return std::move(table_); } -std::unique_ptr<Reference> BuildReference(const StringPiece& ref, - const std::optional<ResourceId>& id) { +std::unique_ptr<Reference> BuildReference(StringPiece ref, const std::optional<ResourceId>& id) { std::unique_ptr<Reference> reference = util::make_unique<Reference>(ParseNameOrDie(ref)); reference->id = id; return reference; @@ -188,7 +177,7 @@ AttributeBuilder& AttributeBuilder::SetWeak(bool weak) { return *this; } -AttributeBuilder& AttributeBuilder::AddItem(const StringPiece& name, uint32_t value) { +AttributeBuilder& AttributeBuilder::AddItem(StringPiece name, uint32_t value) { attr_->symbols.push_back( Attribute::Symbol{Reference(ResourceName({}, ResourceType::kId, name)), value}); return *this; @@ -198,17 +187,17 @@ std::unique_ptr<Attribute> AttributeBuilder::Build() { return std::move(attr_); } -StyleBuilder& StyleBuilder::SetParent(const StringPiece& str) { +StyleBuilder& StyleBuilder::SetParent(StringPiece str) { style_->parent = Reference(ParseNameOrDie(str)); return *this; } -StyleBuilder& StyleBuilder::AddItem(const StringPiece& str, std::unique_ptr<Item> value) { +StyleBuilder& StyleBuilder::AddItem(StringPiece str, std::unique_ptr<Item> value) { style_->entries.push_back(Style::Entry{Reference(ParseNameOrDie(str)), std::move(value)}); return *this; } -StyleBuilder& StyleBuilder::AddItem(const StringPiece& str, const ResourceId& id, +StyleBuilder& StyleBuilder::AddItem(StringPiece str, const ResourceId& id, std::unique_ptr<Item> value) { AddItem(str, std::move(value)); style_->entries.back().key.id = id; @@ -219,8 +208,7 @@ std::unique_ptr<Style> StyleBuilder::Build() { return std::move(style_); } -StyleableBuilder& StyleableBuilder::AddItem(const StringPiece& str, - const std::optional<ResourceId>& id) { +StyleableBuilder& StyleableBuilder::AddItem(StringPiece str, const std::optional<ResourceId>& id) { styleable_->entries.push_back(Reference(ParseNameOrDie(str))); styleable_->entries.back().id = id; return *this; @@ -230,7 +218,7 @@ std::unique_ptr<Styleable> StyleableBuilder::Build() { return std::move(styleable_); } -std::unique_ptr<xml::XmlResource> BuildXmlDom(const StringPiece& str) { +std::unique_ptr<xml::XmlResource> BuildXmlDom(StringPiece str) { std::string input = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"; input.append(str.data(), str.size()); StringInputStream in(input); @@ -241,7 +229,7 @@ std::unique_ptr<xml::XmlResource> BuildXmlDom(const StringPiece& str) { } std::unique_ptr<xml::XmlResource> BuildXmlDomForPackageName(IAaptContext* context, - const StringPiece& str) { + StringPiece str) { std::unique_ptr<xml::XmlResource> doc = BuildXmlDom(str); doc->file.name.package = context->GetCompilationPackage(); return doc; diff --git a/tools/aapt2/test/Builders.h b/tools/aapt2/test/Builders.h index 780bd0df8f16..f03d6fcd03f1 100644 --- a/tools/aapt2/test/Builders.h +++ b/tools/aapt2/test/Builders.h @@ -38,40 +38,35 @@ class ResourceTableBuilder { public: ResourceTableBuilder() = default; - ResourceTableBuilder& AddSimple(const android::StringPiece& name, const ResourceId& id = {}); - ResourceTableBuilder& AddSimple(const android::StringPiece& name, + ResourceTableBuilder& AddSimple(android::StringPiece name, const ResourceId& id = {}); + ResourceTableBuilder& AddSimple(android::StringPiece name, const android::ConfigDescription& config, const ResourceId& id = {}); - ResourceTableBuilder& AddReference(const android::StringPiece& name, - const android::StringPiece& ref); - ResourceTableBuilder& AddReference(const android::StringPiece& name, const ResourceId& id, - const android::StringPiece& ref); - ResourceTableBuilder& AddString(const android::StringPiece& name, - const android::StringPiece& str); - ResourceTableBuilder& AddString(const android::StringPiece& name, const ResourceId& id, - const android::StringPiece& str); - ResourceTableBuilder& AddString(const android::StringPiece& name, const ResourceId& id, + ResourceTableBuilder& AddReference(android::StringPiece name, android::StringPiece ref); + ResourceTableBuilder& AddReference(android::StringPiece name, const ResourceId& id, + android::StringPiece ref); + ResourceTableBuilder& AddString(android::StringPiece name, android::StringPiece str); + ResourceTableBuilder& AddString(android::StringPiece name, const ResourceId& id, + android::StringPiece str); + ResourceTableBuilder& AddString(android::StringPiece name, const ResourceId& id, const android::ConfigDescription& config, - const android::StringPiece& str); - ResourceTableBuilder& AddFileReference(const android::StringPiece& name, - const android::StringPiece& path, + android::StringPiece str); + ResourceTableBuilder& AddFileReference(android::StringPiece name, android::StringPiece path, io::IFile* file = nullptr); - ResourceTableBuilder& AddFileReference(const android::StringPiece& name, const ResourceId& id, - const android::StringPiece& path, - io::IFile* file = nullptr); - ResourceTableBuilder& AddFileReference(const android::StringPiece& name, - const android::StringPiece& path, + ResourceTableBuilder& AddFileReference(android::StringPiece name, const ResourceId& id, + android::StringPiece path, io::IFile* file = nullptr); + ResourceTableBuilder& AddFileReference(android::StringPiece name, android::StringPiece path, const android::ConfigDescription& config, io::IFile* file = nullptr); - ResourceTableBuilder& AddValue(const android::StringPiece& name, std::unique_ptr<Value> value); - ResourceTableBuilder& AddValue(const android::StringPiece& name, const ResourceId& id, + ResourceTableBuilder& AddValue(android::StringPiece name, std::unique_ptr<Value> value); + ResourceTableBuilder& AddValue(android::StringPiece name, const ResourceId& id, + std::unique_ptr<Value> value); + ResourceTableBuilder& AddValue(android::StringPiece name, + const android::ConfigDescription& config, const ResourceId& id, std::unique_ptr<Value> value); - ResourceTableBuilder& AddValue(const android::StringPiece& name, - const android::ConfigDescription& config, - const ResourceId& id, std::unique_ptr<Value> value); - ResourceTableBuilder& SetSymbolState(const android::StringPiece& name, const ResourceId& id, + ResourceTableBuilder& SetSymbolState(android::StringPiece name, const ResourceId& id, Visibility::Level level, bool allow_new = false); - ResourceTableBuilder& SetOverlayable(const android::StringPiece& name, + ResourceTableBuilder& SetOverlayable(android::StringPiece name, const OverlayableItem& overlayable); ResourceTableBuilder& Add(NewResource&& res); @@ -84,7 +79,7 @@ class ResourceTableBuilder { std::unique_ptr<ResourceTable> table_ = util::make_unique<ResourceTable>(); }; -std::unique_ptr<Reference> BuildReference(const android::StringPiece& ref, +std::unique_ptr<Reference> BuildReference(android::StringPiece ref, const std::optional<ResourceId>& id = {}); std::unique_ptr<BinaryPrimitive> BuildPrimitive(uint8_t type, uint32_t data); @@ -101,7 +96,7 @@ class ValueBuilder { return *this; } - ValueBuilder& SetComment(const android::StringPiece& str) { + ValueBuilder& SetComment(android::StringPiece str) { value_->SetComment(str); return *this; } @@ -121,7 +116,7 @@ class AttributeBuilder { AttributeBuilder(); AttributeBuilder& SetTypeMask(uint32_t typeMask); AttributeBuilder& SetWeak(bool weak); - AttributeBuilder& AddItem(const android::StringPiece& name, uint32_t value); + AttributeBuilder& AddItem(android::StringPiece name, uint32_t value); std::unique_ptr<Attribute> Build(); private: @@ -133,9 +128,9 @@ class AttributeBuilder { class StyleBuilder { public: StyleBuilder() = default; - StyleBuilder& SetParent(const android::StringPiece& str); - StyleBuilder& AddItem(const android::StringPiece& str, std::unique_ptr<Item> value); - StyleBuilder& AddItem(const android::StringPiece& str, const ResourceId& id, + StyleBuilder& SetParent(android::StringPiece str); + StyleBuilder& AddItem(android::StringPiece str, std::unique_ptr<Item> value); + StyleBuilder& AddItem(android::StringPiece str, const ResourceId& id, std::unique_ptr<Item> value); std::unique_ptr<Style> Build(); @@ -148,8 +143,7 @@ class StyleBuilder { class StyleableBuilder { public: StyleableBuilder() = default; - StyleableBuilder& AddItem(const android::StringPiece& str, - const std::optional<ResourceId>& id = {}); + StyleableBuilder& AddItem(android::StringPiece str, const std::optional<ResourceId>& id = {}); std::unique_ptr<Styleable> Build(); private: @@ -158,9 +152,9 @@ class StyleableBuilder { std::unique_ptr<Styleable> styleable_ = util::make_unique<Styleable>(); }; -std::unique_ptr<xml::XmlResource> BuildXmlDom(const android::StringPiece& str); +std::unique_ptr<xml::XmlResource> BuildXmlDom(android::StringPiece str); std::unique_ptr<xml::XmlResource> BuildXmlDomForPackageName(IAaptContext* context, - const android::StringPiece& str); + android::StringPiece str); class ArtifactBuilder { public: diff --git a/tools/aapt2/test/Common.cpp b/tools/aapt2/test/Common.cpp index eca0c1c12bab..cdf245341844 100644 --- a/tools/aapt2/test/Common.cpp +++ b/tools/aapt2/test/Common.cpp @@ -44,10 +44,9 @@ android::IDiagnostics* GetDiagnostics() { } template <> -Value* GetValueForConfigAndProduct<Value>(ResourceTable* table, - const android::StringPiece& res_name, +Value* GetValueForConfigAndProduct<Value>(ResourceTable* table, android::StringPiece res_name, const ConfigDescription& config, - const android::StringPiece& product) { + android::StringPiece product) { std::optional<ResourceTable::SearchResult> result = table->FindResource(ParseNameOrDie(res_name)); if (result) { ResourceConfigValue* config_value = result.value().entry->FindValue(config, product); diff --git a/tools/aapt2/test/Common.h b/tools/aapt2/test/Common.h index 3f28361f6c2b..83a0f3f3f652 100644 --- a/tools/aapt2/test/Common.h +++ b/tools/aapt2/test/Common.h @@ -39,22 +39,22 @@ namespace test { android::IDiagnostics* GetDiagnostics(); -inline ResourceName ParseNameOrDie(const android::StringPiece& str) { +inline ResourceName ParseNameOrDie(android::StringPiece str) { ResourceNameRef ref; CHECK(ResourceUtils::ParseResourceName(str, &ref)) << "invalid resource name: " << str; return ref.ToResourceName(); } -inline android::ConfigDescription ParseConfigOrDie(const android::StringPiece& str) { - android::ConfigDescription config; +inline android::ConfigDescription ParseConfigOrDie(android::StringPiece str) { + android::ConfigDescription config; CHECK(android::ConfigDescription::Parse(str, &config)) << "invalid configuration: " << str; return config; } template <typename T = Value> -T* GetValueForConfigAndProduct(ResourceTable* table, const android::StringPiece& res_name, +T* GetValueForConfigAndProduct(ResourceTable* table, android::StringPiece res_name, const android::ConfigDescription& config, - const android::StringPiece& product) { + android::StringPiece product) { std::optional<ResourceTable::SearchResult> result = table->FindResource(ParseNameOrDie(res_name)); if (result) { ResourceConfigValue* config_value = result.value().entry->FindValue(config, product); @@ -66,25 +66,25 @@ T* GetValueForConfigAndProduct(ResourceTable* table, const android::StringPiece& } template <> -Value* GetValueForConfigAndProduct<Value>(ResourceTable* table, - const android::StringPiece& res_name, +Value* GetValueForConfigAndProduct<Value>(ResourceTable* table, android::StringPiece res_name, const android::ConfigDescription& config, - const android::StringPiece& product); + android::StringPiece product); template <typename T = Value> -T* GetValueForConfig(ResourceTable* table, const android::StringPiece& res_name, +T* GetValueForConfig(ResourceTable* table, android::StringPiece res_name, const android::ConfigDescription& config) { return GetValueForConfigAndProduct<T>(table, res_name, config, {}); } template <typename T = Value> -T* GetValue(ResourceTable* table, const android::StringPiece& res_name) { +T* GetValue(ResourceTable* table, android::StringPiece res_name) { return GetValueForConfig<T>(table, res_name, {}); } class TestFile : public io::IFile { public: - explicit TestFile(const android::StringPiece& path) : source_(path) {} + explicit TestFile(android::StringPiece path) : source_(path) { + } std::unique_ptr<io::IData> OpenAsData() override { return {}; diff --git a/tools/aapt2/test/Context.h b/tools/aapt2/test/Context.h index 4e4973ea39be..c5331fb87381 100644 --- a/tools/aapt2/test/Context.h +++ b/tools/aapt2/test/Context.h @@ -52,8 +52,8 @@ class Context : public IAaptContext { return compilation_package_.value(); } - void SetCompilationPackage(const android::StringPiece& package) { - compilation_package_ = package.to_string(); + void SetCompilationPackage(android::StringPiece package) { + compilation_package_ = std::string(package); } uint8_t GetPackageId() override { @@ -111,8 +111,8 @@ class ContextBuilder { return *this; } - ContextBuilder& SetCompilationPackage(const android::StringPiece& package) { - context_->compilation_package_ = package.to_string(); + ContextBuilder& SetCompilationPackage(android::StringPiece package) { + context_->compilation_package_ = std::string(package); return *this; } @@ -149,7 +149,7 @@ class ContextBuilder { class StaticSymbolSourceBuilder { public: - StaticSymbolSourceBuilder& AddPublicSymbol(const android::StringPiece& name, ResourceId id, + StaticSymbolSourceBuilder& AddPublicSymbol(android::StringPiece name, ResourceId id, std::unique_ptr<Attribute> attr = {}) { std::unique_ptr<SymbolTable::Symbol> symbol = util::make_unique<SymbolTable::Symbol>(id, std::move(attr), true); @@ -159,7 +159,7 @@ class StaticSymbolSourceBuilder { return *this; } - StaticSymbolSourceBuilder& AddSymbol(const android::StringPiece& name, ResourceId id, + StaticSymbolSourceBuilder& AddSymbol(android::StringPiece name, ResourceId id, std::unique_ptr<Attribute> attr = {}) { std::unique_ptr<SymbolTable::Symbol> symbol = util::make_unique<SymbolTable::Symbol>(id, std::move(attr), false); diff --git a/tools/aapt2/test/Fixture.cpp b/tools/aapt2/test/Fixture.cpp index dbc0e3643104..428372f31d0d 100644 --- a/tools/aapt2/test/Fixture.cpp +++ b/tools/aapt2/test/Fixture.cpp @@ -38,8 +38,8 @@ namespace aapt { const char* CommandTestFixture::kDefaultPackageName = "com.aapt.command.test"; -void ClearDirectory(const android::StringPiece& path) { - const std::string root_dir = path.to_string(); +void ClearDirectory(android::StringPiece path) { + const std::string root_dir(path); std::unique_ptr<DIR, decltype(closedir)*> dir(opendir(root_dir.data()), closedir); if (!dir) { StdErrDiagnostics().Error(android::DiagMessage() @@ -91,8 +91,7 @@ void TestDirectoryFixture::WriteFile(const std::string& path, const std::string& } bool CommandTestFixture::CompileFile(const std::string& path, const std::string& contents, - const android::StringPiece& out_dir, - android::IDiagnostics* diag) { + android::StringPiece out_dir, android::IDiagnostics* diag) { WriteFile(path, contents); CHECK(file::mkdirs(out_dir.data())); return CompileCommand(diag).Execute({path, "-o", out_dir, "-v"}, &std::cerr) == 0; @@ -113,8 +112,8 @@ bool CommandTestFixture::Link(const std::vector<std::string>& args, android::IDi return LinkCommand(diag).Execute(link_args, &std::cerr) == 0; } -bool CommandTestFixture::Link(const std::vector<std::string>& args, - const android::StringPiece& flat_dir, android::IDiagnostics* diag) { +bool CommandTestFixture::Link(const std::vector<std::string>& args, android::StringPiece flat_dir, + android::IDiagnostics* diag) { std::vector<android::StringPiece> link_args; for(const std::string& arg : args) { link_args.emplace_back(arg); @@ -148,7 +147,7 @@ std::string CommandTestFixture::GetDefaultManifest(const char* package_name) { } std::unique_ptr<io::IData> CommandTestFixture::OpenFileAsData(LoadedApk* apk, - const android::StringPiece& path) { + android::StringPiece path) { return apk ->GetFileCollection() ->FindFile(path) diff --git a/tools/aapt2/test/Fixture.h b/tools/aapt2/test/Fixture.h index 61403b7b0a6d..ba4a734e03bb 100644 --- a/tools/aapt2/test/Fixture.h +++ b/tools/aapt2/test/Fixture.h @@ -48,7 +48,7 @@ class TestDirectoryFixture : public ::testing::Test { // Retrieves the absolute path of the specified relative path in the test directory. Directories // should be separated using forward slashes ('/'), and these slashes will be translated to // backslashes when running Windows tests. - std::string GetTestPath(const android::StringPiece& path) { + std::string GetTestPath(android::StringPiece path) { std::string base = temp_dir_; for (android::StringPiece part : util::Split(path, '/')) { file::AppendPath(&base, part); @@ -73,22 +73,21 @@ class CommandTestFixture : public TestDirectoryFixture { // Wries the contents of the file to the specified path. The file is compiled and the flattened // file is written to the out directory. bool CompileFile(const std::string& path, const std::string& contents, - const android::StringPiece& flat_out_dir, android::IDiagnostics* diag); + android::StringPiece flat_out_dir, android::IDiagnostics* diag); // Executes the link command with the specified arguments. bool Link(const std::vector<std::string>& args, android::IDiagnostics* diag); // Executes the link command with the specified arguments. The flattened files residing in the // flat directory will be added to the link command as file arguments. - bool Link(const std::vector<std::string>& args, const android::StringPiece& flat_dir, + bool Link(const std::vector<std::string>& args, android::StringPiece flat_dir, android::IDiagnostics* diag); // Creates a minimal android manifest within the test directory and returns the file path. std::string GetDefaultManifest(const char* package_name = kDefaultPackageName); // Returns pointer to data inside APK files - std::unique_ptr<io::IData> OpenFileAsData(LoadedApk* apk, - const android::StringPiece& path); + std::unique_ptr<io::IData> OpenFileAsData(LoadedApk* apk, android::StringPiece path); // Asserts that loading the tree from the specified file in the apk succeeds. void AssertLoadXml(LoadedApk* apk, const io::IData* data, diff --git a/tools/aapt2/text/Printer.cpp b/tools/aapt2/text/Printer.cpp index 243800c9385f..8e491aca794d 100644 --- a/tools/aapt2/text/Printer.cpp +++ b/tools/aapt2/text/Printer.cpp @@ -26,7 +26,7 @@ using ::android::StringPiece; namespace aapt { namespace text { -Printer& Printer::Println(const StringPiece& str) { +Printer& Printer::Println(StringPiece str) { Print(str); return Print("\n"); } @@ -35,7 +35,7 @@ Printer& Printer::Println() { return Print("\n"); } -Printer& Printer::Print(const StringPiece& str) { +Printer& Printer::Print(StringPiece str) { if (error_) { return *this; } @@ -47,7 +47,7 @@ Printer& Printer::Print(const StringPiece& str) { const auto new_line_iter = std::find(remaining_str_begin, remaining_str_end, '\n'); // We will copy the string up until the next new-line (or end of string). - const StringPiece str_to_copy = str.substr(remaining_str_begin, new_line_iter); + const StringPiece str_to_copy(remaining_str_begin, new_line_iter - remaining_str_begin); if (!str_to_copy.empty()) { if (needs_indent_) { for (int i = 0; i < indent_level_; i++) { diff --git a/tools/aapt2/text/Printer.h b/tools/aapt2/text/Printer.h index f399f8ea5e0f..f7ad98bfd981 100644 --- a/tools/aapt2/text/Printer.h +++ b/tools/aapt2/text/Printer.h @@ -31,8 +31,8 @@ class Printer { explicit Printer(::aapt::io::OutputStream* out) : out_(out) { } - Printer& Print(const ::android::StringPiece& str); - Printer& Println(const ::android::StringPiece& str); + Printer& Print(android::StringPiece str); + Printer& Println(android::StringPiece str); Printer& Println(); void Indent(); diff --git a/tools/aapt2/text/Unicode.cpp b/tools/aapt2/text/Unicode.cpp index 3735b3e841e0..5e25be3e2812 100644 --- a/tools/aapt2/text/Unicode.cpp +++ b/tools/aapt2/text/Unicode.cpp @@ -77,7 +77,7 @@ bool IsWhitespace(char32_t codepoint) { (codepoint == 0x3000); } -bool IsJavaIdentifier(const StringPiece& str) { +bool IsJavaIdentifier(StringPiece str) { Utf8Iterator iter(str); // Check the first character. @@ -99,7 +99,7 @@ bool IsJavaIdentifier(const StringPiece& str) { return true; } -bool IsValidResourceEntryName(const StringPiece& str) { +bool IsValidResourceEntryName(StringPiece str) { Utf8Iterator iter(str); // Check the first character. diff --git a/tools/aapt2/text/Unicode.h b/tools/aapt2/text/Unicode.h index 546714e9a290..ab3e82b00f08 100644 --- a/tools/aapt2/text/Unicode.h +++ b/tools/aapt2/text/Unicode.h @@ -46,11 +46,11 @@ bool IsWhitespace(char32_t codepoint); // Returns true if the UTF8 string can be used as a Java identifier. // NOTE: This does not check against the set of reserved Java keywords. -bool IsJavaIdentifier(const android::StringPiece& str); +bool IsJavaIdentifier(android::StringPiece str); // Returns true if the UTF8 string can be used as the entry name of a resource name. // This is the `entry` part of package:type/entry. -bool IsValidResourceEntryName(const android::StringPiece& str); +bool IsValidResourceEntryName(android::StringPiece str); } // namespace text } // namespace aapt diff --git a/tools/aapt2/text/Utf8Iterator.cpp b/tools/aapt2/text/Utf8Iterator.cpp index 20b9073b9a26..0bd8a375a255 100644 --- a/tools/aapt2/text/Utf8Iterator.cpp +++ b/tools/aapt2/text/Utf8Iterator.cpp @@ -24,7 +24,7 @@ using ::android::StringPiece; namespace aapt { namespace text { -Utf8Iterator::Utf8Iterator(const StringPiece& str) +Utf8Iterator::Utf8Iterator(StringPiece str) : str_(str), current_pos_(0), next_pos_(0), current_codepoint_(0) { DoNext(); } diff --git a/tools/aapt2/text/Utf8Iterator.h b/tools/aapt2/text/Utf8Iterator.h index 9318401876d1..2bba1984a8ce 100644 --- a/tools/aapt2/text/Utf8Iterator.h +++ b/tools/aapt2/text/Utf8Iterator.h @@ -25,7 +25,7 @@ namespace text { class Utf8Iterator { public: - explicit Utf8Iterator(const android::StringPiece& str); + explicit Utf8Iterator(android::StringPiece str); bool HasNext() const; diff --git a/tools/aapt2/trace/TraceBuffer.cpp b/tools/aapt2/trace/TraceBuffer.cpp index b4b31d9daf6e..da5373936306 100644 --- a/tools/aapt2/trace/TraceBuffer.cpp +++ b/tools/aapt2/trace/TraceBuffer.cpp @@ -103,7 +103,7 @@ Trace::Trace(const std::string& tag, const std::vector<android::StringPiece>& ar s << tag; s << " "; for (auto& arg : args) { - s << arg.to_string(); + s << arg; s << " "; } tracebuffer::Add(s.str(), tracebuffer::kBegin); @@ -124,7 +124,7 @@ FlushTrace::FlushTrace(const std::string& basepath, const std::string& tag, s << tag; s << " "; for (auto& arg : args) { - s << arg.to_string(); + s << arg; s << " "; } tracebuffer::Add(s.str(), tracebuffer::kBegin); diff --git a/tools/aapt2/util/Files.cpp b/tools/aapt2/util/Files.cpp index 5d5b7cd7d472..93c1b61f9a57 100644 --- a/tools/aapt2/util/Files.cpp +++ b/tools/aapt2/util/Files.cpp @@ -139,7 +139,7 @@ bool mkdirs(const std::string& path) { return ::android::base::utf8::mkdir(path.c_str(), mode) == 0 || errno == EEXIST; } -StringPiece GetStem(const StringPiece& path) { +StringPiece GetStem(StringPiece path) { const char* start = path.begin(); const char* end = path.end(); for (const char* current = end - 1; current != start - 1; --current) { @@ -150,7 +150,7 @@ StringPiece GetStem(const StringPiece& path) { return {}; } -StringPiece GetFilename(const StringPiece& path) { +StringPiece GetFilename(StringPiece path) { const char* end = path.end(); const char* last_dir_sep = path.begin(); for (const char* c = path.begin(); c != end; ++c) { @@ -161,7 +161,7 @@ StringPiece GetFilename(const StringPiece& path) { return StringPiece(last_dir_sep, end - last_dir_sep); } -StringPiece GetExtension(const StringPiece& path) { +StringPiece GetExtension(StringPiece path) { StringPiece filename = GetFilename(path); const char* const end = filename.end(); const char* c = std::find(filename.begin(), end, '.'); @@ -171,7 +171,7 @@ StringPiece GetExtension(const StringPiece& path) { return {}; } -bool IsHidden(const android::StringPiece& path) { +bool IsHidden(android::StringPiece path) { return util::StartsWith(GetFilename(path), "."); } @@ -193,16 +193,16 @@ std::string BuildPath(std::vector<const StringPiece>&& args) { if (args.empty()) { return ""; } - std::string out = args[0].to_string(); + std::string out{args[0]}; for (int i = 1; i < args.size(); i++) { file::AppendPath(&out, args[i]); } return out; } -std::string PackageToPath(const StringPiece& package) { +std::string PackageToPath(StringPiece package) { std::string out_path; - for (const StringPiece& part : util::Tokenize(package, '.')) { + for (StringPiece part : util::Tokenize(package, '.')) { AppendPath(&out_path, part); } return out_path; @@ -241,10 +241,10 @@ std::optional<FileMap> MmapPath(const std::string& path, std::string* out_error) return std::move(filemap); } -bool AppendArgsFromFile(const StringPiece& path, std::vector<std::string>* out_arglist, +bool AppendArgsFromFile(StringPiece path, std::vector<std::string>* out_arglist, std::string* out_error) { std::string contents; - if (!ReadFileToString(path.to_string(), &contents, true /*follow_symlinks*/)) { + if (!ReadFileToString(std::string(path), &contents, true /*follow_symlinks*/)) { if (out_error) { *out_error = "failed to read argument-list file"; } @@ -254,16 +254,16 @@ bool AppendArgsFromFile(const StringPiece& path, std::vector<std::string>* out_a for (StringPiece line : util::Tokenize(contents, ' ')) { line = util::TrimWhitespace(line); if (!line.empty()) { - out_arglist->push_back(line.to_string()); + out_arglist->emplace_back(line); } } return true; } -bool AppendSetArgsFromFile(const StringPiece& path, std::unordered_set<std::string>* out_argset, +bool AppendSetArgsFromFile(StringPiece path, std::unordered_set<std::string>* out_argset, std::string* out_error) { std::string contents; - if(!ReadFileToString(path.to_string(), &contents, true /*follow_symlinks*/)) { + if (!ReadFileToString(std::string(path), &contents, true /*follow_symlinks*/)) { if (out_error) { *out_error = "failed to read argument-list file"; } @@ -273,13 +273,13 @@ bool AppendSetArgsFromFile(const StringPiece& path, std::unordered_set<std::stri for (StringPiece line : util::Tokenize(contents, ' ')) { line = util::TrimWhitespace(line); if (!line.empty()) { - out_argset->insert(line.to_string()); + out_argset->emplace(line); } } return true; } -bool FileFilter::SetPattern(const StringPiece& pattern) { +bool FileFilter::SetPattern(StringPiece pattern) { pattern_tokens_ = util::SplitAndLowercase(pattern, ':'); return true; } @@ -343,10 +343,10 @@ bool FileFilter::operator()(const std::string& filename, FileType type) const { return true; } -std::optional<std::vector<std::string>> FindFiles(const android::StringPiece& path, +std::optional<std::vector<std::string>> FindFiles(android::StringPiece path, android::IDiagnostics* diag, const FileFilter* filter) { - const std::string root_dir = path.to_string(); + const auto& root_dir = path; std::unique_ptr<DIR, decltype(closedir)*> d(opendir(root_dir.data()), closedir); if (!d) { diag->Error(android::DiagMessage() << SystemErrorCodeToString(errno) << ": " << root_dir); @@ -361,7 +361,7 @@ std::optional<std::vector<std::string>> FindFiles(const android::StringPiece& pa } std::string file_name = entry->d_name; - std::string full_path = root_dir; + std::string full_path{root_dir}; AppendPath(&full_path, file_name); const FileType file_type = GetFileType(full_path); @@ -380,7 +380,7 @@ std::optional<std::vector<std::string>> FindFiles(const android::StringPiece& pa // Now process subdirs. for (const std::string& subdir : subdirs) { - std::string full_subdir = root_dir; + std::string full_subdir{root_dir}; AppendPath(&full_subdir, subdir); std::optional<std::vector<std::string>> subfiles = FindFiles(full_subdir, diag, filter); if (!subfiles) { diff --git a/tools/aapt2/util/Files.h b/tools/aapt2/util/Files.h index ee95712f157d..42eeaf2d2e2a 100644 --- a/tools/aapt2/util/Files.h +++ b/tools/aapt2/util/Files.h @@ -66,31 +66,31 @@ std::string BuildPath(std::vector<const android::StringPiece>&& args); bool mkdirs(const std::string& path); // Returns all but the last part of the path. -android::StringPiece GetStem(const android::StringPiece& path); +android::StringPiece GetStem(android::StringPiece path); // Returns the last part of the path with extension. -android::StringPiece GetFilename(const android::StringPiece& path); +android::StringPiece GetFilename(android::StringPiece path); // Returns the extension of the path. This is the entire string after the first '.' of the last part // of the path. -android::StringPiece GetExtension(const android::StringPiece& path); +android::StringPiece GetExtension(android::StringPiece path); // Returns whether or not the name of the file or directory is a hidden file name -bool IsHidden(const android::StringPiece& path); +bool IsHidden(android::StringPiece path); // Converts a package name (com.android.app) to a path: com/android/app -std::string PackageToPath(const android::StringPiece& package); +std::string PackageToPath(android::StringPiece package); // Creates a FileMap for the file at path. std::optional<android::FileMap> MmapPath(const std::string& path, std::string* out_error); // Reads the file at path and appends each line to the outArgList vector. -bool AppendArgsFromFile(const android::StringPiece& path, std::vector<std::string>* out_arglist, +bool AppendArgsFromFile(android::StringPiece path, std::vector<std::string>* out_arglist, std::string* out_error); // Reads the file at path and appends each line to the outargset set. -bool AppendSetArgsFromFile(const android::StringPiece& path, - std::unordered_set<std::string>* out_argset, std::string* out_error); +bool AppendSetArgsFromFile(android::StringPiece path, std::unordered_set<std::string>* out_argset, + std::string* out_error); // Filter that determines which resource files/directories are // processed by AAPT. Takes a pattern string supplied by the user. @@ -112,7 +112,7 @@ class FileFilter { // - The special filenames "." and ".." are always ignored. // - Otherwise the full string is matched. // - match is not case-sensitive. - bool SetPattern(const android::StringPiece& pattern); + bool SetPattern(android::StringPiece pattern); // Applies the filter, returning true for pass, false for fail. bool operator()(const std::string& filename, FileType type) const; @@ -126,7 +126,7 @@ class FileFilter { // Returns a list of files relative to the directory identified by `path`. // An optional FileFilter filters out any files that don't pass. -std::optional<std::vector<std::string>> FindFiles(const android::StringPiece& path, +std::optional<std::vector<std::string>> FindFiles(android::StringPiece path, android::IDiagnostics* diag, const FileFilter* filter = nullptr); diff --git a/tools/aapt2/util/Util.cpp b/tools/aapt2/util/Util.cpp index 9b7ebdd690ac..be877660ef72 100644 --- a/tools/aapt2/util/Util.cpp +++ b/tools/aapt2/util/Util.cpp @@ -43,15 +43,14 @@ namespace util { // See frameworks/base/core/java/android/content/pm/parsing/ParsingPackageUtils.java constexpr static const size_t kMaxPackageNameSize = 223; -static std::vector<std::string> SplitAndTransform( - const StringPiece& str, char sep, const std::function<char(char)>& f) { +static std::vector<std::string> SplitAndTransform(StringPiece str, char sep, char (*f)(char)) { std::vector<std::string> parts; const StringPiece::const_iterator end = std::end(str); StringPiece::const_iterator start = std::begin(str); StringPiece::const_iterator current; do { current = std::find(start, end, sep); - parts.emplace_back(str.substr(start, current).to_string()); + parts.emplace_back(start, current); if (f) { std::string& part = parts.back(); std::transform(part.begin(), part.end(), part.begin(), f); @@ -61,29 +60,29 @@ static std::vector<std::string> SplitAndTransform( return parts; } -std::vector<std::string> Split(const StringPiece& str, char sep) { +std::vector<std::string> Split(StringPiece str, char sep) { return SplitAndTransform(str, sep, nullptr); } -std::vector<std::string> SplitAndLowercase(const StringPiece& str, char sep) { - return SplitAndTransform(str, sep, ::tolower); +std::vector<std::string> SplitAndLowercase(StringPiece str, char sep) { + return SplitAndTransform(str, sep, [](char c) -> char { return ::tolower(c); }); } -bool StartsWith(const StringPiece& str, const StringPiece& prefix) { +bool StartsWith(StringPiece str, StringPiece prefix) { if (str.size() < prefix.size()) { return false; } return str.substr(0, prefix.size()) == prefix; } -bool EndsWith(const StringPiece& str, const StringPiece& suffix) { +bool EndsWith(StringPiece str, StringPiece suffix) { if (str.size() < suffix.size()) { return false; } return str.substr(str.size() - suffix.size(), suffix.size()) == suffix; } -StringPiece TrimLeadingWhitespace(const StringPiece& str) { +StringPiece TrimLeadingWhitespace(StringPiece str) { if (str.size() == 0 || str.data() == nullptr) { return str; } @@ -97,7 +96,7 @@ StringPiece TrimLeadingWhitespace(const StringPiece& str) { return StringPiece(start, end - start); } -StringPiece TrimTrailingWhitespace(const StringPiece& str) { +StringPiece TrimTrailingWhitespace(StringPiece str) { if (str.size() == 0 || str.data() == nullptr) { return str; } @@ -111,7 +110,7 @@ StringPiece TrimTrailingWhitespace(const StringPiece& str) { return StringPiece(start, end - start); } -StringPiece TrimWhitespace(const StringPiece& str) { +StringPiece TrimWhitespace(StringPiece str) { if (str.size() == 0 || str.data() == nullptr) { return str; } @@ -130,9 +129,9 @@ StringPiece TrimWhitespace(const StringPiece& str) { return StringPiece(start, end - start); } -static int IsJavaNameImpl(const StringPiece& str) { +static int IsJavaNameImpl(StringPiece str) { int pieces = 0; - for (const StringPiece& piece : Tokenize(str, '.')) { + for (StringPiece piece : Tokenize(str, '.')) { pieces++; if (!text::IsJavaIdentifier(piece)) { return -1; @@ -141,17 +140,17 @@ static int IsJavaNameImpl(const StringPiece& str) { return pieces; } -bool IsJavaClassName(const StringPiece& str) { +bool IsJavaClassName(StringPiece str) { return IsJavaNameImpl(str) >= 2; } -bool IsJavaPackageName(const StringPiece& str) { +bool IsJavaPackageName(StringPiece str) { return IsJavaNameImpl(str) >= 1; } -static int IsAndroidNameImpl(const StringPiece& str) { +static int IsAndroidNameImpl(StringPiece str) { int pieces = 0; - for (const StringPiece& piece : Tokenize(str, '.')) { + for (StringPiece piece : Tokenize(str, '.')) { if (piece.empty()) { return -1; } @@ -173,15 +172,14 @@ static int IsAndroidNameImpl(const StringPiece& str) { return pieces; } -bool IsAndroidPackageName(const StringPiece& str) { +bool IsAndroidPackageName(StringPiece str) { if (str.size() > kMaxPackageNameSize) { return false; } return IsAndroidNameImpl(str) > 1 || str == "android"; } -bool IsAndroidSharedUserId(const android::StringPiece& package_name, - const android::StringPiece& shared_user_id) { +bool IsAndroidSharedUserId(android::StringPiece package_name, android::StringPiece shared_user_id) { if (shared_user_id.size() > kMaxPackageNameSize) { return false; } @@ -189,25 +187,24 @@ bool IsAndroidSharedUserId(const android::StringPiece& package_name, package_name == "android"; } -bool IsAndroidSplitName(const StringPiece& str) { +bool IsAndroidSplitName(StringPiece str) { return IsAndroidNameImpl(str) > 0; } -std::optional<std::string> GetFullyQualifiedClassName(const StringPiece& package, - const StringPiece& classname) { +std::optional<std::string> GetFullyQualifiedClassName(StringPiece package, StringPiece classname) { if (classname.empty()) { return {}; } if (util::IsJavaClassName(classname)) { - return classname.to_string(); + return std::string(classname); } if (package.empty()) { return {}; } - std::string result = package.to_string(); + std::string result{package}; if (classname.data()[0] != '.') { result += '.'; } @@ -251,7 +248,7 @@ static size_t ConsumeDigits(const char* start, const char* end) { return static_cast<size_t>(c - start); } -bool VerifyJavaStringFormat(const StringPiece& str) { +bool VerifyJavaStringFormat(StringPiece str) { const char* c = str.begin(); const char* const end = str.end(); @@ -341,7 +338,7 @@ bool VerifyJavaStringFormat(const StringPiece& str) { return true; } -std::u16string Utf8ToUtf16(const StringPiece& utf8) { +std::u16string Utf8ToUtf16(StringPiece utf8) { ssize_t utf16_length = utf8_to_utf16_length( reinterpret_cast<const uint8_t*>(utf8.data()), utf8.length()); if (utf16_length <= 0) { @@ -381,7 +378,7 @@ typename Tokenizer::iterator& Tokenizer::iterator::operator++() { const char* end = str_.end(); if (start == end) { end_ = true; - token_.assign(token_.end(), 0); + token_ = StringPiece(token_.end(), 0); return *this; } @@ -389,12 +386,12 @@ typename Tokenizer::iterator& Tokenizer::iterator::operator++() { const char* current = start; while (current != end) { if (*current == separator_) { - token_.assign(start, current - start); + token_ = StringPiece(start, current - start); return *this; } ++current; } - token_.assign(start, end - start); + token_ = StringPiece(start, end - start); return *this; } @@ -409,15 +406,17 @@ bool Tokenizer::iterator::operator!=(const iterator& rhs) const { return !(*this == rhs); } -Tokenizer::iterator::iterator(const StringPiece& s, char sep, const StringPiece& tok, bool end) - : str_(s), separator_(sep), token_(tok), end_(end) {} +Tokenizer::iterator::iterator(StringPiece s, char sep, StringPiece tok, bool end) + : str_(s), separator_(sep), token_(tok), end_(end) { +} -Tokenizer::Tokenizer(const StringPiece& str, char sep) +Tokenizer::Tokenizer(StringPiece str, char sep) : begin_(++iterator(str, sep, StringPiece(str.begin() - 1, 0), false)), - end_(str, sep, StringPiece(str.end(), 0), true) {} + end_(str, sep, StringPiece(str.end(), 0), true) { +} -bool ExtractResFilePathParts(const StringPiece& path, StringPiece* out_prefix, - StringPiece* out_entry, StringPiece* out_suffix) { +bool ExtractResFilePathParts(StringPiece path, StringPiece* out_prefix, StringPiece* out_entry, + StringPiece* out_suffix) { const StringPiece res_prefix("res/"); if (!StartsWith(path, res_prefix)) { return false; diff --git a/tools/aapt2/util/Util.h b/tools/aapt2/util/Util.h index 8d3b41315485..40ff5b633d97 100644 --- a/tools/aapt2/util/Util.h +++ b/tools/aapt2/util/Util.h @@ -48,44 +48,44 @@ struct Range { T end; }; -std::vector<std::string> Split(const android::StringPiece& str, char sep); -std::vector<std::string> SplitAndLowercase(const android::StringPiece& str, char sep); +std::vector<std::string> Split(android::StringPiece str, char sep); +std::vector<std::string> SplitAndLowercase(android::StringPiece str, char sep); // Returns true if the string starts with prefix. -bool StartsWith(const android::StringPiece& str, const android::StringPiece& prefix); +bool StartsWith(android::StringPiece str, android::StringPiece prefix); // Returns true if the string ends with suffix. -bool EndsWith(const android::StringPiece& str, const android::StringPiece& suffix); +bool EndsWith(android::StringPiece str, android::StringPiece suffix); // Creates a new StringPiece that points to a substring of the original string without leading // whitespace. -android::StringPiece TrimLeadingWhitespace(const android::StringPiece& str); +android::StringPiece TrimLeadingWhitespace(android::StringPiece str); // Creates a new StringPiece that points to a substring of the original string without trailing // whitespace. -android::StringPiece TrimTrailingWhitespace(const android::StringPiece& str); +android::StringPiece TrimTrailingWhitespace(android::StringPiece str); // Creates a new StringPiece that points to a substring of the original string without leading or // trailing whitespace. -android::StringPiece TrimWhitespace(const android::StringPiece& str); +android::StringPiece TrimWhitespace(android::StringPiece str); // Tests that the string is a valid Java class name. -bool IsJavaClassName(const android::StringPiece& str); +bool IsJavaClassName(android::StringPiece str); // Tests that the string is a valid Java package name. -bool IsJavaPackageName(const android::StringPiece& str); +bool IsJavaPackageName(android::StringPiece str); // Tests that the string is a valid Android package name. More strict than a Java package name. // - First character of each component (separated by '.') must be an ASCII letter. // - Subsequent characters of a component can be ASCII alphanumeric or an underscore. // - Package must contain at least two components, unless it is 'android'. // - The maximum package name length is 223. -bool IsAndroidPackageName(const android::StringPiece& str); +bool IsAndroidPackageName(android::StringPiece str); // Tests that the string is a valid Android split name. // - First character of each component (separated by '.') must be an ASCII letter. // - Subsequent characters of a component can be ASCII alphanumeric or an underscore. -bool IsAndroidSplitName(const android::StringPiece& str); +bool IsAndroidSplitName(android::StringPiece str); // Tests that the string is a valid Android shared user id. // - First character of each component (separated by '.') must be an ASCII letter. @@ -93,8 +93,7 @@ bool IsAndroidSplitName(const android::StringPiece& str); // - Must contain at least two components, unless package name is 'android'. // - The maximum shared user id length is 223. // - Treat empty string as valid, it's the case of no shared user id. -bool IsAndroidSharedUserId(const android::StringPiece& package_name, - const android::StringPiece& shared_user_id); +bool IsAndroidSharedUserId(android::StringPiece package_name, android::StringPiece shared_user_id); // Converts the class name to a fully qualified class name from the given // `package`. Ex: @@ -103,8 +102,8 @@ bool IsAndroidSharedUserId(const android::StringPiece& package_name, // .asdf --> package.asdf // .a.b --> package.a.b // asdf.adsf --> asdf.adsf -std::optional<std::string> GetFullyQualifiedClassName(const android::StringPiece& package, - const android::StringPiece& class_name); +std::optional<std::string> GetFullyQualifiedClassName(android::StringPiece package, + android::StringPiece class_name); // Retrieves the formatted name of aapt2. const char* GetToolName(); @@ -152,16 +151,16 @@ template <typename Container> // explicitly specifying an index) when there are more than one argument. This is an error // because translations may rearrange the order of the arguments in the string, which will // break the string interpolation. -bool VerifyJavaStringFormat(const android::StringPiece& str); +bool VerifyJavaStringFormat(android::StringPiece str); -bool AppendStyledString(const android::StringPiece& input, bool preserve_spaces, - std::string* out_str, std::string* out_error); +bool AppendStyledString(android::StringPiece input, bool preserve_spaces, std::string* out_str, + std::string* out_error); class StringBuilder { public: StringBuilder() = default; - StringBuilder& Append(const android::StringPiece& str); + StringBuilder& Append(android::StringPiece str); const std::string& ToString() const; const std::string& Error() const; bool IsEmpty() const; @@ -229,7 +228,7 @@ class Tokenizer { private: friend class Tokenizer; - iterator(const android::StringPiece& s, char sep, const android::StringPiece& tok, bool end); + iterator(android::StringPiece s, char sep, android::StringPiece tok, bool end); android::StringPiece str_; char separator_; @@ -237,7 +236,7 @@ class Tokenizer { bool end_; }; - Tokenizer(const android::StringPiece& str, char sep); + Tokenizer(android::StringPiece str, char sep); iterator begin() const { return begin_; @@ -252,7 +251,7 @@ class Tokenizer { const iterator end_; }; -inline Tokenizer Tokenize(const android::StringPiece& str, char sep) { +inline Tokenizer Tokenize(android::StringPiece str, char sep) { return Tokenizer(str, sep); } @@ -263,7 +262,7 @@ inline Tokenizer Tokenize(const android::StringPiece& str, char sep) { // Extracts ".xml" into outSuffix. // // Returns true if successful. -bool ExtractResFilePathParts(const android::StringPiece& path, android::StringPiece* out_prefix, +bool ExtractResFilePathParts(android::StringPiece path, android::StringPiece* out_prefix, android::StringPiece* out_entry, android::StringPiece* out_suffix); } // namespace util diff --git a/tools/aapt2/util/Util_test.cpp b/tools/aapt2/util/Util_test.cpp index 4ebcb115306f..15135690d0de 100644 --- a/tools/aapt2/util/Util_test.cpp +++ b/tools/aapt2/util/Util_test.cpp @@ -84,6 +84,14 @@ TEST(UtilTest, TokenizeAtEnd) { ASSERT_THAT(*iter, Eq(StringPiece())); } +TEST(UtilTest, TokenizeNone) { + auto tokenizer = util::Tokenize(StringPiece("none"), '.'); + auto iter = tokenizer.begin(); + ASSERT_THAT(*iter, Eq("none")); + ++iter; + ASSERT_THAT(iter, Eq(tokenizer.end())); +} + TEST(UtilTest, IsJavaClassName) { EXPECT_TRUE(util::IsJavaClassName("android.test.Class")); EXPECT_TRUE(util::IsJavaClassName("android.test.Class$Inner")); diff --git a/tools/aapt2/xml/XmlActionExecutor.cpp b/tools/aapt2/xml/XmlActionExecutor.cpp index 9bdbd22b5697..3ccbaa2a4b6c 100644 --- a/tools/aapt2/xml/XmlActionExecutor.cpp +++ b/tools/aapt2/xml/XmlActionExecutor.cpp @@ -84,7 +84,7 @@ bool XmlNodeAction::Execute(XmlActionExecutorPolicy policy, std::vector<StringPi error_msg << "unexpected element "; PrintElementToDiagMessage(child_el, &error_msg); error_msg << " found in "; - for (const StringPiece& element : *bread_crumb) { + for (StringPiece element : *bread_crumb) { error_msg << "<" << element << ">"; } if (policy == XmlActionExecutorPolicy::kAllowListWarning) { diff --git a/tools/aapt2/xml/XmlDom.cpp b/tools/aapt2/xml/XmlDom.cpp index f51e8a47041d..8dea8ea52f92 100644 --- a/tools/aapt2/xml/XmlDom.cpp +++ b/tools/aapt2/xml/XmlDom.cpp @@ -169,7 +169,7 @@ static void XMLCALL CharacterDataHandler(void* user_data, const char* s, int len stack->last_text_node = util::make_unique<Text>(); stack->last_text_node->line_number = XML_GetCurrentLineNumber(parser); stack->last_text_node->column_number = XML_GetCurrentColumnNumber(parser); - stack->last_text_node->text = str.to_string(); + stack->last_text_node->text.assign(str); } static void XMLCALL CommentDataHandler(void* user_data, const char* comment) { @@ -417,11 +417,11 @@ void Element::InsertChild(size_t index, std::unique_ptr<Node> child) { children.insert(children.begin() + index, std::move(child)); } -Attribute* Element::FindAttribute(const StringPiece& ns, const StringPiece& name) { +Attribute* Element::FindAttribute(StringPiece ns, StringPiece name) { return const_cast<Attribute*>(static_cast<const Element*>(this)->FindAttribute(ns, name)); } -const Attribute* Element::FindAttribute(const StringPiece& ns, const StringPiece& name) const { +const Attribute* Element::FindAttribute(StringPiece ns, StringPiece name) const { for (const auto& attr : attributes) { if (ns == attr.namespace_uri && name == attr.name) { return &attr; @@ -430,7 +430,7 @@ const Attribute* Element::FindAttribute(const StringPiece& ns, const StringPiece return nullptr; } -void Element::RemoveAttribute(const StringPiece& ns, const StringPiece& name) { +void Element::RemoveAttribute(StringPiece ns, StringPiece name) { auto new_attr_end = std::remove_if(attributes.begin(), attributes.end(), [&](const Attribute& attr) -> bool { return ns == attr.namespace_uri && name == attr.name; @@ -439,34 +439,32 @@ void Element::RemoveAttribute(const StringPiece& ns, const StringPiece& name) { attributes.erase(new_attr_end, attributes.end()); } -Attribute* Element::FindOrCreateAttribute(const StringPiece& ns, const StringPiece& name) { +Attribute* Element::FindOrCreateAttribute(StringPiece ns, StringPiece name) { Attribute* attr = FindAttribute(ns, name); if (attr == nullptr) { - attributes.push_back(Attribute{ns.to_string(), name.to_string()}); + attributes.push_back(Attribute{std::string(ns), std::string(name)}); attr = &attributes.back(); } return attr; } -Element* Element::FindChild(const StringPiece& ns, const StringPiece& name) { +Element* Element::FindChild(StringPiece ns, StringPiece name) { return FindChildWithAttribute(ns, name, {}, {}, {}); } -const Element* Element::FindChild(const StringPiece& ns, const StringPiece& name) const { +const Element* Element::FindChild(StringPiece ns, StringPiece name) const { return FindChildWithAttribute(ns, name, {}, {}, {}); } -Element* Element::FindChildWithAttribute(const StringPiece& ns, const StringPiece& name, - const StringPiece& attr_ns, const StringPiece& attr_name, - const StringPiece& attr_value) { +Element* Element::FindChildWithAttribute(StringPiece ns, StringPiece name, StringPiece attr_ns, + StringPiece attr_name, StringPiece attr_value) { return const_cast<Element*>(static_cast<const Element*>(this)->FindChildWithAttribute( ns, name, attr_ns, attr_name, attr_value)); } -const Element* Element::FindChildWithAttribute(const StringPiece& ns, const StringPiece& name, - const StringPiece& attr_ns, - const StringPiece& attr_name, - const StringPiece& attr_value) const { +const Element* Element::FindChildWithAttribute(StringPiece ns, StringPiece name, + StringPiece attr_ns, StringPiece attr_name, + StringPiece attr_value) const { for (const auto& child : children) { if (const Element* el = NodeCast<Element>(child.get())) { if (ns == el->namespace_uri && name == el->name) { @@ -559,7 +557,7 @@ void PackageAwareVisitor::AfterVisitElement(Element* el) { } std::optional<ExtractedPackage> PackageAwareVisitor::TransformPackageAlias( - const StringPiece& alias) const { + StringPiece alias) const { if (alias.empty()) { return ExtractedPackage{{}, false /*private*/}; } diff --git a/tools/aapt2/xml/XmlDom.h b/tools/aapt2/xml/XmlDom.h index 5bc55b6b68a1..c253b0a1f4a9 100644 --- a/tools/aapt2/xml/XmlDom.h +++ b/tools/aapt2/xml/XmlDom.h @@ -96,27 +96,22 @@ class Element : public Node { void AppendChild(std::unique_ptr<Node> child); void InsertChild(size_t index, std::unique_ptr<Node> child); - Attribute* FindAttribute(const android::StringPiece& ns, const android::StringPiece& name); - const Attribute* FindAttribute(const android::StringPiece& ns, - const android::StringPiece& name) const; - Attribute* FindOrCreateAttribute(const android::StringPiece& ns, - const android::StringPiece& name); - void RemoveAttribute(const android::StringPiece& ns, - const android::StringPiece& name); - - Element* FindChild(const android::StringPiece& ns, const android::StringPiece& name); - const Element* FindChild(const android::StringPiece& ns, const android::StringPiece& name) const; - - Element* FindChildWithAttribute(const android::StringPiece& ns, const android::StringPiece& name, - const android::StringPiece& attr_ns, - const android::StringPiece& attr_name, - const android::StringPiece& attr_value); - - const Element* FindChildWithAttribute(const android::StringPiece& ns, - const android::StringPiece& name, - const android::StringPiece& attr_ns, - const android::StringPiece& attr_name, - const android::StringPiece& attr_value) const; + Attribute* FindAttribute(android::StringPiece ns, android::StringPiece name); + const Attribute* FindAttribute(android::StringPiece ns, android::StringPiece name) const; + Attribute* FindOrCreateAttribute(android::StringPiece ns, android::StringPiece name); + void RemoveAttribute(android::StringPiece ns, android::StringPiece name); + + Element* FindChild(android::StringPiece ns, android::StringPiece name); + const Element* FindChild(android::StringPiece ns, android::StringPiece name) const; + + Element* FindChildWithAttribute(android::StringPiece ns, android::StringPiece name, + android::StringPiece attr_ns, android::StringPiece attr_name, + android::StringPiece attr_value); + + const Element* FindChildWithAttribute(android::StringPiece ns, android::StringPiece name, + android::StringPiece attr_ns, + android::StringPiece attr_name, + android::StringPiece attr_value) const; std::vector<Element*> GetChildElements(); @@ -235,8 +230,7 @@ class PackageAwareVisitor : public Visitor, public IPackageDeclStack { public: using Visitor::Visit; - std::optional<ExtractedPackage> TransformPackageAlias( - const android::StringPiece& alias) const override; + std::optional<ExtractedPackage> TransformPackageAlias(android::StringPiece alias) const override; protected: PackageAwareVisitor() = default; diff --git a/tools/aapt2/xml/XmlPullParser.cpp b/tools/aapt2/xml/XmlPullParser.cpp index bfa07490b9c0..d79446bfae6f 100644 --- a/tools/aapt2/xml/XmlPullParser.cpp +++ b/tools/aapt2/xml/XmlPullParser.cpp @@ -140,8 +140,7 @@ const std::string& XmlPullParser::namespace_uri() const { return event_queue_.front().data2; } -std::optional<ExtractedPackage> XmlPullParser::TransformPackageAlias( - const StringPiece& alias) const { +std::optional<ExtractedPackage> XmlPullParser::TransformPackageAlias(StringPiece alias) const { if (alias.empty()) { return ExtractedPackage{{}, false /*private*/}; } @@ -307,7 +306,7 @@ void XMLCALL XmlPullParser::EndCdataSectionHandler(void* user_data) { parser->depth_ }); } -std::optional<StringPiece> FindAttribute(const XmlPullParser* parser, const StringPiece& name) { +std::optional<StringPiece> FindAttribute(const XmlPullParser* parser, StringPiece name) { auto iter = parser->FindAttribute("", name); if (iter != parser->end_attributes()) { return StringPiece(util::TrimWhitespace(iter->value)); @@ -315,8 +314,7 @@ std::optional<StringPiece> FindAttribute(const XmlPullParser* parser, const Stri return {}; } -std::optional<StringPiece> FindNonEmptyAttribute(const XmlPullParser* parser, - const StringPiece& name) { +std::optional<StringPiece> FindNonEmptyAttribute(const XmlPullParser* parser, StringPiece name) { auto iter = parser->FindAttribute("", name); if (iter != parser->end_attributes()) { StringPiece trimmed = util::TrimWhitespace(iter->value); diff --git a/tools/aapt2/xml/XmlPullParser.h b/tools/aapt2/xml/XmlPullParser.h index ab347728ae4b..fe4cd018d808 100644 --- a/tools/aapt2/xml/XmlPullParser.h +++ b/tools/aapt2/xml/XmlPullParser.h @@ -120,8 +120,7 @@ class XmlPullParser : public IPackageDeclStack { * If xmlns:app="http://schemas.android.com/apk/res-auto", then * 'package' will be set to 'defaultPackage'. */ - std::optional<ExtractedPackage> TransformPackageAlias( - const android::StringPiece& alias) const override; + std::optional<ExtractedPackage> TransformPackageAlias(android::StringPiece alias) const override; struct PackageDecl { std::string prefix; @@ -194,7 +193,7 @@ class XmlPullParser : public IPackageDeclStack { * Finds the attribute in the current element within the global namespace. */ std::optional<android::StringPiece> FindAttribute(const XmlPullParser* parser, - const android::StringPiece& name); + android::StringPiece name); /** * Finds the attribute in the current element within the global namespace. The @@ -202,7 +201,7 @@ std::optional<android::StringPiece> FindAttribute(const XmlPullParser* parser, * must not be the empty string. */ std::optional<android::StringPiece> FindNonEmptyAttribute(const XmlPullParser* parser, - const android::StringPiece& name); + android::StringPiece name); // // Implementation diff --git a/tools/aapt2/xml/XmlUtil.cpp b/tools/aapt2/xml/XmlUtil.cpp index 114b5ba7ab1a..709755e69292 100644 --- a/tools/aapt2/xml/XmlUtil.cpp +++ b/tools/aapt2/xml/XmlUtil.cpp @@ -27,7 +27,7 @@ using ::android::StringPiece; namespace aapt { namespace xml { -std::string BuildPackageNamespace(const StringPiece& package, bool private_reference) { +std::string BuildPackageNamespace(StringPiece package, bool private_reference) { std::string result = private_reference ? kSchemaPrivatePrefix : kSchemaPublicPrefix; result.append(package.data(), package.size()); return result; @@ -41,7 +41,7 @@ std::optional<ExtractedPackage> ExtractPackageFromNamespace(const std::string& n if (package.empty()) { return {}; } - return ExtractedPackage{package.to_string(), false /* is_private */}; + return ExtractedPackage{std::string(package), false /* is_private */}; } else if (util::StartsWith(namespace_uri, kSchemaPrivatePrefix)) { StringPiece schema_prefix = kSchemaPrivatePrefix; @@ -50,7 +50,7 @@ std::optional<ExtractedPackage> ExtractPackageFromNamespace(const std::string& n if (package.empty()) { return {}; } - return ExtractedPackage{package.to_string(), true /* is_private */}; + return ExtractedPackage{std::string(package), true /* is_private */}; } else if (namespace_uri == kSchemaAuto) { return ExtractedPackage{std::string(), true /* is_private */}; diff --git a/tools/aapt2/xml/XmlUtil.h b/tools/aapt2/xml/XmlUtil.h index 1ab05a93d314..ad676ca91886 100644 --- a/tools/aapt2/xml/XmlUtil.h +++ b/tools/aapt2/xml/XmlUtil.h @@ -59,8 +59,7 @@ std::optional<ExtractedPackage> ExtractPackageFromNamespace(const std::string& n // // If privateReference == true, the package will be of the form: // http://schemas.android.com/apk/prv/res/<package> -std::string BuildPackageNamespace(const android::StringPiece& package, - bool private_reference = false); +std::string BuildPackageNamespace(android::StringPiece package, bool private_reference = false); // Interface representing a stack of XML namespace declarations. When looking up the package for a // namespace prefix, the stack is checked from top to bottom. @@ -69,7 +68,7 @@ struct IPackageDeclStack { // Returns an ExtractedPackage struct if the alias given corresponds with a package declaration. virtual std::optional<ExtractedPackage> TransformPackageAlias( - const android::StringPiece& alias) const = 0; + android::StringPiece alias) const = 0; }; // Helper function for transforming the original Reference inRef to a fully qualified reference |