Debian Codegraph @

csv.h

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // Copyright: (2012-2015) Ben Strasser <[email protected]>
2 // License: BSD-3
3 //
4 // All rights reserved.
5 //
6 // Redistribution and use in source and binary forms, with or without
7 // modification, are permitted provided that the following conditions are met:
8 //
9 // 1. Redistributions of source code must retain the above copyright notice,
10 // this list of conditions and the following disclaimer.
11 //
12 //2. Redistributions in binary form must reproduce the above copyright notice,
13 // this list of conditions and the following disclaimer in the documentation
14 // and/or other materials provided with the distribution.
15 //
16 //3. Neither the name of the copyright holder nor the names of its contributors
17 // may be used to endorse or promote products derived from this software
18 // without specific prior written permission.
19 //
20 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21 // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
24 // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 // POSSIBILITY OF SUCH DAMAGE.
31
32 #ifndef CSV_H
33 #define CSV_H
34
35 #include <vector>
36 #include <string>
37 #include <cstring>
38 #include <algorithm>
39 #include <utility>
40 #include <cstdio>
41 #include <exception>
42 #ifndef CSV_IO_NO_THREAD
43 #include <mutex>
44 #include <thread>
45 #include <condition_variable>
46 #endif
47 #include <memory>
48 #include <cassert>
49 #include <cerrno>
50 #include <istream>
51
52 namespace io{
53 ////////////////////////////////////////////////////////////////////////////
54 // LineReader //
55 ////////////////////////////////////////////////////////////////////////////
56
57 namespace error{
58 struct base : std::exception{
59 virtual void format_error_message()const = 0;
60
61 const char*what()const throw(){
62 format_error_message();
63 return error_message_buffer;
64 }
65
66 mutable char error_message_buffer[256];
67 };
68
69 const int max_file_name_length = 255;
70
71 struct with_file_name{
72 with_file_name(){
73 std::memset(file_name, 0, max_file_name_length+1);
74 }
75
76 void set_file_name(const char*file_name){
77 std::strncpy(this->file_name, file_name, max_file_name_length);
78 this->file_name[max_file_name_length] = '\0';
79 }
80
81 char file_name[max_file_name_length+1];
82 };
83
84 struct with_file_line{
85 with_file_line(){
86 file_line = -1;
87 }
88
89 void set_file_line(int file_line){
90 this->file_line = file_line;
91 }
92
93 int file_line;
94 };
95
96 struct with_errno{
97 with_errno(){
98 errno_value = 0;
99 }
100
101 void set_errno(int errno_value){
102 this->errno_value = errno_value;
103 }
104
105 int errno_value;
106 };
107
108 struct can_not_open_file :
109 base,
110 with_file_name,
111 with_errno{
112 void format_error_message()const{
113 if(errno_value != 0)
114 std::snprintf(error_message_buffer, sizeof(error_message_buffer),
115 "Can not open file \"%s\" because \"%s\"."
116 , file_name, std::strerror(errno_value));
117 else
118 std::snprintf(error_message_buffer, sizeof(error_message_buffer),
119 "Can not open file \"%s\"."
120 , file_name);
121 }
122 };
123
124 struct line_length_limit_exceeded :
125 base,
126 with_file_name,
127 with_file_line{
128 void format_error_message()const{
129 std::snprintf(error_message_buffer, sizeof(error_message_buffer),
130 "Line number %d in file \"%s\" exceeds the maximum length of 2^24-1."
131 , file_line, file_name);
132 }
133 };
134 }
135
136 class ByteSourceBase{
137 public:
138 virtual int read(char*buffer, int size)=0;
139 virtual ~ByteSourceBase(){}
140 };
141
142 namespace detail{
143
144 class OwningStdIOByteSourceBase : public ByteSourceBase{
145 public:
146 explicit OwningStdIOByteSourceBase(FILE*file):file(file){
147 // Tell the std library that we want to do the buffering ourself.
148 std::setvbuf(file, 0, _IONBF, 0);
149 }
150
151 int read(char*buffer, int size){
152 return std::fread(buffer, 1, size, file);
153 }
154
155 ~OwningStdIOByteSourceBase(){
156 std::fclose(file);
157 }
158
159 private:
160 FILE*file;
161 };
162
163 class NonOwningIStreamByteSource : public ByteSourceBase{
164 public:
165 explicit NonOwningIStreamByteSource(std::istream&in):in(in){}
166
167 int read(char*buffer, int size){
168 in.read(buffer, size);
169 return in.gcount();
170 }
171
172 ~NonOwningIStreamByteSource(){}
173
174 private:
175 std::istream&in;
176 };
177
178 class NonOwningStringByteSource : public ByteSourceBase{
179 public:
180 NonOwningStringByteSource(const char*str, long long size):str(str), remaining_byte_count(size){}
181
182 int read(char*buffer, int desired_byte_count){
183 int to_copy_byte_count = desired_byte_count;
184 if(remaining_byte_count < to_copy_byte_count)
185 to_copy_byte_count = remaining_byte_count;
186 std::memcpy(buffer, str, to_copy_byte_count);
187 remaining_byte_count -= to_copy_byte_count;
188 str += to_copy_byte_count;
189 return to_copy_byte_count;
190 }
191
192 ~NonOwningStringByteSource(){}
193
194 private:
195 const char*str;
196 long long remaining_byte_count;
197 };
198
199 #ifndef CSV_IO_NO_THREAD
200 class AsynchronousReader{
201 public:
202 void init(std::unique_ptr<ByteSourceBase>arg_byte_source){
203 std::unique_lock<std::mutex>guard(lock);
204 byte_source = std::move(arg_byte_source);
205 desired_byte_count = -1;
206 termination_requested = false;
207 worker = std::thread(
208 [&]{
209 std::unique_lock<std::mutex>guard(lock);
210 try{
211 for(;;){
212 read_requested_condition.wait(
213 guard,
214 [&]{
215 return desired_byte_count != -1 || termination_requested;
216 }
217 );
218 if(termination_requested)
219 return;
220
221 read_byte_count = byte_source->read(buffer, desired_byte_count);
222 desired_byte_count = -1;
223 if(read_byte_count == 0)
224 break;
225 read_finished_condition.notify_one();
226 }
227 }catch(...){
228 read_error = std::current_exception();
229 }
230 read_finished_condition.notify_one();
231 }
232 );
233 }
234
235 bool is_valid()const{
236 return byte_source != 0;
237 }
238
239 void start_read(char*arg_buffer, int arg_desired_byte_count){
240 std::unique_lock<std::mutex>guard(lock);
241 buffer = arg_buffer;
242 desired_byte_count = arg_desired_byte_count;
243 read_byte_count = -1;
244 read_requested_condition.notify_one();
245 }
246
247 int finish_read(){
248 std::unique_lock<std::mutex>guard(lock);
249 read_finished_condition.wait(
250 guard,
251 [&]{
252 return read_byte_count != -1 || read_error;
253 }
254 );
255 if(read_error)
256 std::rethrow_exception(read_error);
257 else
258 return read_byte_count;
259 }
260
261 ~AsynchronousReader(){
262 if(byte_source != 0){
263 {
264 std::unique_lock<std::mutex>guard(lock);
265 termination_requested = true;
266 }
267 read_requested_condition.notify_one();
268 worker.join();
269 }
270 }
271
272 private:
273 std::unique_ptr<ByteSourceBase>byte_source;
274
275 std::thread worker;
276
277 bool termination_requested;
278 std::exception_ptr read_error;
279 char*buffer;
280 int desired_byte_count;
281 int read_byte_count;
282
283 std::mutex lock;
284 std::condition_variable read_finished_condition;
285 std::condition_variable read_requested_condition;
286 };
287 #endif
288
289 class SynchronousReader{
290 public:
291 void init(std::unique_ptr<ByteSourceBase>arg_byte_source){
292 byte_source = std::move(arg_byte_source);
293 }
294
295 bool is_valid()const{
296 return byte_source != 0;
297 }
298
299 void start_read(char*arg_buffer, int arg_desired_byte_count){
300 buffer = arg_buffer;
301 desired_byte_count = arg_desired_byte_count;
302 }
303
304 int finish_read(){
305 return byte_source->read(buffer, desired_byte_count);
306 }
307 private:
308 std::unique_ptr<ByteSourceBase>byte_source;
309 char*buffer;
310 int desired_byte_count;
311 };
312 }
313
314 class LineReader{
315 private:
316 static const int block_len = 1<<24;
317 #ifdef CSV_IO_NO_THREAD
318 detail::SynchronousReader reader;
319 #else
320 detail::AsynchronousReader reader;
321 #endif
322 char*buffer;
323 int data_begin;
324 int data_end;
325
326 char file_name[error::max_file_name_length+1];
327 unsigned file_line;
328
329 static std::unique_ptr<ByteSourceBase> open_file(const char*file_name){
330 // We open the file in binary mode as it makes no difference under *nix
331 // and under Windows we handle \r\n newlines ourself.
332 FILE*file = std::fopen(file_name, "rb");
333 if(file == 0){
334 int x = errno; // store errno as soon as possible, doing it after constructor call can fail.
335 error::can_not_open_file err;
336 err.set_errno(x);
337 err.set_file_name(file_name);
338 throw err;
339 }
340 return std::unique_ptr<ByteSourceBase>(new detail::OwningStdIOByteSourceBase(file));
341 }
342
343 void init(std::unique_ptr<ByteSourceBase>byte_source){
344 file_line = 0;
345
346 buffer = new char[3*block_len];
347 try{
348 data_begin = 0;
349 data_end = byte_source->read(buffer, 2*block_len);
350
351 // Ignore UTF-8 BOM
352 if(data_end >= 3 && buffer[0] == '\xEF' && buffer[1] == '\xBB' && buffer[2] == '\xBF')
353 data_begin = 3;
354
355 if(data_end == 2*block_len){
356 reader.init(std::move(byte_source));
357 reader.start_read(buffer + 2*block_len, block_len);
358 }
359 }catch(...){
360 delete[]buffer;
361 throw;
362 }
363 }
364
365 public:
366 LineReader() = delete;
367 LineReader(const LineReader&) = delete;
368 LineReader&operator=(const LineReader&) = delete;
369
370 explicit LineReader(const char*file_name){
371 set_file_name(file_name);
372 init(open_file(file_name));
373 }
374
375 explicit LineReader(const std::string&file_name){
376 set_file_name(file_name.c_str());
377 init(open_file(file_name.c_str()));
378 }
379
380 LineReader(const char*file_name, std::unique_ptr<ByteSourceBase>byte_source){
381 set_file_name(file_name);
382 init(std::move(byte_source));
383 }
384
385 LineReader(const std::string&file_name, std::unique_ptr<ByteSourceBase>byte_source){
386 set_file_name(file_name.c_str());
387 init(std::move(byte_source));
388 }
389
390 LineReader(const char*file_name, const char*data_begin, const char*data_end){
391 set_file_name(file_name);
392 init(std::unique_ptr<ByteSourceBase>(new detail::NonOwningStringByteSource(data_begin, data_end-data_begin)));
393 }
394
395 LineReader(const std::string&file_name, const char*data_begin, const char*data_end){
396 set_file_name(file_name.c_str());
397 init(std::unique_ptr<ByteSourceBase>(new detail::NonOwningStringByteSource(data_begin, data_end-data_begin)));
398 }
399
400 LineReader(const char*file_name, FILE*file){
401 set_file_name(file_name);
402 init(std::unique_ptr<ByteSourceBase>(new detail::OwningStdIOByteSourceBase(file)));
403 }
404
405 LineReader(const std::string&file_name, FILE*file){
406 set_file_name(file_name.c_str());
407 init(std::unique_ptr<ByteSourceBase>(new detail::OwningStdIOByteSourceBase(file)));
408 }
409
410 LineReader(const char*file_name, std::istream&in){
411 set_file_name(file_name);
412 init(std::unique_ptr<ByteSourceBase>(new detail::NonOwningIStreamByteSource(in)));
413 }
414
415 LineReader(const std::string&file_name, std::istream&in){
416 set_file_name(file_name.c_str());
417 init(std::unique_ptr<ByteSourceBase>(new detail::NonOwningIStreamByteSource(in)));
418 }
419
420 void set_file_name(const std::string&file_name){
421 set_file_name(file_name.c_str());
422 }
423
424 void set_file_name(const char*file_name){
425 strncpy(this->file_name, file_name, error::max_file_name_length);
426 this->file_name[error::max_file_name_length] = '\0';
427 }
428
429 const char*get_truncated_file_name()const{
430 return file_name;
431 }
432
433 void set_file_line(unsigned file_line){
434 this->file_line = file_line;
435 }
436
437 unsigned get_file_line()const{
438 return file_line;
439 }
440
441 char*next_line(){
442 if(data_begin == data_end)
443 return 0;
444
445 ++file_line;
446
447 assert(data_begin < data_end);
448 assert(data_end <= block_len*2);
449
450 if(data_begin >= block_len){
451 std::memcpy(buffer, buffer+block_len, block_len);
452 data_begin -= block_len;
453 data_end -= block_len;
454 if(reader.is_valid())
455 {
456 data_end += reader.finish_read();
457 std::memcpy(buffer+block_len, buffer+2*block_len, block_len);
458 reader.start_read(buffer + 2*block_len, block_len);
459 }
460 }
461
462 int line_end = data_begin;
463 while(buffer[line_end] != '\n' && line_end != data_end){
464 ++line_end;
465 }
466
467 if(line_end - data_begin + 1 > block_len){
468 error::line_length_limit_exceeded err;
469 err.set_file_name(file_name);
470 err.set_file_line(file_line);
471 throw err;
472 }
473
474 if(buffer[line_end] == '\n'){
475 buffer[line_end] = '\0';
476 }else{
477 // some files are missing the newline at the end of the
478 // last line
479 ++data_end;
480 buffer[line_end] = '\0';
481 }
482
483 // handle windows \r\n-line breaks
484 if(line_end != data_begin && buffer[line_end-1] == '\r')
485 buffer[line_end-1] = '\0';
486
487 char*ret = buffer + data_begin;
488 data_begin = line_end+1;
489 return ret;
490 }
491
492 ~LineReader(){
493 delete[] buffer;
494 }
495 };
496
497
498 ////////////////////////////////////////////////////////////////////////////
499 // CSV //
500 ////////////////////////////////////////////////////////////////////////////
501
502 namespace error{
503 const int max_column_name_length = 63;
504 struct with_column_name{
505 with_column_name(){
506 std::memset(column_name, 0, max_column_name_length+1);
507 }
508
509 void set_column_name(const char*column_name){
510 std::strncpy(this->column_name, column_name, max_column_name_length);
511 this->column_name[max_column_name_length] = '\0';
512 }
513
514 char column_name[max_column_name_length+1];
515 };
516
517
518 const int max_column_content_length = 63;
519
520 struct with_column_content{
521 with_column_content(){
522 std::memset(column_content, 0, max_column_content_length+1);
523 }
524
525 void set_column_content(const char*column_content){
526 std::strncpy(this->column_content, column_content, max_column_content_length);
527 this->column_content[max_column_content_length] = '\0';
528 }
529
530 char column_content[max_column_content_length+1];
531 };
532
533
534 struct extra_column_in_header :
535 base,
536 with_file_name,
537 with_column_name{
538 void format_error_message()const{
539 std::snprintf(error_message_buffer, sizeof(error_message_buffer),
540 "Extra column \"%s\" in header of file \"%s\"."
541 , column_name, file_name);
542 }
543 };
544
545 struct missing_column_in_header :
546 base,
547 with_file_name,
548 with_column_name{
549 void format_error_message()const{
550 std::snprintf(error_message_buffer, sizeof(error_message_buffer),
551 "Missing column \"%s\" in header of file \"%s\"."
552 , column_name, file_name);
553 }
554 };
555
556 struct duplicated_column_in_header :
557 base,
558 with_file_name,
559 with_column_name{
560 void format_error_message()const{
561 std::snprintf(error_message_buffer, sizeof(error_message_buffer),
562 "Duplicated column \"%s\" in header of file \"%s\"."
563 , column_name, file_name);
564 }
565 };
566
567 struct header_missing :
568 base,
569 with_file_name{
570 void format_error_message()const{
571 std::snprintf(error_message_buffer, sizeof(error_message_buffer),
572 "Header missing in file \"%s\"."
573 , file_name);
574 }
575 };
576
577 struct too_few_columns :
578 base,
579 with_file_name,
580 with_file_line{
581 void format_error_message()const{
582 std::snprintf(error_message_buffer, sizeof(error_message_buffer),
583 "Too few columns in line %d in file \"%s\"."
584 , file_line, file_name);
585 }
586 };
587
588 struct too_many_columns :
589 base,
590 with_file_name,
591 with_file_line{
592 void format_error_message()const{
593 std::snprintf(error_message_buffer, sizeof(error_message_buffer),
594 "Too many columns in line %d in file \"%s\"."
595 , file_line, file_name);
596 }
597 };
598
599 struct escaped_string_not_closed :
600 base,
601 with_file_name,
602 with_file_line{
603 void format_error_message()const{
604 std::snprintf(error_message_buffer, sizeof(error_message_buffer),
605 "Escaped string was not closed in line %d in file \"%s\"."
606 , file_line, file_name);
607 }
608 };
609
610 struct integer_must_be_positive :
611 base,
612 with_file_name,
613 with_file_line,
614 with_column_name,
615 with_column_content{
616 void format_error_message()const{
617 std::snprintf(error_message_buffer, sizeof(error_message_buffer),
618 "The integer \"%s\" must be positive or 0 in column \"%s\" in file \"%s\" in line \"%d\"."
619 , column_content, column_name, file_name, file_line);
620 }
621 };
622
623 struct no_digit :
624 base,
625 with_file_name,
626 with_file_line,
627 with_column_name,
628 with_column_content{
629 void format_error_message()const{
630 std::snprintf(error_message_buffer, sizeof(error_message_buffer),
631 "The integer \"%s\" contains an invalid digit in column \"%s\" in file \"%s\" in line \"%d\"."
632 , column_content, column_name, file_name, file_line);
633 }
634 };
635
636 struct integer_overflow :
637 base,
638 with_file_name,
639 with_file_line,
640 with_column_name,
641 with_column_content{
642 void format_error_message()const{
643 std::snprintf(error_message_buffer, sizeof(error_message_buffer),
644 "The integer \"%s\" overflows in column \"%s\" in file \"%s\" in line \"%d\"."
645 , column_content, column_name, file_name, file_line);
646 }
647 };
648
649 struct integer_underflow :
650 base,
651 with_file_name,
652 with_file_line,
653 with_column_name,
654 with_column_content{
655 void format_error_message()const{
656 std::snprintf(error_message_buffer, sizeof(error_message_buffer),
657 "The integer \"%s\" underflows in column \"%s\" in file \"%s\" in line \"%d\"."
658 , column_content, column_name, file_name, file_line);
659 }
660 };
661
662 struct invalid_single_character :
663 base,
664 with_file_name,
665 with_file_line,
666 with_column_name,
667 with_column_content{
668 void format_error_message()const{
669 std::snprintf(error_message_buffer, sizeof(error_message_buffer),
670 "The content \"%s\" of column \"%s\" in file \"%s\" in line \"%d\" is not a single character."
671 , column_content, column_name, file_name, file_line);
672 }
673 };
674 }
675
676 typedef unsigned ignore_column;
677 static const ignore_column ignore_no_column = 0;
678 static const ignore_column ignore_extra_column = 1;
679 static const ignore_column ignore_missing_column = 2;
680
681 template<char ... trim_char_list>
682 struct trim_chars{
683 private:
684 constexpr static bool is_trim_char(char){
685 return false;
686 }
687
688 template<class ...OtherTrimChars>
689 constexpr static bool is_trim_char(char c, char trim_char, OtherTrimChars...other_trim_chars){
690 return c == trim_char || is_trim_char(c, other_trim_chars...);
691 }
692
693 public:
694 static void trim(char*&str_begin, char*&str_end){
695 while(is_trim_char(*str_begin, trim_char_list...) && str_begin != str_end)
696 ++str_begin;
697 while(is_trim_char(*(str_end-1), trim_char_list...) && str_begin != str_end)
698 --str_end;
699 *str_end = '\0';
700 }
701 };
702
703
704 struct no_comment{
705 static bool is_comment(const char*){
706 return false;
707 }
708 };
709
710 template<char ... comment_start_char_list>
711 struct single_line_comment{
712 private:
713 constexpr static bool is_comment_start_char(char){
714 return false;
715 }
716
717 template<class ...OtherCommentStartChars>
718 constexpr static bool is_comment_start_char(char c, char comment_start_char, OtherCommentStartChars...other_comment_start_chars){
719 return c == comment_start_char || is_comment_start_char(c, other_comment_start_chars...);
720 }
721
722 public:
723
724 static bool is_comment(const char*line){
725 return is_comment_start_char(*line, comment_start_char_list...);
726 }
727 };
728
729 struct empty_line_comment{
730 static bool is_comment(const char*line){
731 if(*line == '\0')
732 return true;
733 while(*line == ' ' || *line == '\t'){
734 ++line;
735 if(*line == 0)
736 return true;
737 }
738 return false;
739 }
740 };
741
742 template<char ... comment_start_char_list>
743 struct single_and_empty_line_comment{
744 static bool is_comment(const char*line){
745 return single_line_comment<comment_start_char_list...>::is_comment(line) || empty_line_comment::is_comment(line);
746 }
747 };
748
749 template<char sep>
750 struct no_quote_escape{
751 static const char*find_next_column_end(const char*col_begin){
752 while(*col_begin != sep && *col_begin != '\0')
753 ++col_begin;
754 return col_begin;
755 }
756
757 static void unescape(char*&, char*&){
758
759 }
760 };
761
762 template<char sep, char quote>
763 struct double_quote_escape{
764 static const char*find_next_column_end(const char*col_begin){
765 while(*col_begin != sep && *col_begin != '\0')
766 if(*col_begin != quote)
767 ++col_begin;
768 else{
769 do{
770 ++col_begin;
771 while(*col_begin != quote){
772 if(*col_begin == '\0')
773 throw error::escaped_string_not_closed();
774 ++col_begin;
775 }
776 ++col_begin;
777 }while(*col_begin == quote);
778 }
779 return col_begin;
780 }
781
782 static void unescape(char*&col_begin, char*&col_end){
783 if(col_end - col_begin >= 2){
784 if(*col_begin == quote && *(col_end-1) == quote){
785 ++col_begin;
786 --col_end;
787 char*out = col_begin;
788 for(char*in = col_begin; in!=col_end; ++in){
789 if(*in == quote && *(in+1) == quote){
790 ++in;
791 }
792 *out = *in;
793 ++out;
794 }
795 col_end = out;
796 *col_end = '\0';
797 }
798 }
799
800 }
801 };
802
803 struct throw_on_overflow{
804 template<class T>
805 static void on_overflow(T&){
806 throw error::integer_overflow();
807 }
808
809 template<class T>
810 static void on_underflow(T&){
811 throw error::integer_underflow();
812 }
813 };
814
815 struct ignore_overflow{
816 template<class T>
817 static void on_overflow(T&){}
818
819 template<class T>
820 static void on_underflow(T&){}
821 };
822
823 struct set_to_max_on_overflow{
824 template<class T>
825 static void on_overflow(T&x){
826 x = std::numeric_limits<T>::max();
827 }
828
829 template<class T>
830 static void on_underflow(T&x){
831 x = std::numeric_limits<T>::min();
832 }
833 };
834
835
836 namespace detail{
837 template<class quote_policy>
838 void chop_next_column(
839 char*&line, char*&col_begin, char*&col_end
840 ){
841 assert(line != nullptr);
842
843 col_begin = line;
844 // the col_begin + (... - col_begin) removes the constness
845 col_end = col_begin + (quote_policy::find_next_column_end(col_begin) - col_begin);
846
847 if(*col_end == '\0'){
848 line = nullptr;
849 }else{
850 *col_end = '\0';
851 line = col_end + 1;
852 }
853 }
854
855 template<class trim_policy, class quote_policy>
856 void parse_line(
857 char*line,
858 char**sorted_col,
859 const std::vector<int>&col_order
860 ){
861 for(std::size_t i=0; i<col_order.size(); ++i){
862 if(line == nullptr)
863 throw ::io::error::too_few_columns();
864 char*col_begin, *col_end;
865 chop_next_column<quote_policy>(line, col_begin, col_end);
866
867 if(col_order[i] != -1){
868 trim_policy::trim(col_begin, col_end);
869 quote_policy::unescape(col_begin, col_end);
870
871 sorted_col[col_order[i]] = col_begin;
872 }
873 }
874 if(line != nullptr)
875 throw ::io::error::too_many_columns();
876 }
877
878 template<unsigned column_count, class trim_policy, class quote_policy>
879 void parse_header_line(
880 char*line,
881 std::vector<int>&col_order,
882 const std::string*col_name,
883 ignore_column ignore_policy
884 ){
885 col_order.clear();
886
887 bool found[column_count];
888 std::fill(found, found + column_count, false);
889 while(line){
890 char*col_begin,*col_end;
891 chop_next_column<quote_policy>(line, col_begin, col_end);
892
893 trim_policy::trim(col_begin, col_end);
894 quote_policy::unescape(col_begin, col_end);
895
896 for(unsigned i=0; i<column_count; ++i)
897 if(col_begin == col_name[i]){
898 if(found[i]){
899 error::duplicated_column_in_header err;
900 err.set_column_name(col_begin);
901 throw err;
902 }
903 found[i] = true;
904 col_order.push_back(i);
905 col_begin = 0;
906 break;
907 }
908 if(col_begin){
909 if(ignore_policy & ::io::ignore_extra_column)
910 col_order.push_back(-1);
911 else{
912 error::extra_column_in_header err;
913 err.set_column_name(col_begin);
914 throw err;
915 }
916 }
917 }
918 if(!(ignore_policy & ::io::ignore_missing_column)){
919 for(unsigned i=0; i<column_count; ++i){
920 if(!found[i]){
921 error::missing_column_in_header err;
922 err.set_column_name(col_name[i].c_str());
923 throw err;
924 }
925 }
926 }
927 }
928
929 template<class overflow_policy>
930 void parse(char*col, char &x){
931 if(!*col)
932 throw error::invalid_single_character();
933 x = *col;
934 ++col;
935 if(*col)
936 throw error::invalid_single_character();
937 }
938
939 template<class overflow_policy>
940 void parse(char*col, std::string&x){
941 x = col;
942 }
943
944 template<class overflow_policy>
945 void parse(char*col, const char*&x){
946 x = col;
947 }
948
949 template<class overflow_policy>
950 void parse(char*col, char*&x){
951 x = col;
952 }
953
954 template<class overflow_policy, class T>
955 void parse_unsigned_integer(const char*col, T&x){
956 x = 0;
957 while(*col != '\0'){
958 if('0' <= *col && *col <= '9'){
959 T y = *col - '0';
960 if(x > (std::numeric_limits<T>::max()-y)/10){
961 overflow_policy::on_overflow(x);
962 return;
963 }
964 x = 10*x+y;
965 }else
966 throw error::no_digit();
967 ++col;
968 }
969 }
970
971 template<class overflow_policy>void parse(char*col, unsigned char &x)
972 {parse_unsigned_integer<overflow_policy>(col, x);}
973 template<class overflow_policy>void parse(char*col, unsigned short &x)
974 {parse_unsigned_integer<overflow_policy>(col, x);}
975 template<class overflow_policy>void parse(char*col, unsigned int &x)
976 {parse_unsigned_integer<overflow_policy>(col, x);}
977 template<class overflow_policy>void parse(char*col, unsigned long &x)
978 {parse_unsigned_integer<overflow_policy>(col, x);}
979 template<class overflow_policy>void parse(char*col, unsigned long long &x)
980 {parse_unsigned_integer<overflow_policy>(col, x);}
981
982 template<class overflow_policy, class T>
983 void parse_signed_integer(const char*col, T&x){
984 if(*col == '-'){
985 ++col;
986
987 x = 0;
988 while(*col != '\0'){
989 if('0' <= *col && *col <= '9'){
990 T y = *col - '0';
991 if(x < (std::numeric_limits<T>::min()+y)/10){
992 overflow_policy::on_underflow(x);
993 return;
994 }
995 x = 10*x-y;
996 }else
997 throw error::no_digit();
998 ++col;
999 }
1000 return;
1001 }else if(*col == '+')
1002 ++col;
1003 parse_unsigned_integer<overflow_policy>(col, x);
1004 }
1005
1006 template<class overflow_policy>void parse(char*col, signed char &x)
1007 {parse_signed_integer<overflow_policy>(col, x);}
1008 template<class overflow_policy>void parse(char*col, signed short &x)
1009 {parse_signed_integer<overflow_policy>(col, x);}
1010 template<class overflow_policy>void parse(char*col, signed int &x)
1011 {parse_signed_integer<overflow_policy>(col, x);}
1012 template<class overflow_policy>void parse(char*col, signed long &x)
1013 {parse_signed_integer<overflow_policy>(col, x);}
1014 template<class overflow_policy>void parse(char*col, signed long long &x)
1015 {parse_signed_integer<overflow_policy>(col, x);}
1016
1017 template<class T>
1018 void parse_float(const char*col, T&x){
1019 bool is_neg = false;
1020 if(*col == '-'){
1021 is_neg = true;
1022 ++col;
1023 }else if(*col == '+')
1024 ++col;
1025
1026 x = 0;
1027 while('0' <= *col && *col <= '9'){
1028 int y = *col - '0';
1029 x *= 10;
1030 x += y;
1031 ++col;
1032 }
1033
1034 if(*col == '.'|| *col == ','){
1035 ++col;
1036 T pos = 1;
1037 while('0' <= *col && *col <= '9'){
1038 pos /= 10;
1039 int y = *col - '0';
1040 ++col;
1041 x += y*pos;
1042 }
1043 }
1044
1045 if(*col == 'e' || *col == 'E'){
1046 ++col;
1047 int e;
1048
1049 parse_signed_integer<set_to_max_on_overflow>(col, e);
1050
1051 if(e != 0){
1052 T base;
1053 if(e < 0){
1054 base = 0.1;
1055 e = -e;
1056 }else{
1057 base = 10;
1058 }
1059
1060 while(e != 1){
1061 if((e & 1) == 0){
1062 base = base*base;
1063 e >>= 1;
1064 }else{
1065 x *= base;
1066 --e;
1067 }
1068 }
1069 x *= base;
1070 }
1071 }else{
1072 if(*col != '\0')
1073 throw error::no_digit();
1074 }
1075
1076 if(is_neg)
1077 x = -x;
1078 }
1079
1080 template<class overflow_policy> void parse(char*col, float&x) { parse_float(col, x); }
1081 template<class overflow_policy> void parse(char*col, double&x) { parse_float(col, x); }
1082 template<class overflow_policy> void parse(char*col, long double&x) { parse_float(col, x); }
1083
1084 template<class overflow_policy, class T>
1085 void parse(char*col, T&x){
1086 // GCC evalutes "false" when reading the template and
1087 // "sizeof(T)!=sizeof(T)" only when instantiating it. This is why
1088 // this strange construct is used.
1089 static_assert(sizeof(T)!=sizeof(T),
1090 "Can not parse this type. Only buildin integrals, floats, char, char*, const char* and std::string are supported");
1091 }
1092
1093 }
1094
1095 template<unsigned column_count,
1096 class trim_policy = trim_chars<' ', '\t'>,
1097 class quote_policy = no_quote_escape<','>,
1098 class overflow_policy = throw_on_overflow,
1099 class comment_policy = no_comment
1100 >
1101 class CSVReader{
1102 private:
1103 LineReader in;
1104
1105 char*(row[column_count]);
1106 std::string column_names[column_count];
1107
1108 std::vector<int>col_order;
1109
1110 template<class ...ColNames>
1111 void set_column_names(std::string s, ColNames...cols){
1112 column_names[column_count-sizeof...(ColNames)-1] = std::move(s);
1113 set_column_names(std::forward<ColNames>(cols)...);
1114 }
1115
1116 void set_column_names(){}
1117
1118
1119 public:
1120 CSVReader() = delete;
1121 CSVReader(const CSVReader&) = delete;
1122 CSVReader&operator=(const CSVReader&);
1123
1124 template<class ...Args>
1125 explicit CSVReader(Args&&...args):in(std::forward<Args>(args)...){
1126 std::fill(row, row+column_count, nullptr);
1127 col_order.resize(column_count);
1128 for(unsigned i=0; i<column_count; ++i)
1129 col_order[i] = i;
1130 for(unsigned i=1; i<=column_count; ++i)
1131 column_names[i-1] = "col"+std::to_string(i);
1132 }
1133
1134 char*next_line(){
1135 return in.next_line();
1136 }
1137
1138 template<class ...ColNames>
1139 void read_header(ignore_column ignore_policy, ColNames...cols){
1140 static_assert(sizeof...(ColNames)>=column_count, "not enough column names specified");
1141 static_assert(sizeof...(ColNames)<=column_count, "too many column names specified");
1142 try{
1143 set_column_names(std::forward<ColNames>(cols)...);
1144
1145 char*line;
1146 do{
1147 line = in.next_line();
1148 if(!line)
1149 throw error::header_missing();
1150 }while(comment_policy::is_comment(line));
1151
1152 detail::parse_header_line
1153 <column_count, trim_policy, quote_policy>
1154 (line, col_order, column_names, ignore_policy);
1155 }catch(error::with_file_name&err){
1156 err.set_file_name(in.get_truncated_file_name());
1157 throw;
1158 }
1159 }
1160
1161 template<class ...ColNames>
1162 void set_header(ColNames...cols){
1163 static_assert(sizeof...(ColNames)>=column_count,
1164 "not enough column names specified");
1165 static_assert(sizeof...(ColNames)<=column_count,
1166 "too many column names specified");
1167 set_column_names(std::forward<ColNames>(cols)...);
1168 std::fill(row, row+column_count, nullptr);
1169 col_order.resize(column_count);
1170 for(unsigned i=0; i<column_count; ++i)
1171 col_order[i] = i;
1172 }
1173
1174 bool has_column(const std::string&name) const {
1175 return col_order.end() != std::find(
1176 col_order.begin(), col_order.end(),
1177 std::find(std::begin(column_names), std::end(column_names), name)
1178 - std::begin(column_names));
1179 }
1180
1181 void set_file_name(const std::string&file_name){
1182 in.set_file_name(file_name);
1183 }
1184
1185 void set_file_name(const char*file_name){
1186 in.set_file_name(file_name);
1187 }
1188
1189 const char*get_truncated_file_name()const{
1190 return in.get_truncated_file_name();
1191 }
1192
1193 void set_file_line(unsigned file_line){
1194 in.set_file_line(file_line);
1195 }
1196
1197 unsigned get_file_line()const{
1198 return in.get_file_line();
1199 }
1200
1201 private:
1202 void parse_helper(std::size_t){}
1203
1204 template<class T, class ...ColType>
1205 void parse_helper(std::size_t r, T&t, ColType&...cols){
1206 if(row[r]){
1207 try{
1208 try{
1209 ::io::detail::parse<overflow_policy>(row[r], t);
1210 }catch(error::with_column_content&err){
1211 err.set_column_content(row[r]);
1212 throw;
1213 }
1214 }catch(error::with_column_name&err){
1215 err.set_column_name(column_names[r].c_str());
1216 throw;
1217 }
1218 }
1219 parse_helper(r+1, cols...);
1220 }
1221
1222
1223 public:
1224 template<class ...ColType>
1225 bool read_row(ColType& ...cols){
1226 static_assert(sizeof...(ColType)>=column_count,
1227 "not enough columns specified");
1228 static_assert(sizeof...(ColType)<=column_count,
1229 "too many columns specified");
1230 try{
1231 try{
1232
1233 char*line;
1234 do{
1235 line = in.next_line();
1236 if(!line)
1237 return false;
1238 }while(comment_policy::is_comment(line));
1239
1240 detail::parse_line<trim_policy, quote_policy>
1241 (line, row, col_order);
1242
1243 parse_helper(0, cols...);
1244 }catch(error::with_file_name&err){
1245 err.set_file_name(in.get_truncated_file_name());
1246 throw;
1247 }
1248 }catch(error::with_file_line&err){
1249 err.set_file_line(in.get_file_line());
1250 throw;
1251 }
1252
1253 return true;
1254 }
1255 };
1256 }
1257 #endif
1258