Vince's CSV Parser
Loading...
Searching...
No Matches
col_names.cpp
1#include <algorithm>
2#include <cctype>
3#include "col_names.hpp"
4
5namespace csv {
6 namespace internals {
7 CSV_INLINE std::vector<std::string> ColNames::get_col_names() const {
8 return this->col_names;
9 }
10
11 CSV_INLINE void ColNames::set_col_names(const std::vector<std::string>& cnames) {
12 this->col_names = cnames;
13 this->col_pos.clear();
14
15 for (size_t i = 0; i < cnames.size(); i++) {
16 if (this->_policy == csv::ColumnNamePolicy::CASE_INSENSITIVE) {
17 // For case-insensitive lookup, cache a lowercase version
18 // of the column name in the map
19 std::string lower(cnames[i]);
20 std::transform(lower.begin(), lower.end(), lower.begin(),
21 [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
22 this->col_pos[lower] = i;
23 } else {
24 this->col_pos[cnames[i]] = i;
25 }
26 }
27 }
28
29 CSV_INLINE int ColNames::index_of(csv::string_view col_name) const {
30 if (this->_policy == csv::ColumnNamePolicy::CASE_INSENSITIVE) {
31 std::string lower(col_name);
32 std::transform(lower.begin(), lower.end(), lower.begin(),
33 [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
34 auto pos = this->col_pos.find(lower);
35 if (pos != this->col_pos.end())
36 return (int)pos->second;
37 return CSV_NOT_FOUND;
38 }
39
40 auto pos = this->col_pos.find(col_name.data());
41 if (pos != this->col_pos.end())
42 return (int)pos->second;
43
44 return CSV_NOT_FOUND;
45 }
46
48 this->_policy = policy;
49 }
50
51 CSV_INLINE size_t ColNames::size() const noexcept {
52 return this->col_names.size();
53 }
54
55 CSV_INLINE const std::string& ColNames::operator[](size_t i) const {
56 if (i >= this->col_names.size())
57 throw std::out_of_range("Column index out of bounds.");
58
59 return this->col_names[i];
60 }
61 }
62}
#define CSV_INLINE
Helper macro which should be #defined as "inline" in the single header version.
Definition common.hpp:26
The all encompassing namespace.
ColumnNamePolicy
Determines how column name lookups are performed.
@ CASE_INSENSITIVE
Case-insensitive match.
constexpr int CSV_NOT_FOUND
Integer indicating a requested column wasn't found.
Definition common.hpp:296
nonstd::string_view string_view
The string_view class used by this library.
Definition common.hpp:135
const std::string & operator[](size_t i) const
Retrieve column name by index.
Definition col_names.cpp:55
void set_policy(csv::ColumnNamePolicy policy)
Sets the column name lookup policy.
Definition col_names.cpp:47