blob: 486763b7360ac92bcf210b6aaa3532fa4237dc88 (
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
91
92
93
94
95
96
97
98
99
100
101
102
103
|
#include "tsvserializer.h"
#ifdef Q_OS_MACX
QString TsvSerializer::rowSeparator = "\r";
#else
QString TsvSerializer::rowSeparator = "\n";
#endif
QString TsvSerializer::columnSeparator = "\t";
QString TsvSerializer::serialize(const QList<QStringList>& data)
{
QStringList outputRows;
foreach (const QStringList& dataRow, data)
outputRows << serialize(dataRow);
return outputRows.join(rowSeparator);
}
QString TsvSerializer::serialize(const QStringList& data)
{
QString value;
bool hasQuote;
QStringList outputCells;
foreach (const QString& rowValue, data)
{
value = rowValue;
hasQuote = value.contains("\"");
if (value.contains(columnSeparator) || value.contains(rowSeparator))
{
if (hasQuote)
value.replace("\"", "\"\"");
value = "\""+value+"\"";
}
outputCells << value;
}
return outputCells.join(columnSeparator);
}
QList<QStringList> TsvSerializer::deserialize(const QString& data)
{
QList<QStringList> rows;
QStringList cells;
int pos = 0;
int lgt = data.length();
bool quotes = false;
QString field = "";
QChar c;
while (pos < lgt)
{
c = data[pos];
if (!quotes && c == '"' )
{
if (field.isEmpty())
quotes = true;
else
field += c;
}
else if (quotes && c == '"' )
{
if (pos + 1 < data.length() && data[pos+1] == '"' )
{
field += c;
pos++;
}
else
{
quotes = false;
}
}
else if (!quotes && c == columnSeparator)
{
cells << field;
field.clear();
}
else if (!quotes && c == rowSeparator)
{
cells << field;
rows << cells;
cells.clear();
field.clear();
}
else
{
field += c;
}
pos++;
}
if (field.size() > 0)
cells << field;
if (cells.size() > 0)
rows << cells;
return rows;
}
|