From 61fd71f69e080790da722e0e03b71ecd7c2538a2 Mon Sep 17 00:00:00 2001 From: bculkin2442 Date: Tue, 10 May 2016 16:02:45 -0400 Subject: General update --- .../utils/parserutils/RuleBasedReaderPragmas.java | 81 ++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedReaderPragmas.java (limited to 'BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedReaderPragmas.java') diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedReaderPragmas.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedReaderPragmas.java new file mode 100644 index 0000000..9d9d1b1 --- /dev/null +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedReaderPragmas.java @@ -0,0 +1,81 @@ +package bjc.utils.parserutils; + +import java.util.function.BiConsumer; + +import bjc.utils.exceptions.PragmaFormatException; +import bjc.utils.funcdata.FunctionalStringTokenizer; +import bjc.utils.funcutils.ListUtils; + +/** + * Contains factory methods for common pragma types + * + * @author ben + * + */ +public class RuleBasedReaderPragmas { + + /** + * Creates a pragma that takes any number of arguments and collapses + * them all into a single string + * + * @param + * The type of state that goes along with this pragma + * @param name + * The name of this pragma, for error message purpose + * @param consumer + * The function to invoke with the parsed string + * @return A pragma that functions as described above. + */ + public static + BiConsumer + buildStringCollapser(String name, + BiConsumer consumer) { + return (tokenizer, state) -> { + if (!tokenizer.hasMoreTokens()) { + throw new PragmaFormatException("Pragma " + name + + " requires one string argument"); + } + + consumer.accept(ListUtils.collapseTokens( + tokenizer.toList((strang) -> strang)), state); + }; + } + + /** + * Creates a pragma that takes a single integer argument + * + * @param + * The type of state that goes along with this pragma + * @param name + * The name of this pragma, for error message purpose + * @param consumer + * The function to invoke with the parsed integer + * @return A pragma that functions as described above. + */ + public static + BiConsumer buildInteger( + String name, BiConsumer consumer) { + return (tokenizer, state) -> { + if (!tokenizer.hasMoreTokens()) { + throw new PragmaFormatException("Pragma " + name + + " requires one integer argument"); + } + + String token = tokenizer.nextToken(); + + try { + consumer.accept(Integer.parseInt(token), state); + } catch (NumberFormatException nfex) { + PragmaFormatException pfex = + new PragmaFormatException("Argument " + token + + " to version pragma isn't a valid integer. " + + "This pragma requires a integer argument"); + + pfex.initCause(nfex); + + throw pfex; + } + }; + } + +} -- cgit v1.2.3