AAPT2: Rename to match new style
Use Google3 naming style to match new
projects' and open source google projects' style.
Preferred to do this in a massive CL so as to avoid
style inconsistencies that plague legacy code bases.
This is a relatively NEW code base, may as well keep
it up to date.
Test: name/style refactor - existing tests pass
Change-Id: Ie80ecb78d46ec53efdfca2336bb57d96cbb7fb87
diff --git a/tools/aapt2/util/BigBuffer.cpp b/tools/aapt2/util/BigBuffer.cpp
index de4ecd2..ef99dca2 100644
--- a/tools/aapt2/util/BigBuffer.cpp
+++ b/tools/aapt2/util/BigBuffer.cpp
@@ -20,58 +20,60 @@
#include <memory>
#include <vector>
+#include "android-base/logging.h"
+
namespace aapt {
-void* BigBuffer::nextBlockImpl(size_t size) {
- if (!mBlocks.empty()) {
- Block& block = mBlocks.back();
- if (block.mBlockSize - block.size >= size) {
- void* outBuffer = block.buffer.get() + block.size;
- block.size += size;
- mSize += size;
- return outBuffer;
- }
+void* BigBuffer::NextBlockImpl(size_t size) {
+ if (!blocks_.empty()) {
+ Block& block = blocks_.back();
+ if (block.block_size_ - block.size >= size) {
+ void* out_buffer = block.buffer.get() + block.size;
+ block.size += size;
+ size_ += size;
+ return out_buffer;
}
+ }
- const size_t actualSize = std::max(mBlockSize, size);
+ const size_t actual_size = std::max(block_size_, size);
- Block block = {};
+ Block block = {};
- // Zero-allocate the block's buffer.
- block.buffer = std::unique_ptr<uint8_t[]>(new uint8_t[actualSize]());
- assert(block.buffer);
+ // Zero-allocate the block's buffer.
+ block.buffer = std::unique_ptr<uint8_t[]>(new uint8_t[actual_size]());
+ CHECK(block.buffer);
- block.size = size;
- block.mBlockSize = actualSize;
+ block.size = size;
+ block.block_size_ = actual_size;
- mBlocks.push_back(std::move(block));
- mSize += size;
- return mBlocks.back().buffer.get();
+ blocks_.push_back(std::move(block));
+ size_ += size;
+ return blocks_.back().buffer.get();
}
-void* BigBuffer::nextBlock(size_t* outSize) {
- if (!mBlocks.empty()) {
- Block& block = mBlocks.back();
- if (block.size != block.mBlockSize) {
- void* outBuffer = block.buffer.get() + block.size;
- size_t size = block.mBlockSize - block.size;
- block.size = block.mBlockSize;
- mSize += size;
- *outSize = size;
- return outBuffer;
- }
+void* BigBuffer::NextBlock(size_t* out_size) {
+ if (!blocks_.empty()) {
+ Block& block = blocks_.back();
+ if (block.size != block.block_size_) {
+ void* out_buffer = block.buffer.get() + block.size;
+ size_t size = block.block_size_ - block.size;
+ block.size = block.block_size_;
+ size_ += size;
+ *out_size = size;
+ return out_buffer;
}
+ }
- // Zero-allocate the block's buffer.
- Block block = {};
- block.buffer = std::unique_ptr<uint8_t[]>(new uint8_t[mBlockSize]());
- assert(block.buffer);
- block.size = mBlockSize;
- block.mBlockSize = mBlockSize;
- mBlocks.push_back(std::move(block));
- mSize += mBlockSize;
- *outSize = mBlockSize;
- return mBlocks.back().buffer.get();
+ // Zero-allocate the block's buffer.
+ Block block = {};
+ block.buffer = std::unique_ptr<uint8_t[]>(new uint8_t[block_size_]());
+ CHECK(block.buffer);
+ block.size = block_size_;
+ block.block_size_ = block_size_;
+ blocks_.push_back(std::move(block));
+ size_ += block_size_;
+ *out_size = block_size_;
+ return blocks_.back().buffer.get();
}
-} // namespace aapt
+} // namespace aapt
diff --git a/tools/aapt2/util/BigBuffer.h b/tools/aapt2/util/BigBuffer.h
index b273733..d23c41d 100644
--- a/tools/aapt2/util/BigBuffer.h
+++ b/tools/aapt2/util/BigBuffer.h
@@ -17,12 +17,14 @@
#ifndef AAPT_BIG_BUFFER_H
#define AAPT_BIG_BUFFER_H
-#include <cassert>
#include <cstring>
#include <memory>
#include <type_traits>
#include <vector>
+#include "android-base/logging.h"
+#include "android-base/macros.h"
+
namespace aapt {
/**
@@ -54,18 +56,16 @@
/**
* The size of the memory block allocation.
*/
- size_t mBlockSize;
+ size_t block_size_;
};
typedef std::vector<Block>::const_iterator const_iterator;
/**
* Create a BigBuffer with block allocation sizes
- * of blockSize.
+ * of block_size.
*/
- explicit BigBuffer(size_t blockSize);
-
- BigBuffer(const BigBuffer&) = delete; // No copying.
+ explicit BigBuffer(size_t block_size);
BigBuffer(BigBuffer&& rhs);
@@ -79,104 +79,106 @@
* a POD type. The elements are zero-initialized.
*/
template <typename T>
- T* nextBlock(size_t count = 1);
+ T* NextBlock(size_t count = 1);
/**
- * Returns the next block available and puts the size in outCount.
+ * Returns the next block available and puts the size in out_count.
* This is useful for grabbing blocks where the size doesn't matter.
- * Use backUp() to give back any bytes that were not used.
+ * Use BackUp() to give back any bytes that were not used.
*/
- void* nextBlock(size_t* outCount);
+ void* NextBlock(size_t* out_count);
/**
- * Backs up count bytes. This must only be called after nextBlock()
- * and can not be larger than sizeof(T) * count of the last nextBlock()
+ * Backs up count bytes. This must only be called after NextBlock()
+ * and can not be larger than sizeof(T) * count of the last NextBlock()
* call.
*/
- void backUp(size_t count);
+ void BackUp(size_t count);
/**
* Moves the specified BigBuffer into this one. When this method
* returns, buffer is empty.
*/
- void appendBuffer(BigBuffer&& buffer);
+ void AppendBuffer(BigBuffer&& buffer);
/**
* Pads the block with 'bytes' bytes of zero values.
*/
- void pad(size_t bytes);
+ void Pad(size_t bytes);
/**
* Pads the block so that it aligns on a 4 byte boundary.
*/
- void align4();
+ void Align4();
- size_t getBlockSize() const;
+ size_t block_size() const;
const_iterator begin() const;
const_iterator end() const;
private:
+ DISALLOW_COPY_AND_ASSIGN(BigBuffer);
+
/**
* Returns a pointer to a buffer of the requested size.
* The buffer is zero-initialized.
*/
- void* nextBlockImpl(size_t size);
+ void* NextBlockImpl(size_t size);
- size_t mBlockSize;
- size_t mSize;
- std::vector<Block> mBlocks;
+ size_t block_size_;
+ size_t size_;
+ std::vector<Block> blocks_;
};
-inline BigBuffer::BigBuffer(size_t blockSize)
- : mBlockSize(blockSize), mSize(0) {}
+inline BigBuffer::BigBuffer(size_t block_size)
+ : block_size_(block_size), size_(0) {}
inline BigBuffer::BigBuffer(BigBuffer&& rhs)
- : mBlockSize(rhs.mBlockSize),
- mSize(rhs.mSize),
- mBlocks(std::move(rhs.mBlocks)) {}
+ : block_size_(rhs.block_size_),
+ size_(rhs.size_),
+ blocks_(std::move(rhs.blocks_)) {}
-inline size_t BigBuffer::size() const { return mSize; }
+inline size_t BigBuffer::size() const { return size_; }
-inline size_t BigBuffer::getBlockSize() const { return mBlockSize; }
+inline size_t BigBuffer::block_size() const { return block_size_; }
template <typename T>
-inline T* BigBuffer::nextBlock(size_t count) {
+inline T* BigBuffer::NextBlock(size_t count) {
static_assert(std::is_standard_layout<T>::value,
"T must be standard_layout type");
- assert(count != 0);
- return reinterpret_cast<T*>(nextBlockImpl(sizeof(T) * count));
+ CHECK(count != 0);
+ return reinterpret_cast<T*>(NextBlockImpl(sizeof(T) * count));
}
-inline void BigBuffer::backUp(size_t count) {
- Block& block = mBlocks.back();
+inline void BigBuffer::BackUp(size_t count) {
+ Block& block = blocks_.back();
block.size -= count;
- mSize -= count;
+ size_ -= count;
}
-inline void BigBuffer::appendBuffer(BigBuffer&& buffer) {
- std::move(buffer.mBlocks.begin(), buffer.mBlocks.end(),
- std::back_inserter(mBlocks));
- mSize += buffer.mSize;
- buffer.mBlocks.clear();
- buffer.mSize = 0;
+inline void BigBuffer::AppendBuffer(BigBuffer&& buffer) {
+ std::move(buffer.blocks_.begin(), buffer.blocks_.end(),
+ std::back_inserter(blocks_));
+ size_ += buffer.size_;
+ buffer.blocks_.clear();
+ buffer.size_ = 0;
}
-inline void BigBuffer::pad(size_t bytes) { nextBlock<char>(bytes); }
+inline void BigBuffer::Pad(size_t bytes) { NextBlock<char>(bytes); }
-inline void BigBuffer::align4() {
- const size_t unaligned = mSize % 4;
+inline void BigBuffer::Align4() {
+ const size_t unaligned = size_ % 4;
if (unaligned != 0) {
- pad(4 - unaligned);
+ Pad(4 - unaligned);
}
}
inline BigBuffer::const_iterator BigBuffer::begin() const {
- return mBlocks.begin();
+ return blocks_.begin();
}
inline BigBuffer::const_iterator BigBuffer::end() const {
- return mBlocks.end();
+ return blocks_.end();
}
} // namespace aapt
diff --git a/tools/aapt2/util/BigBuffer_test.cpp b/tools/aapt2/util/BigBuffer_test.cpp
index 2a24f12..12c0b3e 100644
--- a/tools/aapt2/util/BigBuffer_test.cpp
+++ b/tools/aapt2/util/BigBuffer_test.cpp
@@ -16,83 +16,83 @@
#include "util/BigBuffer.h"
-#include <gtest/gtest.h>
+#include "test/Test.h"
namespace aapt {
TEST(BigBufferTest, AllocateSingleBlock) {
- BigBuffer buffer(4);
+ BigBuffer buffer(4);
- EXPECT_NE(nullptr, buffer.nextBlock<char>(2));
- EXPECT_EQ(2u, buffer.size());
+ EXPECT_NE(nullptr, buffer.NextBlock<char>(2));
+ EXPECT_EQ(2u, buffer.size());
}
TEST(BigBufferTest, ReturnSameBlockIfNextAllocationFits) {
- BigBuffer buffer(16);
+ BigBuffer buffer(16);
- char* b1 = buffer.nextBlock<char>(8);
- EXPECT_NE(nullptr, b1);
+ char* b1 = buffer.NextBlock<char>(8);
+ EXPECT_NE(nullptr, b1);
- char* b2 = buffer.nextBlock<char>(4);
- EXPECT_NE(nullptr, b2);
+ char* b2 = buffer.NextBlock<char>(4);
+ EXPECT_NE(nullptr, b2);
- EXPECT_EQ(b1 + 8, b2);
+ EXPECT_EQ(b1 + 8, b2);
}
TEST(BigBufferTest, AllocateExactSizeBlockIfLargerThanBlockSize) {
- BigBuffer buffer(16);
+ BigBuffer buffer(16);
- EXPECT_NE(nullptr, buffer.nextBlock<char>(32));
- EXPECT_EQ(32u, buffer.size());
+ EXPECT_NE(nullptr, buffer.NextBlock<char>(32));
+ EXPECT_EQ(32u, buffer.size());
}
TEST(BigBufferTest, AppendAndMoveBlock) {
- BigBuffer buffer(16);
+ BigBuffer buffer(16);
- uint32_t* b1 = buffer.nextBlock<uint32_t>();
+ uint32_t* b1 = buffer.NextBlock<uint32_t>();
+ ASSERT_NE(nullptr, b1);
+ *b1 = 33;
+
+ {
+ BigBuffer buffer2(16);
+ b1 = buffer2.NextBlock<uint32_t>();
ASSERT_NE(nullptr, b1);
- *b1 = 33;
+ *b1 = 44;
- {
- BigBuffer buffer2(16);
- b1 = buffer2.nextBlock<uint32_t>();
- ASSERT_NE(nullptr, b1);
- *b1 = 44;
+ buffer.AppendBuffer(std::move(buffer2));
+ EXPECT_EQ(0u, buffer2.size());
+ EXPECT_EQ(buffer2.begin(), buffer2.end());
+ }
- buffer.appendBuffer(std::move(buffer2));
- EXPECT_EQ(0u, buffer2.size());
- EXPECT_EQ(buffer2.begin(), buffer2.end());
- }
+ EXPECT_EQ(2 * sizeof(uint32_t), buffer.size());
- EXPECT_EQ(2 * sizeof(uint32_t), buffer.size());
+ auto b = buffer.begin();
+ ASSERT_NE(b, buffer.end());
+ ASSERT_EQ(sizeof(uint32_t), b->size);
+ ASSERT_EQ(33u, *reinterpret_cast<uint32_t*>(b->buffer.get()));
+ ++b;
- auto b = buffer.begin();
- ASSERT_NE(b, buffer.end());
- ASSERT_EQ(sizeof(uint32_t), b->size);
- ASSERT_EQ(33u, *reinterpret_cast<uint32_t*>(b->buffer.get()));
- ++b;
+ ASSERT_NE(b, buffer.end());
+ ASSERT_EQ(sizeof(uint32_t), b->size);
+ ASSERT_EQ(44u, *reinterpret_cast<uint32_t*>(b->buffer.get()));
+ ++b;
- ASSERT_NE(b, buffer.end());
- ASSERT_EQ(sizeof(uint32_t), b->size);
- ASSERT_EQ(44u, *reinterpret_cast<uint32_t*>(b->buffer.get()));
- ++b;
-
- ASSERT_EQ(b, buffer.end());
+ ASSERT_EQ(b, buffer.end());
}
TEST(BigBufferTest, PadAndAlignProperly) {
- BigBuffer buffer(16);
+ BigBuffer buffer(16);
- ASSERT_NE(buffer.nextBlock<char>(2), nullptr);
- ASSERT_EQ(2u, buffer.size());
- buffer.pad(2);
- ASSERT_EQ(4u, buffer.size());
- buffer.align4();
- ASSERT_EQ(4u, buffer.size());
- buffer.pad(2);
- ASSERT_EQ(6u, buffer.size());
- buffer.align4();
- ASSERT_EQ(8u, buffer.size());
+ ASSERT_NE(buffer.NextBlock<char>(2), nullptr);
+ ASSERT_EQ(2u, buffer.size());
+ buffer.Pad(2);
+ ASSERT_EQ(4u, buffer.size());
+ buffer.Align4();
+ ASSERT_EQ(4u, buffer.size());
+ buffer.Pad(2);
+ ASSERT_EQ(6u, buffer.size());
+ buffer.Align4();
+ ASSERT_EQ(8u, buffer.size());
}
-} // namespace aapt
+} // namespace aapt
diff --git a/tools/aapt2/util/Files.cpp b/tools/aapt2/util/Files.cpp
index 4cba921..f034607 100644
--- a/tools/aapt2/util/Files.cpp
+++ b/tools/aapt2/util/Files.cpp
@@ -15,15 +15,20 @@
*/
#include "util/Files.h"
-#include "util/Util.h"
+
+#include <dirent.h>
+#include <sys/stat.h>
#include <algorithm>
-#include <android-base/file.h>
#include <cerrno>
#include <cstdio>
-#include <dirent.h>
#include <string>
-#include <sys/stat.h>
+
+#include "android-base/errors.h"
+#include "android-base/file.h"
+#include "android-base/logging.h"
+
+#include "util/Util.h"
#ifdef _WIN32
// Windows includes.
@@ -33,244 +38,230 @@
namespace aapt {
namespace file {
-FileType getFileType(const StringPiece& path) {
- struct stat sb;
- if (stat(path.data(), &sb) < 0) {
- if (errno == ENOENT || errno == ENOTDIR) {
- return FileType::kNonexistant;
- }
- return FileType::kUnknown;
+FileType GetFileType(const StringPiece& path) {
+ struct stat sb;
+ if (stat(path.data(), &sb) < 0) {
+ if (errno == ENOENT || errno == ENOTDIR) {
+ return FileType::kNonexistant;
}
+ return FileType::kUnknown;
+ }
- if (S_ISREG(sb.st_mode)) {
- return FileType::kRegular;
- } else if (S_ISDIR(sb.st_mode)) {
- return FileType::kDirectory;
- } else if (S_ISCHR(sb.st_mode)) {
- return FileType::kCharDev;
- } else if (S_ISBLK(sb.st_mode)) {
- return FileType::kBlockDev;
- } else if (S_ISFIFO(sb.st_mode)) {
- return FileType::kFifo;
+ if (S_ISREG(sb.st_mode)) {
+ return FileType::kRegular;
+ } else if (S_ISDIR(sb.st_mode)) {
+ return FileType::kDirectory;
+ } else if (S_ISCHR(sb.st_mode)) {
+ return FileType::kCharDev;
+ } else if (S_ISBLK(sb.st_mode)) {
+ return FileType::kBlockDev;
+ } else if (S_ISFIFO(sb.st_mode)) {
+ return FileType::kFifo;
#if defined(S_ISLNK)
- } else if (S_ISLNK(sb.st_mode)) {
- return FileType::kSymlink;
+ } else if (S_ISLNK(sb.st_mode)) {
+ return FileType::kSymlink;
#endif
#if defined(S_ISSOCK)
- } else if (S_ISSOCK(sb.st_mode)) {
- return FileType::kSocket;
+ } else if (S_ISSOCK(sb.st_mode)) {
+ return FileType::kSocket;
#endif
- } else {
- return FileType::kUnknown;
- }
+ } else {
+ return FileType::kUnknown;
+ }
}
-std::vector<std::string> listFiles(const StringPiece& root, std::string* outError) {
- DIR* dir = opendir(root.data());
- if (dir == nullptr) {
- if (outError) {
- std::stringstream errorStr;
- errorStr << "unable to open file: " << strerror(errno);
- *outError = errorStr.str();
- }
- return {};
- }
-
- std::vector<std::string> files;
- dirent* entry;
- while ((entry = readdir(dir))) {
- files.emplace_back(entry->d_name);
- }
-
- closedir(dir);
- return files;
-}
-
-inline static int mkdirImpl(const StringPiece& path) {
+inline static int MkdirImpl(const StringPiece& path) {
#ifdef _WIN32
- return _mkdir(path.toString().c_str());
+ return _mkdir(path.ToString().c_str());
#else
- return mkdir(path.toString().c_str(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP);
+ return mkdir(path.ToString().c_str(),
+ S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP);
#endif
}
bool mkdirs(const StringPiece& path) {
- const char* start = path.begin();
- const char* end = path.end();
- for (const char* current = start; current != end; ++current) {
- if (*current == sDirSep && current != start) {
- StringPiece parentPath(start, current - start);
- int result = mkdirImpl(parentPath);
- if (result < 0 && errno != EEXIST) {
- return false;
- }
- }
- }
- return mkdirImpl(path) == 0 || errno == EEXIST;
-}
-
-StringPiece getStem(const StringPiece& path) {
- const char* start = path.begin();
- const char* end = path.end();
- for (const char* current = end - 1; current != start - 1; --current) {
- if (*current == sDirSep) {
- return StringPiece(start, current - start);
- }
- }
- return {};
-}
-
-StringPiece getFilename(const StringPiece& path) {
- const char* end = path.end();
- const char* lastDirSep = path.begin();
- for (const char* c = path.begin(); c != end; ++c) {
- if (*c == sDirSep) {
- lastDirSep = c + 1;
- }
- }
- return StringPiece(lastDirSep, end - lastDirSep);
-}
-
-StringPiece getExtension(const StringPiece& path) {
- StringPiece filename = getFilename(path);
- const char* const end = filename.end();
- const char* c = std::find(filename.begin(), end, '.');
- if (c != end) {
- return StringPiece(c, end - c);
- }
- return {};
-}
-
-void appendPath(std::string* base, StringPiece part) {
- assert(base);
- const bool baseHasTrailingSep = (!base->empty() && *(base->end() - 1) == sDirSep);
- const bool partHasLeadingSep = (!part.empty() && *(part.begin()) == sDirSep);
- if (baseHasTrailingSep && partHasLeadingSep) {
- // Remove the part's leading sep
- part = part.substr(1, part.size() - 1);
- } else if (!baseHasTrailingSep && !partHasLeadingSep) {
- // None of the pieces has a separator.
- *base += sDirSep;
- }
- base->append(part.data(), part.size());
-}
-
-std::string packageToPath(const StringPiece& package) {
- std::string outPath;
- for (StringPiece part : util::tokenize(package, '.')) {
- appendPath(&outPath, part);
- }
- return outPath;
-}
-
-Maybe<android::FileMap> mmapPath(const StringPiece& path, std::string* outError) {
- std::unique_ptr<FILE, decltype(fclose)*> f = { fopen(path.data(), "rb"), fclose };
- if (!f) {
- if (outError) *outError = strerror(errno);
- return {};
- }
-
- int fd = fileno(f.get());
-
- struct stat fileStats = {};
- if (fstat(fd, &fileStats) != 0) {
- if (outError) *outError = strerror(errno);
- return {};
- }
-
- android::FileMap fileMap;
- if (fileStats.st_size == 0) {
- // mmap doesn't like a length of 0. Instead we return an empty FileMap.
- return std::move(fileMap);
- }
-
- if (!fileMap.create(path.data(), fd, 0, fileStats.st_size, true)) {
- if (outError) *outError = strerror(errno);
- return {};
- }
- return std::move(fileMap);
-}
-
-bool appendArgsFromFile(const StringPiece& path, std::vector<std::string>* outArgList,
- std::string* outError) {
- std::string contents;
- if (!android::base::ReadFileToString(path.toString(), &contents)) {
- if (outError) *outError = "failed to read argument-list file";
+ const char* start = path.begin();
+ const char* end = path.end();
+ for (const char* current = start; current != end; ++current) {
+ if (*current == sDirSep && current != start) {
+ StringPiece parent_path(start, current - start);
+ int result = MkdirImpl(parent_path);
+ if (result < 0 && errno != EEXIST) {
return false;
+ }
}
-
- for (StringPiece line : util::tokenize(contents, ' ')) {
- line = util::trimWhitespace(line);
- if (!line.empty()) {
- outArgList->push_back(line.toString());
- }
- }
- return true;
+ }
+ return MkdirImpl(path) == 0 || errno == EEXIST;
}
-bool FileFilter::setPattern(const StringPiece& pattern) {
- mPatternTokens = util::splitAndLowercase(pattern, ':');
- return true;
+StringPiece GetStem(const StringPiece& path) {
+ const char* start = path.begin();
+ const char* end = path.end();
+ for (const char* current = end - 1; current != start - 1; --current) {
+ if (*current == sDirSep) {
+ return StringPiece(start, current - start);
+ }
+ }
+ return {};
+}
+
+StringPiece GetFilename(const StringPiece& path) {
+ const char* end = path.end();
+ const char* last_dir_sep = path.begin();
+ for (const char* c = path.begin(); c != end; ++c) {
+ if (*c == sDirSep) {
+ last_dir_sep = c + 1;
+ }
+ }
+ return StringPiece(last_dir_sep, end - last_dir_sep);
+}
+
+StringPiece GetExtension(const StringPiece& path) {
+ StringPiece filename = GetFilename(path);
+ const char* const end = filename.end();
+ const char* c = std::find(filename.begin(), end, '.');
+ if (c != end) {
+ return StringPiece(c, end - c);
+ }
+ return {};
+}
+
+void AppendPath(std::string* base, StringPiece part) {
+ CHECK(base != nullptr);
+ const bool base_has_trailing_sep =
+ (!base->empty() && *(base->end() - 1) == sDirSep);
+ const bool part_has_leading_sep =
+ (!part.empty() && *(part.begin()) == sDirSep);
+ if (base_has_trailing_sep && part_has_leading_sep) {
+ // Remove the part's leading sep
+ part = part.substr(1, part.size() - 1);
+ } else if (!base_has_trailing_sep && !part_has_leading_sep) {
+ // None of the pieces has a separator.
+ *base += sDirSep;
+ }
+ base->append(part.data(), part.size());
+}
+
+std::string PackageToPath(const StringPiece& package) {
+ std::string out_path;
+ for (StringPiece part : util::Tokenize(package, '.')) {
+ AppendPath(&out_path, part);
+ }
+ return out_path;
+}
+
+Maybe<android::FileMap> MmapPath(const StringPiece& path,
+ std::string* out_error) {
+ std::unique_ptr<FILE, decltype(fclose)*> f = {fopen(path.data(), "rb"),
+ fclose};
+ if (!f) {
+ if (out_error) *out_error = android::base::SystemErrorCodeToString(errno);
+ return {};
+ }
+
+ int fd = fileno(f.get());
+
+ struct stat filestats = {};
+ if (fstat(fd, &filestats) != 0) {
+ if (out_error) *out_error = android::base::SystemErrorCodeToString(errno);
+ return {};
+ }
+
+ android::FileMap filemap;
+ if (filestats.st_size == 0) {
+ // mmap doesn't like a length of 0. Instead we return an empty FileMap.
+ return std::move(filemap);
+ }
+
+ if (!filemap.create(path.data(), fd, 0, filestats.st_size, true)) {
+ if (out_error) *out_error = android::base::SystemErrorCodeToString(errno);
+ return {};
+ }
+ return std::move(filemap);
+}
+
+bool AppendArgsFromFile(const StringPiece& path,
+ std::vector<std::string>* out_arglist,
+ std::string* out_error) {
+ std::string contents;
+ if (!android::base::ReadFileToString(path.ToString(), &contents)) {
+ if (out_error) *out_error = "failed to read argument-list file";
+ return false;
+ }
+
+ for (StringPiece line : util::Tokenize(contents, ' ')) {
+ line = util::TrimWhitespace(line);
+ if (!line.empty()) {
+ out_arglist->push_back(line.ToString());
+ }
+ }
+ return true;
+}
+
+bool FileFilter::SetPattern(const StringPiece& pattern) {
+ pattern_tokens_ = util::SplitAndLowercase(pattern, ':');
+ return true;
}
bool FileFilter::operator()(const std::string& filename, FileType type) const {
- if (filename == "." || filename == "..") {
- return false;
+ if (filename == "." || filename == "..") {
+ return false;
+ }
+
+ const char kDir[] = "dir";
+ const char kFile[] = "file";
+ const size_t filename_len = filename.length();
+ bool chatty = true;
+ for (const std::string& token : pattern_tokens_) {
+ const char* token_str = token.c_str();
+ if (*token_str == '!') {
+ chatty = false;
+ token_str++;
}
- const char kDir[] = "dir";
- const char kFile[] = "file";
- const size_t filenameLen = filename.length();
- bool chatty = true;
- for (const std::string& token : mPatternTokens) {
- const char* tokenStr = token.c_str();
- if (*tokenStr == '!') {
- chatty = false;
- tokenStr++;
- }
-
- if (strncasecmp(tokenStr, kDir, sizeof(kDir)) == 0) {
- if (type != FileType::kDirectory) {
- continue;
- }
- tokenStr += sizeof(kDir);
- }
-
- if (strncasecmp(tokenStr, kFile, sizeof(kFile)) == 0) {
- if (type != FileType::kRegular) {
- continue;
- }
- tokenStr += sizeof(kFile);
- }
-
- bool ignore = false;
- size_t n = strlen(tokenStr);
- if (*tokenStr == '*') {
- // Math suffix.
- tokenStr++;
- n--;
- if (n <= filenameLen) {
- ignore = strncasecmp(tokenStr, filename.c_str() + filenameLen - n, n) == 0;
- }
- } else if (n > 1 && tokenStr[n - 1] == '*') {
- // Match prefix.
- ignore = strncasecmp(tokenStr, filename.c_str(), n - 1) == 0;
- } else {
- ignore = strcasecmp(tokenStr, filename.c_str()) == 0;
- }
-
- if (ignore) {
- if (chatty) {
- mDiag->warn(DiagMessage() << "skipping "
- << (type == FileType::kDirectory ? "dir '" : "file '")
- << filename << "' due to ignore pattern '"
- << token << "'");
- }
- return false;
- }
+ if (strncasecmp(token_str, kDir, sizeof(kDir)) == 0) {
+ if (type != FileType::kDirectory) {
+ continue;
+ }
+ token_str += sizeof(kDir);
}
- return true;
+
+ if (strncasecmp(token_str, kFile, sizeof(kFile)) == 0) {
+ if (type != FileType::kRegular) {
+ continue;
+ }
+ token_str += sizeof(kFile);
+ }
+
+ bool ignore = false;
+ size_t n = strlen(token_str);
+ if (*token_str == '*') {
+ // Math suffix.
+ token_str++;
+ n--;
+ if (n <= filename_len) {
+ ignore =
+ strncasecmp(token_str, filename.c_str() + filename_len - n, n) == 0;
+ }
+ } else if (n > 1 && token_str[n - 1] == '*') {
+ // Match prefix.
+ ignore = strncasecmp(token_str, filename.c_str(), n - 1) == 0;
+ } else {
+ ignore = strcasecmp(token_str, filename.c_str()) == 0;
+ }
+
+ if (ignore) {
+ if (chatty) {
+ diag_->Warn(DiagMessage()
+ << "skipping "
+ << (type == FileType::kDirectory ? "dir '" : "file '")
+ << filename << "' due to ignore pattern '" << token << "'");
+ }
+ return false;
+ }
+ }
+ return true;
}
-} // namespace file
-} // namespace aapt
+} // namespace file
+} // namespace aapt
diff --git a/tools/aapt2/util/Files.h b/tools/aapt2/util/Files.h
index d90c6b6..a157dbd 100644
--- a/tools/aapt2/util/Files.h
+++ b/tools/aapt2/util/Files.h
@@ -17,18 +17,18 @@
#ifndef AAPT_FILES_H
#define AAPT_FILES_H
-#include "Diagnostics.h"
-#include "Maybe.h"
-#include "Source.h"
-
-#include "util/StringPiece.h"
-
-#include <utils/FileMap.h>
-#include <cassert>
#include <memory>
#include <string>
#include <vector>
+#include "android-base/macros.h"
+#include "utils/FileMap.h"
+
+#include "Diagnostics.h"
+#include "Maybe.h"
+#include "Source.h"
+#include "util/StringPiece.h"
+
namespace aapt {
namespace file {
@@ -50,18 +50,12 @@
kSocket,
};
-FileType getFileType(const StringPiece& path);
-
-/*
- * Lists files under the directory `root`. Files are listed
- * with just their leaf (filename) names.
- */
-std::vector<std::string> listFiles(const StringPiece& root);
+FileType GetFileType(const StringPiece& path);
/*
* Appends a path to `base`, separated by the directory separator.
*/
-void appendPath(std::string* base, StringPiece part);
+void AppendPath(std::string* base, StringPiece part);
/*
* Makes all the directories in `path`. The last element in the path
@@ -72,46 +66,45 @@
/**
* Returns all but the last part of the path.
*/
-StringPiece getStem(const StringPiece& path);
+StringPiece GetStem(const StringPiece& path);
/**
* Returns the last part of the path with extension.
*/
-StringPiece getFilename(const StringPiece& path);
+StringPiece GetFilename(const StringPiece& path);
/**
* Returns the extension of the path. This is the entire string after
* the first '.' of the last part of the path.
*/
-StringPiece getExtension(const StringPiece& path);
+StringPiece GetExtension(const StringPiece& path);
/**
* Converts a package name (com.android.app) to a path: com/android/app
*/
-std::string packageToPath(const StringPiece& package);
+std::string PackageToPath(const StringPiece& package);
/**
* Creates a FileMap for the file at path.
*/
-Maybe<android::FileMap> mmapPath(const StringPiece& path,
- std::string* outError);
+Maybe<android::FileMap> MmapPath(const StringPiece& path,
+ std::string* out_error);
/**
* Reads the file at path and appends each line to the outArgList vector.
*/
-bool appendArgsFromFile(const StringPiece& path,
- std::vector<std::string>* outArgList,
- std::string* outError);
+bool AppendArgsFromFile(const StringPiece& path,
+ std::vector<std::string>* out_arglist,
+ std::string* out_error);
/*
* Filter that determines which resource files/directories are
* processed by AAPT. Takes a pattern string supplied by the user.
- * Pattern format is specified in the
- * FileFilter::setPattern(const std::string&) method.
+ * Pattern format is specified in the FileFilter::SetPattern() method.
*/
class FileFilter {
public:
- explicit FileFilter(IDiagnostics* diag) : mDiag(diag) {}
+ explicit FileFilter(IDiagnostics* diag) : diag_(diag) {}
/*
* Patterns syntax:
@@ -127,7 +120,7 @@
* - Otherwise the full string is matched.
* - match is not case-sensitive.
*/
- bool setPattern(const StringPiece& pattern);
+ bool SetPattern(const StringPiece& pattern);
/**
* Applies the filter, returning true for pass, false for fail.
@@ -135,8 +128,10 @@
bool operator()(const std::string& filename, FileType type) const;
private:
- IDiagnostics* mDiag;
- std::vector<std::string> mPatternTokens;
+ DISALLOW_COPY_AND_ASSIGN(FileFilter);
+
+ IDiagnostics* diag_;
+ std::vector<std::string> pattern_tokens_;
};
} // namespace file
diff --git a/tools/aapt2/util/Files_test.cpp b/tools/aapt2/util/Files_test.cpp
index efb0459..219c183 100644
--- a/tools/aapt2/util/Files_test.cpp
+++ b/tools/aapt2/util/Files_test.cpp
@@ -14,45 +14,46 @@
* limitations under the License.
*/
-#include "test/Test.h"
#include "util/Files.h"
#include <sstream>
+#include "test/Test.h"
+
namespace aapt {
namespace file {
class FilesTest : public ::testing::Test {
-public:
- void SetUp() override {
- std::stringstream builder;
- builder << "hello" << sDirSep << "there";
- mExpectedPath = builder.str();
- }
+ public:
+ void SetUp() override {
+ std::stringstream builder;
+ builder << "hello" << sDirSep << "there";
+ expected_path_ = builder.str();
+ }
-protected:
- std::string mExpectedPath;
+ protected:
+ std::string expected_path_;
};
-TEST_F(FilesTest, appendPath) {
- std::string base = "hello";
- appendPath(&base, "there");
- EXPECT_EQ(mExpectedPath, base);
+TEST_F(FilesTest, AppendPath) {
+ std::string base = "hello";
+ AppendPath(&base, "there");
+ EXPECT_EQ(expected_path_, base);
}
-TEST_F(FilesTest, appendPathWithLeadingOrTrailingSeparators) {
- std::string base = "hello/";
- appendPath(&base, "there");
- EXPECT_EQ(mExpectedPath, base);
+TEST_F(FilesTest, AppendPathWithLeadingOrTrailingSeparators) {
+ std::string base = "hello/";
+ AppendPath(&base, "there");
+ EXPECT_EQ(expected_path_, base);
- base = "hello";
- appendPath(&base, "/there");
- EXPECT_EQ(mExpectedPath, base);
+ base = "hello";
+ AppendPath(&base, "/there");
+ EXPECT_EQ(expected_path_, base);
- base = "hello/";
- appendPath(&base, "/there");
- EXPECT_EQ(mExpectedPath, base);
+ base = "hello/";
+ AppendPath(&base, "/there");
+ EXPECT_EQ(expected_path_, base);
}
-} // namespace files
-} // namespace aapt
+} // namespace files
+} // namespace aapt
diff --git a/tools/aapt2/util/ImmutableMap.h b/tools/aapt2/util/ImmutableMap.h
index 6f48764..59858e4 100644
--- a/tools/aapt2/util/ImmutableMap.h
+++ b/tools/aapt2/util/ImmutableMap.h
@@ -17,39 +17,31 @@
#ifndef AAPT_UTIL_IMMUTABLEMAP_H
#define AAPT_UTIL_IMMUTABLEMAP_H
-#include "util/TypeTraits.h"
-
#include <utility>
#include <vector>
+#include "util/TypeTraits.h"
+
namespace aapt {
template <typename TKey, typename TValue>
class ImmutableMap {
static_assert(is_comparable<TKey, TKey>::value, "key is not comparable");
- private:
- std::vector<std::pair<TKey, TValue>> mData;
-
- explicit ImmutableMap(std::vector<std::pair<TKey, TValue>> data)
- : mData(std::move(data)) {}
-
public:
- using const_iterator = typename decltype(mData)::const_iterator;
+ using const_iterator =
+ typename std::vector<std::pair<TKey, TValue>>::const_iterator;
ImmutableMap(ImmutableMap&&) = default;
ImmutableMap& operator=(ImmutableMap&&) = default;
- ImmutableMap(const ImmutableMap&) = delete;
- ImmutableMap& operator=(const ImmutableMap&) = delete;
-
- static ImmutableMap<TKey, TValue> createPreSorted(
+ static ImmutableMap<TKey, TValue> CreatePreSorted(
std::initializer_list<std::pair<TKey, TValue>> list) {
return ImmutableMap(
std::vector<std::pair<TKey, TValue>>(list.begin(), list.end()));
}
- static ImmutableMap<TKey, TValue> createAndSort(
+ static ImmutableMap<TKey, TValue> CreateAndSort(
std::initializer_list<std::pair<TKey, TValue>> list) {
std::vector<std::pair<TKey, TValue>> data(list.begin(), list.end());
std::sort(data.begin(), data.end());
@@ -64,17 +56,25 @@
return candidate.first < target;
};
- const_iterator endIter = end();
- auto iter = std::lower_bound(mData.begin(), endIter, key, cmp);
- if (iter == endIter || iter->first == key) {
+ const_iterator end_iter = end();
+ auto iter = std::lower_bound(data_.begin(), end_iter, key, cmp);
+ if (iter == end_iter || iter->first == key) {
return iter;
}
- return endIter;
+ return end_iter;
}
- const_iterator begin() const { return mData.begin(); }
+ const_iterator begin() const { return data_.begin(); }
- const_iterator end() const { return mData.end(); }
+ const_iterator end() const { return data_.end(); }
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(ImmutableMap);
+
+ explicit ImmutableMap(std::vector<std::pair<TKey, TValue>> data)
+ : data_(std::move(data)) {}
+
+ std::vector<std::pair<TKey, TValue>> data_;
};
} // namespace aapt
diff --git a/tools/aapt2/util/Maybe.h b/tools/aapt2/util/Maybe.h
index 90a0198..b43f8e8 100644
--- a/tools/aapt2/util/Maybe.h
+++ b/tools/aapt2/util/Maybe.h
@@ -17,12 +17,13 @@
#ifndef AAPT_MAYBE_H
#define AAPT_MAYBE_H
-#include "util/TypeTraits.h"
-
-#include <cassert>
#include <type_traits>
#include <utility>
+#include "android-base/logging.h"
+
+#include "util/TypeTraits.h"
+
namespace aapt {
/**
@@ -88,7 +89,7 @@
*/
const T& value() const;
- T valueOrDefault(const T& def) const;
+ T value_or_default(const T& def) const;
private:
template <typename U>
@@ -102,55 +103,55 @@
void destroy();
- bool mNothing;
+ bool nothing_;
- typename std::aligned_storage<sizeof(T), alignof(T)>::type mStorage;
+ typename std::aligned_storage<sizeof(T), alignof(T)>::type storage_;
};
template <typename T>
-Maybe<T>::Maybe() : mNothing(true) {}
+Maybe<T>::Maybe() : nothing_(true) {}
template <typename T>
Maybe<T>::~Maybe() {
- if (!mNothing) {
+ if (!nothing_) {
destroy();
}
}
template <typename T>
-Maybe<T>::Maybe(const Maybe& rhs) : mNothing(rhs.mNothing) {
- if (!rhs.mNothing) {
- new (&mStorage) T(reinterpret_cast<const T&>(rhs.mStorage));
+Maybe<T>::Maybe(const Maybe& rhs) : nothing_(rhs.nothing_) {
+ if (!rhs.nothing_) {
+ new (&storage_) T(reinterpret_cast<const T&>(rhs.storage_));
}
}
template <typename T>
template <typename U>
-Maybe<T>::Maybe(const Maybe<U>& rhs) : mNothing(rhs.mNothing) {
- if (!rhs.mNothing) {
- new (&mStorage) T(reinterpret_cast<const U&>(rhs.mStorage));
+Maybe<T>::Maybe(const Maybe<U>& rhs) : nothing_(rhs.nothing_) {
+ if (!rhs.nothing_) {
+ new (&storage_) T(reinterpret_cast<const U&>(rhs.storage_));
}
}
template <typename T>
-Maybe<T>::Maybe(Maybe&& rhs) : mNothing(rhs.mNothing) {
- if (!rhs.mNothing) {
- rhs.mNothing = true;
+Maybe<T>::Maybe(Maybe&& rhs) : nothing_(rhs.nothing_) {
+ if (!rhs.nothing_) {
+ rhs.nothing_ = true;
// Move the value from rhs.
- new (&mStorage) T(std::move(reinterpret_cast<T&>(rhs.mStorage)));
+ new (&storage_) T(std::move(reinterpret_cast<T&>(rhs.storage_)));
rhs.destroy();
}
}
template <typename T>
template <typename U>
-Maybe<T>::Maybe(Maybe<U>&& rhs) : mNothing(rhs.mNothing) {
- if (!rhs.mNothing) {
- rhs.mNothing = true;
+Maybe<T>::Maybe(Maybe<U>&& rhs) : nothing_(rhs.nothing_) {
+ if (!rhs.nothing_) {
+ rhs.nothing_ = true;
// Move the value from rhs.
- new (&mStorage) T(std::move(reinterpret_cast<U&>(rhs.mStorage)));
+ new (&storage_) T(std::move(reinterpret_cast<U&>(rhs.storage_)));
rhs.destroy();
}
}
@@ -170,21 +171,21 @@
template <typename T>
template <typename U>
Maybe<T>& Maybe<T>::copy(const Maybe<U>& rhs) {
- if (mNothing && rhs.mNothing) {
+ if (nothing_ && rhs.nothing_) {
// Both are nothing, nothing to do.
return *this;
- } else if (!mNothing && !rhs.mNothing) {
+ } else if (!nothing_ && !rhs.nothing_) {
// We both are something, so assign rhs to us.
- reinterpret_cast<T&>(mStorage) = reinterpret_cast<const U&>(rhs.mStorage);
- } else if (mNothing) {
+ reinterpret_cast<T&>(storage_) = reinterpret_cast<const U&>(rhs.storage_);
+ } else if (nothing_) {
// We are nothing but rhs is something.
- mNothing = rhs.mNothing;
+ nothing_ = rhs.nothing_;
// Copy the value from rhs.
- new (&mStorage) T(reinterpret_cast<const U&>(rhs.mStorage));
+ new (&storage_) T(reinterpret_cast<const U&>(rhs.storage_));
} else {
// We are something but rhs is nothing, so destroy our value.
- mNothing = rhs.mNothing;
+ nothing_ = rhs.nothing_;
destroy();
}
return *this;
@@ -205,69 +206,69 @@
template <typename T>
template <typename U>
Maybe<T>& Maybe<T>::move(Maybe<U>&& rhs) {
- if (mNothing && rhs.mNothing) {
+ if (nothing_ && rhs.nothing_) {
// Both are nothing, nothing to do.
return *this;
- } else if (!mNothing && !rhs.mNothing) {
+ } else if (!nothing_ && !rhs.nothing_) {
// We both are something, so move assign rhs to us.
- rhs.mNothing = true;
- reinterpret_cast<T&>(mStorage) =
- std::move(reinterpret_cast<U&>(rhs.mStorage));
+ rhs.nothing_ = true;
+ reinterpret_cast<T&>(storage_) =
+ std::move(reinterpret_cast<U&>(rhs.storage_));
rhs.destroy();
- } else if (mNothing) {
+ } else if (nothing_) {
// We are nothing but rhs is something.
- mNothing = false;
- rhs.mNothing = true;
+ nothing_ = false;
+ rhs.nothing_ = true;
// Move the value from rhs.
- new (&mStorage) T(std::move(reinterpret_cast<U&>(rhs.mStorage)));
+ new (&storage_) T(std::move(reinterpret_cast<U&>(rhs.storage_)));
rhs.destroy();
} else {
// We are something but rhs is nothing, so destroy our value.
- mNothing = true;
+ nothing_ = true;
destroy();
}
return *this;
}
template <typename T>
-Maybe<T>::Maybe(const T& value) : mNothing(false) {
- new (&mStorage) T(value);
+Maybe<T>::Maybe(const T& value) : nothing_(false) {
+ new (&storage_) T(value);
}
template <typename T>
-Maybe<T>::Maybe(T&& value) : mNothing(false) {
- new (&mStorage) T(std::forward<T>(value));
+Maybe<T>::Maybe(T&& value) : nothing_(false) {
+ new (&storage_) T(std::forward<T>(value));
}
template <typename T>
Maybe<T>::operator bool() const {
- return !mNothing;
+ return !nothing_;
}
template <typename T>
T& Maybe<T>::value() {
- assert(!mNothing && "Maybe<T>::value() called on Nothing");
- return reinterpret_cast<T&>(mStorage);
+ CHECK(!nothing_) << "Maybe<T>::value() called on Nothing";
+ return reinterpret_cast<T&>(storage_);
}
template <typename T>
const T& Maybe<T>::value() const {
- assert(!mNothing && "Maybe<T>::value() called on Nothing");
- return reinterpret_cast<const T&>(mStorage);
+ CHECK(!nothing_) << "Maybe<T>::value() called on Nothing";
+ return reinterpret_cast<const T&>(storage_);
}
template <typename T>
-T Maybe<T>::valueOrDefault(const T& def) const {
- if (mNothing) {
+T Maybe<T>::value_or_default(const T& def) const {
+ if (nothing_) {
return def;
}
- return reinterpret_cast<const T&>(mStorage);
+ return reinterpret_cast<const T&>(storage_);
}
template <typename T>
void Maybe<T>::destroy() {
- reinterpret_cast<T&>(mStorage).~T();
+ reinterpret_cast<T&>(storage_).~T();
}
template <typename T>
diff --git a/tools/aapt2/util/Maybe_test.cpp b/tools/aapt2/util/Maybe_test.cpp
index 5d42dc3..ca14793 100644
--- a/tools/aapt2/util/Maybe_test.cpp
+++ b/tools/aapt2/util/Maybe_test.cpp
@@ -14,122 +14,116 @@
* limitations under the License.
*/
-#include "test/Common.h"
#include "util/Maybe.h"
-#include <gtest/gtest.h>
#include <string>
+#include "test/Test.h"
+
namespace aapt {
struct Dummy {
- Dummy() {
- data = new int;
- *data = 1;
- std::cerr << "Construct Dummy{0x" << (void *) this
- << "} with data=0x" << (void*) data
- << std::endl;
+ Dummy() {
+ data = new int;
+ *data = 1;
+ std::cerr << "Construct Dummy{0x" << (void*)this << "} with data=0x"
+ << (void*)data << std::endl;
+ }
+
+ Dummy(const Dummy& rhs) {
+ data = nullptr;
+ if (rhs.data) {
+ data = new int;
+ *data = *rhs.data;
}
+ std::cerr << "CopyConstruct Dummy{0x" << (void*)this << "} from Dummy{0x"
+ << (const void*)&rhs << "}" << std::endl;
+ }
- Dummy(const Dummy& rhs) {
- data = nullptr;
- if (rhs.data) {
- data = new int;
- *data = *rhs.data;
- }
- std::cerr << "CopyConstruct Dummy{0x" << (void *) this
- << "} from Dummy{0x" << (const void*) &rhs
- << "}" << std::endl;
+ Dummy(Dummy&& rhs) {
+ data = rhs.data;
+ rhs.data = nullptr;
+ std::cerr << "MoveConstruct Dummy{0x" << (void*)this << "} from Dummy{0x"
+ << (const void*)&rhs << "}" << std::endl;
+ }
+
+ Dummy& operator=(const Dummy& rhs) {
+ delete data;
+ data = nullptr;
+
+ if (rhs.data) {
+ data = new int;
+ *data = *rhs.data;
}
+ std::cerr << "CopyAssign Dummy{0x" << (void*)this << "} from Dummy{0x"
+ << (const void*)&rhs << "}" << std::endl;
+ return *this;
+ }
- Dummy(Dummy&& rhs) {
- data = rhs.data;
- rhs.data = nullptr;
- std::cerr << "MoveConstruct Dummy{0x" << (void *) this
- << "} from Dummy{0x" << (const void*) &rhs
- << "}" << std::endl;
- }
+ Dummy& operator=(Dummy&& rhs) {
+ delete data;
+ data = rhs.data;
+ rhs.data = nullptr;
+ std::cerr << "MoveAssign Dummy{0x" << (void*)this << "} from Dummy{0x"
+ << (const void*)&rhs << "}" << std::endl;
+ return *this;
+ }
- Dummy& operator=(const Dummy& rhs) {
- delete data;
- data = nullptr;
+ ~Dummy() {
+ std::cerr << "Destruct Dummy{0x" << (void*)this << "} with data=0x"
+ << (void*)data << std::endl;
+ delete data;
+ }
- if (rhs.data) {
- data = new int;
- *data = *rhs.data;
- }
- std::cerr << "CopyAssign Dummy{0x" << (void *) this
- << "} from Dummy{0x" << (const void*) &rhs
- << "}" << std::endl;
- return *this;
- }
-
- Dummy& operator=(Dummy&& rhs) {
- delete data;
- data = rhs.data;
- rhs.data = nullptr;
- std::cerr << "MoveAssign Dummy{0x" << (void *) this
- << "} from Dummy{0x" << (const void*) &rhs
- << "}" << std::endl;
- return *this;
- }
-
- ~Dummy() {
- std::cerr << "Destruct Dummy{0x" << (void *) this
- << "} with data=0x" << (void*) data
- << std::endl;
- delete data;
- }
-
- int* data;
+ int* data;
};
TEST(MaybeTest, MakeNothing) {
- Maybe<int> val = make_nothing<int>();
- AAPT_EXPECT_FALSE(val);
+ Maybe<int> val = make_nothing<int>();
+ AAPT_EXPECT_FALSE(val);
- Maybe<std::string> val2 = make_nothing<std::string>();
- AAPT_EXPECT_FALSE(val2);
+ Maybe<std::string> val2 = make_nothing<std::string>();
+ AAPT_EXPECT_FALSE(val2);
- val2 = make_nothing<std::string>();
- AAPT_EXPECT_FALSE(val2);
+ val2 = make_nothing<std::string>();
+ AAPT_EXPECT_FALSE(val2);
}
TEST(MaybeTest, MakeSomething) {
- Maybe<int> val = make_value(23);
- AAPT_ASSERT_TRUE(val);
- EXPECT_EQ(23, val.value());
+ Maybe<int> val = make_value(23);
+ AAPT_ASSERT_TRUE(val);
+ EXPECT_EQ(23, val.value());
- Maybe<std::string> val2 = make_value(std::string("hey"));
- AAPT_ASSERT_TRUE(val2);
- EXPECT_EQ(std::string("hey"), val2.value());
+ Maybe<std::string> val2 = make_value(std::string("hey"));
+ AAPT_ASSERT_TRUE(val2);
+ EXPECT_EQ(std::string("hey"), val2.value());
}
TEST(MaybeTest, Lifecycle) {
- Maybe<Dummy> val = make_nothing<Dummy>();
+ Maybe<Dummy> val = make_nothing<Dummy>();
- Maybe<Dummy> val2 = make_value(Dummy());
+ Maybe<Dummy> val2 = make_value(Dummy());
}
TEST(MaybeTest, MoveAssign) {
- Maybe<Dummy> val;
- {
- Maybe<Dummy> val2 = Dummy();
- val = std::move(val2);
- }
+ Maybe<Dummy> val;
+ {
+ Maybe<Dummy> val2 = Dummy();
+ val = std::move(val2);
+ }
}
TEST(MaybeTest, Equality) {
- Maybe<int> a = 1;
- Maybe<int> b = 1;
- Maybe<int> c;
+ Maybe<int> a = 1;
+ Maybe<int> b = 1;
+ Maybe<int> c;
- Maybe<int> emptyA, emptyB;
+ Maybe<int> emptyA, emptyB;
- EXPECT_EQ(a, b);
- EXPECT_EQ(b, a);
- EXPECT_NE(a, c);
- EXPECT_EQ(emptyA, emptyB);
+ EXPECT_EQ(a, b);
+ EXPECT_EQ(b, a);
+ EXPECT_NE(a, c);
+ EXPECT_EQ(emptyA, emptyB);
}
-} // namespace aapt
+} // namespace aapt
diff --git a/tools/aapt2/util/StringPiece.h b/tools/aapt2/util/StringPiece.h
index de93822..5144b1f 100644
--- a/tools/aapt2/util/StringPiece.h
+++ b/tools/aapt2/util/StringPiece.h
@@ -17,12 +17,13 @@
#ifndef AAPT_STRING_PIECE_H
#define AAPT_STRING_PIECE_H
-#include <utils/JenkinsHash.h>
-#include <utils/String8.h>
-#include <utils/Unicode.h>
#include <ostream>
#include <string>
+#include "utils/JenkinsHash.h"
+#include "utils/String8.h"
+#include "utils/Unicode.h"
+
namespace aapt {
/**
@@ -60,7 +61,7 @@
size_t length() const;
size_t size() const;
bool empty() const;
- std::basic_string<TChar> toString() const;
+ std::basic_string<TChar> ToString() const;
bool contains(const BasicStringPiece<TChar>& rhs) const;
int compare(const BasicStringPiece<TChar>& rhs) const;
@@ -73,8 +74,8 @@
const_iterator end() const;
private:
- const TChar* mData;
- size_t mLength;
+ const TChar* data_;
+ size_t length_;
};
using StringPiece = BasicStringPiece<char>;
@@ -89,43 +90,43 @@
template <typename TChar>
inline BasicStringPiece<TChar>::BasicStringPiece()
- : mData(nullptr), mLength(0) {}
+ : data_(nullptr), length_(0) {}
template <typename TChar>
inline BasicStringPiece<TChar>::BasicStringPiece(
const BasicStringPiece<TChar>& str)
- : mData(str.mData), mLength(str.mLength) {}
+ : data_(str.data_), length_(str.length_) {}
template <typename TChar>
inline BasicStringPiece<TChar>::BasicStringPiece(
const std::basic_string<TChar>& str)
- : mData(str.data()), mLength(str.length()) {}
+ : data_(str.data()), length_(str.length()) {}
template <>
inline BasicStringPiece<char>::BasicStringPiece(const char* str)
- : mData(str), mLength(str != nullptr ? strlen(str) : 0) {}
+ : data_(str), length_(str != nullptr ? strlen(str) : 0) {}
template <>
inline BasicStringPiece<char16_t>::BasicStringPiece(const char16_t* str)
- : mData(str), mLength(str != nullptr ? strlen16(str) : 0) {}
+ : data_(str), length_(str != nullptr ? strlen16(str) : 0) {}
template <typename TChar>
inline BasicStringPiece<TChar>::BasicStringPiece(const TChar* str, size_t len)
- : mData(str), mLength(len) {}
+ : data_(str), length_(len) {}
template <typename TChar>
inline BasicStringPiece<TChar>& BasicStringPiece<TChar>::operator=(
const BasicStringPiece<TChar>& rhs) {
- mData = rhs.mData;
- mLength = rhs.mLength;
+ data_ = rhs.data_;
+ length_ = rhs.length_;
return *this;
}
template <typename TChar>
inline BasicStringPiece<TChar>& BasicStringPiece<TChar>::assign(
const TChar* str, size_t len) {
- mData = str;
- mLength = len;
+ data_ = str;
+ length_ = len;
return *this;
}
@@ -133,13 +134,13 @@
inline BasicStringPiece<TChar> BasicStringPiece<TChar>::substr(
size_t start, size_t len) const {
if (len == npos) {
- len = mLength - start;
+ len = length_ - start;
}
- if (start > mLength || start + len > mLength) {
+ if (start > length_ || start + len > length_) {
return BasicStringPiece<TChar>();
}
- return BasicStringPiece<TChar>(mData + start, len);
+ return BasicStringPiece<TChar>(data_ + start, len);
}
template <typename TChar>
@@ -151,49 +152,49 @@
template <typename TChar>
inline const TChar* BasicStringPiece<TChar>::data() const {
- return mData;
+ return data_;
}
template <typename TChar>
inline size_t BasicStringPiece<TChar>::length() const {
- return mLength;
+ return length_;
}
template <typename TChar>
inline size_t BasicStringPiece<TChar>::size() const {
- return mLength;
+ return length_;
}
template <typename TChar>
inline bool BasicStringPiece<TChar>::empty() const {
- return mLength == 0;
+ return length_ == 0;
}
template <typename TChar>
-inline std::basic_string<TChar> BasicStringPiece<TChar>::toString() const {
- return std::basic_string<TChar>(mData, mLength);
+inline std::basic_string<TChar> BasicStringPiece<TChar>::ToString() const {
+ return std::basic_string<TChar>(data_, length_);
}
template <>
inline bool BasicStringPiece<char>::contains(
const BasicStringPiece<char>& rhs) const {
- if (!mData || !rhs.mData) {
+ if (!data_ || !rhs.data_) {
return false;
}
- if (rhs.mLength > mLength) {
+ if (rhs.length_ > length_) {
return false;
}
- return strstr(mData, rhs.mData) != nullptr;
+ return strstr(data_, rhs.data_) != nullptr;
}
template <>
inline int BasicStringPiece<char>::compare(
const BasicStringPiece<char>& rhs) const {
const char nullStr = '\0';
- const char* b1 = mData != nullptr ? mData : &nullStr;
- const char* e1 = b1 + mLength;
- const char* b2 = rhs.mData != nullptr ? rhs.mData : &nullStr;
- const char* e2 = b2 + rhs.mLength;
+ 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++);
@@ -201,7 +202,7 @@
return d;
}
}
- return static_cast<int>(mLength - rhs.mLength);
+ return static_cast<int>(length_ - rhs.length_);
}
inline ::std::ostream& operator<<(::std::ostream& out,
@@ -213,22 +214,22 @@
template <>
inline bool BasicStringPiece<char16_t>::contains(
const BasicStringPiece<char16_t>& rhs) const {
- if (!mData || !rhs.mData) {
+ if (!data_ || !rhs.data_) {
return false;
}
- if (rhs.mLength > mLength) {
+ if (rhs.length_ > length_) {
return false;
}
- return strstr16(mData, rhs.mData) != nullptr;
+ 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 = mData != nullptr ? mData : &nullStr;
- const char16_t* b2 = rhs.mData != nullptr ? rhs.mData : &nullStr;
- return strzcmp16(b1, mLength, b2, rhs.mLength);
+ 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>
@@ -258,13 +259,13 @@
template <typename TChar>
inline typename BasicStringPiece<TChar>::const_iterator
BasicStringPiece<TChar>::begin() const {
- return mData;
+ return data_;
}
template <typename TChar>
inline typename BasicStringPiece<TChar>::const_iterator
BasicStringPiece<TChar>::end() const {
- return mData + mLength;
+ return data_ + length_;
}
inline ::std::ostream& operator<<(::std::ostream& out,
diff --git a/tools/aapt2/util/StringPiece_test.cpp b/tools/aapt2/util/StringPiece_test.cpp
index a87065a..048961d 100644
--- a/tools/aapt2/util/StringPiece_test.cpp
+++ b/tools/aapt2/util/StringPiece_test.cpp
@@ -14,81 +14,82 @@
* limitations under the License.
*/
+#include "util/StringPiece.h"
+
#include <algorithm>
-#include <gtest/gtest.h>
#include <string>
#include <vector>
-#include "util/StringPiece.h"
+#include "test/Test.h"
namespace aapt {
TEST(StringPieceTest, CompareNonNullTerminatedPiece) {
- StringPiece a("hello world", 5);
- StringPiece b("hello moon", 5);
- EXPECT_EQ(a, b);
+ StringPiece a("hello world", 5);
+ StringPiece b("hello moon", 5);
+ EXPECT_EQ(a, b);
- StringPiece16 a16(u"hello world", 5);
- StringPiece16 b16(u"hello moon", 5);
- EXPECT_EQ(a16, b16);
+ StringPiece16 a16(u"hello world", 5);
+ StringPiece16 b16(u"hello moon", 5);
+ EXPECT_EQ(a16, b16);
}
TEST(StringPieceTest, PiecesHaveCorrectSortOrder) {
- std::string testing("testing");
- std::string banana("banana");
- std::string car("car");
+ std::string testing("testing");
+ std::string banana("banana");
+ std::string car("car");
- EXPECT_TRUE(StringPiece(testing) > banana);
- EXPECT_TRUE(StringPiece(testing) > car);
- EXPECT_TRUE(StringPiece(banana) < testing);
- EXPECT_TRUE(StringPiece(banana) < car);
- EXPECT_TRUE(StringPiece(car) < testing);
- EXPECT_TRUE(StringPiece(car) > banana);
+ EXPECT_TRUE(StringPiece(testing) > banana);
+ EXPECT_TRUE(StringPiece(testing) > car);
+ EXPECT_TRUE(StringPiece(banana) < testing);
+ EXPECT_TRUE(StringPiece(banana) < car);
+ EXPECT_TRUE(StringPiece(car) < testing);
+ EXPECT_TRUE(StringPiece(car) > banana);
}
TEST(StringPieceTest, PiecesHaveCorrectSortOrderUtf8) {
- std::string testing("testing");
- std::string banana("banana");
- std::string car("car");
+ std::string testing("testing");
+ std::string banana("banana");
+ std::string car("car");
- EXPECT_TRUE(StringPiece(testing) > banana);
- EXPECT_TRUE(StringPiece(testing) > car);
- EXPECT_TRUE(StringPiece(banana) < testing);
- EXPECT_TRUE(StringPiece(banana) < car);
- EXPECT_TRUE(StringPiece(car) < testing);
- EXPECT_TRUE(StringPiece(car) > banana);
+ EXPECT_TRUE(StringPiece(testing) > banana);
+ EXPECT_TRUE(StringPiece(testing) > car);
+ EXPECT_TRUE(StringPiece(banana) < testing);
+ EXPECT_TRUE(StringPiece(banana) < car);
+ EXPECT_TRUE(StringPiece(car) < testing);
+ EXPECT_TRUE(StringPiece(car) > banana);
}
TEST(StringPieceTest, ContainsOtherStringPiece) {
- StringPiece text("I am a leaf on the wind.");
- StringPiece startNeedle("I am");
- StringPiece endNeedle("wind.");
- StringPiece middleNeedle("leaf");
- StringPiece emptyNeedle("");
- StringPiece missingNeedle("soar");
- StringPiece longNeedle("This string is longer than the text.");
+ 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(startNeedle));
- EXPECT_TRUE(text.contains(endNeedle));
- EXPECT_TRUE(text.contains(middleNeedle));
- EXPECT_TRUE(text.contains(emptyNeedle));
- EXPECT_FALSE(text.contains(missingNeedle));
- EXPECT_FALSE(text.contains(longNeedle));
+ 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 startNeedle16(u"I am");
- StringPiece16 endNeedle16(u"wind.");
- StringPiece16 middleNeedle16(u"leaf");
- StringPiece16 emptyNeedle16(u"");
- StringPiece16 missingNeedle16(u"soar");
- StringPiece16 longNeedle16(u"This string is longer than the text.");
+ 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(startNeedle16));
- EXPECT_TRUE(text16.contains(endNeedle16));
- EXPECT_TRUE(text16.contains(middleNeedle16));
- EXPECT_TRUE(text16.contains(emptyNeedle16));
- EXPECT_FALSE(text16.contains(missingNeedle16));
- EXPECT_FALSE(text16.contains(longNeedle16));
+ 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 aapt
+} // namespace aapt
diff --git a/tools/aapt2/util/Util.cpp b/tools/aapt2/util/Util.cpp
index b0bec62..d5c0c8a 100644
--- a/tools/aapt2/util/Util.cpp
+++ b/tools/aapt2/util/Util.cpp
@@ -14,559 +14,558 @@
* limitations under the License.
*/
+#include "util/Util.h"
#include "util/BigBuffer.h"
#include "util/Maybe.h"
#include "util/StringPiece.h"
-#include "util/Util.h"
+#include <utils/Unicode.h>
#include <algorithm>
#include <ostream>
#include <string>
-#include <utils/Unicode.h>
#include <vector>
namespace aapt {
namespace util {
-static std::vector<std::string> splitAndTransform(const StringPiece& str, char sep,
- const std::function<char(char)>& 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).toString());
- if (f) {
- std::string& part = parts.back();
- std::transform(part.begin(), part.end(), part.begin(), f);
- }
- start = current + 1;
- } while (current != end);
- return parts;
+static std::vector<std::string> SplitAndTransform(
+ const StringPiece& str, char sep, const std::function<char(char)>& 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).ToString());
+ if (f) {
+ 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> split(const StringPiece& str, char sep) {
- return splitAndTransform(str, sep, nullptr);
+std::vector<std::string> Split(const 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(const StringPiece& str, char sep) {
+ return SplitAndTransform(str, sep, ::tolower);
}
-bool stringStartsWith(const StringPiece& str, const StringPiece& prefix) {
- if (str.size() < prefix.size()) {
- return false;
- }
- return str.substr(0, prefix.size()) == prefix;
+bool StartsWith(const StringPiece& str, const StringPiece& prefix) {
+ if (str.size() < prefix.size()) {
+ return false;
+ }
+ return str.substr(0, prefix.size()) == prefix;
}
-bool stringEndsWith(const StringPiece& str, const StringPiece& suffix) {
- if (str.size() < suffix.size()) {
- return false;
- }
- return str.substr(str.size() - suffix.size(), suffix.size()) == suffix;
+bool EndsWith(const StringPiece& str, const StringPiece& suffix) {
+ if (str.size() < suffix.size()) {
+ return false;
+ }
+ return str.substr(str.size() - suffix.size(), suffix.size()) == suffix;
}
-StringPiece trimWhitespace(const StringPiece& str) {
- if (str.size() == 0 || str.data() == nullptr) {
- return str;
- }
+StringPiece TrimWhitespace(const StringPiece& str) {
+ if (str.size() == 0 || str.data() == nullptr) {
+ return str;
+ }
- const char* start = str.data();
- const char* end = str.data() + str.length();
+ const char* start = str.data();
+ const char* end = str.data() + str.length();
- while (start != end && isspace(*start)) {
- start++;
- }
+ while (start != end && isspace(*start)) {
+ start++;
+ }
- while (end != start && isspace(*(end - 1))) {
- end--;
- }
+ while (end != start && isspace(*(end - 1))) {
+ end--;
+ }
- return StringPiece(start, end - start);
+ return StringPiece(start, end - start);
}
-StringPiece::const_iterator findNonAlphaNumericAndNotInSet(const StringPiece& str,
- const StringPiece& allowedChars) {
- const auto endIter = str.end();
- for (auto iter = str.begin(); iter != endIter; ++iter) {
- char c = *iter;
- if ((c >= u'a' && c <= u'z') ||
- (c >= u'A' && c <= u'Z') ||
- (c >= u'0' && c <= u'9')) {
- continue;
- }
-
- bool match = false;
- for (char i : allowedChars) {
- if (c == i) {
- match = true;
- break;
- }
- }
-
- if (!match) {
- return iter;
- }
+StringPiece::const_iterator FindNonAlphaNumericAndNotInSet(
+ const StringPiece& str, const StringPiece& allowed_chars) {
+ const auto end_iter = str.end();
+ for (auto iter = str.begin(); iter != end_iter; ++iter) {
+ char c = *iter;
+ if ((c >= u'a' && c <= u'z') || (c >= u'A' && c <= u'Z') ||
+ (c >= u'0' && c <= u'9')) {
+ continue;
}
- return endIter;
+
+ bool match = false;
+ for (char i : allowed_chars) {
+ if (c == i) {
+ match = true;
+ break;
+ }
+ }
+
+ if (!match) {
+ return iter;
+ }
+ }
+ return end_iter;
}
-bool isJavaClassName(const StringPiece& str) {
- size_t pieces = 0;
- for (const StringPiece& piece : tokenize(str, '.')) {
- pieces++;
- if (piece.empty()) {
- return false;
- }
-
- // Can't have starting or trailing $ character.
- if (piece.data()[0] == '$' || piece.data()[piece.size() - 1] == '$') {
- return false;
- }
-
- if (findNonAlphaNumericAndNotInSet(piece, "$_") != piece.end()) {
- return false;
- }
+bool IsJavaClassName(const StringPiece& str) {
+ size_t pieces = 0;
+ for (const StringPiece& piece : Tokenize(str, '.')) {
+ pieces++;
+ if (piece.empty()) {
+ return false;
}
- return pieces >= 2;
+
+ // Can't have starting or trailing $ character.
+ if (piece.data()[0] == '$' || piece.data()[piece.size() - 1] == '$') {
+ return false;
+ }
+
+ if (FindNonAlphaNumericAndNotInSet(piece, "$_") != piece.end()) {
+ return false;
+ }
+ }
+ return pieces >= 2;
}
-bool isJavaPackageName(const StringPiece& str) {
- if (str.empty()) {
- return false;
+bool IsJavaPackageName(const StringPiece& str) {
+ if (str.empty()) {
+ return false;
+ }
+
+ size_t pieces = 0;
+ for (const StringPiece& piece : Tokenize(str, '.')) {
+ pieces++;
+ if (piece.empty()) {
+ return false;
}
- size_t pieces = 0;
- for (const StringPiece& piece : tokenize(str, '.')) {
- pieces++;
- if (piece.empty()) {
- return false;
- }
-
- if (piece.data()[0] == '_' || piece.data()[piece.size() - 1] == '_') {
- return false;
- }
-
- if (findNonAlphaNumericAndNotInSet(piece, "_") != piece.end()) {
- return false;
- }
+ if (piece.data()[0] == '_' || piece.data()[piece.size() - 1] == '_') {
+ return false;
}
- return pieces >= 1;
+
+ if (FindNonAlphaNumericAndNotInSet(piece, "_") != piece.end()) {
+ return false;
+ }
+ }
+ return pieces >= 1;
}
-Maybe<std::string> getFullyQualifiedClassName(const StringPiece& package,
- const StringPiece& className) {
- if (className.empty()) {
- return {};
- }
+Maybe<std::string> GetFullyQualifiedClassName(const StringPiece& package,
+ const StringPiece& classname) {
+ if (classname.empty()) {
+ return {};
+ }
- if (util::isJavaClassName(className)) {
- return className.toString();
- }
+ if (util::IsJavaClassName(classname)) {
+ return classname.ToString();
+ }
- if (package.empty()) {
- return {};
- }
+ if (package.empty()) {
+ return {};
+ }
- std::string result(package.data(), package.size());
- if (className.data()[0] != '.') {
- result += '.';
- }
+ std::string result(package.data(), package.size());
+ if (classname.data()[0] != '.') {
+ result += '.';
+ }
- result.append(className.data(), className.size());
- if (!isJavaClassName(result)) {
- return {};
- }
- return result;
+ result.append(classname.data(), classname.size());
+ if (!IsJavaClassName(result)) {
+ return {};
+ }
+ return result;
}
-static size_t consumeDigits(const char* start, const char* end) {
- const char* c = start;
- for (; c != end && *c >= '0' && *c <= '9'; c++) {}
- return static_cast<size_t>(c - start);
+static size_t ConsumeDigits(const char* start, const char* end) {
+ const char* c = start;
+ for (; c != end && *c >= '0' && *c <= '9'; c++) {
+ }
+ return static_cast<size_t>(c - start);
}
-bool verifyJavaStringFormat(const StringPiece& str) {
- const char* c = str.begin();
- const char* const end = str.end();
+bool VerifyJavaStringFormat(const StringPiece& str) {
+ const char* c = str.begin();
+ const char* const end = str.end();
- size_t argCount = 0;
- bool nonpositional = false;
- while (c != end) {
- if (*c == '%' && c + 1 < end) {
- c++;
+ size_t arg_count = 0;
+ bool nonpositional = false;
+ while (c != end) {
+ if (*c == '%' && c + 1 < end) {
+ c++;
- if (*c == '%') {
- c++;
- continue;
- }
+ if (*c == '%') {
+ c++;
+ continue;
+ }
- argCount++;
+ arg_count++;
- size_t numDigits = consumeDigits(c, end);
- if (numDigits > 0) {
- c += numDigits;
- if (c != end && *c != '$') {
- // The digits were a size, but not a positional argument.
- nonpositional = true;
- }
- } else if (*c == '<') {
- // Reusing last argument, bad idea since positions can be moved around
- // during translation.
- nonpositional = true;
-
- c++;
-
- // Optionally we can have a $ after
- if (c != end && *c == '$') {
- c++;
- }
- } else {
- nonpositional = true;
- }
-
- // Ignore size, width, flags, etc.
- while (c != end && (*c == '-' ||
- *c == '#' ||
- *c == '+' ||
- *c == ' ' ||
- *c == ',' ||
- *c == '(' ||
- (*c >= '0' && *c <= '9'))) {
- c++;
- }
-
- /*
- * This is a shortcut to detect strings that are going to Time.format()
- * instead of String.format()
- *
- * Comparison of String.format() and Time.format() args:
- *
- * String: ABC E GH ST X abcdefgh nost x
- * Time: DEFGHKMS W Za d hkm s w yz
- *
- * Therefore we know it's definitely Time if we have:
- * DFKMWZkmwyz
- */
- if (c != end) {
- switch (*c) {
- case 'D':
- case 'F':
- case 'K':
- case 'M':
- case 'W':
- case 'Z':
- case 'k':
- case 'm':
- case 'w':
- case 'y':
- case 'z':
- return true;
- }
- }
+ size_t num_digits = ConsumeDigits(c, end);
+ if (num_digits > 0) {
+ c += num_digits;
+ if (c != end && *c != '$') {
+ // The digits were a size, but not a positional argument.
+ nonpositional = true;
}
+ } else if (*c == '<') {
+ // Reusing last argument, bad idea since positions can be moved around
+ // during translation.
+ nonpositional = true;
- if (c != end) {
- c++;
+ c++;
+
+ // Optionally we can have a $ after
+ if (c != end && *c == '$') {
+ c++;
}
+ } else {
+ nonpositional = true;
+ }
+
+ // Ignore size, width, flags, etc.
+ while (c != end && (*c == '-' || *c == '#' || *c == '+' || *c == ' ' ||
+ *c == ',' || *c == '(' || (*c >= '0' && *c <= '9'))) {
+ c++;
+ }
+
+ /*
+ * This is a shortcut to detect strings that are going to Time.format()
+ * instead of String.format()
+ *
+ * Comparison of String.format() and Time.format() args:
+ *
+ * String: ABC E GH ST X abcdefgh nost x
+ * Time: DEFGHKMS W Za d hkm s w yz
+ *
+ * Therefore we know it's definitely Time if we have:
+ * DFKMWZkmwyz
+ */
+ if (c != end) {
+ switch (*c) {
+ case 'D':
+ case 'F':
+ case 'K':
+ case 'M':
+ case 'W':
+ case 'Z':
+ case 'k':
+ case 'm':
+ case 'w':
+ case 'y':
+ case 'z':
+ return true;
+ }
+ }
}
- if (argCount > 1 && nonpositional) {
- // Multiple arguments were specified, but some or all were non positional. Translated
- // strings may rearrange the order of the arguments, which will break the string.
- return false;
+ if (c != end) {
+ c++;
}
- return true;
+ }
+
+ if (arg_count > 1 && nonpositional) {
+ // Multiple arguments were specified, but some or all were non positional.
+ // Translated
+ // strings may rearrange the order of the arguments, which will break the
+ // string.
+ return false;
+ }
+ return true;
}
-static Maybe<std::string> parseUnicodeCodepoint(const char** start, const char* end) {
- char32_t code = 0;
- for (size_t i = 0; i < 4 && *start != end; i++, (*start)++) {
- char c = **start;
- char32_t a;
- if (c >= '0' && c <= '9') {
- a = c - '0';
- } else if (c >= 'a' && c <= 'f') {
- a = c - 'a' + 10;
- } else if (c >= 'A' && c <= 'F') {
- a = c - 'A' + 10;
- } else {
- return {};
- }
- code = (code << 4) | a;
+static Maybe<std::string> ParseUnicodeCodepoint(const char** start,
+ const char* end) {
+ char32_t code = 0;
+ for (size_t i = 0; i < 4 && *start != end; i++, (*start)++) {
+ char c = **start;
+ char32_t a;
+ if (c >= '0' && c <= '9') {
+ a = c - '0';
+ } else if (c >= 'a' && c <= 'f') {
+ a = c - 'a' + 10;
+ } else if (c >= 'A' && c <= 'F') {
+ a = c - 'A' + 10;
+ } else {
+ return {};
}
+ code = (code << 4) | a;
+ }
- ssize_t len = utf32_to_utf8_length(&code, 1);
- if (len < 0) {
- return {};
- }
+ ssize_t len = utf32_to_utf8_length(&code, 1);
+ if (len < 0) {
+ return {};
+ }
- std::string resultUtf8;
- resultUtf8.resize(len);
- utf32_to_utf8(&code, 1, &*resultUtf8.begin(), len + 1);
- return resultUtf8;
+ std::string result_utf8;
+ result_utf8.resize(len);
+ utf32_to_utf8(&code, 1, &*result_utf8.begin(), len + 1);
+ return result_utf8;
}
-StringBuilder& StringBuilder::append(const StringPiece& str) {
- if (!mError.empty()) {
- return *this;
- }
-
- // Where the new data will be appended to.
- size_t newDataIndex = mStr.size();
-
- const char* const end = str.end();
- const char* start = str.begin();
- const char* current = start;
- while (current != end) {
- if (mLastCharWasEscape) {
- switch (*current) {
- case 't':
- mStr += '\t';
- break;
- case 'n':
- mStr += '\n';
- break;
- case '#':
- mStr += '#';
- break;
- case '@':
- mStr += '@';
- break;
- case '?':
- mStr += '?';
- break;
- case '"':
- mStr += '"';
- break;
- case '\'':
- mStr += '\'';
- break;
- case '\\':
- mStr += '\\';
- break;
- case 'u': {
- current++;
- Maybe<std::string> c = parseUnicodeCodepoint(¤t, end);
- if (!c) {
- mError = "invalid unicode escape sequence";
- return *this;
- }
- mStr += c.value();
- current -= 1;
- break;
- }
-
- default:
- // Ignore.
- break;
- }
- mLastCharWasEscape = false;
- start = current + 1;
- } else if (*current == '"') {
- if (!mQuote && mTrailingSpace) {
- // We found an opening quote, and we have
- // trailing space, so we should append that
- // space now.
- if (mTrailingSpace) {
- // We had trailing whitespace, so
- // replace with a single space.
- if (!mStr.empty()) {
- mStr += ' ';
- }
- mTrailingSpace = false;
- }
- }
- mQuote = !mQuote;
- mStr.append(start, current - start);
- start = current + 1;
- } else if (*current == '\'' && !mQuote) {
- // This should be escaped.
- mError = "unescaped apostrophe";
- return *this;
- } else if (*current == '\\') {
- // This is an escape sequence, convert to the real value.
- if (!mQuote && mTrailingSpace) {
- // We had trailing whitespace, so
- // replace with a single space.
- if (!mStr.empty()) {
- mStr += ' ';
- }
- mTrailingSpace = false;
- }
- mStr.append(start, current - start);
- start = current + 1;
- mLastCharWasEscape = true;
- } else if (!mQuote) {
- // This is not quoted text, so look for whitespace.
- if (isspace(*current)) {
- // We found whitespace, see if we have seen some
- // before.
- if (!mTrailingSpace) {
- // We didn't see a previous adjacent space,
- // so mark that we did.
- mTrailingSpace = true;
- mStr.append(start, current - start);
- }
-
- // Keep skipping whitespace.
- start = current + 1;
- } else if (mTrailingSpace) {
- // We saw trailing space before, so replace all
- // that trailing space with one space.
- if (!mStr.empty()) {
- mStr += ' ';
- }
- mTrailingSpace = false;
- }
- }
- current++;
- }
- mStr.append(start, end - start);
-
- // Accumulate the added string's UTF-16 length.
- ssize_t len = utf8_to_utf16_length(
- reinterpret_cast<const uint8_t*>(mStr.data()) + newDataIndex,
- mStr.size() - newDataIndex);
- if (len < 0) {
- mError = "invalid unicode code point";
- return *this;
- }
- mUtf16Len += len;
+StringBuilder& StringBuilder::Append(const StringPiece& str) {
+ if (!error_.empty()) {
return *this;
-}
+ }
-std::u16string utf8ToUtf16(const StringPiece& utf8) {
- ssize_t utf16Length = utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(utf8.data()),
- utf8.length());
- if (utf16Length <= 0) {
- return {};
- }
+ // Where the new data will be appended to.
+ size_t new_data_index = str_.size();
- std::u16string utf16;
- utf16.resize(utf16Length);
- utf8_to_utf16(reinterpret_cast<const uint8_t*>(utf8.data()), utf8.length(),
- &*utf16.begin(), utf16Length + 1);
- return utf16;
-}
-
-std::string utf16ToUtf8(const StringPiece16& utf16) {
- ssize_t utf8Length = utf16_to_utf8_length(utf16.data(), utf16.length());
- if (utf8Length <= 0) {
- return {};
- }
-
- std::string utf8;
- utf8.resize(utf8Length);
- utf16_to_utf8(utf16.data(), utf16.length(), &*utf8.begin(), utf8Length + 1);
- return utf8;
-}
-
-bool writeAll(std::ostream& out, const BigBuffer& buffer) {
- for (const auto& b : buffer) {
- if (!out.write(reinterpret_cast<const char*>(b.buffer.get()), b.size)) {
- return false;
+ const char* const end = str.end();
+ const char* start = str.begin();
+ const char* current = start;
+ while (current != end) {
+ if (last_char_was_escape_) {
+ switch (*current) {
+ case 't':
+ str_ += '\t';
+ break;
+ case 'n':
+ str_ += '\n';
+ break;
+ case '#':
+ str_ += '#';
+ break;
+ case '@':
+ str_ += '@';
+ break;
+ case '?':
+ str_ += '?';
+ break;
+ case '"':
+ str_ += '"';
+ break;
+ case '\'':
+ str_ += '\'';
+ break;
+ case '\\':
+ str_ += '\\';
+ break;
+ case 'u': {
+ current++;
+ Maybe<std::string> c = ParseUnicodeCodepoint(¤t, end);
+ if (!c) {
+ error_ = "invalid unicode escape sequence";
+ return *this;
+ }
+ str_ += c.value();
+ current -= 1;
+ break;
}
+
+ default:
+ // Ignore.
+ break;
+ }
+ last_char_was_escape_ = false;
+ start = current + 1;
+ } else if (*current == '"') {
+ if (!quote_ && trailing_space_) {
+ // We found an opening quote, and we have
+ // trailing space, so we should append that
+ // space now.
+ if (trailing_space_) {
+ // We had trailing whitespace, so
+ // replace with a single space.
+ if (!str_.empty()) {
+ str_ += ' ';
+ }
+ trailing_space_ = false;
+ }
+ }
+ quote_ = !quote_;
+ str_.append(start, current - start);
+ start = current + 1;
+ } else if (*current == '\'' && !quote_) {
+ // This should be escaped.
+ error_ = "unescaped apostrophe";
+ return *this;
+ } else if (*current == '\\') {
+ // This is an escape sequence, convert to the real value.
+ if (!quote_ && trailing_space_) {
+ // We had trailing whitespace, so
+ // replace with a single space.
+ if (!str_.empty()) {
+ str_ += ' ';
+ }
+ trailing_space_ = false;
+ }
+ str_.append(start, current - start);
+ start = current + 1;
+ last_char_was_escape_ = true;
+ } else if (!quote_) {
+ // This is not quoted text, so look for whitespace.
+ if (isspace(*current)) {
+ // We found whitespace, see if we have seen some
+ // before.
+ if (!trailing_space_) {
+ // We didn't see a previous adjacent space,
+ // so mark that we did.
+ trailing_space_ = true;
+ str_.append(start, current - start);
+ }
+
+ // Keep skipping whitespace.
+ start = current + 1;
+ } else if (trailing_space_) {
+ // We saw trailing space before, so replace all
+ // that trailing space with one space.
+ if (!str_.empty()) {
+ str_ += ' ';
+ }
+ trailing_space_ = false;
+ }
}
- return true;
+ current++;
+ }
+ str_.append(start, end - start);
+
+ // Accumulate the added string's UTF-16 length.
+ ssize_t len = utf8_to_utf16_length(
+ reinterpret_cast<const uint8_t*>(str_.data()) + new_data_index,
+ str_.size() - new_data_index);
+ if (len < 0) {
+ error_ = "invalid unicode code point";
+ return *this;
+ }
+ utf16_len_ += len;
+ return *this;
}
-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()]);
- uint8_t* p = data.get();
- for (const auto& block : buffer) {
- memcpy(p, block.buffer.get(), block.size);
- p += block.size;
+std::u16string Utf8ToUtf16(const StringPiece& utf8) {
+ ssize_t utf16_length = utf8_to_utf16_length(
+ reinterpret_cast<const uint8_t*>(utf8.data()), utf8.length());
+ if (utf16_length <= 0) {
+ return {};
+ }
+
+ std::u16string utf16;
+ utf16.resize(utf16_length);
+ utf8_to_utf16(reinterpret_cast<const uint8_t*>(utf8.data()), utf8.length(),
+ &*utf16.begin(), utf16_length + 1);
+ return utf16;
+}
+
+std::string Utf16ToUtf8(const StringPiece16& utf16) {
+ ssize_t utf8_length = utf16_to_utf8_length(utf16.data(), utf16.length());
+ if (utf8_length <= 0) {
+ return {};
+ }
+
+ std::string utf8;
+ utf8.resize(utf8_length);
+ utf16_to_utf8(utf16.data(), utf16.length(), &*utf8.begin(), utf8_length + 1);
+ return utf8;
+}
+
+bool WriteAll(std::ostream& out, const BigBuffer& buffer) {
+ for (const auto& b : buffer) {
+ if (!out.write(reinterpret_cast<const char*>(b.buffer.get()), b.size)) {
+ return false;
}
- return data;
+ }
+ return true;
+}
+
+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()]);
+ uint8_t* p = data.get();
+ for (const auto& block : buffer) {
+ memcpy(p, block.buffer.get(), block.size);
+ p += block.size;
+ }
+ return data;
}
typename Tokenizer::iterator& Tokenizer::iterator::operator++() {
- const char* start = mToken.end();
- const char* end = mStr.end();
- if (start == end) {
- mEnd = true;
- mToken.assign(mToken.end(), 0);
- return *this;
- }
-
- start += 1;
- const char* current = start;
- while (current != end) {
- if (*current == mSeparator) {
- mToken.assign(start, current - start);
- return *this;
- }
- ++current;
- }
- mToken.assign(start, end - start);
+ const char* start = token_.end();
+ const char* end = str_.end();
+ if (start == end) {
+ end_ = true;
+ token_.assign(token_.end(), 0);
return *this;
+ }
+
+ start += 1;
+ const char* current = start;
+ while (current != end) {
+ if (*current == separator_) {
+ token_.assign(start, current - start);
+ return *this;
+ }
+ ++current;
+ }
+ token_.assign(start, end - start);
+ return *this;
}
bool Tokenizer::iterator::operator==(const iterator& rhs) const {
- // We check equality here a bit differently.
- // We need to know that the addresses are the same.
- return mToken.begin() == rhs.mToken.begin() && mToken.end() == rhs.mToken.end() &&
- mEnd == rhs.mEnd;
+ // We check equality here a bit differently.
+ // We need to know that the addresses are the same.
+ return token_.begin() == rhs.token_.begin() &&
+ token_.end() == rhs.token_.end() && end_ == rhs.end_;
}
bool Tokenizer::iterator::operator!=(const iterator& rhs) const {
- return !(*this == rhs);
+ return !(*this == rhs);
}
-Tokenizer::iterator::iterator(StringPiece s, char sep, StringPiece tok, bool end) :
- mStr(s), mSeparator(sep), mToken(tok), mEnd(end) {
-}
+Tokenizer::iterator::iterator(StringPiece s, char sep, StringPiece tok,
+ bool end)
+ : str_(s), separator_(sep), token_(tok), end_(end) {}
-Tokenizer::Tokenizer(StringPiece str, char sep) :
- mBegin(++iterator(str, sep, StringPiece(str.begin() - 1, 0), false)),
- mEnd(str, sep, StringPiece(str.end(), 0), true) {
-}
+Tokenizer::Tokenizer(StringPiece str, char sep)
+ : begin_(++iterator(str, sep, StringPiece(str.begin() - 1, 0), false)),
+ end_(str, sep, StringPiece(str.end(), 0), true) {}
-bool extractResFilePathParts(const StringPiece& path, StringPiece* outPrefix,
- StringPiece* outEntry, StringPiece* outSuffix) {
- const StringPiece resPrefix("res/");
- if (!stringStartsWith(path, resPrefix)) {
- return false;
+bool ExtractResFilePathParts(const StringPiece& path, StringPiece* out_prefix,
+ StringPiece* out_entry, StringPiece* out_suffix) {
+ const StringPiece res_prefix("res/");
+ if (!StartsWith(path, res_prefix)) {
+ return false;
+ }
+
+ StringPiece::const_iterator last_occurence = path.end();
+ for (auto iter = path.begin() + res_prefix.size(); iter != path.end();
+ ++iter) {
+ if (*iter == '/') {
+ last_occurence = iter;
}
+ }
- StringPiece::const_iterator lastOccurence = path.end();
- for (auto iter = path.begin() + resPrefix.size(); iter != path.end(); ++iter) {
- if (*iter == '/') {
- lastOccurence = iter;
- }
- }
+ if (last_occurence == path.end()) {
+ return false;
+ }
- if (lastOccurence == path.end()) {
- return false;
- }
-
- auto iter = std::find(lastOccurence, path.end(), '.');
- *outSuffix = StringPiece(iter, path.end() - iter);
- *outEntry = StringPiece(lastOccurence + 1, iter - lastOccurence - 1);
- *outPrefix = StringPiece(path.begin(), lastOccurence - path.begin() + 1);
- return true;
+ auto iter = std::find(last_occurence, path.end(), '.');
+ *out_suffix = StringPiece(iter, path.end() - iter);
+ *out_entry = StringPiece(last_occurence + 1, iter - last_occurence - 1);
+ *out_prefix = StringPiece(path.begin(), last_occurence - path.begin() + 1);
+ return true;
}
-StringPiece16 getString16(const android::ResStringPool& pool, size_t idx) {
- size_t len;
- const char16_t* str = pool.stringAt(idx, &len);
- if (str != nullptr) {
- return StringPiece16(str, len);
- }
- return StringPiece16();
+StringPiece16 GetString16(const android::ResStringPool& pool, size_t idx) {
+ size_t len;
+ const char16_t* str = pool.stringAt(idx, &len);
+ if (str != nullptr) {
+ return StringPiece16(str, len);
+ }
+ return StringPiece16();
}
-std::string getString(const android::ResStringPool& pool, size_t idx) {
- size_t len;
- const char* str = pool.string8At(idx, &len);
- if (str != nullptr) {
- return std::string(str, len);
- }
- return utf16ToUtf8(getString16(pool, idx));
+std::string GetString(const android::ResStringPool& pool, size_t idx) {
+ size_t len;
+ const char* str = pool.string8At(idx, &len);
+ if (str != nullptr) {
+ return std::string(str, len);
+ }
+ return Utf16ToUtf8(GetString16(pool, idx));
}
-} // namespace util
-} // namespace aapt
+} // namespace util
+} // namespace aapt
diff --git a/tools/aapt2/util/Util.h b/tools/aapt2/util/Util.h
index 077e193..05e9cc5 100644
--- a/tools/aapt2/util/Util.h
+++ b/tools/aapt2/util/Util.h
@@ -17,40 +17,53 @@
#ifndef AAPT_UTIL_H
#define AAPT_UTIL_H
-#include "util/BigBuffer.h"
-#include "util/Maybe.h"
-#include "util/StringPiece.h"
-
-#include <androidfw/ResourceTypes.h>
#include <functional>
#include <memory>
#include <ostream>
#include <string>
#include <vector>
+#include "androidfw/ResourceTypes.h"
+#include "utils/ByteOrder.h"
+
+#include "util/BigBuffer.h"
+#include "util/Maybe.h"
+#include "util/StringPiece.h"
+
+#ifdef _WIN32
+// TODO(adamlesinski): remove once http://b/32447322 is resolved.
+// utils/ByteOrder.h includes winsock2.h on WIN32,
+// which will pull in the ERROR definition. This conflicts
+// with android-base/logging.h, which takes care of undefining
+// ERROR, but it gets included too early (before winsock2.h).
+#ifdef ERROR
+#undef ERROR
+#endif
+#endif
+
namespace aapt {
namespace util {
-std::vector<std::string> split(const StringPiece& str, char sep);
-std::vector<std::string> splitAndLowercase(const StringPiece& str, char sep);
+std::vector<std::string> Split(const StringPiece& str, char sep);
+std::vector<std::string> SplitAndLowercase(const StringPiece& str, char sep);
/**
* Returns true if the string starts with prefix.
*/
-bool stringStartsWith(const StringPiece& str, const StringPiece& prefix);
+bool StartsWith(const StringPiece& str, const StringPiece& prefix);
/**
* Returns true if the string ends with suffix.
*/
-bool stringEndsWith(const StringPiece& str, const StringPiece& suffix);
+bool EndsWith(const StringPiece& str, const StringPiece& suffix);
/**
* Creates a new StringPiece16 that points to a substring
* of the original string without leading or trailing whitespace.
*/
-StringPiece trimWhitespace(const StringPiece& str);
+StringPiece TrimWhitespace(const StringPiece& str);
-StringPiece trimWhitespace(const StringPiece& str);
+StringPiece TrimWhitespace(const StringPiece& str);
/**
* UTF-16 isspace(). It basically checks for lower range characters that are
@@ -62,18 +75,18 @@
* Returns an iterator to the first character that is not alpha-numeric and that
* is not in the allowedChars set.
*/
-StringPiece::const_iterator findNonAlphaNumericAndNotInSet(
- const StringPiece& str, const StringPiece& allowedChars);
+StringPiece::const_iterator FindNonAlphaNumericAndNotInSet(
+ const StringPiece& str, const StringPiece& allowed_chars);
/**
* Tests that the string is a valid Java class name.
*/
-bool isJavaClassName(const StringPiece& str);
+bool IsJavaClassName(const StringPiece& str);
/**
* Tests that the string is a valid Java package name.
*/
-bool isJavaPackageName(const StringPiece& str);
+bool IsJavaPackageName(const StringPiece& str);
/**
* Converts the class name to a fully qualified class name from the given
@@ -84,8 +97,8 @@
* .a.b --> package.a.b
* asdf.adsf --> asdf.adsf
*/
-Maybe<std::string> getFullyQualifiedClassName(const StringPiece& package,
- const StringPiece& className);
+Maybe<std::string> GetFullyQualifiedClassName(const StringPiece& package,
+ const StringPiece& class_name);
/**
* Makes a std::unique_ptr<> with the template parameter inferred by the
@@ -103,15 +116,15 @@
* separator.
*/
template <typename Container>
-::std::function<::std::ostream&(::std::ostream&)> joiner(
+::std::function<::std::ostream&(::std::ostream&)> Joiner(
const Container& container, const char* sep) {
using std::begin;
using std::end;
- const auto beginIter = begin(container);
- const auto endIter = end(container);
- return [beginIter, endIter, sep](::std::ostream& out) -> ::std::ostream& {
- for (auto iter = beginIter; iter != endIter; ++iter) {
- if (iter != beginIter) {
+ const auto begin_iter = begin(container);
+ const auto end_iter = end(container);
+ return [begin_iter, end_iter, sep](::std::ostream& out) -> ::std::ostream& {
+ for (auto iter = begin_iter; iter != end_iter; ++iter) {
+ if (iter != begin_iter) {
out << sep;
}
out << *iter;
@@ -120,31 +133,12 @@
};
}
-inline ::std::function<::std::ostream&(::std::ostream&)> formatSize(
- size_t size) {
- return [size](::std::ostream& out) -> ::std::ostream& {
- constexpr size_t K = 1024u;
- constexpr size_t M = K * K;
- constexpr size_t G = M * K;
- if (size < K) {
- out << size << "B";
- } else if (size < M) {
- out << (double(size) / K) << " KiB";
- } else if (size < G) {
- out << (double(size) / M) << " MiB";
- } else {
- out << (double(size) / G) << " GiB";
- }
- return out;
- };
-}
-
/**
* Helper method to extract a UTF-16 string from a StringPool. If the string is
* stored as UTF-8,
* the conversion to UTF-16 happens within ResStringPool.
*/
-StringPiece16 getString16(const android::ResStringPool& pool, size_t idx);
+StringPiece16 GetString16(const android::ResStringPool& pool, size_t idx);
/**
* Helper method to extract a UTF-8 string from a StringPool. If the string is
@@ -154,7 +148,7 @@
* which maintains no state or cache. This means we must return an std::string
* copy.
*/
-std::string getString(const android::ResStringPool& pool, size_t idx);
+std::string GetString(const android::ResStringPool& pool, size_t idx);
/**
* Checks that the Java string format contains no non-positional arguments
@@ -165,53 +159,53 @@
* which will
* break the string interpolation.
*/
-bool verifyJavaStringFormat(const StringPiece& str);
+bool VerifyJavaStringFormat(const StringPiece& str);
class StringBuilder {
public:
- StringBuilder& append(const StringPiece& str);
- const std::string& str() const;
- const std::string& error() const;
+ StringBuilder& Append(const StringPiece& str);
+ const std::string& ToString() const;
+ const std::string& Error() const;
// When building StyledStrings, we need UTF-16 indices into the string,
// which is what the Java layer expects when dealing with java
// String.charAt().
- size_t utf16Len() const;
+ size_t Utf16Len() const;
- operator bool() const;
+ explicit operator bool() const;
private:
- std::string mStr;
- size_t mUtf16Len = 0;
- bool mQuote = false;
- bool mTrailingSpace = false;
- bool mLastCharWasEscape = false;
- std::string mError;
+ std::string str_;
+ size_t utf16_len_ = 0;
+ bool quote_ = false;
+ bool trailing_space_ = false;
+ bool last_char_was_escape_ = false;
+ std::string error_;
};
-inline const std::string& StringBuilder::str() const { return mStr; }
+inline const std::string& StringBuilder::ToString() const { return str_; }
-inline const std::string& StringBuilder::error() const { return mError; }
+inline const std::string& StringBuilder::Error() const { return error_; }
-inline size_t StringBuilder::utf16Len() const { return mUtf16Len; }
+inline size_t StringBuilder::Utf16Len() const { return utf16_len_; }
-inline StringBuilder::operator bool() const { return mError.empty(); }
+inline StringBuilder::operator bool() const { return error_.empty(); }
/**
* Converts a UTF8 string to a UTF16 string.
*/
-std::u16string utf8ToUtf16(const StringPiece& utf8);
-std::string utf16ToUtf8(const StringPiece16& utf16);
+std::u16string Utf8ToUtf16(const StringPiece& utf8);
+std::string Utf16ToUtf8(const StringPiece16& utf16);
/**
* Writes the entire BigBuffer to the output stream.
*/
-bool writeAll(std::ostream& out, const BigBuffer& buffer);
+bool WriteAll(std::ostream& out, const BigBuffer& buffer);
/*
* Copies the entire BigBuffer into a single buffer.
*/
-std::unique_ptr<uint8_t[]> copy(const BigBuffer& buffer);
+std::unique_ptr<uint8_t[]> Copy(const BigBuffer& buffer);
/**
* A Tokenizer implemented as an iterable collection. It does not allocate
@@ -226,7 +220,7 @@
iterator& operator++();
- StringPiece operator*() { return mToken; }
+ StringPiece operator*() { return token_; }
bool operator==(const iterator& rhs) const;
bool operator!=(const iterator& rhs) const;
@@ -235,34 +229,34 @@
iterator(StringPiece s, char sep, StringPiece tok, bool end);
- StringPiece mStr;
- char mSeparator;
- StringPiece mToken;
- bool mEnd;
+ StringPiece str_;
+ char separator_;
+ StringPiece token_;
+ bool end_;
};
Tokenizer(StringPiece str, char sep);
- iterator begin() { return mBegin; }
+ iterator begin() { return begin_; }
- iterator end() { return mEnd; }
+ iterator end() { return end_; }
private:
- const iterator mBegin;
- const iterator mEnd;
+ const iterator begin_;
+ const iterator end_;
};
-inline Tokenizer tokenize(const StringPiece& str, char sep) {
+inline Tokenizer Tokenize(const StringPiece& str, char sep) {
return Tokenizer(str, sep);
}
-inline uint16_t hostToDevice16(uint16_t value) { return htods(value); }
+inline uint16_t HostToDevice16(uint16_t value) { return htods(value); }
-inline uint32_t hostToDevice32(uint32_t value) { return htodl(value); }
+inline uint32_t HostToDevice32(uint32_t value) { return htodl(value); }
-inline uint16_t deviceToHost16(uint16_t value) { return dtohs(value); }
+inline uint16_t DeviceToHost16(uint16_t value) { return dtohs(value); }
-inline uint32_t deviceToHost32(uint32_t value) { return dtohl(value); }
+inline uint32_t DeviceToHost32(uint32_t value) { return dtohl(value); }
/**
* Given a path like: res/xml-sw600dp/foo.xml
@@ -273,8 +267,8 @@
*
* Returns true if successful.
*/
-bool extractResFilePathParts(const StringPiece& path, StringPiece* outPrefix,
- StringPiece* outEntry, StringPiece* outSuffix);
+bool ExtractResFilePathParts(const StringPiece& path, StringPiece* out_prefix,
+ StringPiece* out_entry, StringPiece* out_suffix);
} // namespace util
diff --git a/tools/aapt2/util/Util_test.cpp b/tools/aapt2/util/Util_test.cpp
index 0e27213..cac3de4 100644
--- a/tools/aapt2/util/Util_test.cpp
+++ b/tools/aapt2/util/Util_test.cpp
@@ -14,191 +14,196 @@
* limitations under the License.
*/
-#include "test/Test.h"
-#include "util/StringPiece.h"
#include "util/Util.h"
#include <string>
+#include "test/Test.h"
+
namespace aapt {
TEST(UtilTest, TrimOnlyWhitespace) {
- const std::string full = "\n ";
+ const std::string full = "\n ";
- StringPiece trimmed = util::trimWhitespace(full);
- EXPECT_TRUE(trimmed.empty());
- EXPECT_EQ(0u, trimmed.size());
+ StringPiece trimmed = util::TrimWhitespace(full);
+ EXPECT_TRUE(trimmed.empty());
+ EXPECT_EQ(0u, trimmed.size());
}
TEST(UtilTest, StringEndsWith) {
- EXPECT_TRUE(util::stringEndsWith("hello.xml", ".xml"));
+ EXPECT_TRUE(util::EndsWith("hello.xml", ".xml"));
}
TEST(UtilTest, StringStartsWith) {
- EXPECT_TRUE(util::stringStartsWith("hello.xml", "he"));
+ EXPECT_TRUE(util::StartsWith("hello.xml", "he"));
}
TEST(UtilTest, StringBuilderSplitEscapeSequence) {
- EXPECT_EQ(StringPiece("this is a new\nline."),
- util::StringBuilder().append("this is a new\\")
- .append("nline.")
- .str());
+ EXPECT_EQ(StringPiece("this is a new\nline."), util::StringBuilder()
+ .Append("this is a new\\")
+ .Append("nline.")
+ .ToString());
}
TEST(UtilTest, StringBuilderWhitespaceRemoval) {
- EXPECT_EQ(StringPiece("hey guys this is so cool"),
- util::StringBuilder().append(" hey guys ")
- .append(" this is so cool ")
- .str());
+ EXPECT_EQ(StringPiece("hey guys this is so cool"),
+ util::StringBuilder()
+ .Append(" hey guys ")
+ .Append(" this is so cool ")
+ .ToString());
- EXPECT_EQ(StringPiece(" wow, so many \t spaces. what?"),
- util::StringBuilder().append(" \" wow, so many \t ")
- .append("spaces. \"what? ")
- .str());
+ EXPECT_EQ(StringPiece(" wow, so many \t spaces. what?"),
+ util::StringBuilder()
+ .Append(" \" wow, so many \t ")
+ .Append("spaces. \"what? ")
+ .ToString());
- EXPECT_EQ(StringPiece("where is the pie?"),
- util::StringBuilder().append(" where \t ")
- .append(" \nis the "" pie?")
- .str());
+ EXPECT_EQ(StringPiece("where is the pie?"), util::StringBuilder()
+ .Append(" where \t ")
+ .Append(" \nis the "
+ " pie?")
+ .ToString());
}
TEST(UtilTest, StringBuilderEscaping) {
- EXPECT_EQ(StringPiece("hey guys\n this \t is so\\ cool"),
- util::StringBuilder().append(" hey guys\\n ")
- .append(" this \\t is so\\\\ cool ")
- .str());
+ EXPECT_EQ(StringPiece("hey guys\n this \t is so\\ cool"),
+ util::StringBuilder()
+ .Append(" hey guys\\n ")
+ .Append(" this \\t is so\\\\ cool ")
+ .ToString());
- EXPECT_EQ(StringPiece("@?#\\\'"),
- util::StringBuilder().append("\\@\\?\\#\\\\\\'")
- .str());
+ EXPECT_EQ(StringPiece("@?#\\\'"),
+ util::StringBuilder().Append("\\@\\?\\#\\\\\\'").ToString());
}
TEST(UtilTest, StringBuilderMisplacedQuote) {
- util::StringBuilder builder{};
- EXPECT_FALSE(builder.append("they're coming!"));
+ util::StringBuilder builder{};
+ EXPECT_FALSE(builder.Append("they're coming!"));
}
TEST(UtilTest, StringBuilderUnicodeCodes) {
- EXPECT_EQ(std::string("\u00AF\u0AF0 woah"),
- util::StringBuilder().append("\\u00AF\\u0AF0 woah")
- .str());
+ EXPECT_EQ(std::string("\u00AF\u0AF0 woah"),
+ util::StringBuilder().Append("\\u00AF\\u0AF0 woah").ToString());
- EXPECT_FALSE(util::StringBuilder().append("\\u00 yo"));
+ EXPECT_FALSE(util::StringBuilder().Append("\\u00 yo"));
}
TEST(UtilTest, TokenizeInput) {
- auto tokenizer = util::tokenize(StringPiece("this| is|the|end"), '|');
- auto iter = tokenizer.begin();
- ASSERT_EQ(*iter, StringPiece("this"));
- ++iter;
- ASSERT_EQ(*iter, StringPiece(" is"));
- ++iter;
- ASSERT_EQ(*iter, StringPiece("the"));
- ++iter;
- ASSERT_EQ(*iter, StringPiece("end"));
- ++iter;
- ASSERT_EQ(tokenizer.end(), iter);
+ auto tokenizer = util::Tokenize(StringPiece("this| is|the|end"), '|');
+ auto iter = tokenizer.begin();
+ ASSERT_EQ(*iter, StringPiece("this"));
+ ++iter;
+ ASSERT_EQ(*iter, StringPiece(" is"));
+ ++iter;
+ ASSERT_EQ(*iter, StringPiece("the"));
+ ++iter;
+ ASSERT_EQ(*iter, StringPiece("end"));
+ ++iter;
+ ASSERT_EQ(tokenizer.end(), iter);
}
TEST(UtilTest, TokenizeEmptyString) {
- auto tokenizer = util::tokenize(StringPiece(""), '|');
- auto iter = tokenizer.begin();
- ASSERT_NE(tokenizer.end(), iter);
- ASSERT_EQ(StringPiece(), *iter);
- ++iter;
- ASSERT_EQ(tokenizer.end(), iter);
+ auto tokenizer = util::Tokenize(StringPiece(""), '|');
+ auto iter = tokenizer.begin();
+ ASSERT_NE(tokenizer.end(), iter);
+ ASSERT_EQ(StringPiece(), *iter);
+ ++iter;
+ ASSERT_EQ(tokenizer.end(), iter);
}
TEST(UtilTest, TokenizeAtEnd) {
- auto tokenizer = util::tokenize(StringPiece("one."), '.');
- auto iter = tokenizer.begin();
- ASSERT_EQ(*iter, StringPiece("one"));
- ++iter;
- ASSERT_NE(iter, tokenizer.end());
- ASSERT_EQ(*iter, StringPiece());
+ auto tokenizer = util::Tokenize(StringPiece("one."), '.');
+ auto iter = tokenizer.begin();
+ ASSERT_EQ(*iter, StringPiece("one"));
+ ++iter;
+ ASSERT_NE(iter, tokenizer.end());
+ ASSERT_EQ(*iter, StringPiece());
}
TEST(UtilTest, IsJavaClassName) {
- EXPECT_TRUE(util::isJavaClassName("android.test.Class"));
- EXPECT_TRUE(util::isJavaClassName("android.test.Class$Inner"));
- EXPECT_TRUE(util::isJavaClassName("android_test.test.Class"));
- EXPECT_TRUE(util::isJavaClassName("_android_.test._Class_"));
- EXPECT_FALSE(util::isJavaClassName("android.test.$Inner"));
- EXPECT_FALSE(util::isJavaClassName("android.test.Inner$"));
- EXPECT_FALSE(util::isJavaClassName(".test.Class"));
- EXPECT_FALSE(util::isJavaClassName("android"));
+ EXPECT_TRUE(util::IsJavaClassName("android.test.Class"));
+ EXPECT_TRUE(util::IsJavaClassName("android.test.Class$Inner"));
+ EXPECT_TRUE(util::IsJavaClassName("android_test.test.Class"));
+ EXPECT_TRUE(util::IsJavaClassName("_android_.test._Class_"));
+ EXPECT_FALSE(util::IsJavaClassName("android.test.$Inner"));
+ EXPECT_FALSE(util::IsJavaClassName("android.test.Inner$"));
+ EXPECT_FALSE(util::IsJavaClassName(".test.Class"));
+ EXPECT_FALSE(util::IsJavaClassName("android"));
}
TEST(UtilTest, IsJavaPackageName) {
- EXPECT_TRUE(util::isJavaPackageName("android"));
- EXPECT_TRUE(util::isJavaPackageName("android.test"));
- EXPECT_TRUE(util::isJavaPackageName("android.test_thing"));
- EXPECT_FALSE(util::isJavaPackageName("_android"));
- EXPECT_FALSE(util::isJavaPackageName("android_"));
- EXPECT_FALSE(util::isJavaPackageName("android."));
- EXPECT_FALSE(util::isJavaPackageName(".android"));
- EXPECT_FALSE(util::isJavaPackageName("android._test"));
- EXPECT_FALSE(util::isJavaPackageName(".."));
+ EXPECT_TRUE(util::IsJavaPackageName("android"));
+ EXPECT_TRUE(util::IsJavaPackageName("android.test"));
+ EXPECT_TRUE(util::IsJavaPackageName("android.test_thing"));
+ EXPECT_FALSE(util::IsJavaPackageName("_android"));
+ EXPECT_FALSE(util::IsJavaPackageName("android_"));
+ EXPECT_FALSE(util::IsJavaPackageName("android."));
+ EXPECT_FALSE(util::IsJavaPackageName(".android"));
+ EXPECT_FALSE(util::IsJavaPackageName("android._test"));
+ EXPECT_FALSE(util::IsJavaPackageName(".."));
}
TEST(UtilTest, FullyQualifiedClassName) {
- Maybe<std::string> res = util::getFullyQualifiedClassName("android", ".asdf");
- AAPT_ASSERT_TRUE(res);
- EXPECT_EQ(res.value(), "android.asdf");
+ Maybe<std::string> res = util::GetFullyQualifiedClassName("android", ".asdf");
+ AAPT_ASSERT_TRUE(res);
+ EXPECT_EQ(res.value(), "android.asdf");
- res = util::getFullyQualifiedClassName("android", ".a.b");
- AAPT_ASSERT_TRUE(res);
- EXPECT_EQ(res.value(), "android.a.b");
+ res = util::GetFullyQualifiedClassName("android", ".a.b");
+ AAPT_ASSERT_TRUE(res);
+ EXPECT_EQ(res.value(), "android.a.b");
- res = util::getFullyQualifiedClassName("android", "a.b");
- AAPT_ASSERT_TRUE(res);
- EXPECT_EQ(res.value(), "a.b");
+ res = util::GetFullyQualifiedClassName("android", "a.b");
+ AAPT_ASSERT_TRUE(res);
+ EXPECT_EQ(res.value(), "a.b");
- res = util::getFullyQualifiedClassName("", "a.b");
- AAPT_ASSERT_TRUE(res);
- EXPECT_EQ(res.value(), "a.b");
+ res = util::GetFullyQualifiedClassName("", "a.b");
+ AAPT_ASSERT_TRUE(res);
+ EXPECT_EQ(res.value(), "a.b");
- res = util::getFullyQualifiedClassName("android", "Class");
- AAPT_ASSERT_TRUE(res);
- EXPECT_EQ(res.value(), "android.Class");
+ res = util::GetFullyQualifiedClassName("android", "Class");
+ AAPT_ASSERT_TRUE(res);
+ EXPECT_EQ(res.value(), "android.Class");
- res = util::getFullyQualifiedClassName("", "");
- AAPT_ASSERT_FALSE(res);
+ res = util::GetFullyQualifiedClassName("", "");
+ AAPT_ASSERT_FALSE(res);
- res = util::getFullyQualifiedClassName("android", "./Apple");
- AAPT_ASSERT_FALSE(res);
+ res = util::GetFullyQualifiedClassName("android", "./Apple");
+ AAPT_ASSERT_FALSE(res);
}
TEST(UtilTest, ExtractResourcePathComponents) {
- StringPiece prefix, entry, suffix;
- ASSERT_TRUE(util::extractResFilePathParts("res/xml-sw600dp/entry.xml", &prefix, &entry,
- &suffix));
- EXPECT_EQ(prefix, "res/xml-sw600dp/");
- EXPECT_EQ(entry, "entry");
- EXPECT_EQ(suffix, ".xml");
+ StringPiece prefix, entry, suffix;
+ ASSERT_TRUE(util::ExtractResFilePathParts("res/xml-sw600dp/entry.xml",
+ &prefix, &entry, &suffix));
+ EXPECT_EQ(prefix, "res/xml-sw600dp/");
+ EXPECT_EQ(entry, "entry");
+ EXPECT_EQ(suffix, ".xml");
- ASSERT_TRUE(util::extractResFilePathParts("res/xml-sw600dp/entry.9.png", &prefix, &entry,
- &suffix));
+ ASSERT_TRUE(util::ExtractResFilePathParts("res/xml-sw600dp/entry.9.png",
+ &prefix, &entry, &suffix));
- EXPECT_EQ(prefix, "res/xml-sw600dp/");
- EXPECT_EQ(entry, "entry");
- EXPECT_EQ(suffix, ".9.png");
+ EXPECT_EQ(prefix, "res/xml-sw600dp/");
+ EXPECT_EQ(entry, "entry");
+ EXPECT_EQ(suffix, ".9.png");
- EXPECT_FALSE(util::extractResFilePathParts("AndroidManifest.xml", &prefix, &entry, &suffix));
- EXPECT_FALSE(util::extractResFilePathParts("res/.xml", &prefix, &entry, &suffix));
+ EXPECT_FALSE(util::ExtractResFilePathParts("AndroidManifest.xml", &prefix,
+ &entry, &suffix));
+ EXPECT_FALSE(
+ util::ExtractResFilePathParts("res/.xml", &prefix, &entry, &suffix));
- ASSERT_TRUE(util::extractResFilePathParts("res//.", &prefix, &entry, &suffix));
- EXPECT_EQ(prefix, "res//");
- EXPECT_EQ(entry, "");
- EXPECT_EQ(suffix, ".");
+ ASSERT_TRUE(
+ util::ExtractResFilePathParts("res//.", &prefix, &entry, &suffix));
+ EXPECT_EQ(prefix, "res//");
+ EXPECT_EQ(entry, "");
+ EXPECT_EQ(suffix, ".");
}
TEST(UtilTest, VerifyJavaStringFormat) {
- ASSERT_TRUE(util::verifyJavaStringFormat("%09.34f"));
- ASSERT_TRUE(util::verifyJavaStringFormat("%9$.34f %8$"));
- ASSERT_TRUE(util::verifyJavaStringFormat("%% %%"));
- ASSERT_FALSE(util::verifyJavaStringFormat("%09$f %f"));
- ASSERT_FALSE(util::verifyJavaStringFormat("%09f %08s"));
+ ASSERT_TRUE(util::VerifyJavaStringFormat("%09.34f"));
+ ASSERT_TRUE(util::VerifyJavaStringFormat("%9$.34f %8$"));
+ ASSERT_TRUE(util::VerifyJavaStringFormat("%% %%"));
+ ASSERT_FALSE(util::VerifyJavaStringFormat("%09$f %f"));
+ ASSERT_FALSE(util::VerifyJavaStringFormat("%09f %08s"));
}
-} // namespace aapt
+} // namespace aapt