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