summaryrefslogtreecommitdiff
path: root/project2/files/streamRows.cpp
blob: 26fb55be77040ac35cac5cf3bdea0bcae1031356 (plain)
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
#include <pch.hpp>
#include "streamRows.h"
#include "rowProcessor.h"

StreamRows::StreamRows(ScriptNodePtr p) :
	DefinedColumns(p, "columns", boost::bind(&Column::make, _1, _2)),
	RowSet(p),
	fieldSep(p->value("fieldSep", ",").as<Glib::ustring>()[0]),
	quoteChar(p->value("quoteChar", "\"").as<Glib::ustring>()[0]),
	keepBlankRows(p->value("keepBlankRows", false)),
	countBlankRows(p->value("countBlankRows", false)),
	newline(p->value("newline", "\n").as<Glib::ustring>()),
	newlin(newline, 0, newline.length() - 1),
	encoding(p->value("encoding", "utf-8").as<std::string>()),
	skipheader(p->value("skipheader", 0).as<int64_t>())
{
}

StreamRows::~StreamRows()
{
}

void
StreamRows::pushChar(gunichar c, ParseState & ps) const
{
	if ((!ps.inQuotes) && (c == *newline.rbegin()) && (ps.tok.compare(ps.tok.length() - newlin.length(), newlin.length(), newlin) == 0)) {
		if (skipheader) {
			ps.skipheader -= 1;
		}
		else {
			ps.tok.erase(ps.tok.length() - newlin.length());
			if (!ps.tok.empty()) {
				*ps.curCol++ = VariableType(ps.tok);
			}
			if (keepBlankRows || ps.curCol != ps.fields.begin()) {
				while (ps.curCol != ps.fields.end()) {
					*ps.curCol++ = Null();
				}
				ps.process(ps.rp);
			}
			else if (countBlankRows) {
				ps.blankRow();
			}
			ps.curCol = ps.fields.begin();
		}
		ps.tok.clear();
	}
	else if (c == quoteChar) {
		if (ps.prevWasQuote) {
			ps.tok += c;
			ps.prevWasQuote = false;
			ps.inQuotes = !ps.inQuotes;
		}
		else {
			ps.prevWasQuote = ps.inQuotes;
			ps.inQuotes = !ps.inQuotes;
		}
	}
	else if ((!ps.inQuotes) && (c == fieldSep)) {
		ps.prevWasQuote = false;
		if (skipheader == 0) {
			*ps.curCol++ = VariableType(ps.tok);
		}
		ps.tok.clear();
	}
	else {
		ps.prevWasQuote = false;
		ps.tok += c;
	}
}

StreamRows::ParseState::ParseState(const StreamRows * rows, const RowProcessor * proc) :
	ColumnValues(rows),
	sr(rows),
	rp(proc),
	inQuotes(false),
	prevWasQuote(false),
	curCol(fields.begin())
{
}

StreamRows::ParseState::~ParseState()
{
	if (!std::uncaught_exception()) {
		sr->end(*this);
	}
}

void
StreamRows::end(ParseState & ps) const
{
	if (!ps.tok.empty()) {
		if (skipheader == 0) {
			*ps.curCol++ = VariableType(ps.tok);
		}
	}
	if (keepBlankRows || ps.curCol != ps.fields.begin()) {
		while (ps.curCol != ps.fields.end()) {
			*ps.curCol++ = Null();
		}
		ps.process(ps.rp);
	}
	else if (countBlankRows) {
		ps.blankRow();
	}
}