Skip to content

Commit

Permalink
Generalize zen::to_string() to handle nested iterables + test
Browse files Browse the repository at this point in the history
  • Loading branch information
heinsaar committed Sep 16, 2023
1 parent 4cbd2a7 commit 105fa25
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 6 deletions.
10 changes: 4 additions & 6 deletions functions/utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -278,17 +278,15 @@ std::string to_string(const T& x) {
// First check for string-likeness so that zen::pring("abc") prints "abc"
// and not [a, b, c] as a result of considering strings as iterable below
if constexpr (is_string_like<T>()) {
return x;
}

if constexpr (is_iterable_v<T>) {
return x;
} else if constexpr (is_iterable_v<T>) {
ss << "[";
auto it = std::begin(x);
if (it != std::end(x)) {
ss << *it++;
ss << to_string(*it++); // recursive call to handle nested iterables
}
for (; it != std::end(x); ++it) {
ss << ", " << *it;
ss << ", " << to_string(*it); // recursive call to handle nested iterables
}
ss << "]";
} else { // not iterable, single item
Expand Down
31 changes: 31 additions & 0 deletions tests/test_utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,36 @@ void test_utils_sum()
//zen::sum(int_umap); // should fail compilation with message: ZEN STATIC ASSERTION FAILED. "ELEMENT TYPE EXPECTED TO BE Addable, BUT IS NOT"
}

void test_to_string()
{
std::vector<std::vector<std::vector<int>>> vvv = { {{1, 2}, {3, 4}}, {{5, 6}, {7, 8}} };
std::vector<std::vector<int>> vv = { {1, 2}, {3, 4} };
std::vector<std::vector<int>> vve = { {}, {}, {} };
std::vector<std::list<int>> vx = { {1, 2}, {3, 4} };
std::list<std::vector<int>> xv = { {1, 2}, {3, 4} };
std::vector<int> vone = { 1 };
std::vector<int> v = { 1, 2, 3 };
std::vector<std::array<int, 2>> va = { {1, 2}, {3, 4} };
std::vector<int> vmix = { 1, 2, 3 };
std::vector<int> vempty;

ZEN_EXPECT(zen::to_string() == "");
ZEN_EXPECT(zen::to_string(1, 2, 3) == "1 2 3");
ZEN_EXPECT(zen::to_string(42.24) == "42.24");
ZEN_EXPECT(zen::to_string("hello") == "hello");
ZEN_EXPECT(zen::to_string(v) == "[1, 2, 3]");
ZEN_EXPECT(zen::to_string(vempty) == "[]");
ZEN_EXPECT(zen::to_string(1, 42.24, "hello") == "1 42.24 hello");
ZEN_EXPECT(zen::to_string(vone) == "[1]");
ZEN_EXPECT(zen::to_string(vv) == "[[1, 2], [3, 4]]");
ZEN_EXPECT(zen::to_string(vve) == "[[], [], []]");
ZEN_EXPECT(zen::to_string(vx) == "[[1, 2], [3, 4]]");
ZEN_EXPECT(zen::to_string(xv) == "[[1, 2], [3, 4]]");
ZEN_EXPECT(zen::to_string(va) == "[[1, 2], [3, 4]]");
ZEN_EXPECT(zen::to_string(vvv) == "[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]");
ZEN_EXPECT(zen::to_string(vmix, "mixed", 42) == "[1, 2, 3] mixed 42");
}

void main_test_utils()
{
BEGIN_TEST;
Expand All @@ -57,4 +87,5 @@ void main_test_utils()
ZEN_EXPECT(zen::random_int() <= 10);

test_utils_sum();
test_to_string();
}

0 comments on commit 105fa25

Please sign in to comment.