Fix GetUtfLength to add offset to char array data.
GetUtfLength isn't used by much, so I made ToModifiedUtf8 use it so it
can be exercised more. Also added a test to make sure it's working.
Change-Id: I9d569642aaf2313cc70a2e22f631aec138e2e71b
diff --git a/src/object.cc b/src/object.cc
index 207a175..ad0f6b9 100644
--- a/src/object.cc
+++ b/src/object.cc
@@ -1469,7 +1469,7 @@
// Create a modified UTF-8 encoded std::string from a java/lang/String object.
std::string String::ToModifiedUtf8() const {
const uint16_t* chars = GetCharArray()->GetData() + GetOffset();
- size_t byte_count(CountUtf8Bytes(chars, GetLength()));
+ size_t byte_count = GetUtfLength();
std::string result(byte_count, static_cast<char>(0));
ConvertUtf16ToModifiedUtf8(&result[0], chars, GetLength());
return result;
diff --git a/src/object.h b/src/object.h
index 7ba0847..ad8194a 100644
--- a/src/object.h
+++ b/src/object.h
@@ -2216,7 +2216,7 @@
}
int32_t GetUtfLength() const {
- return CountUtf8Bytes(GetCharArray()->GetData(), GetLength());
+ return CountUtf8Bytes(GetCharArray()->GetData() + GetOffset(), GetLength());
}
uint16_t CharAt(int32_t index) const;
@@ -2297,6 +2297,7 @@
static Class* java_lang_String_;
friend struct StringOffsets; // for verifying offset information
+ FRIEND_TEST(ObjectTest, StringLength); // for SetOffset and SetCount
DISALLOW_IMPLICIT_CONSTRUCTORS(String);
};
diff --git a/src/object_test.cc b/src/object_test.cc
index 80ed0bb..bf07aa3 100644
--- a/src/object_test.cc
+++ b/src/object_test.cc
@@ -293,6 +293,18 @@
EXPECT_FALSE(empty->Equals("a"));
}
+TEST_F(ObjectTest, StringLength) {
+ SirtRef<String> string(String::AllocFromModifiedUtf8("android"));
+ EXPECT_EQ(string->GetLength(), 7);
+ EXPECT_EQ(string->GetUtfLength(), 7);
+
+ string->SetOffset(2);
+ string->SetCount(5);
+ EXPECT_TRUE(string->Equals("droid"));
+ EXPECT_EQ(string->GetLength(), 5);
+ EXPECT_EQ(string->GetUtfLength(), 5);
+}
+
TEST_F(ObjectTest, DescriptorCompare) {
ClassLinker* linker = class_linker_;