blob: fd3d932fcd5c11c55f27233ff1882c0a3d8bd910 (
plain) (
blame)
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
|
#include "csv.h"
TStringBuf NCsvFormat::CsvSplitter::Consume() {
if (Begin == End) {
return nullptr;
}
TString::const_iterator TokenStart = Begin;
TString::const_iterator TokenEnd = Begin;
if (Quote == '\0') {
while (1) {
if (TokenEnd == End || *TokenEnd == Delimeter) {
Begin = TokenEnd;
return TStringBuf(TokenStart, TokenEnd);
}
++TokenEnd;
}
} else {
bool Escape = false;
if (*Begin == Quote) {
Escape = true;
++TokenStart;
++TokenEnd;
Y_ENSURE(TokenStart != End, TStringBuf("RFC4180 violation: quotation mark must be followed by something"));
}
while (1) {
if (TokenEnd == End || (!Escape && *TokenEnd == Delimeter)) {
Begin = TokenEnd;
return TStringBuf(TokenStart, TokenEnd);
} else if (*TokenEnd == Quote) {
Y_ENSURE(Escape, TStringBuf("RFC4180 violation: quotation mark must be in the escaped string only"));
if (TokenEnd + 1 == End) {
Begin = TokenEnd + 1;
} else if (*(TokenEnd + 1) == Delimeter) {
Begin = TokenEnd + 1;
} else if (*(TokenEnd + 1) == Quote) {
TempResultParts.push_back(TStringBuf(TokenStart, (TokenEnd + 1)));
TokenEnd += 2;
TokenStart = TokenEnd;
continue;
} else {
Y_ENSURE(false, TStringBuf("RFC4180 violation: in escaped string quotation mark must be followed by a delimiter, EOL or another quotation mark"));
}
if (TempResultParts.size()) {
auto newEscapedStringPtr = std::make_unique<TString>();
size_t newStringSize = 0;
for (auto tempResultPart : TempResultParts) {
newStringSize += tempResultPart.size();
}
newStringSize += TokenEnd - TokenStart;
newEscapedStringPtr->reserve(newStringSize);
for (auto tempResultPart : TempResultParts) {
*newEscapedStringPtr += TString{ tempResultPart };
}
*newEscapedStringPtr += TString{ TStringBuf(TokenStart, TokenEnd) };
TempResultParts.clear();
// Storing built string so that returned TStringBuf won't change until this splitter is destroyed
TempResults.push_back(std::move(newEscapedStringPtr));
return TStringBuf(*TempResults.back());
} else {
return TStringBuf(TokenStart, TokenEnd);
}
}
++TokenEnd;
}
}
}
TString NCsvFormat::TLinesSplitter::ConsumeLine() {
bool Escape = false;
TString result;
TString line;
while (Input.ReadLine(line)) {
for (auto it = line.begin(); it != line.end(); ++it) {
if (*it == Quote) {
Escape = !Escape;
}
}
if (!result) {
result = line;
} else {
result += line;
}
if (!Escape) {
break;
} else {
result += "\n";
}
}
return result;
}
|