Merge "Implement IntArrayView::split for dicttoolkit."

main
Keisuke Kuroyanagi 2014-11-11 06:15:39 +00:00 committed by Android (Google) Code Review
commit 7a3e624210
2 changed files with 70 additions and 0 deletions

View File

@ -133,6 +133,29 @@ class IntArrayView {
return std::vector<int>(begin(), end());
}
std::vector<IntArrayView> split(const int separator, const int limit = S_INT_MAX) const {
if (limit <= 0) {
return std::vector<IntArrayView>();
}
std::vector<IntArrayView> result;
if (limit == 1) {
result.emplace_back(mPtr, mSize);
return result;
}
size_t startIndex = 0;
for (size_t i = 0; i < mSize; ++i) {
if (mPtr[i] == separator) {
result.emplace_back(mPtr + startIndex, i - startIndex);
startIndex = i + 1;
if (result.size() >= static_cast<size_t>(limit - 1)) {
break;
}
}
}
result.emplace_back(mPtr + startIndex, mSize - startIndex);
return result;
}
private:
DISALLOW_ASSIGNMENT_OPERATOR(IntArrayView);

View File

@ -151,5 +151,52 @@ TEST(IntArrayViewTest, TestToVector) {
EXPECT_EQ(std::vector<int>(), CodePointArrayView().toVector());
}
TEST(IntArrayViewTest, TestSplit) {
EXPECT_TRUE(IntArrayView().split(0, 0).empty());
{
const auto intArrayViews = IntArrayView().split(0, 1);
EXPECT_EQ(1u, intArrayViews.size());
EXPECT_TRUE(intArrayViews[0].empty());
}
{
const auto intArrayViews = IntArrayView().split(0, 100);
EXPECT_EQ(1u, intArrayViews.size());
EXPECT_TRUE(intArrayViews[0].empty());
}
const std::vector<int> intVector = {1, 2, 3, 3, 2, 3};
const IntArrayView intArrayView(intVector);
{
const auto intArrayViews = intArrayView.split(2);
EXPECT_EQ(3u, intArrayViews.size());
EXPECT_EQ(std::vector<int>({1}), intArrayViews[0].toVector());
EXPECT_EQ(std::vector<int>({3, 3}), intArrayViews[1].toVector());
EXPECT_EQ(std::vector<int>({3}), intArrayViews[2].toVector());
}
{
const auto intArrayViews = intArrayView.split(2, 2);
EXPECT_EQ(2u, intArrayViews.size());
EXPECT_EQ(std::vector<int>({1}), intArrayViews[0].toVector());
EXPECT_EQ(std::vector<int>({3, 3, 2, 3}), intArrayViews[1].toVector());
}
{
const auto intArrayViews = intArrayView.split(2, 1);
EXPECT_EQ(1u, intArrayViews.size());
EXPECT_EQ(intVector, intArrayViews[0].toVector());
}
{
const auto intArrayViews = intArrayView.split(2, 0);
EXPECT_EQ(0u, intArrayViews.size());
}
{
const auto intArrayViews = intArrayView.split(3);
EXPECT_EQ(4u, intArrayViews.size());
EXPECT_EQ(std::vector<int>({1, 2}), intArrayViews[0].toVector());
EXPECT_EQ(std::vector<int>(), intArrayViews[1].toVector());
EXPECT_EQ(std::vector<int>({2}), intArrayViews[2].toVector());
EXPECT_EQ(std::vector<int>(), intArrayViews[3].toVector());
}
}
} // namespace
} // namespace latinime