Mercurial Hosting > luan
diff src/luan/modules/parsers/Csv.java @ 775:1a68fc55a80c
simplify dir structure
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Fri, 26 Aug 2016 14:36:40 -0600 |
parents | core/src/luan/modules/parsers/Csv.java@bb3818249dfb |
children | 88b5b81cad4a |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/luan/modules/parsers/Csv.java Fri Aug 26 14:36:40 2016 -0600 @@ -0,0 +1,61 @@ +package luan.modules.parsers; + +import luan.LuanTable; + + +public final class Csv { + + public static LuanTable toList(String line) throws ParseException { + return new Csv(line).parse(); + } + + private final Parser parser; + + private Csv(String line) { + this.parser = new Parser(line); + } + + private ParseException exception(String msg) { + return new ParseException(parser,msg); + } + + private LuanTable parse() throws ParseException { + LuanTable list = new LuanTable(); + while(true) { + Spaces(); + String field = parseField(); + list.rawPut(list.rawLength()+1,field); + Spaces(); + if( parser.endOfInput() ) + return list; + if( !parser.match(',') ) + throw exception("unexpected char"); + } + } + + private String parseField() throws ParseException { + parser.begin(); + String rtn; + if( parser.match('"') ) { + int start = parser.currentIndex(); + do { + if( parser.endOfInput() ) { + parser.failure(); + throw exception("unclosed quote"); + } + } while( parser.noneOf("\"") ); + rtn = parser.textFrom(start); + parser.match('"'); + } else { + int start = parser.currentIndex(); + while( !parser.endOfInput() && parser.noneOf(",") ); + rtn = parser.textFrom(start).trim(); + } + return parser.success(rtn); + } + + private void Spaces() { + while( parser.anyOf(" \t") ); + } + +}