-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsv.hpp
1722 lines (1441 loc) · 64.2 KB
/
csv.hpp
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/// @file
/// @brief C++ CSV library
// Copyright 2020 Matthew Chandler
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#ifndef CSV_HPP
#define CSV_HPP
#include <exception>
#include <fstream>
#include <map>
#include <memory>
#include <optional>
#include <sstream>
#include <string>
#include <vector>
#include <cassert>
#include <cerrno>
#include <cstring>
//#include "version.h"
#define CSVPP_VERSION_MAJOR 1
#define CSVPP_VERSION_MINOR 2
#define CSVPP_VERSION_PATCH 0
/// @defgroup cpp C++ library
/// CSV library namespace
/// @ingroup cpp
namespace csv
{
/// @addtogroup cpp
/// @{
/// Library version
static constexpr struct
{
int major {CSVPP_VERSION_MAJOR},
minor {CSVPP_VERSION_MINOR},
patch {CSVPP_VERSION_PATCH};
} version;
/// Error base class
/// Base class for all library exceptions. Do not use directly
class Error: virtual public std::exception
{
public:
virtual ~Error() = default;
/// @returns Exception message
const char * what() const throw() override { return msg_.c_str(); }
protected:
Error() = default;
explicit Error(const std::string & msg): msg_{msg} {}
private:
std::string msg_;
};
/// Internal error
/// Thrown when an illegal state occurs
struct Internal_error: virtual public Error
{
/// @param msg Error message
explicit Internal_error(const std::string & msg): Error{msg} {}
};
/// Parsing error
/// Thrown when Reader encounters a parsing error
class Parse_error final: virtual public Error
{
public:
/// @param type Parsing error type (ie. quote found inside of unquoted field)
/// @param line_no Line that the error occured on
/// @param col_no Column that the error occured on
Parse_error(const std::string & type, int line_no, int col_no):
Error{"Error parsing CSV at line: " +
std::to_string(line_no) + ", col: " + std::to_string(col_no) + ": " + type},
type_{type},
line_no_{line_no},
col_no_{col_no}
{}
/// @returns Paring error type (ie. quote found inside of unquoted field)
std::string type() const { return type_; }
/// @returns Line number that the error occured on
int line_no() const { return line_no_; }
/// @returns Column that the error occured on
int col_no() const { return col_no_; }
private:
std::string type_;
int line_no_;
int col_no_;
};
/// Out of range error
/// Thrown when Reader is read from beyond the end of input
struct Out_of_range_error final: virtual public Error
{
/// @param msg Error message
explicit Out_of_range_error(const std::string & msg): Error{msg} {}
};
/// Type conversion error
/// Thrown when Reader fails convert a field to requested type
struct Type_conversion_error final: virtual public Error
{
public:
/// @param field Value of field that failed to convert
explicit Type_conversion_error(const std::string & field):
Error{"Could not convert '" + field + "' to requested type"},
field_(field)
{}
/// @returns Value of field that failed to convert
std::string field() const { return field_; }
private:
std::string field_;
};
/// IO error
/// Thrown when an IO error occurs
class IO_error final: virtual public Error
{
public:
/// @param msg Error message
/// @param errno_code \c errno code
explicit IO_error(const std::string & msg, int errno_code):
Error{msg + ": " + std::strerror(errno_code)},
errno_code_{errno_code}
{}
/// @returns %Error message
int errno_code() const { return errno_code_; }
/// @returns \c errno code
std::string errno_str() const { return std::strerror(errno_code_); }
private:
int errno_code_;
};
namespace detail
{
// SFINAE types to determine the best way to convert a given type to a std::string
// Does the type support std::to_string?
template <typename T, typename = void>
struct has_std_to_string: std::false_type{};
template <typename T>
struct has_std_to_string<T, std::void_t<decltype(std::to_string(std::declval<T>()))>> : std::true_type{};
template <typename T>
inline constexpr bool has_std_to_string_v = has_std_to_string<T>::value;
// Does the type support a custom to_string?
template <typename T, typename = void>
struct has_to_string: std::false_type{};
template <typename T>
struct has_to_string<T, std::void_t<decltype(to_string(std::declval<T>()))>> : std::true_type{};
template <typename T>
inline constexpr bool has_to_string_v = has_to_string<T>::value;
// Does the type support conversion via std::ostream::operator>>
template <typename T, typename = void>
struct has_ostr: std::false_type{};
template <typename T>
struct has_ostr<T, std::void_t<decltype(std::declval<std::ostringstream&>() << std::declval<T>())>> : std::true_type{};
template <typename T>
inline constexpr bool has_ostr_v = has_ostr<T>::value;
};
/// String conversion
/// Convert a given type to std::string, using conversion, to_string, or std::ostream insertion
/// @param t Data to convert to std::string
/// @returns Input converted to std::string
template <typename T, typename std::enable_if_t<std::is_convertible_v<T, std::string>, int> = 0>
std::string str(const T & t)
{
return t;
}
template <typename T, typename std::enable_if_t<!std::is_convertible_v<T, std::string> && detail::has_std_to_string_v<T>, int> = 0>
std::string str(const T & t)
{
return std::to_string(t);
}
template <typename T, typename std::enable_if_t<!std::is_convertible_v<T, std::string> && !detail::has_std_to_string_v<T> && detail::has_to_string_v<T>, int> = 0>
std::string str(const T & t)
{
return to_string(t);
}
template <typename T, typename std::enable_if_t<!std::is_convertible_v<T, std::string> && !detail::has_std_to_string_v<T> && !detail::has_to_string_v<T> && detail::has_ostr_v<T>, int> = 0>
std::string str(const T & t)
{
std::ostringstream os;
os<<t;
return os.str();
}
// special conversion for char using std::string's initializer list ctor
std::string str(char c)
{
return {c};
}
/// Parses CSV data
/// By default, parses according to RFC 4180 rules, and throws a Parse_error
/// when given non-conformant input. The field delimiter and quote
/// characters may be changed, and there is a lenient parsing option to ignore
/// violations.
///
/// Blank rows are ignored and skipped over.
///
/// Most methods operate on rows, but some read field-by-field. Mixing
/// row-wise and field-wise methods is not recommended, but is possible.
/// Row-wise methods will act as if the current position is the start of a
/// row, regardless of any fields that have been read from the current row so
/// far.
class Reader
{
public:
/// Represents a single row of CSV data
/// A Row may be obtained from Reader::get_row or Reader::Iterator
/// @warning Reader object must not be destroyed or read from during Row lifetime
class Row
{
public:
/// Iterates over the fields within a Row
/// @tparam T Type to convert fields to. Defaults to std::string
template <typename T = std::string> class Iterator
{
public:
using value_type = T;
using difference_type = std::ptrdiff_t;
using pointer = const T*;
using reference = const T&;
using iterator_category = std::input_iterator_tag;
/// Empty constructor
/// Denotes the end of iteration
Iterator(): row_{nullptr} {}
/// Creates an iterator from a Row, and parses the first field
/// @param row Row to iterate over.
/// @warning \c row must not be destroyed or read from during iteration
/// @throws Parse_error if error parsing first field (*only when not parsing in lenient mode*)
/// @throws IO_error if error reading CSV data
/// @throws Type_conversion_error if error converting to type T. Caller may call this again with a different type to try again
explicit Iterator(Reader::Row & row): row_{&row}
{
++*this;
}
/// @returns Current field
const T & operator*() const { return obj_; }
/// @returns Pointer to current field
const T * operator->() const { return &obj_; }
/// Parse and iterate to next field
/// @throws Parse_error if error parsing field (*only when not parsing in lenient mode*)
/// @throws IO_error if error reading CSV data
/// @throws Type_conversion_error if error converting to type T. Caller may call this again with a different type to try again
Iterator & operator++()
{
assert(row_);
if(end_of_row_)
{
row_ = nullptr;
}
else
{
obj_ = row_->read_field<T>();
if(row_->end_of_row())
end_of_row_ = true;
}
return *this;
}
/// Compare to another Reader::Row::Iterator
bool equals(const Iterator<T> & rhs) const
{
return row_ == rhs.row_;
}
private:
Reader::Row * row_; ///< Pointer to parent Row object, or \c nullptr if past end of row
T obj_{}; ///< Storage for current field
bool end_of_row_ = false; ///< Keeps track of when the Row has hit end-of-row
};
/// Helper class for iterating over a Row. Use Row::range to obtain
/// @tparam T Type to convert fields to. Defaults to std::string
template<typename T = std::string>
class Range
{
public:
/// @returns Iterator to current field in row
Row::Iterator<T> begin()
{
return Row::Iterator<T>{row_};
}
/// @returns Iterator to end of row
Row::Iterator<T> end()
{
return Row::Iterator<T>{};
}
private:
friend Row;
explicit Range(Row & row):row_{row} {} ///< Construct a Range. Only for use by Row::range
Row & row_; ///< Ref to parent Row object
};
/// @tparam T Type to convert fields to. Defaults to std::string
/// @returns Iterator to current field in row
template<typename T = std::string>
Row::Iterator<T> begin()
{
return Row::Iterator<T>{*this};
}
/// @tparam T Type to convert fields to. Defaults to std::string
/// @returns Iterator to end of row
template<typename T = std::string>
Row::Iterator<T> end()
{
return Row::Iterator<T>{};
}
/// Range helper
/// Useful when iterating over a row and converting to a specific type
/// @tparam T Type to convert fields to. Defaults to std::string
/// @returns A Range object containing begin and end methods corresponding to this Row
template<typename T = std::string>
Range<T> range()
{
return Range<T>{*this};
}
/// Read a single field from the row
/// @tparam T Type to convert fields to. Defaults to std::string
/// @returns The next field from the row, or a default-initialized object if past the end of the row
/// @throws Parse_error if error parsing field (*only when not parsing in lenient mode*)
/// @throws IO_error if error reading CSV data
/// @throws Type_conversion_error if error converting to type T. Caller may call this again with a different type to try again
template<typename T = std::string>
T read_field()
{
assert(reader_);
if(end_of_row_)
{
past_end_of_row_ = true;
return T{};
}
auto field = reader_->read_field<T>();
if(reader_->end_of_row())
end_of_row_ = true;
return field;
}
/// Read a single field from the row
/// @param[out] data Variable to to write field to. Will store a
/// default initialized object if past the end of the row
/// @returns This Row object
/// @throws Parse_error if error parsing field (*only when not parsing in lenient mode*)
/// @throws IO_error if error reading CSV data
/// @throws Type_conversion_error if error converting to type T. Caller may call this again with a different type to try again
template<typename T>
Row & operator>>(T & data)
{
data = read_field<T>();
return * this;
}
/// Reads row into an output iterator
/// @tparam T Type to convert fields to. Defaults to std::string
/// @param it an output iterator to receive the row data
/// @throws Parse_error if error parsing field (*only when not parsing in lenient mode*)
/// @throws IO_error if error reading CSV data
/// @throws Type_conversion_error if error converting to type T
template<typename T = std::string, typename OutputIter>
void read(OutputIter it)
{
std::copy(begin<T>(), end<T>(), it);
}
/// Reads row into a std::vector
/// @tparam T Type to convert fields to. Defaults to std::string
/// @returns std::vector containing the fields from the Row
/// @throws Parse_error if error parsing field (*only when not parsing in lenient mode*)
/// @throws IO_error if error reading CSV data
/// @throws Type_conversion_error if error converting to type T
template<typename T = std::string>
std::vector<T> read_vec()
{
std::vector<T> vec;
std::copy(begin<T>(), end<T>(), std::back_inserter(vec));
return vec;
}
/// Reads row into a tuple
/// @tparam Args types to convert fields to
/// @returns std::tuple containing the fields from the Row.
/// If Args contains more elements than there are fields in the row,
/// the remaining elements of the tuple will be default initialized
/// @throws Parse_error if error parsing field (*only when not parsing in lenient mode*)
/// @throws IO_error if error reading CSV data
/// @throws Type_conversion_error if error converting to specified types
template <typename ... Args>
std::tuple<Args...> read_tuple()
{
std::tuple<Args...> ret;
read_tuple_helper(ret, std::index_sequence_for<Args...>{});
return ret;
}
/// Reads row into variadic arguments
/// @param[out] data Variables to read into.
/// If more parameters are passed than there are fields in the row,
/// the remaining parameters will be default initialized
/// @throws Parse_error if error parsing field (*only when not parsing in lenient mode*)
/// @throws IO_error if error reading CSV data
/// @throws Type_conversion_error if error converting to specified types
template <typename ... Data>
void read_v(Data & ... data)
{
(void)(*this >> ... >> data);
}
/// @returns \c true if the last field in the row has been read
bool end_of_row() const { return end_of_row_; }
/// @returns \c true if more fields can be read
operator bool() { return reader_ && !past_end_of_row_; }
private:
friend Reader;
/// Helper function for read_tuple
/// Uses a std::index_sequence to generate indexes for std::get
/// @param t tuple to load data into
template <typename Tuple, std::size_t ... Is>
void read_tuple_helper(Tuple & t, std::index_sequence<Is...>)
{
((*this >> std::get<Is>(t)), ...);
}
/// Empty constructor
/// Used to denote that no rows remain
Row(): reader_{nullptr} {}
/// Construct a Row from a Reader
/// For use by Reader::get_row only
explicit Row(Reader & reader): reader_{&reader} {}
Reader * reader_ { nullptr }; ///< Pointer to parent Reader object or nullptr if no rows remain
bool end_of_row_ { false }; ///< Tracks if the end of the current row has been reacehd
bool past_end_of_row_ { false }; ///< Tracks if past the end of the row, and prevents reading from the next row
};
/// Iterates over Rows in CSV data
class Iterator
{
public:
using value_type = Row;
using difference_type = std::ptrdiff_t;
using pointer = const value_type*;
using reference = const value_type&;
using iterator_category = std::input_iterator_tag;
/// Empty constructor
/// Denotes the end of iteration
Iterator(): reader_{nullptr} {}
/// Creates an iterator from a Reader object
/// @param r Reader object to iterate over
/// @warning \c r must not be destroyed or read from during iteration
explicit Iterator(Reader & r): reader_{&r}
{
obj_ = reader_->get_row();
if(!*reader_)
reader_ = nullptr;
}
/// @returns Current row
const value_type & operator*() const { return obj_; }
/// @returns Current row
value_type & operator*() { return obj_; }
/// @returns Pointer to current row
const value_type * operator->() const { return &obj_; }
/// @returns pointer to current row
value_type * operator->() { return &obj_; }
/// Iterate to next Row
Iterator & operator++()
{
// discard any remaining fields
while(!obj_.end_of_row())
obj_.read_field();
assert(reader_);
obj_ = reader_->get_row();
if(!*reader_)
reader_ = nullptr;
return *this;
}
/// Compare to another Reader::Iterator
bool equals(const Iterator & rhs) const
{
return reader_ == rhs.reader_;
}
private:
Reader * reader_ { nullptr }; ///< pointer to parent Reader object or nullptr if no rows remain
value_type obj_; ///< Storage for the current Row
};
/// Use a std::istream for CSV parsing
/// @param input_stream std::istream to read from
/// @param delimiter Delimiter character
/// @param quote Quote character
/// @param lenient Enable lenient parsing (will attempt to read past syntax errors)
/// @warning \c input_stream must not be destroyed or read from during the lifetime of this Reader
explicit Reader(std::istream & input_stream,
const char delimiter = ',', const char quote = '"',
const bool lenient = false):
input_stream_{&input_stream},
delimiter_{delimiter},
quote_{quote},
lenient_{lenient}
{}
/// Open a file for CSV parsing
/// @param filename Path to a file to parse
/// @param delimiter Delimiter character
/// @param quote Quote character
/// @param lenient Enable lenient parsing (will attempt to read past syntax errors)
/// @throws IO_error if there is an error opening the file
explicit Reader(const std::string & filename,
const char delimiter = ',', const char quote = '"',
const bool lenient = false):
internal_input_stream_{std::make_unique<std::ifstream>(filename)},
input_stream_{internal_input_stream_.get()},
delimiter_{delimiter},
quote_{quote},
lenient_{lenient}
{
if(!(*internal_input_stream_))
throw IO_error("Could not open file '" + filename + "'", errno);
}
/// Disambiguation tag type
/// Distinguishes opening a Reader with a filename from opening a Reader
/// with a string
struct input_string_t{};
/// Disambiguation tag
/// Distinguishes opening a Reader with a filename from opening a Reader
/// with a string
static inline constexpr input_string_t input_string{};
/// Parse CSV from memory
/// Use Reader::input_string to distinguish this constructor from the
/// constructor accepting a filename
/// @param input_data \c std::string containing CSV to parse
/// @param delimiter Delimiter character
/// @param quote Quote character
/// @param lenient Enable lenient parsing (will attempt to read past syntax errors)
Reader(input_string_t, const std::string & input_data,
const char delimiter = ',', const char quote = '"',
const bool lenient = false):
internal_input_stream_{std::make_unique<std::istringstream>(input_data)},
input_stream_{internal_input_stream_.get()},
delimiter_{delimiter},
quote_{quote},
lenient_{lenient}
{}
~Reader() = default;
Reader(const Reader &) = delete;
Reader & operator=(const Reader &) = delete;
Reader(Reader &&) = default;
Reader & operator=(Reader &&) = default;
/// Check for end of input
/// @returns \c true if the last field in the row has been read
bool end_of_row() const { return end_of_row_ || eof(); }
/// Check for end of row
/// @returns \c true if no fields remain in the current row
bool eof() const { return state_ == State::eof; }
/// @returns \c true if there is more data to be read
operator bool() { return !eof(); }
/// Change the delimiter character
/// @param delimiter New delimiter character
void set_delimiter(const char delimiter) { delimiter_ = delimiter; }
/// Change the quote character
/// @param quote New quote character
void set_quote(const char quote) { quote_ = quote; }
/// Enable / disable lenient parsing
/// Lenient parsing will attempt to ignore syntax errors in CSV input.
/// @param lenient \c true for lenient parsing
void set_lenient(const bool lenient) { lenient_ = lenient; }
/// @returns Iterator to current row
Iterator begin()
{
return Iterator(*this);
}
/// @returns Iterator to end of CSV data
auto end()
{
return Iterator();
}
/// Read a single field
/// Check end_of_row() to see if this is the last field in the current row
/// @tparam T Type to convert fields to. Defaults to std::string
/// @returns The next field from the row, or a default-initialized object if past the end of the input data
/// @throws Parse_error if error parsing field (*only when not parsing in lenient mode*)
/// @throws IO_error if error reading CSV data
/// @throws Type_conversion_error if error converting to type T. Caller may call this again with a different type to try again
template<typename T = std::string>
T read_field()
{
if(eof())
return {};
end_of_row_ = false;
std::string field;
if(conversion_retry_)
{
field = *conversion_retry_;
conversion_retry_.reset();
}
else
{
field = parse();
}
// no conversion needed for strings
if constexpr(std::is_convertible_v<std::string, T>)
{
return field;
}
else
{
T field_val{};
std::istringstream convert(field);
convert>>field_val;
if(!convert || convert.peek() != std::istream::traits_type::eof())
{
conversion_retry_ = field;
throw Type_conversion_error(field);
}
return field_val;
}
}
/// Read a single field
/// Check end_of_row() to see if this is the last field in the current row
/// @param[out] data Variable to to write field to
/// @returns This Reader object
/// @throws Parse_error if error parsing field (*only when not parsing in lenient mode*)
/// @throws IO_error if error reading CSV data
/// @throws Type_conversion_error if error converting to type T. Caller may call this again with a different type to try again
template<typename T>
Reader & operator>>(T & data)
{
data = read_field<T>();
return * this;
}
/// Reads fields into variadic arguments
/// @warning This may be used to fields from multiple rows at a time.
/// Use with caution if the number of fields per row is not known
/// beforehand.
/// @param[out] data Variables to read into.
/// If more parameters are passed than there are fields remaining,
/// the remaining parameters will be default initialized
/// @throws Parse_error if error parsing field (*only when not parsing in lenient mode*)
/// @throws IO_error if error reading CSV data
/// @throws Type_conversion_error if error converting to specified types
template <typename ... Data>
void read_v(Data & ... data)
{
(void)(*this >> ... >> data);
}
/// Get the current Row
/// @returns Row object for the current row
Row get_row()
{
consume_newlines();
if(eof())
return Row{};
else
return Row{*this};
}
/// Reads current row into an output iterator
/// @tparam T Type to convert fields to. Defaults to std::string
/// @param it An output iterator to receive the row data
/// @returns \c false if this is the last row
/// @throws Parse_error if error parsing field (*only when not parsing in lenient mode*)
/// @throws IO_error if error reading CSV data
/// @throws Type_conversion_error if error converting to type T
template <typename T = std::string, typename OutputIter>
bool read_row(OutputIter it)
{
auto row = get_row();
if(!row)
return false;
row.read<T>(it);
return true;
}
/// Reads current row into a std::vector
/// @tparam T Type to convert fields to. Defaults to std::string
/// @returns std::vector containing the fields from the row or empty optional if no rows remain
/// @throws Parse_error if error parsing field (*only when not parsing in lenient mode*)
/// @throws IO_error if error reading CSV data
/// @throws Type_conversion_error if error converting to type T
template <typename T = std::string>
std::optional<std::vector<T>> read_row_vec()
{
auto row = get_row();
if(!row)
return {};
return row.read_vec<T>();
}
/// Reads current row into a tuple
/// @tparam Args types to convert fields to
/// @returns std::tuple containing the fields from the row or empty
/// optional if no rows remain. If Args contains more elements than there
/// are fields in the row, the remaining elements of the tuple will be
/// default initialized
/// @throws Parse_error if error parsing field (*only when not parsing in lenient mode*)
/// @throws IO_error if error reading CSV data
/// @throws Type_conversion_error if error converting to specified types
template <typename ... Args>
std::optional<std::tuple<Args...>> read_row_tuple()
{
auto row = get_row();
if(!row)
return {};
return row.read_tuple<Args...>();
}
/// Read entire CSV data into a vector of vectors
/// @tparam T Type to convert fields to. Defaults to std::string
/// @returns 2D vector of CSV data.
/// @throws Parse_error if error parsing field (*only when not parsing in lenient mode*)
/// @throws IO_error if error reading CSV data
/// @throws Type_conversion_error if error converting to type T
template <typename T = std::string>
std::vector<std::vector<T>> read_all()
{
std::vector<std::vector<T>> data;
while(true)
{
auto row = read_row_vec<T>();
if(row)
data.push_back(*row);
else
break;
}
return data;
}
private:
/// Get next character from input
/// Updates line and column position, and checks for IO error
/// @returns Next character
/// @throws IO_error
int getc()
{
int c = input_stream_->get();
if(input_stream_->bad() && !input_stream_->eof())
throw IO_error{"Error reading from input", errno};
if(c == '\n')
{
++line_no_;
col_no_ = 0;
}
else if(c != std::istream::traits_type::eof())
++col_no_;
return c;
}
/// Consume newline characters
/// Advance stream position until first non-newline character
/// @throws IO_error
void consume_newlines()
{
if(state_ != State::consume_newlines)
return;
while(true)
{
if(int c = getc(); c == std::istream::traits_type::eof())
{
end_of_row_ = true;
state_ = State::eof;
break;
}
else if(c != '\r' && c != '\n')
{
state_ = State::read;
input_stream_->unget();
--col_no_;
break;
}
}
}
/// Core parsing method
/// Reads and parses character stream to obtain next field
/// @returns Next field, or empty string if at EOF
/// @throws Parse_error if error parsing field (*only when not parsing in lenient mode*)
/// @throws IO_error if error reading from stream
std::string parse()
{
consume_newlines();
if(eof())
return {};
bool quoted = false;
std::string field;
bool field_done = false;
while(!field_done)
{
int c = getc();
bool c_done = false;
while(!c_done)
{
switch(state_)
{
case State::quote:
// end of the field?
if(c == delimiter_ || c == '\n' || c == '\r' || c == std::istream::traits_type::eof())
{
quoted = false;
state_ = State::read;
break;
}
// if it's not an escaped quote, then it's an error
else if(c == quote_)
{
field += c;
state_ = State::read;
c_done = true;
break;
}
else if(lenient_)
{
field += quote_;
field += c;
state_ = State::read;
c_done = true;
break;
}
else
throw Parse_error("Unescaped quote", line_no_, col_no_ - 1);
case State::read:
// we need special handling for quotes
if(c == quote_)
{
if(quoted)
{
state_ = State::quote;
c_done = true;
break;
}
else
{
if(field.empty())
{
quoted = true;
c_done = true;
break;
}
else if(!lenient_)
{
// quotes are not allowed inside of an unquoted field
throw Parse_error("quote found in unquoted field", line_no_, col_no_);
}
}
}
if(quoted && c == std::istream::traits_type::eof())
{
if(lenient_)
{
end_of_row_ = field_done = c_done = true;
state_ = State::consume_newlines;
break;
}
else
throw Parse_error("Unterminated quoted field - reached end-of-file", line_no_, col_no_);
}
else if(!quoted && c == delimiter_)
{