Add base::utf8() and utf8_const() wrappers

This commit is contained in:
David Capello 2016-10-19 14:06:29 -03:00
parent 3f052cfe2e
commit 6baf3fb0f0
2 changed files with 48 additions and 1 deletions

View File

@ -1,5 +1,5 @@
// Aseprite Base Library
// Copyright (c) 2001-2013, 2015 David Capello
// Copyright (c) 2001-2016 David Capello
//
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.
@ -141,6 +141,30 @@ namespace base {
}
};
class utf8 {
public:
utf8(std::string& s) : m_begin(utf8_iterator(s.begin())),
m_end(utf8_iterator(s.end())) {
}
const utf8_iterator& begin() const { return m_begin; }
const utf8_iterator& end() const { return m_end; }
private:
utf8_iterator m_begin;
utf8_iterator m_end;
};
class utf8_const {
public:
utf8_const(const std::string& s) : m_begin(utf8_const_iterator(s.begin())),
m_end(utf8_const_iterator(s.end())) {
}
const utf8_const_iterator& begin() const { return m_begin; }
const utf8_const_iterator& end() const { return m_end; }
private:
utf8_const_iterator m_begin;
utf8_const_iterator m_end;
};
}
#endif

View File

@ -29,6 +29,29 @@ TEST(String, Utf8Conversion)
ASSERT_EQ(a, c);
}
TEST(String, Utf8Wrapper)
{
std::string a, b = "abc";
for (int ch : utf8(b))
a.push_back(ch);
EXPECT_EQ("abc", a);
std::string c;
for (int ch : utf8_const("def"))
c.push_back(ch);
EXPECT_EQ("def", c);
int i = 0;
for (int ch : utf8_const("\xE6\x97\xA5\xE6\x9C\xAC\xE8\xAA\x9E")) { // 日本語
switch (i++) {
case 0: EXPECT_EQ(ch, 0x65E5); break;
case 1: EXPECT_EQ(ch, 0x672C); break;
case 2: EXPECT_EQ(ch, 0x8A9E); break;
default: EXPECT_FALSE(true); break;
}
}
}
TEST(String, Utf8Iterator)
{
std::string a = "Hello";