Skip to content

Commit a076175

Browse files
Alex-PLACETCopilot
andcommitted
Add CSV dumping functionality with configurable delimiters
Co-authored-by: Copilot <copilot@github.com>
1 parent 68a21c5 commit a076175

2 files changed

Lines changed: 67 additions & 2 deletions

File tree

include/xtensor/io/xcsv.hpp

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,47 @@ namespace xt
274274
}
275275
};
276276

277+
template <class E>
278+
void dump_csv(std::ostream& stream, const xexpression<E>& e, const xcsv_config& config)
279+
{
280+
using size_type = typename E::size_type;
281+
const E& ex = e.derived_cast();
282+
if (ex.dimension() == 1)
283+
{
284+
const size_type n = ex.shape()[0];
285+
for (size_type i = 0; i != n; ++i)
286+
{
287+
stream << ex(i);
288+
if (i != n - 1)
289+
{
290+
stream << config.delimiter;
291+
}
292+
}
293+
stream << std::endl;
294+
}
295+
else if (ex.dimension() == 2)
296+
{
297+
const size_type nbrows = ex.shape()[0];
298+
const size_type nbcols = ex.shape()[1];
299+
for (size_type r = 0; r != nbrows; ++r)
300+
{
301+
for (size_type c = 0; c != nbcols; ++c)
302+
{
303+
stream << ex(r, c);
304+
if (c != nbcols - 1)
305+
{
306+
stream << config.delimiter;
307+
}
308+
}
309+
stream << std::endl;
310+
}
311+
}
312+
else
313+
{
314+
XTENSOR_THROW(std::runtime_error, "Only 1-D and 2-D expressions can be serialized to CSV");
315+
}
316+
}
317+
277318
template <class E>
278319
void load_file(std::istream& stream, xexpression<E>& e, const xcsv_config& config)
279320
{
@@ -287,9 +328,9 @@ namespace xt
287328
}
288329

289330
template <class E>
290-
void dump_file(std::ostream& stream, const xexpression<E>& e, const xcsv_config&)
331+
void dump_file(std::ostream& stream, const xexpression<E>& e, const xcsv_config& config)
291332
{
292-
dump_csv(stream, e);
333+
dump_csv(stream, e, config);
293334
}
294335
}
295336

test/test_xcsv.cpp

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,4 +79,28 @@ namespace xt
7979
dump_csv(res, data);
8080
ASSERT_EQ("1,2,3,4\n10,12,15,18\n", res.str());
8181
}
82+
83+
TEST(xcsv, dump_with_config)
84+
{
85+
xtensor<double, 2> data{{1.0, 2.0, 3.0, 4.0}, {10.0, 12.0, 15.0, 18.0}};
86+
87+
std::stringstream res;
88+
89+
xcsv_config config;
90+
config.delimiter = ' ';
91+
dump_csv(res, data, config);
92+
ASSERT_EQ("1 2 3 4\n10 12 15 18\n", res.str());
93+
}
94+
95+
TEST(xcsv, dump_file_with_config)
96+
{
97+
xtensor<double, 2> data{{1.0, 2.0, 3.0, 4.0}, {10.0, 12.0, 15.0, 18.0}};
98+
99+
std::stringstream res;
100+
101+
xcsv_config config;
102+
config.delimiter = ';';
103+
dump_file(res, data, config);
104+
ASSERT_EQ("1;2;3;4\n10;12;15;18\n", res.str());
105+
}
82106
}

0 commit comments

Comments
 (0)