Add zero file size check

This commit is contained in:
Michael Krasnyk 2017-05-05 08:41:40 +02:00 committed by Patrick Niklaus
parent 669ac058b8
commit 6b103c6d0b

View File

@ -11,6 +11,7 @@
#include <tbb/spin_mutex.h> #include <tbb/spin_mutex.h>
#include <boost/exception/diagnostic_information.hpp> #include <boost/exception/diagnostic_information.hpp>
#include <boost/filesystem.hpp>
#include <boost/iostreams/device/mapped_file.hpp> #include <boost/iostreams/device/mapped_file.hpp>
#include <boost/spirit/include/phoenix.hpp> #include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/qi.hpp>
@ -93,8 +94,12 @@ template <typename Key, typename Value> struct CSVFilesParser
// Parse a single CSV file and return result as a vector<Key, Value> // Parse a single CSV file and return result as a vector<Key, Value>
auto ParseCSVFile(const std::string &filename, std::size_t file_id) const auto ParseCSVFile(const std::string &filename, std::size_t file_id) const
{ {
std::vector<std::pair<Key, Value>> result;
try try
{ {
if (boost::filesystem::file_size(filename) == 0)
return result;
boost::iostreams::mapped_file_source mmap(filename); boost::iostreams::mapped_file_source mmap(filename);
auto first = mmap.begin(), last = mmap.end(); auto first = mmap.begin(), last = mmap.end();
@ -103,7 +108,6 @@ template <typename Key, typename Value> struct CSVFilesParser
value_rule[qi::_val = qi::_1, boost::phoenix::bind(&Value::source, qi::_val) = file_id]; value_rule[qi::_val = qi::_1, boost::phoenix::bind(&Value::source, qi::_val) = file_id];
qi::rule<Iterator, std::pair<Key, Value>()> csv_line = qi::rule<Iterator, std::pair<Key, Value>()> csv_line =
(key_rule >> ',' >> value_source) >> -(',' >> *(qi::char_ - qi::eol)); (key_rule >> ',' >> value_source) >> -(',' >> *(qi::char_ - qi::eol));
std::vector<std::pair<Key, Value>> result;
const auto ok = qi::parse(first, last, -(csv_line % qi::eol) >> *qi::eol, result); const auto ok = qi::parse(first, last, -(csv_line % qi::eol) >> *qi::eol, result);
if (!ok || first != last) if (!ok || first != last)
@ -112,7 +116,7 @@ template <typename Key, typename Value> struct CSVFilesParser
while (begin_of_line >= mmap.begin() && *begin_of_line != '\n') while (begin_of_line >= mmap.begin() && *begin_of_line != '\n')
--begin_of_line; --begin_of_line;
auto line_number = std::count(mmap.begin(), first, '\n') + 1; auto line_number = std::count(mmap.begin(), first, '\n') + 1;
const auto message = boost::format("CSV file %1% malformed on line %2%: %3%") % const auto message = boost::format("CSV file %1% malformed on line %2%:\n %3%\n") %
filename % std::to_string(line_number) % filename % std::to_string(line_number) %
std::string(begin_of_line + 1, std::find(first, last, '\n')); std::string(begin_of_line + 1, std::find(first, last, '\n'));
throw util::exception(message.str() + SOURCE_REF); throw util::exception(message.str() + SOURCE_REF);