| 12 | namespace coding |
| 13 | { |
| 14 | class CSVReader |
| 15 | { |
| 16 | public: |
| 17 | using Row = std::vector<std::string>; |
| 18 | using Rows = std::vector<Row>; |
| 19 | |
| 20 | explicit CSVReader(std::string const & filename, bool hasHeader = false, char delimiter = ','); |
| 21 | explicit CSVReader(std::istream & stream, bool hasHeader = false, char delimiter = ','); |
| 22 | explicit CSVReader(Reader const & reader, bool hasHeader = false, char delimiter = ','); |
| 23 | |
| 24 | bool HasHeader() const; |
| 25 | char GetDelimiter() const; |
| 26 | |
| 27 | Row const & GetHeader() const; |
| 28 | std::optional<Row> ReadRow(); |
| 29 | Rows ReadAll(); |
| 30 | |
| 31 | template <typename Fn> |
| 32 | void ForEachRow(Fn && fn) |
| 33 | { |
| 34 | while (auto const optRow = ReadRow()) |
| 35 | fn(*optRow); |
| 36 | } |
| 37 | |
| 38 | // The total number of lines read including the header. Count starts at 0. |
| 39 | size_t GetCurrentLineNumber() const; |
| 40 | |
| 41 | private: |
| 42 | class ReaderInterface |
| 43 | { |
| 44 | public: |
| 45 | virtual ~ReaderInterface() = default; |
| 46 | |
| 47 | virtual std::optional<std::string> ReadLine() = 0; |
| 48 | }; |
| 49 | |
| 50 | class IstreamWrapper : public ReaderInterface |
| 51 | { |
| 52 | public: |
| 53 | explicit IstreamWrapper(std::istream & stream); |
| 54 | |
| 55 | // ReaderInterface overrides: |
| 56 | std::optional<std::string> ReadLine() override; |
| 57 | |
| 58 | private: |
| 59 | std::istream & m_stream; |
| 60 | }; |
| 61 | |
| 62 | class ReaderWrapper : public ReaderInterface |
| 63 | { |
| 64 | public: |
| 65 | explicit ReaderWrapper(Reader const & reader); |
| 66 | |
| 67 | // ReaderInterface overrides: |
| 68 | std::optional<std::string> ReadLine() override; |
| 69 | |
| 70 | private: |
| 71 | size_t m_pos = 0; |
no outgoing calls