Created
March 31, 2011 04:21
-
-
Save JesseKPhillips/895807 to your computer and use it in GitHub Desktop.
Crashing CSV
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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