kraken: add 'csv' library

A very basic, naive CSV parser.
This commit is contained in:
Bruno BELANYI 2022-03-11 23:57:27 +01:00
parent 94f1c8e731
commit 9d862c6a62
4 changed files with 84 additions and 0 deletions

View file

@ -1,4 +1,10 @@
add_executable(kraken kraken.cc)
target_link_libraries(kraken PRIVATE common_options)
add_subdirectory(csv)
target_link_libraries(kraken PRIVATE
csv
)
install(TARGETS kraken)

5
src/csv/CMakeLists.txt Normal file
View file

@ -0,0 +1,5 @@
add_library(csv STATIC
read-csv.cc
read-csv.hh
)
target_link_libraries(csv PRIVATE common_options)

44
src/csv/read-csv.cc Normal file
View file

@ -0,0 +1,44 @@
#include "read-csv.hh"
#include <sstream>
namespace kraken::csv {
namespace {
// for convenience, use a stringstream which does not accept string_view inputs
csv_line_type parse_line(std::string const& line) {
auto parsed = csv_line_type{};
auto input = std::istringstream(line);
for (std::string atom; std::getline(input, atom, ',');) {
parsed.emplace_back(std::move(atom));
}
return parsed;
}
} // namespace
csv_type read_csv(std::istream& input, CsvHeader header) {
auto parsed = std::vector<csv_line_type>{};
bool first = true;
for (std::string line; std::getline(input, line);) {
if (first && header == CsvHeader::SKIP) {
first = false;
continue;
}
parsed.emplace_back(parse_line(std::move(line)));
}
return parsed;
}
csv_type read_csv(std::string const& input, CsvHeader header) {
auto input_stream = std::istringstream(input);
return read_csv(input_stream, header);
}
} // namespace kraken::csv

29
src/csv/read-csv.hh Normal file
View file

@ -0,0 +1,29 @@
#pragma once
#include <iosfwd>
#include <string>
#include <vector>
namespace kraken::csv {
/// Should the first line of the CSV file be kept or ignored.
enum class CsvHeader {
/// Ignored.
SKIP,
/// Kepts.
KEEP,
};
/// Represent a raw CSV line as a vector of strings.
using csv_line_type = std::vector<std::string>;
/// Represent a raw CSV file as a vector of raw CSV lines
using csv_type = std::vector<csv_line_type>;
/// Parse a CSV file from an input-stream, return a vector of parsed lines.
csv_type read_csv(std::istream& input, CsvHeader header = CsvHeader::SKIP);
/// Convenience function which reads CSV from a string.
csv_type read_csv(std::string const& input, CsvHeader header = CsvHeader::SKIP);
} // namespace kraken::csv