-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCSVtokenlist.cpp
More file actions
148 lines (95 loc) · 2.4 KB
/
CSVtokenlist.cpp
File metadata and controls
148 lines (95 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
#include "CSVtokenlist.h"
#include "strmanip.h"
#include <cassert>
#include <algorithm>
#include <stdexcept>
using std::string;
using std::vector;
namespace SDR
{
namespace etc
{
const char _DELIM =',', DQUOTE ='"', SQUOTE ='\'';
const int COMMA = ',', FS = 0x1C;
class noTRAILINGQUOTE {};
CSVtokenlist::CSVtokenlist(const string& buf, int _d) : L(buf), _no_EOL_DQUOTE(0), DELIM(_d)
{
B = E = ltrim(L.begin(), L.end());
if (L.find(FS) != string::npos) DELIM = FS; // FS overrides
if (B != L.end()) // non-blank line
try
{
next_token();
while (B != L.end())
{
if (*E != DELIM)
throw std::domain_error("//nopossible");
B = ++E;
next_token();
}
assert(E == B);
}
catch(noTRAILINGQUOTE)
{
_no_EOL_DQUOTE = 1; //... and fall through
}
}
string CSVtokenlist::operator[](int idx) const
{
assert(size() > idx);
if (size() <= idx)
return ""; // to deliver endless trailing fields:
// the possible side effects of this are: csvtokenlist will not
// complain or fail in other contexts where the missing fields is
// supposed to be detected.
if (idx < 0 || size() <= idx) // we already covered size() <= idx but left it for historical sake
throw std::domain_error("//notoken");
return std::string(base().begin() + tokens[idx].first,
base().begin() + tokens[idx].second);
}
string CSVtokenlist::unscan(string s)
{
std::replace(s.begin(), s.end(), DQUOTE, SQUOTE);
if (s.find(_DELIM) != string::npos)
s = '"' + s + '"';
return s;
}
string CSVtokenlist::unscanD(string s, const char useDELIM)
{
std::replace(s.begin(), s.end(), DQUOTE, SQUOTE);
if (s.find(useDELIM) != string::npos)
s = '"' + s + '"';
return s;
}
static string::const_iterator end_quote(string::const_iterator B,
string::const_iterator E)
{
string::const_iterator s;
s = std::find(B, E, DQUOTE);
return s;
}
void CSVtokenlist::next_token()
{
B = E = ltrim(E, L.end());
bool Q = E != L.end() && *E == DQUOTE;
if (Q)
{
B = E = ltrim(++E, L.end());
E = end_quote(B, string::const_iterator(L.end()));
}
else
E = std::find(B, string::const_iterator(L.end()), DELIM);
int i1 = B - L.begin();
int i2 = rtrim(B, E) - L.begin();
tokens.push_back(std::make_pair(B - L.begin(), rtrim(B, E) - L.begin()));
if (Q)
{
if (E == L.end())
throw noTRAILINGQUOTE();
assert(*E == DQUOTE);
E = ltrim(++E, L.end());
}
B = E;
}
}
}