view src/luan/modules/parsers/Csv.java @ 1330:f41919741100

fix security
author Franklin Schmidt <fschmidt@gmail.com>
date Mon, 11 Feb 2019 01:38:55 -0700
parents 9fa8b8389578
children 25746915a241
line wrap: on
line source

package luan.modules.parsers;

import luan.LuanState;
import luan.LuanTable;
import luan.LuanException;
import luan.lib.parser.Parser;
import luan.lib.parser.ParseException;


public final class Csv {

	public static LuanTable toList(LuanState luan,String line) throws ParseException {
		try {
			return new Csv(line).parse(luan);
		} catch(LuanException e) {
			throw new RuntimeException(e);
		}
	}

	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(LuanState luan) throws ParseException, LuanException {
		LuanTable list = new LuanTable(luan);
		while(true) {
			Spaces();
			String field = parseField();
			list.put(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") );
	}

}