iw4x-client/src/Utils/CSV.cpp

145 lines
2.4 KiB
C++
Raw Normal View History

2016-01-05 19:23:43 -05:00
#include "STDInclude.hpp"
namespace Utils
{
CSV::CSV(std::string file, bool isFile, bool allowComments)
2016-01-05 19:23:43 -05:00
{
CSV::Parse(file, isFile, allowComments);
2016-01-05 19:23:43 -05:00
}
CSV::~CSV()
{
for (auto row : CSV::DataMap)
{
for (auto entry : row)
{
entry.clear();
}
row.clear();
}
CSV::DataMap.clear();
}
int CSV::GetRows()
{
return CSV::DataMap.size();
}
int CSV::GetColumns(size_t row)
{
if (CSV::DataMap.size() > row)
{
return CSV::DataMap[row].size();
}
return 0;
}
2016-01-12 15:17:55 -05:00
int CSV::GetColumns()
{
int count = 0;
2016-01-24 13:58:13 -05:00
for (int i = 0; i < CSV::GetRows(); ++i)
2016-01-12 15:17:55 -05:00
{
count = std::max(CSV::GetColumns(i), count);
2016-01-12 15:17:55 -05:00
}
return count;
}
2016-01-05 19:23:43 -05:00
std::string CSV::GetElementAt(size_t row, size_t column)
{
if (CSV::DataMap.size() > row)
{
auto _row = CSV::DataMap[row];
if (_row.size() > column)
{
return _row[column];
}
}
return "";
}
void CSV::Parse(std::string file, bool isFile, bool allowComments)
2016-01-05 19:23:43 -05:00
{
2016-01-12 15:17:55 -05:00
std::string buffer;
2016-01-05 19:23:43 -05:00
2016-01-12 15:17:55 -05:00
if (isFile)
{
if (!Utils::FileExists(file)) return;
buffer = Utils::ReadFile(file);
}
else
{
buffer = file;
}
2016-01-05 19:23:43 -05:00
if (!buffer.empty())
2016-01-05 19:23:43 -05:00
{
auto rows = Utils::Explode(buffer, '\n');
for (auto row : rows)
{
CSV::ParseRow(row, allowComments);
2016-01-05 19:23:43 -05:00
}
}
}
void CSV::ParseRow(std::string row, bool allowComments)
2016-01-05 19:23:43 -05:00
{
bool isString = false;
std::string element;
std::vector<std::string> _row;
2016-01-12 15:17:55 -05:00
char tempStr = 0;
2016-01-05 19:23:43 -05:00
2016-01-24 13:58:13 -05:00
for (unsigned int i = 0; i < row.size(); ++i)
2016-01-05 19:23:43 -05:00
{
if (row[i] == ',' && !isString) // FLush entry
{
_row.push_back(element);
element.clear();
continue;
}
else if (row[i] == '"') // Start/Terminate string
{
isString = !isString;
continue;
}
else if (i < (row.size() - 1) && row[i] == '\\' &&row[i + 1] == '"' && isString) // Handle quotes in strings as \"
{
2016-01-12 15:17:55 -05:00
tempStr = '"';
2016-01-05 19:23:43 -05:00
++i;
}
else if (!isString && (row[i] == '\n' || row[i] == '\x0D' || row[i] == '\x0A' || row[i] == '\t'))
{
//++i;
continue;
}
else if (!isString && row[i] == '#' && allowComments) // Skip comments. I know CSVs usually don't have comments, but in this case it's useful
2016-01-05 19:23:43 -05:00
{
return;
}
else
{
2016-01-12 15:17:55 -05:00
tempStr = row[i];
2016-01-05 19:23:43 -05:00
}
2016-01-12 15:17:55 -05:00
element.append(&tempStr, 1);
2016-01-05 19:23:43 -05:00
}
// Push last element
_row.push_back(element);
if (_row.size() == 0 || (_row.size() == 1 && !_row[0].size())) // Skip empty rows
{
return;
}
DataMap.push_back(_row);
}
}