Skip to content

Instantly share code, notes, and snippets.

@JesseKPhillips
Created March 31, 2011 04:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JesseKPhillips/895807 to your computer and use it in GitHub Desktop.
Save JesseKPhillips/895807 to your computer and use it in GitHub Desktop.
Crashing CSV
module csv;
import std.algorithm;
import std.array;
import std.range;
import std.conv;
import std.traits;
import std.stdio;
void main() {
string str = "Hello,World\nsimple,test";
auto records = csvText(str);
auto record = records.front;
assert(record.front == "Hello");
record.popFront();
assert(record.front == "World");
foreach(r; csvText(str)) {
foreach(cell; r) {
writeln(cell);
}
}
}
RecordList csvText(string data) {
return RecordList(data);
}
/**
* Range which provides access to CSV Records and Tokens.
*/
struct RecordList
{
private:
string _input;
bool _empty;
Record recordRange;
public:
this(string input)
{
_input = input;
prime();
}
this(this)
{
recordRange._input = &_input;
}
@property auto front()
{
return recordRange;
}
@property bool empty()
{
return _input.empty;
}
void popFront()
{
prime();
}
void prime()
{
recordRange = typeof(recordRange)(&_input);
}
}
struct Record {
private:
string* _input;
string curContentsoken;
bool _empty;
public:
this(string* input)
{
_input = input;
prime();
}
@property string front()
{
assert(!empty);
return curContentsoken;
}
@property bool empty()
{
return (*_input).empty;
}
void popFront()
{
prime();
}
void prime() {
auto count = countUntil(*_input, ',');
string ans;
if(count != -1) {
ans = (*_input)[0..count];
*_input = (*_input)[count+1..$];
curContentsoken = ans;
return;
}
ans = *_input;
*_input = null;
curContentsoken = ans;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment