Add some string helpers and unit tests

functions int_to_str(int) and split(const String&, Character),
plus corresponding unit tests
This commit is contained in:
Maxime Coste 2012-05-29 05:19:50 +00:00
parent 96c440fcaa
commit 62202a46c1
4 changed files with 65 additions and 7 deletions

View File

@ -5,13 +5,6 @@
namespace Kakoune namespace Kakoune
{ {
String int_to_str(int value)
{
std::ostringstream oss;
oss << value;
return oss.str();
}
Option& OptionManager::operator[] (const String& name) Option& OptionManager::operator[] (const String& name)
{ {
auto it = m_options.find(name); auto it = m_options.find(name);

46
src/string.cc Normal file
View File

@ -0,0 +1,46 @@
#include "string.hh"
namespace Kakoune
{
String int_to_str(int value)
{
const bool negative = value < 0;
if (negative)
value = -value;
char buffer[16];
size_t pos = sizeof(buffer);
buffer[--pos] = 0;
do
{
buffer[--pos] = '0' + (value % 10);
value /= 10;
}
while (value);
if (negative)
buffer[--pos] = '-';
return String(buffer + pos);
}
std::vector<String> split(const String& str, Character separator)
{
auto begin = str.begin();
auto end = str.begin();
std::vector<String> res;
while (end != str.end())
{
while (end != str.end() and *end != separator)
++end;
res.push_back(String(begin, end));
if (end == str.end())
break;
begin = ++end;
}
return res;
}
}

View File

@ -109,6 +109,9 @@ inline String operator+(Character lhs, const String& rhs)
return String(lhs) + rhs; return String(lhs) + rhs;
} }
String int_to_str(int value);
std::vector<String> split(const String& str, Character separator);
} }
namespace std namespace std

View File

@ -45,8 +45,24 @@ void test_editor()
} }
} }
void test_string()
{
assert(int_to_str(124) == "124");
assert(int_to_str(-129) == "-129");
assert(int_to_str(0) == "0");
assert(String("youpi ") + "matin" == "youpi matin");
std::vector<String> splited = split("youpi:matin::tchou", ':');
assert(splited[0] == "youpi");
assert(splited[1] == "matin");
assert(splited[2] == "");
assert(splited[3] == "tchou");
}
void run_unit_tests() void run_unit_tests()
{ {
test_string();
test_buffer(); test_buffer();
test_editor(); test_editor();
} }