forked from vincentlaucsb/csv-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsv_writer.hpp
More file actions
431 lines (369 loc) · 13.6 KB
/
csv_writer.hpp
File metadata and controls
431 lines (369 loc) · 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
/** @file
* A standalone header file for writing delimiter-separated files
*/
#pragma once
#include <fstream>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <tuple>
#include <type_traits>
#include <vector>
#include "common.hpp"
#include "data_type.hpp"
namespace csv {
namespace internals {
static int DECIMAL_PLACES = 5;
/**
* Calculate the absolute value of a number
*/
template<typename T = int>
inline T csv_abs(T x) {
return abs(x);
}
template<>
inline int csv_abs(int x) {
return abs(x);
}
template<>
inline long int csv_abs(long int x) {
return labs(x);
}
template<>
inline long long int csv_abs(long long int x) {
return llabs(x);
}
template<>
inline float csv_abs(float x) {
return fabsf(x);
}
template<>
inline double csv_abs(double x) {
return fabs(x);
}
template<>
inline long double csv_abs(long double x) {
return fabsl(x);
}
/**
* Calculate the number of digits in a number
*/
template<
typename T,
csv::enable_if_t<std::is_arithmetic<T>::value, int> = 0
>
int num_digits(T x)
{
x = csv_abs(x);
int digits = 0;
while (x >= 1) {
x /= 10;
digits++;
}
return digits;
}
/** to_string() for unsigned integers */
template<typename T,
csv::enable_if_t<std::is_unsigned<T>::value, int> = 0>
inline std::string to_string(T value) {
std::string digits_reverse = "";
if (value == 0) return "0";
while (value > 0) {
digits_reverse += (char)('0' + (value % 10));
value /= 10;
}
return std::string(digits_reverse.rbegin(), digits_reverse.rend());
}
/** to_string() for signed integers */
template<
typename T,
csv::enable_if_t<std::is_integral<T>::value && std::is_signed<T>::value, int> = 0
>
inline std::string to_string(T value) {
if (value >= 0)
return to_string((size_t)value);
return "-" + to_string((size_t)(value * -1));
}
/** to_string() for floating point numbers */
template<
typename T,
csv::enable_if_t<std::is_floating_point<T>::value, int> = 0
>
inline std::string to_string(T value) {
#ifdef __clang__
return std::to_string(value);
#else
// TODO: Figure out why the below code doesn't work on clang
std::string result = "";
T integral_part;
T fractional_part = std::abs(std::modf(value, &integral_part));
integral_part = std::abs(integral_part);
// Integral part
if (value < 0) result = "-";
if (integral_part == 0) {
result += "0";
}
else {
for (int n_digits = num_digits(integral_part); n_digits > 0; n_digits --) {
int digit = (int)(std::fmod(integral_part, pow10(n_digits)) / pow10(n_digits - 1));
result += (char)('0' + digit);
}
}
// Decimal part
result += ".";
if (fractional_part > 0) {
fractional_part *= (T)(pow10(DECIMAL_PLACES));
for (int n_digits = DECIMAL_PLACES; n_digits > 0; n_digits--) {
int digit = (int)(std::fmod(fractional_part, pow10(n_digits)) / pow10(n_digits - 1));
result += (char)('0' + digit);
}
}
else {
result += "0";
}
return result;
#endif
}
}
/** Sets how many places after the decimal will be written for floating point numbers
*
* @param precision Number of decimal places
*/
#ifndef __clang___
inline static void set_decimal_places(int precision) {
internals::DECIMAL_PLACES = precision;
}
#endif
/** @name CSV Writing */
///@{
/**
* Class for writing delimiter separated values files
*
* To write formatted strings, one should
* -# Initialize a DelimWriter with respect to some output stream
* -# Call write_row() on std::vector<std::string>s of unformatted text
*
* @tparam OutputStream The output stream, e.g. `std::ofstream`, `std::stringstream`
* @tparam Delim The delimiter character
* @tparam Quote The quote character
* @tparam Flush True: flush after every writing function,
* false: you need to flush explicitly if needed.
* In both cases the destructor will flush.
*
* @par Hint
* Use the aliases csv::CSVWriter<OutputStream> to write CSV
* formatted strings and csv::TSVWriter<OutputStream>
* to write tab separated strings
*
* @par Example w/ std::vector, std::deque, std::list
* @snippet test_write_csv.cpp CSV Writer Example
*
* @par Example w/ std::tuple
* @snippet test_write_csv.cpp CSV Writer Tuple Example
*/
template<class OutputStream, char Delim, char Quote, bool Flush>
class DelimWriter {
public:
/** Construct a DelimWriter over the specified output stream
*
* @param _out Stream to write to
* @param _quote_minimal Limit field quoting to only when necessary
*/
DelimWriter(OutputStream& _out, bool _quote_minimal = true)
: out(&_out), quote_minimal(_quote_minimal) {};
/** Construct a DelimWriter over the file
*
* @param[out] filename File to write to
*/
template<typename T = OutputStream,
csv::enable_if_t<std::is_same<T, std::ofstream>::value, int> = 0>
DelimWriter(const std::string& filename, bool _quote_minimal = true)
: owned_out(new std::ofstream(filename, std::ios::out)),
out(owned_out.get()),
quote_minimal(_quote_minimal) {
if (!owned_out->is_open())
throw std::runtime_error("Failed to open file for writing: " + filename);
};
/** Destructor will flush remaining data
*
*/
~DelimWriter() {
out->flush();
}
/** Format a sequence of strings and write to CSV according to RFC 4180
*
* @warning This does not check to make sure row lengths are consistent
*
* @param[in] record Sequence of strings to be formatted
*
* @return The current DelimWriter instance (allowing for operator chaining)
*/
template<typename T, size_t Size>
DelimWriter& operator<<(const std::array<T, Size>& record) {
for (size_t i = 0; i < Size; i++) {
(*out) << csv_escape(record[i]);
if (i + 1 != Size) (*out) << Delim;
}
end_out();
return *this;
}
/** @copydoc operator<< */
template<typename... T>
DelimWriter& operator<<(const std::tuple<T...>& record) {
this->write_tuple<0, T...>(record);
return *this;
}
/**
* @tparam T A container such as std::vector, std::deque, or std::list
*
* @copydoc operator<<
*/
template<
typename T, typename Alloc, template <typename, typename> class Container,
// Avoid conflicting with tuples with two elements
csv::enable_if_t<std::is_class<Alloc>::value, int> = 0
>
DelimWriter& operator<<(const Container<T, Alloc>& record) {
const size_t ilen = record.size();
size_t i = 0;
for (const auto& field : record) {
(*out) << csv_escape(field);
if (i + 1 != ilen) (*out) << Delim;
i++;
}
end_out();
return *this;
}
/** Flushes the written data
*
*/
void flush() {
out->flush();
}
private:
template<
typename T,
csv::enable_if_t<
!std::is_convertible<T, std::string>::value
&& !std::is_convertible<T, csv::string_view>::value
, int> = 0
>
std::string csv_escape(T in) {
return internals::to_string(in);
}
template<
typename T,
csv::enable_if_t<
std::is_convertible<T, std::string>::value
|| std::is_convertible<T, csv::string_view>::value
, int> = 0
>
std::string csv_escape(T in) {
IF_CONSTEXPR(std::is_convertible<T, csv::string_view>::value) {
return _csv_escape(in);
}
return _csv_escape(std::string(in));
}
std::string _csv_escape(csv::string_view in) {
/** Format a string to be RFC 4180-compliant
* @param[in] in String to be CSV-formatted
* @param[out] quote_minimal Only quote fields if necessary.
* If False, everything is quoted.
*/
// Do we need a quote escape
bool quote_escape = false;
for (auto ch : in) {
if (ch == Quote || ch == Delim || ch == '\r' || ch == '\n') {
quote_escape = true;
break;
}
}
if (!quote_escape) {
if (quote_minimal) return std::string(in);
else {
std::string ret(1, Quote);
ret += in.data();
ret += Quote;
return ret;
}
}
// Start initial quote escape sequence
std::string ret(1, Quote);
for (auto ch: in) {
if (ch == Quote) ret += std::string(2, Quote);
else ret += ch;
}
// Finish off quote escape
ret += Quote;
return ret;
}
/** Recurisve template for writing std::tuples */
template<size_t Index = 0, typename... T>
typename std::enable_if<Index < sizeof...(T), void>::type write_tuple(const std::tuple<T...>& record) {
(*out) << csv_escape(std::get<Index>(record));
IF_CONSTEXPR (Index + 1 < sizeof...(T)) (*out) << Delim;
this->write_tuple<Index + 1>(record);
}
/** Base case for writing std::tuples */
template<size_t Index = 0, typename... T>
typename std::enable_if<Index == sizeof...(T), void>::type write_tuple(const std::tuple<T...>& record) {
(void)record;
end_out();
}
/** Ends a line in 'out' and flushes, if Flush is true.*/
void end_out() {
(*out) << '\n';
IF_CONSTEXPR(Flush) out->flush();
}
/**
* An owned output stream, if the writer owns it.
* May be null if the writer does not own its output stream, i.e.
* if it was initialized with an output stream reference instead of a filename.
*/
std::unique_ptr<OutputStream> owned_out;
/** Pointer to the output stream (which may or may not be owned by this writer). */
OutputStream* out;
bool quote_minimal;
};
/** An alias for csv::DelimWriter for writing standard CSV files
*
* @sa csv::DelimWriter::operator<<()
*
* @note Use `csv::make_csv_writer()` to in instatiate this class over
* an actual output stream.
*/
template<class OutputStream, bool Flush = true>
using CSVWriter = DelimWriter<OutputStream, ',', '"', Flush>;
/** Class for writing tab-separated values files
*
* @sa csv::DelimWriter::write_row()
* @sa csv::DelimWriter::operator<<()
*
* @note Use `csv::make_tsv_writer()` to in instatiate this class over
* an actual output stream.
*/
template<class OutputStream, bool Flush = true>
using TSVWriter = DelimWriter<OutputStream, '\t', '"', Flush>;
/** Return a csv::CSVWriter over the output stream */
template<class OutputStream>
inline CSVWriter<OutputStream> make_csv_writer(OutputStream& out, bool quote_minimal=true) {
return CSVWriter<OutputStream>(out, quote_minimal);
}
/** Return a buffered csv::CSVWriter over the output stream (does not auto flush) */
template<class OutputStream>
inline CSVWriter<OutputStream, false> make_csv_writer_buffered(OutputStream& out, bool quote_minimal=true) {
return CSVWriter<OutputStream, false>(out, quote_minimal);
}
/** Return a csv::TSVWriter over the output stream */
template<class OutputStream>
inline TSVWriter<OutputStream> make_tsv_writer(OutputStream& out, bool quote_minimal=true) {
return TSVWriter<OutputStream>(out, quote_minimal);
}
/** Return a buffered csv::TSVWriter over the output stream (does not auto flush) */
template<class OutputStream>
inline TSVWriter<OutputStream, false> make_tsv_writer_buffered(OutputStream& out, bool quote_minimal=true) {
return TSVWriter<OutputStream, false>(out, quote_minimal);
}
///@}
}