Mercurial Hosting > luan
comparison core/src/luan/modules/parsers/Csv.java @ 585:bb3818249dfb
add Parsers
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Fri, 14 Aug 2015 06:35:20 -0600 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
584:0742ac78fa69 | 585:bb3818249dfb |
---|---|
1 package luan.modules.parsers; | |
2 | |
3 import luan.LuanTable; | |
4 | |
5 | |
6 public final class Csv { | |
7 | |
8 public static LuanTable toList(String line) throws ParseException { | |
9 return new Csv(line).parse(); | |
10 } | |
11 | |
12 private final Parser parser; | |
13 | |
14 private Csv(String line) { | |
15 this.parser = new Parser(line); | |
16 } | |
17 | |
18 private ParseException exception(String msg) { | |
19 return new ParseException(parser,msg); | |
20 } | |
21 | |
22 private LuanTable parse() throws ParseException { | |
23 LuanTable list = new LuanTable(); | |
24 while(true) { | |
25 Spaces(); | |
26 String field = parseField(); | |
27 list.rawPut(list.rawLength()+1,field); | |
28 Spaces(); | |
29 if( parser.endOfInput() ) | |
30 return list; | |
31 if( !parser.match(',') ) | |
32 throw exception("unexpected char"); | |
33 } | |
34 } | |
35 | |
36 private String parseField() throws ParseException { | |
37 parser.begin(); | |
38 String rtn; | |
39 if( parser.match('"') ) { | |
40 int start = parser.currentIndex(); | |
41 do { | |
42 if( parser.endOfInput() ) { | |
43 parser.failure(); | |
44 throw exception("unclosed quote"); | |
45 } | |
46 } while( parser.noneOf("\"") ); | |
47 rtn = parser.textFrom(start); | |
48 parser.match('"'); | |
49 } else { | |
50 int start = parser.currentIndex(); | |
51 while( !parser.endOfInput() && parser.noneOf(",") ); | |
52 rtn = parser.textFrom(start).trim(); | |
53 } | |
54 return parser.success(rtn); | |
55 } | |
56 | |
57 private void Spaces() { | |
58 while( parser.anyOf(" \t") ); | |
59 } | |
60 | |
61 } |