diff options
| author | bjculkin <bjculkin@mix.wvu.edu> | 2018-02-12 22:45:04 -0500 |
|---|---|---|
| committer | bjculkin <bjculkin@mix.wvu.edu> | 2018-02-12 22:45:04 -0500 |
| commit | df94066e3af02ff02d5ab4d033a3d603f743234c (patch) | |
| tree | 168a1edaf58d386c175ffb601e9d4da8e13d31e2 /base/src/main/java | |
| parent | ae51c587c53f7ca311e556e3cbd0c5566d6c2843 (diff) | |
Formatting pass
Diffstat (limited to 'base/src/main/java')
160 files changed, 2591 insertions, 2766 deletions
diff --git a/base/src/main/java/bjc/utils/PropertyDB.java b/base/src/main/java/bjc/utils/PropertyDB.java index 713e1e0..9f95d0a 100644 --- a/base/src/main/java/bjc/utils/PropertyDB.java +++ b/base/src/main/java/bjc/utils/PropertyDB.java @@ -45,7 +45,7 @@ public class PropertyDB { * Do the load with the write lock taken. */ loadLock.write(() -> { - if (LOGLOAD) { + if(LOGLOAD) { System.out.println("Reading regex properties:"); } @@ -54,13 +54,13 @@ public class PropertyDB { */ regexes = new SimpleProperties(); regexes.loadFrom(PropertyDB.class.getResourceAsStream("/regexes.sprop"), false); - if (LOGLOAD) { + if(LOGLOAD) { regexes.outputProperties(); System.out.println(); } compiledRegexes = new HashMap<>(); - if (LOGLOAD) { + if(LOGLOAD) { System.out.println("Reading format properties:"); } @@ -69,7 +69,7 @@ public class PropertyDB { */ formats = new SimpleProperties(); formats.loadFrom(PropertyDB.class.getResourceAsStream("/formats.sprop"), false); - if (LOGLOAD) { + if(LOGLOAD) { formats.outputProperties(); System.out.println(); } @@ -80,13 +80,13 @@ public class PropertyDB { * Retrieve a persisted regular expression. * * @param key - * The name of the regular expression. + * The name of the regular expression. * * @return The regular expression with that name. */ public static String getRegex(final String key) { return loadLock.read(() -> { - if (!regexes.containsKey(key)) { + if(!regexes.containsKey(key)) { final String msg = String.format("No regular expression named '%s' found", key); throw new NoSuchElementException(msg); @@ -101,13 +101,13 @@ public class PropertyDB { * expression. * * @param key - * The name of the regular expression. + * The name of the regular expression. * * @return The regular expression with that name. */ public static Pattern getCompiledRegex(final String key) { return loadLock.read(() -> { - if (!regexes.containsKey(key)) { + if(!regexes.containsKey(key)) { final String msg = String.format("No regular expression named '%s' found", key); throw new NoSuchElementException(msg); @@ -126,13 +126,13 @@ public class PropertyDB { * Retrieve a persisted format string. * * @param key - * The name of the format string. + * The name of the format string. * * @return The format string with that name. */ public static String getFormat(final String key) { return loadLock.read(() -> { - if (!formats.containsKey(key)) { + if(!formats.containsKey(key)) { final String msg = String.format("No format string named '%s' found", key); throw new NoSuchElementException(msg); @@ -147,10 +147,10 @@ public class PropertyDB { * arguments. * * @param key - * The name of the format string. + * The name of the format string. * * @param objects - * The parameters to the format string. + * The parameters to the format string. * * @return The format string with that name. */ diff --git a/base/src/main/java/bjc/utils/cli/CLICommander.java b/base/src/main/java/bjc/utils/cli/CLICommander.java index 1504002..ca41c98 100644 --- a/base/src/main/java/bjc/utils/cli/CLICommander.java +++ b/base/src/main/java/bjc/utils/cli/CLICommander.java @@ -24,18 +24,20 @@ public class CLICommander { * Create a new CLI interface powered by streams. * * @param input - * The stream to get user input from. + * The stream to get user input from. * * @param output - * The stream to send normal output to. + * The stream to send normal output to. * * @param error - * The stream to send error output to. + * The stream to send error output to. */ public CLICommander(final InputStream input, final OutputStream output, final OutputStream error) { - if (input == null) throw new NullPointerException("Input stream must not be null"); - else if (output == null) throw new NullPointerException("Output stream must not be null"); - else if (error == null) throw new NullPointerException("Error stream must not be null"); + if(input == null) + throw new NullPointerException("Input stream must not be null"); + else if(output == null) + throw new NullPointerException("Output stream must not be null"); + else if(error == null) throw new NullPointerException("Error stream must not be null"); this.input = input; this.output = output; @@ -46,7 +48,7 @@ public class CLICommander { public void runCommands() { /* Setup output streams. */ final PrintStream normalOutput = new PrintStream(output); - final PrintStream errorOutput = new PrintStream(error); + final PrintStream errorOutput = new PrintStream(error); /* * Set up input streams. @@ -70,15 +72,15 @@ public class CLICommander { int comno = 1; /* * Process commands until we're told to stop, by the mode being - * set to null. + * set to null. */ - while (currentMode != null) { + while(currentMode != null) { /* * Print out the command prompt. * * Use a custom prompt if one is specified. */ - if (currentMode.isCustomPromptEnabled()) { + if(currentMode.isCustomPromptEnabled()) { normalOutput.print(currentMode.getCustomPrompt()); } else { normalOutput.printf("%s (%d)>> ", currentMode.getName(), comno); @@ -90,22 +92,21 @@ public class CLICommander { final String currentLine = inputSource.nextLine(); /* Handle commands we can handle in this mode. */ - if (currentMode.canHandle(currentLine)) { + if(currentMode.canHandle(currentLine)) { final String[] commandTokens = currentLine.split(" "); - String[] commandArgs = null; + String[] commandArgs = null; final int argCount = commandTokens.length; /* Parse args if they are present. */ - if (argCount > 1) { + if(argCount > 1) { commandArgs = Arrays.copyOfRange(commandTokens, 1, argCount); } /* Process command. */ currentMode = currentMode.process(commandTokens[0], commandArgs); } else { - errorOutput.printf("Error: Unrecognized command '%s' (no. %d)\n", - currentLine, comno); + errorOutput.printf("Error: Unrecognized command '%s' (no. %d)\n", currentLine, comno); } } @@ -116,10 +117,10 @@ public class CLICommander { * Set the initial command mode to use. * * @param initialMode - * The initial command mode to use. + * The initial command mode to use. */ public void setInitialCommandMode(final CommandMode initialMode) { - if (initialMode == null) throw new NullPointerException("Initial mode must be non-null"); + if(initialMode == null) throw new NullPointerException("Initial mode must be non-null"); this.initialMode = initialMode; } diff --git a/base/src/main/java/bjc/utils/cli/Command.java b/base/src/main/java/bjc/utils/cli/Command.java index 5969298..7451cf7 100644 --- a/base/src/main/java/bjc/utils/cli/Command.java +++ b/base/src/main/java/bjc/utils/cli/Command.java @@ -9,32 +9,28 @@ public interface Command { /** * Create a command that serves as an alias to this one * - * @return - * A command that serves as an alias to this one + * @return A command that serves as an alias to this one */ Command aliased(); /** * Get the handler that executes this command * - * @return - * The handler that executes this command + * @return The handler that executes this command */ CommandHandler getHandler(); /** * Get the help entry for this command * - * @return - * The help entry for this command + * @return The help entry for this command */ CommandHelp getHelp(); /** * Check if this command is an alias of another command * - * @return - * Whether or not this command is an alias of another + * @return Whether or not this command is an alias of another */ default boolean isAlias() { return false; diff --git a/base/src/main/java/bjc/utils/cli/CommandHandler.java b/base/src/main/java/bjc/utils/cli/CommandHandler.java index fd40aa3..6cc2d68 100644 --- a/base/src/main/java/bjc/utils/cli/CommandHandler.java +++ b/base/src/main/java/bjc/utils/cli/CommandHandler.java @@ -13,11 +13,10 @@ public interface CommandHandler extends Function<String[], CommandMode> { * Execute this command. * * @param args - * The arguments for this command. + * The arguments for this command. * - * @return - * The command mode to switch to after this command, or null to - * stop executing commands. + * @return The command mode to switch to after this command, or null to + * stop executing commands. */ default CommandMode handle(final String[] args) { return this.apply(args); diff --git a/base/src/main/java/bjc/utils/cli/CommandHelp.java b/base/src/main/java/bjc/utils/cli/CommandHelp.java index 90ee404..97d7dad 100644 --- a/base/src/main/java/bjc/utils/cli/CommandHelp.java +++ b/base/src/main/java/bjc/utils/cli/CommandHelp.java @@ -9,8 +9,7 @@ public interface CommandHelp { /** * Get the description of a command. * - * @return - * The description of a command + * @return The description of a command */ String getDescription(); @@ -25,8 +24,7 @@ public interface CommandHelp { * * where anything in angle brackets should be filled in. * - * @return - * The summary line line for a command + * @return The summary line line for a command */ String getSummary(); } diff --git a/base/src/main/java/bjc/utils/cli/CommandMode.java b/base/src/main/java/bjc/utils/cli/CommandMode.java index 0415e27..b33077b 100644 --- a/base/src/main/java/bjc/utils/cli/CommandMode.java +++ b/base/src/main/java/bjc/utils/cli/CommandMode.java @@ -11,11 +11,10 @@ public interface CommandMode extends Comparable<CommandMode> { * Check to see if this mode can handle the specified command. * * @param command - * The command to check. + * The command to check. * - * @return - * Whether or not this mode can handle the command. It is - * assumed not by default. + * @return Whether or not this mode can handle the command. It is + * assumed not by default. */ default boolean canHandle(final String command) { return false; @@ -24,11 +23,10 @@ public interface CommandMode extends Comparable<CommandMode> { /** * Get the custom prompt for this mode. * - * @return - * The custom prompt for this mode. + * @return The custom prompt for this mode. * * @throws UnsupportedOperationException - * If this mode doesn't support a custom prompt. + * If this mode doesn't support a custom prompt. */ default String getCustomPrompt() { throw new UnsupportedOperationException("This mode doesn't support a custom prompt"); @@ -37,9 +35,8 @@ public interface CommandMode extends Comparable<CommandMode> { /** * Get the name of this command mode. * - * @return - * The name of this command mode, or a default string if one isn't - * specified. + * @return The name of this command mode, or a default string if one + * isn't specified. */ public default String getName() { return "(anonymous)"; @@ -48,8 +45,7 @@ public interface CommandMode extends Comparable<CommandMode> { /** * Check if this mode uses a custom prompt. * - * @return - * Whether or not this mode uses a custom prompt. + * @return Whether or not this mode uses a custom prompt. */ default boolean isCustomPromptEnabled() { return false; @@ -59,14 +55,13 @@ public interface CommandMode extends Comparable<CommandMode> { * Process a command in this mode.. * * @param command - * The command to process. + * The command to process. * * @param args - * A list of arguments to the command. + * A list of arguments to the command. * - * @return - * The command mode to use for the next command. Defaults to doing - * nothing, and staying in the current mode. + * @return The command mode to use for the next command. Defaults to + * doing nothing, and staying in the current mode. */ default CommandMode process(final String command, final String[] args) { return this; diff --git a/base/src/main/java/bjc/utils/cli/DelegatingCommand.java b/base/src/main/java/bjc/utils/cli/DelegatingCommand.java index 9e882c2..ff981bd 100644 --- a/base/src/main/java/bjc/utils/cli/DelegatingCommand.java +++ b/base/src/main/java/bjc/utils/cli/DelegatingCommand.java @@ -13,7 +13,7 @@ class DelegatingCommand implements Command { * Create a new command that delegates to another command. * * @param delegate - * The command to delegate to. + * The command to delegate to. */ public DelegatingCommand(final Command delegate) { this.delegate = delegate; diff --git a/base/src/main/java/bjc/utils/cli/GenericCommand.java b/base/src/main/java/bjc/utils/cli/GenericCommand.java index 89539a4..bb624cd 100644 --- a/base/src/main/java/bjc/utils/cli/GenericCommand.java +++ b/base/src/main/java/bjc/utils/cli/GenericCommand.java @@ -16,23 +16,22 @@ public class GenericCommand implements Command { * Create a new generic command. * * @param handler - * The handler to use for the command. + * The handler to use for the command. * * @param description - * The description of the command. May be null, in which - * case a default is provided. + * The description of the command. May be null, in which case a + * default is provided. * * @param help - * The detailed help message for the command. May be - * null, in which case the description is repeated for - * the detailed help. + * The detailed help message for the command. May be null, in + * which case the description is repeated for the detailed help. */ public GenericCommand(final CommandHandler handler, final String description, final String help) { - if (handler == null) throw new NullPointerException("Command handler must not be null"); + if(handler == null) throw new NullPointerException("Command handler must not be null"); this.handler = handler; - if (description == null) { + if(description == null) { this.help = new NullHelp(); } else { this.help = new GenericHelp(description, help); diff --git a/base/src/main/java/bjc/utils/cli/GenericCommandMode.java b/base/src/main/java/bjc/utils/cli/GenericCommandMode.java index e24a17b..a642fe8 100644 --- a/base/src/main/java/bjc/utils/cli/GenericCommandMode.java +++ b/base/src/main/java/bjc/utils/cli/GenericCommandMode.java @@ -29,8 +29,8 @@ public class GenericCommandMode implements CommandMode { private BiConsumer<String, String[]> unknownCommandHandler; /* The functions to use for input/output */ - private final Consumer<String> errorOutput; - private final Consumer<String> normalOutput; + private final Consumer<String> errorOutput; + private final Consumer<String> normalOutput; /* The name of this command mode, or null if it is unnamed */ private String modeName; @@ -42,22 +42,23 @@ public class GenericCommandMode implements CommandMode { * Create a new generic command mode * * @param normalOutput - * The function to use for normal output. + * The function to use for normal output. * * @param errorOutput - * The function to use for error output. + * The function to use for error output. */ public GenericCommandMode(final Consumer<String> normalOutput, final Consumer<String> errorOutput) { - if (normalOutput == null) throw new NullPointerException("Normal output source must be non-null"); - else if (errorOutput == null) throw new NullPointerException("Error output source must be non-null"); + if(normalOutput == null) + throw new NullPointerException("Normal output source must be non-null"); + else if(errorOutput == null) throw new NullPointerException("Error output source must be non-null"); this.normalOutput = normalOutput; - this.errorOutput = errorOutput; + this.errorOutput = errorOutput; /* Initialize maps so that they sort in alphabetical order. */ commandHandlers = new FunctionalMap<>(new TreeMap<>()); defaultHandlers = new FunctionalMap<>(new TreeMap<>()); - helpTopics = new FunctionalMap<>(new TreeMap<>()); + helpTopics = new FunctionalMap<>(new TreeMap<>()); /* Setup default commands. */ setupDefaultCommands(); @@ -67,25 +68,25 @@ public class GenericCommandMode implements CommandMode { * Add an alias to an existing command. * * @param commandName - * The name of the command to add an alias for. + * The name of the command to add an alias for. * * @param aliasName - * The new alias for the command. + * The new alias for the command. * * @throws IllegalArgumentException - * If the specified command doesn't have a bound handler, or if the - * alias name already has a bound value. + * If the specified command doesn't have a bound handler, or if + * the alias name already has a bound value. */ public void addCommandAlias(final String commandName, final String aliasName) { - if (commandName == null) { + if(commandName == null) { throw new NullPointerException("Command name must not be null"); - } else if (aliasName == null) { + } else if(aliasName == null) { String msg = "Alias name must not be null"; throw new NullPointerException(msg); - } else if (!commandHandlers.containsKey(commandName) && !defaultHandlers.containsKey(commandName)) { + } else if(!commandHandlers.containsKey(commandName) && !defaultHandlers.containsKey(commandName)) { String msg = String.format("Cannot alias non-existant command '%s'", commandName); throw new IllegalArgumentException(msg); - } else if (commandHandlers.containsKey(aliasName) || defaultHandlers.containsKey(aliasName)) { + } else if(commandHandlers.containsKey(aliasName) || defaultHandlers.containsKey(aliasName)) { String msg = String.format("Cannot bind alias '%s' to an already bound command.", aliasName); throw new IllegalArgumentException(msg); } else { @@ -93,7 +94,7 @@ public class GenericCommandMode implements CommandMode { Command aliasedCommand; /* Get the alias. */ - if (defaultHandlers.containsKey(commandName)) { + if(defaultHandlers.containsKey(commandName)) { aliasedCommand = defaultHandlers.get(commandName).aliased(); } else { aliasedCommand = commandHandlers.get(commandName).aliased(); @@ -107,20 +108,20 @@ public class GenericCommandMode implements CommandMode { * Add a command to this command mode. * * @param command - * The name of the command to add. + * The name of the command to add. * * @param handler - * The handler to use for the specified command. + * The handler to use for the specified command. * * @throws IllegalArgumentException - * If the specified command already has a handler registered. + * If the specified command already has a handler registered. */ public void addCommandHandler(final String command, final Command handler) { - if (command == null) { + if(command == null) { throw new NullPointerException("Command must not be null"); - } else if (handler == null) { + } else if(handler == null) { throw new NullPointerException("Handler must not be null"); - } else if (canHandle(command)) { + } else if(canHandle(command)) { String msg = String.format("Command '%s' already has a registered handler"); throw new IllegalArgumentException(msg); } else { @@ -132,10 +133,10 @@ public class GenericCommandMode implements CommandMode { * Add a help topic to this command mode that isn't tied to a command. * * @param topicName - * The name of the topic. + * The name of the topic. * * @param topic - * The contents of the topic. + * The contents of the topic. */ public void addHelpTopic(final String topicName, final CommandHelp topic) { helpTopics.put(topicName, topic); @@ -143,9 +144,8 @@ public class GenericCommandMode implements CommandMode { /* Default command builders */ /* - * @TODO 10/09/17 Ben Culkin :CommandExtraction - * These command messages should be extracted into some kind of - * file-based abstraction. + * @TODO 10/09/17 Ben Culkin :CommandExtraction These command messages + * should be extracted into some kind of file-based abstraction. */ private GenericCommand buildAliasCommand() { final String aliasShortHelp = "alias\tAlias one command to another"; @@ -191,7 +191,7 @@ public class GenericCommandMode implements CommandMode { + " while invoking with the name of a topic will print the entry" + " for that topic"; return new GenericCommand((args) -> { - if (args == null || args.length == 0) { + if(args == null || args.length == 0) { /* Invoke general help */ doHelpSummary(); } else { @@ -222,18 +222,19 @@ public class GenericCommandMode implements CommandMode { /* Implement default commands */ private void doAliasCommands(final String[] args) { - if (args.length != 2) { - String msg = String.format("ERROR: Alias requires two arguments. The command name, and the alias for that command. "); + if(args.length != 2) { + String msg = String.format( + "ERROR: Alias requires two arguments. The command name, and the alias for that command. "); errorOutput.accept(msg); } else { final String commandName = args[0]; final String aliasName = args[1]; - if (!canHandle(commandName)) { + if(!canHandle(commandName)) { String msg = String.format("ERROR: '%s' is not a valid command.", commandName); errorOutput.accept(msg); - } else if (canHandle(aliasName)) { + } else if(canHandle(aliasName)) { String msg = String.format("ERROR: Cannot overwrite command '%s'", aliasName); errorOutput.accept(msg); @@ -244,15 +245,15 @@ public class GenericCommandMode implements CommandMode { } private void doHelpCommand(final String commandName) { - if (commandHandlers.containsKey(commandName)) { + if(commandHandlers.containsKey(commandName)) { final String desc = commandHandlers.get(commandName).getHelp().getDescription(); normalOutput.accept("\n" + desc); - } else if (defaultHandlers.containsKey(commandName)) { + } else if(defaultHandlers.containsKey(commandName)) { final String desc = defaultHandlers.get(commandName).getHelp().getDescription(); normalOutput.accept("\n" + desc); - } else if (helpTopics.containsKey(commandName)) { + } else if(helpTopics.containsKey(commandName)) { normalOutput.accept("\n" + helpTopics.get(commandName).getDescription()); } else { String msg = String.format("ERROR: No help available for '%s'", commandName); @@ -264,11 +265,11 @@ public class GenericCommandMode implements CommandMode { private void doHelpSummary() { normalOutput.accept("Help topics for this command mode are as follows:\n"); - if (commandHandlers.size() > 0) { + if(commandHandlers.size() > 0) { commandHandlers.forEachValue(command -> { - if (!command.isAlias()) { + if(!command.isAlias()) { String comLine = command.getHelp().getSummary(); - String msg = String.format("\t%s\n", comLine); + String msg = String.format("\t%s\n", comLine); normalOutput.accept(msg); } @@ -278,16 +279,15 @@ public class GenericCommandMode implements CommandMode { } normalOutput.accept("\nHelp topics available in all command modes are as follows\n"); - if (defaultHandlers.size() > 0) { + if(defaultHandlers.size() > 0) { /* - * @NOTE - * This block here should be abstracted out into a - * method. + * @NOTE This block here should be abstracted out into a + * method. */ defaultHandlers.forEachValue(command -> { - if (!command.isAlias()) { + if(!command.isAlias()) { String comLine = command.getHelp().getSummary(); - String msg = String.format("\t%s\n", comLine); + String msg = String.format("\t%s\n", comLine); normalOutput.accept(msg); } @@ -297,7 +297,7 @@ public class GenericCommandMode implements CommandMode { } normalOutput.accept("\nHelp topics not associated with a command are as follows\n"); - if (helpTopics.size() > 0) { + if(helpTopics.size() > 0) { helpTopics.forEachValue(topic -> { String msg = String.format("\t%s\n", topic.getSummary()); @@ -329,14 +329,14 @@ public class GenericCommandMode implements CommandMode { @Override public String getCustomPrompt() { - if (customPrompt != null) return customPrompt; + if(customPrompt != null) return customPrompt; return CommandMode.super.getCustomPrompt(); } @Override public String getName() { - if (modeName != null) return modeName; + if(modeName != null) return modeName; return CommandMode.super.getName(); } @@ -350,15 +350,15 @@ public class GenericCommandMode implements CommandMode { public CommandMode process(final String command, final String[] args) { normalOutput.accept("\n"); - if (defaultHandlers.containsKey(command)) + if(defaultHandlers.containsKey(command)) return defaultHandlers.get(command).getHandler().handle(args); - else if (commandHandlers.containsKey(command)) + else if(commandHandlers.containsKey(command)) return commandHandlers.get(command).getHandler().handle(args); else { - if (args != null) { + if(args != null) { String argString = String.join(", ", args); - String msg = String.format("ERROR: Unrecognized command %s (arguments %s)", - command, argString); + String msg = String.format("ERROR: Unrecognized command %s (arguments %s)", command, + argString); errorOutput.accept(msg); } else { @@ -367,7 +367,7 @@ public class GenericCommandMode implements CommandMode { errorOutput.accept(msg); } - if (unknownCommandHandler == null) { + if(unknownCommandHandler == null) { String msg = String.format("Command %s is invalid", command); throw new UnsupportedOperationException(msg); @@ -383,8 +383,8 @@ public class GenericCommandMode implements CommandMode { * Set the custom prompt for this mode * * @param prompt - * The custom prompt for this mode, or null to disable the custom - * prompt + * The custom prompt for this mode, or null to disable the custom + * prompt */ public void setCustomPrompt(final String prompt) { customPrompt = prompt; @@ -394,7 +394,7 @@ public class GenericCommandMode implements CommandMode { * Set the name of this mode * * @param name - * The desired name of this mode, or null to use the default name + * The desired name of this mode, or null to use the default name */ public void setModeName(final String name) { modeName = name; @@ -404,29 +404,28 @@ public class GenericCommandMode implements CommandMode { * Set the handler to use for unknown commands * * @param handler - * The handler to use for unknown commands, or null to throw on - * unknown commands + * The handler to use for unknown commands, or null to throw on + * unknown commands */ public void setUnknownCommandHandler(final BiConsumer<String, String[]> handler) { - if (handler == null) throw new NullPointerException("Handler must not be null"); + if(handler == null) throw new NullPointerException("Handler must not be null"); unknownCommandHandler = handler; } /* Setup default commands. */ private void setupDefaultCommands() { - defaultHandlers.put("list", buildListCommand()); + defaultHandlers.put("list", buildListCommand()); defaultHandlers.put("alias", buildAliasCommand()); - defaultHandlers.put("help", buildHelpCommand()); + defaultHandlers.put("help", buildHelpCommand()); /* Help unix people :) */ addCommandAlias("help", "man"); /* Add commands handled in a upper layer. */ /* - * @NOTE - * Figure out a place to put commands that apply across all - * modes, but only to a specific application. + * @NOTE Figure out a place to put commands that apply across + * all modes, but only to a specific application. */ defaultHandlers.put("clear", buildClearCommands()); defaultHandlers.put("exit", buildExitCommand()); @@ -442,30 +441,30 @@ public class GenericCommandMode implements CommandMode { final StringBuilder builder = new StringBuilder(); builder.append("GenericCommandMode ["); - if (commandHandlers != null) { + if(commandHandlers != null) { builder.append("commandHandlers="); builder.append(commandHandlers); } - if (defaultHandlers != null) { + if(defaultHandlers != null) { builder.append(", "); builder.append("defaultHandlers="); builder.append(defaultHandlers); } - if (helpTopics != null) { + if(helpTopics != null) { builder.append(", "); builder.append("helpTopics="); builder.append(helpTopics); } - if (modeName != null) { + if(modeName != null) { builder.append(", "); builder.append("modeName="); builder.append(modeName); } - if (customPrompt != null) { + if(customPrompt != null) { builder.append(", "); builder.append("customPrompt="); builder.append(customPrompt); diff --git a/base/src/main/java/bjc/utils/cli/GenericHelp.java b/base/src/main/java/bjc/utils/cli/GenericHelp.java index 92c1eef..9fca3a9 100644 --- a/base/src/main/java/bjc/utils/cli/GenericHelp.java +++ b/base/src/main/java/bjc/utils/cli/GenericHelp.java @@ -14,24 +14,24 @@ public class GenericHelp implements CommandHelp { * Create a new help topic. * * @param summary - * The summary of this help topic. + * The summary of this help topic. * * @param description - * The description of this help topic, or null if this help topic - * doesn't have a more detailed description. + * The description of this help topic, or null if this help topic + * doesn't have a more detailed description. */ public GenericHelp(final String summary, final String description) { - if (summary == null) { + if(summary == null) { throw new NullPointerException("Help summary must be non-null"); } - this.summary = summary; + this.summary = summary; this.description = description; } @Override public String getDescription() { - if (description == null) { + if(description == null) { return summary; } @@ -49,12 +49,12 @@ public class GenericHelp implements CommandHelp { builder.append("GenericHelp ["); - if (summary != null) { + if(summary != null) { builder.append("summary="); builder.append(summary); } - if (description != null) { + if(description != null) { builder.append(", "); builder.append("description="); builder.append(description); diff --git a/base/src/main/java/bjc/utils/components/ComponentDescription.java b/base/src/main/java/bjc/utils/components/ComponentDescription.java index 4f52ace..222dc09 100644 --- a/base/src/main/java/bjc/utils/components/ComponentDescription.java +++ b/base/src/main/java/bjc/utils/components/ComponentDescription.java @@ -10,39 +10,39 @@ public class ComponentDescription implements IDescribedComponent { @SuppressWarnings("unused") private static void sanityCheckArgs(final String name, final String author, final String description, final int version) { - if (name == null) { + if(name == null) { throw new NullPointerException("Component name can't be null"); - } else if (version <= 0) { + } else if(version <= 0) { throw new IllegalArgumentException("Component version must be greater than 0"); } } /** The author of the component */ - private final String author; + private final String author; /** The description of the component */ - private final String description; + private final String description; /** The name of the component */ - private final String name; + private final String name; /** The version of the component */ - private final int version; + private final int version; /** * Create a new component description. * * @param name - * The name of the component. + * The name of the component. * * @param author - * The author of the component. + * The author of the component. * * @param description - * The description of the component. + * The description of the component. * * @param version - * The version of the component. + * The version of the component. * * @throws IllegalArgumentException - * Thrown if version is less than 1. + * Thrown if version is less than 1. */ public ComponentDescription(final String name, final String author, final String description, final int version) { @@ -56,7 +56,7 @@ public class ComponentDescription implements IDescribedComponent { @Override public String getAuthor() { - if (author == null) { + if(author == null) { return IDescribedComponent.super.getAuthor(); } @@ -65,7 +65,7 @@ public class ComponentDescription implements IDescribedComponent { @Override public String getDescription() { - if (description == null) { + if(description == null) { return IDescribedComponent.super.getDescription(); } @@ -112,25 +112,25 @@ public class ComponentDescription implements IDescribedComponent { */ @Override public boolean equals(final Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; + if(this == obj) return true; + if(obj == null) return false; + if(getClass() != obj.getClass()) return false; final ComponentDescription other = (ComponentDescription) obj; - if (author == null) { - if (other.author != null) return false; - } else if (!author.equals(other.author)) return false; + if(author == null) { + if(other.author != null) return false; + } else if(!author.equals(other.author)) return false; - if (description == null) { - if (other.description != null) return false; - } else if (!description.equals(other.description)) return false; + if(description == null) { + if(other.description != null) return false; + } else if(!description.equals(other.description)) return false; - if (name == null) { - if (other.name != null) return false; - } else if (!name.equals(other.name)) return false; + if(name == null) { + if(other.name != null) return false; + } else if(!name.equals(other.name)) return false; - if (version != other.version) return false; + if(version != other.version) return false; return true; } diff --git a/base/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java b/base/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java index 3855f8f..c720cbf 100644 --- a/base/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java +++ b/base/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java @@ -38,19 +38,19 @@ public class ComponentDescriptionFileParser { * Parse a component description from a stream. * * @param inputSource - * The stream to parse from. + * The stream to parse from. * * @return The description parsed from the stream. */ public static ComponentDescription fromStream(final InputStream inputSource) { - if (inputSource == null) { + if(inputSource == null) { throw new NullPointerException("Input source must not be null"); } ComponentDescriptionState state = new ComponentDescriptionState(); /* * This is valid, because the thing that is returned is the same - * reference we passed in. + * reference we passed in. */ reader.fromStream(inputSource, state); diff --git a/base/src/main/java/bjc/utils/components/ComponentDescriptionState.java b/base/src/main/java/bjc/utils/components/ComponentDescriptionState.java index f944a9e..aea886e 100644 --- a/base/src/main/java/bjc/utils/components/ComponentDescriptionState.java +++ b/base/src/main/java/bjc/utils/components/ComponentDescriptionState.java @@ -22,7 +22,7 @@ public class ComponentDescriptionState { * Set the author of this component. * * @param author - * The author of this component. + * The author of this component. */ public void setAuthor(final String author) { this.author = author; @@ -32,7 +32,7 @@ public class ComponentDescriptionState { * Set the description of this component. * * @param description - * The description of this component. + * The description of this component. */ public void setDescription(final String description) { this.description = description; @@ -42,7 +42,7 @@ public class ComponentDescriptionState { * Set the name of this component. * * @param name - * The name of this component. + * The name of this component. */ public void setName(final String name) { this.name = name; @@ -52,7 +52,7 @@ public class ComponentDescriptionState { * Set the version of this component. * * @param version - * The version of this component. + * The version of this component. */ public void setVersion(final int version) { this.version = version; @@ -61,8 +61,7 @@ public class ComponentDescriptionState { /** * Convert this state into the description it represents. * - * @return - * The description represented by this state. + * @return The description represented by this state. */ public ComponentDescription toDescription() { return new ComponentDescription(name, author, description, version); @@ -71,7 +70,7 @@ public class ComponentDescriptionState { @Override public int hashCode() { final int prime = 31; - int result = 1; + int result = 1; result = prime * result + (author == null ? 0 : author.hashCode()); result = prime * result + (description == null ? 0 : description.hashCode()); @@ -83,25 +82,25 @@ public class ComponentDescriptionState { @Override public boolean equals(final Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; + if(this == obj) return true; + if(obj == null) return false; + if(getClass() != obj.getClass()) return false; final ComponentDescriptionState other = (ComponentDescriptionState) obj; - if (author == null) { - if (other.author != null) return false; - } else if (!author.equals(other.author)) return false; + if(author == null) { + if(other.author != null) return false; + } else if(!author.equals(other.author)) return false; - if (description == null) { - if (other.description != null) return false; - } else if (!description.equals(other.description)) return false; + if(description == null) { + if(other.description != null) return false; + } else if(!description.equals(other.description)) return false; - if (name == null) { - if (other.name != null) return false; - } else if (!name.equals(other.name)) return false; + if(name == null) { + if(other.name != null) return false; + } else if(!name.equals(other.name)) return false; - if (version != other.version) return false; + if(version != other.version) return false; return true; } @@ -116,19 +115,19 @@ public class ComponentDescriptionState { final StringBuilder builder = new StringBuilder(); builder.append("ComponentDescriptionState ["); - if (name != null) { + if(name != null) { builder.append("name="); builder.append(name); builder.append(", "); } - if (description != null) { + if(description != null) { builder.append("description="); builder.append(description); builder.append(", "); } - if (author != null) { + if(author != null) { builder.append("author="); builder.append(author); builder.append(", "); diff --git a/base/src/main/java/bjc/utils/components/FileComponentRepository.java b/base/src/main/java/bjc/utils/components/FileComponentRepository.java index 284c10c..cbf5aa9 100644 --- a/base/src/main/java/bjc/utils/components/FileComponentRepository.java +++ b/base/src/main/java/bjc/utils/components/FileComponentRepository.java @@ -22,7 +22,7 @@ import bjc.utils.funcutils.FileUtils; * @author ben * * @param <ComponentType> - * The type of component being read in. + * The type of component being read in. */ public class FileComponentRepository<ComponentType extends IDescribedComponent> implements IComponentRepository<ComponentType> { @@ -43,22 +43,23 @@ public class FileComponentRepository<ComponentType extends IDescribedComponent> * the loading of that component to fail, but a warning will be logged. * * @param directory - * The directory to read component files from. + * The directory to read component files from. * * @param componentReader - * The function to use to convert files to components. + * The function to use to convert files to components. */ public FileComponentRepository(final File directory, final Function<File, ? extends ComponentType> componentReader) { /* Make sure we have valid arguments. */ - if (directory == null) { + if(directory == null) { throw new NullPointerException("Directory must not be null"); - } else if (!directory.isDirectory()) { - String msg = String.format("File %s is not a directory. Components can only be read from a directory.", + } else if(!directory.isDirectory()) { + String msg = String.format( + "File %s is not a directory. Components can only be read from a directory.", directory); throw new IllegalArgumentException(msg); - } else if (componentReader == null) { + } else if(componentReader == null) { throw new NullPointerException("Component reader must not be null"); } @@ -74,8 +75,8 @@ public class FileComponentRepository<ComponentType extends IDescribedComponent> * but not recurse into sub-directories. */ final BiPredicate<Path, BasicFileAttributes> firstLevelTraverser = (pth, attr) -> { - if (attr.isDirectory() && !isFirstDir.getValue()) { - /* + if(attr.isDirectory() && !isFirstDir.getValue()) { + /* * Skip directories, they probably have * component support files. */ @@ -96,10 +97,13 @@ public class FileComponentRepository<ComponentType extends IDescribedComponent> FileUtils.traverseDirectory(sourceDirectory, firstLevelTraverser, (pth, attr) -> { loadComponent(componentReader, pth); - /* Keep loading components, even if this one failed. */ + /* + * Keep loading components, even if this one + * failed. + */ return true; }); - } catch (final IOException ioex) { + } catch(final IOException ioex) { CLASS_LOGGER.log(Level.WARNING, ioex, () -> "Error found reading component from file."); } } @@ -130,16 +134,16 @@ public class FileComponentRepository<ComponentType extends IDescribedComponent> /* Try to load the component. */ final ComponentType component = componentReader.apply(pth.toFile()); - if (component == null) { + if(component == null) { throw new NullPointerException("Component reader read null component"); - } else if (!components.containsKey(component.getName())) { + } else if(!components.containsKey(component.getName())) { /* * We only care about the latest version of a - * component. + * component. */ final ComponentType oldComponent = components.put(component.getName(), component); - if (oldComponent.getVersion() > component.getVersion()) { + if(oldComponent.getVersion() > component.getVersion()) { components.put(oldComponent.getName(), oldComponent); } } else { @@ -152,16 +156,16 @@ public class FileComponentRepository<ComponentType extends IDescribedComponent> CLASS_LOGGER.warning(sb.toString()); } - } catch (final Exception ex) { - String msg = String.format("Error found reading component from file %s. It will not be loaded.", pth.toString()); + } catch(final Exception ex) { + String msg = String.format("Error found reading component from file %s. It will not be loaded.", + pth.toString()); CLASS_LOGGER.log(Level.WARNING, ex, () -> msg); } } /* - * @NOTE - * Should this be changed to something more readable? + * @NOTE Should this be changed to something more readable? * * (non-Javadoc) * @@ -172,13 +176,13 @@ public class FileComponentRepository<ComponentType extends IDescribedComponent> final StringBuilder builder = new StringBuilder(); builder.append("FileComponentRepository ["); - if (components != null) { + if(components != null) { builder.append("components="); builder.append(components); builder.append(", "); } - if (sourceDirectory != null) { + if(sourceDirectory != null) { builder.append("sourceDirectory="); builder.append(sourceDirectory); } diff --git a/base/src/main/java/bjc/utils/components/IComponentRepository.java b/base/src/main/java/bjc/utils/components/IComponentRepository.java index 099693f..8ecd446 100644 --- a/base/src/main/java/bjc/utils/components/IComponentRepository.java +++ b/base/src/main/java/bjc/utils/components/IComponentRepository.java @@ -10,15 +10,14 @@ import bjc.utils.funcdata.IMap; * @author ben * * @param <ComponentType> - * The type of components contained in this repository. + * The type of components contained in this repository. */ public interface IComponentRepository<ComponentType extends IDescribedComponent> { /** * Get all of the components this repository knows about. * - * @return - * A map from component name to component, containing all of the - * components in the repositories. + * @return A map from component name to component, containing all of the + * components in the repositories. */ public IMap<String, ComponentType> getAll(); @@ -26,18 +25,17 @@ public interface IComponentRepository<ComponentType extends IDescribedComponent> * Get a component with a specific name. * * @param name - * The name of the component to retrieve. + * The name of the component to retrieve. * - * @return - * The named component, or null if no component with that name exists. + * @return The named component, or null if no component with that name + * exists. */ public ComponentType getByName(String name); /** * Get a list of all the registered components. * - * @return - * A list of all the registered components. + * @return A list of all the registered components. */ public default IList<ComponentType> getList() { return getAll().valueList(); @@ -46,8 +44,7 @@ public interface IComponentRepository<ComponentType extends IDescribedComponent> /** * Get the source from which these components came. * - * @return - * The source from which these components came. + * @return The source from which these components came. */ public String getSource(); } diff --git a/base/src/main/java/bjc/utils/components/IDescribedComponent.java b/base/src/main/java/bjc/utils/components/IDescribedComponent.java index 78af4bc..6921849 100644 --- a/base/src/main/java/bjc/utils/components/IDescribedComponent.java +++ b/base/src/main/java/bjc/utils/components/IDescribedComponent.java @@ -13,8 +13,7 @@ public interface IDescribedComponent extends Comparable<IDescribedComponent> { * * Providing this is optional, with "Anonymous" as the default author. * - * @return - * The author of the component. + * @return The author of the component. */ default String getAuthor() { return "Anonymous"; @@ -26,8 +25,7 @@ public interface IDescribedComponent extends Comparable<IDescribedComponent> { * Providing this is optional, with the default being a note that no * description was provided. * - * @return - * The description of the component + * @return The description of the component */ default String getDescription() { return "No description provided."; @@ -38,8 +36,7 @@ public interface IDescribedComponent extends Comparable<IDescribedComponent> { * * This is the only thing required of all components. * - * @return - * The name of the component. + * @return The name of the component. */ String getName(); @@ -48,8 +45,7 @@ public interface IDescribedComponent extends Comparable<IDescribedComponent> { * * Providing this is optional, with "1" as the default version. * - * @return - * The version of this component. + * @return The version of this component. */ default int getVersion() { return 1; @@ -59,7 +55,7 @@ public interface IDescribedComponent extends Comparable<IDescribedComponent> { default int compareTo(final IDescribedComponent o) { int res = getName().compareTo(o.getName()); - if (res == 0) { + if(res == 0) { res = getVersion() - o.getVersion(); } diff --git a/base/src/main/java/bjc/utils/data/BooleanToggle.java b/base/src/main/java/bjc/utils/data/BooleanToggle.java index 280b90d..542d2b6 100644 --- a/base/src/main/java/bjc/utils/data/BooleanToggle.java +++ b/base/src/main/java/bjc/utils/data/BooleanToggle.java @@ -21,7 +21,7 @@ public class BooleanToggle implements Toggle<Boolean> { * Create a flip-flop with the specified initial value. * * @param initial - * The initial value of the flip-flop. + * The initial value of the flip-flop. */ public BooleanToggle(final boolean initial) { val = initial; @@ -59,13 +59,13 @@ public class BooleanToggle implements Toggle<Boolean> { @Override public boolean equals(final Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (!(obj instanceof BooleanToggle)) return false; + if(this == obj) return true; + if(obj == null) return false; + if(!(obj instanceof BooleanToggle)) return false; final BooleanToggle other = (BooleanToggle) obj; - if (val != other.val) return false; + if(val != other.val) return false; return true; } diff --git a/base/src/main/java/bjc/utils/data/CircularIterator.java b/base/src/main/java/bjc/utils/data/CircularIterator.java index 60f815c..507ee01 100644 --- a/base/src/main/java/bjc/utils/data/CircularIterator.java +++ b/base/src/main/java/bjc/utils/data/CircularIterator.java @@ -8,7 +8,7 @@ import java.util.Iterator; * @author EVE * * @param <E> - * The type of the iterable. + * The type of the iterable. */ public class CircularIterator<E> implements Iterator<E> { /* The iterable, and our current iterator into it. */ @@ -28,11 +28,11 @@ public class CircularIterator<E> implements Iterator<E> { * Create a new circular iterator. * * @param src - * The iterable to iterate from. + * The iterable to iterate from. * * @param circ - * Should we actually do circular iteration, or just - * repeat the terminal element? + * Should we actually do circular iteration, or just repeat the + * terminal element? */ public CircularIterator(final Iterable<E> src, final boolean circ) { source = src; @@ -45,7 +45,7 @@ public class CircularIterator<E> implements Iterator<E> { * Create a new circular iterator that does actual circular iteration. * * @param src - * The iterable to iterate from. + * The iterable to iterate from. */ public CircularIterator(final Iterable<E> src) { this(src, true); @@ -59,10 +59,11 @@ public class CircularIterator<E> implements Iterator<E> { @Override public E next() { - if (!curr.hasNext()) { - if (doCircle) { + if(!curr.hasNext()) { + if(doCircle) { curr = source.iterator(); - } else return curElm; + } else + return curElm; } curElm = curr.next(); diff --git a/base/src/main/java/bjc/utils/data/Either.java b/base/src/main/java/bjc/utils/data/Either.java index 20a06f5..6023b60 100644 --- a/base/src/main/java/bjc/utils/data/Either.java +++ b/base/src/main/java/bjc/utils/data/Either.java @@ -9,10 +9,10 @@ import java.util.function.Function; * @author ben * * @param <LeftType> - * The type that could be on the left. + * The type that could be on the left. * * @param <RightType> - * The type that could be on the right. + * The type that could be on the right. * */ public class Either<LeftType, RightType> implements IPair<LeftType, RightType> { @@ -20,16 +20,15 @@ public class Either<LeftType, RightType> implements IPair<LeftType, RightType> { * Create a new either with the left value occupied. * * @param <LeftType> - * The type of the left value. + * The type of the left value. * * @param <RightType> - * The type of the empty right value. - * + * The type of the empty right value. + * * @param left - * The value to put on the left. + * The value to put on the left. * - * @return - * An either with the left side occupied. + * @return An either with the left side occupied. */ public static <LeftType, RightType> Either<LeftType, RightType> left(final LeftType left) { return new Either<>(left, null); @@ -39,16 +38,15 @@ public class Either<LeftType, RightType> implements IPair<LeftType, RightType> { * Create a new either with the right value occupied. * * @param <LeftType> - * The type of the empty left value. + * The type of the empty left value. * * @param <RightType> - * The type of the right value. + * The type of the right value. * * @param right - * The value to put on the right. + * The value to put on the right. * - * @return - * An either with the right side occupied. + * @return An either with the right side occupied. */ public static <LeftType, RightType> Either<LeftType, RightType> right(final RightType right) { return new Either<>(null, right); @@ -63,7 +61,7 @@ public class Either<LeftType, RightType> implements IPair<LeftType, RightType> { /* Create a new either with specifed values. */ private Either(final LeftType left, final RightType right) { - if (left == null) { + if(left == null) { rightVal = right; } else { leftVal = left; @@ -75,7 +73,7 @@ public class Either<LeftType, RightType> implements IPair<LeftType, RightType> { @Override public <BoundLeft, BoundRight> IPair<BoundLeft, BoundRight> bind( final BiFunction<LeftType, RightType, IPair<BoundLeft, BoundRight>> binder) { - if (binder == null) throw new NullPointerException("Binder must not be null"); + if(binder == null) throw new NullPointerException("Binder must not be null"); return binder.apply(leftVal, rightVal); } @@ -83,9 +81,9 @@ public class Either<LeftType, RightType> implements IPair<LeftType, RightType> { @Override public <BoundLeft> IPair<BoundLeft, RightType> bindLeft( final Function<LeftType, IPair<BoundLeft, RightType>> leftBinder) { - if (leftBinder == null) throw new NullPointerException("Left binder must not be null"); + if(leftBinder == null) throw new NullPointerException("Left binder must not be null"); - if (isLeft) return leftBinder.apply(leftVal); + if(isLeft) return leftBinder.apply(leftVal); return new Either<>(null, rightVal); } @@ -93,9 +91,9 @@ public class Either<LeftType, RightType> implements IPair<LeftType, RightType> { @Override public <BoundRight> IPair<LeftType, BoundRight> bindRight( final Function<RightType, IPair<LeftType, BoundRight>> rightBinder) { - if (rightBinder == null) throw new NullPointerException("Right binder must not be null"); + if(rightBinder == null) throw new NullPointerException("Right binder must not be null"); - if (isLeft) return new Either<>(leftVal, null); + if(isLeft) return new Either<>(leftVal, null); return rightBinder.apply(rightVal); } @@ -105,15 +103,15 @@ public class Either<LeftType, RightType> implements IPair<LeftType, RightType> { final IPair<OtherLeft, OtherRight> otherPair, final BiFunction<LeftType, OtherLeft, CombinedLeft> leftCombiner, final BiFunction<RightType, OtherRight, CombinedRight> rightCombiner) { - if (otherPair == null) { + if(otherPair == null) { throw new NullPointerException("Other pair must not be null"); - } else if (leftCombiner == null) { + } else if(leftCombiner == null) { throw new NullPointerException("Left combiner must not be null"); - } else if (rightCombiner == null) { + } else if(rightCombiner == null) { throw new NullPointerException("Right combiner must not be null"); } - if (isLeft) { + if(isLeft) { return otherPair.bind((otherLeft, otherRight) -> { CombinedLeft cLeft = leftCombiner.apply(leftVal, otherLeft); @@ -130,25 +128,25 @@ public class Either<LeftType, RightType> implements IPair<LeftType, RightType> { @Override public <NewLeft> IPair<NewLeft, RightType> mapLeft(final Function<LeftType, NewLeft> mapper) { - if (mapper == null) throw new NullPointerException("Mapper must not be null"); + if(mapper == null) throw new NullPointerException("Mapper must not be null"); - if (isLeft) return new Either<>(mapper.apply(leftVal), null); + if(isLeft) return new Either<>(mapper.apply(leftVal), null); return new Either<>(null, rightVal); } @Override public <NewRight> IPair<LeftType, NewRight> mapRight(final Function<RightType, NewRight> mapper) { - if (mapper == null) throw new NullPointerException("Mapper must not be null"); + if(mapper == null) throw new NullPointerException("Mapper must not be null"); - if (isLeft) return new Either<>(leftVal, null); + if(isLeft) return new Either<>(leftVal, null); return new Either<>(null, mapper.apply(rightVal)); } @Override public <MergedType> MergedType merge(final BiFunction<LeftType, RightType, MergedType> merger) { - if (merger == null) throw new NullPointerException("Merger must not be null"); + if(merger == null) throw new NullPointerException("Merger must not be null"); return merger.apply(leftVal, rightVal); } @@ -167,21 +165,21 @@ public class Either<LeftType, RightType> implements IPair<LeftType, RightType> { @Override public boolean equals(final Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (!(obj instanceof Either<?, ?>)) return false; + if(this == obj) return true; + if(obj == null) return false; + if(!(obj instanceof Either<?, ?>)) return false; final Either<?, ?> other = (Either<?, ?>) obj; - if (isLeft != other.isLeft) return false; + if(isLeft != other.isLeft) return false; - if (leftVal == null) { - if (other.leftVal != null) return false; - } else if (!leftVal.equals(other.leftVal)) return false; + if(leftVal == null) { + if(other.leftVal != null) return false; + } else if(!leftVal.equals(other.leftVal)) return false; - if (rightVal == null) { - if (other.rightVal != null) return false; - } else if (!rightVal.equals(other.rightVal)) return false; + if(rightVal == null) { + if(other.rightVal != null) return false; + } else if(!rightVal.equals(other.rightVal)) return false; return true; } diff --git a/base/src/main/java/bjc/utils/data/GeneratingIterator.java b/base/src/main/java/bjc/utils/data/GeneratingIterator.java index 92d10a5..8e6bcd2 100644 --- a/base/src/main/java/bjc/utils/data/GeneratingIterator.java +++ b/base/src/main/java/bjc/utils/data/GeneratingIterator.java @@ -10,7 +10,7 @@ import java.util.function.UnaryOperator; * @author bjculkin * * @param <E> - * The type of element generated. + * The type of element generated. */ public class GeneratingIterator<E> implements Iterator<E> { /* Our current state. */ @@ -24,14 +24,14 @@ public class GeneratingIterator<E> implements Iterator<E> { * Create a new generative iterator. * * @param initial - * The initial state of the generator. + * The initial state of the generator. * * @param transition - * The function to apply to the state. + * The function to apply to the state. * * @param stopper - * The predicate applied to the current state to - * determine when to stop. + * The predicate applied to the current state to determine when + * to stop. */ public GeneratingIterator(E initial, UnaryOperator<E> transition, Predicate<E> stopper) { state = initial; @@ -45,10 +45,9 @@ public class GeneratingIterator<E> implements Iterator<E> { } /* - * @NOTE - * As this currently is, it only works correctly assuming that - * next() is only called when hasNext() is true. Should we - * safeguard against people who are not doing the right thing? + * @NOTE As this currently is, it only works correctly assuming that + * next() is only called when hasNext() is true. Should we safeguard + * against people who are not doing the right thing? */ @Override public E next() { diff --git a/base/src/main/java/bjc/utils/data/IHolder.java b/base/src/main/java/bjc/utils/data/IHolder.java index 0b0cfd2..4d2ed2c 100644 --- a/base/src/main/java/bjc/utils/data/IHolder.java +++ b/base/src/main/java/bjc/utils/data/IHolder.java @@ -16,20 +16,19 @@ import bjc.utils.funcdata.theory.Functor; * @author ben * * @param <ContainedType> - * The type of value held. + * The type of value held. */ public interface IHolder<ContainedType> extends Functor<ContainedType> { /** * Bind a function across the value in this container. * * @param <BoundType> - * The type of value in this container. + * The type of value in this container. * * @param binder - * The function to bind to the value. + * The function to bind to the value. * - * @return - * A holder from binding the value. + * @return A holder from binding the value. */ public <BoundType> IHolder<BoundType> bind(Function<ContainedType, IHolder<BoundType>> binder); @@ -37,7 +36,7 @@ public interface IHolder<ContainedType> extends Functor<ContainedType> { * Apply an action to the value. * * @param action - * The action to apply to the value. + * The action to apply to the value. */ public default void doWith(final Consumer<? super ContainedType> action) { transform(value -> { @@ -51,7 +50,7 @@ public interface IHolder<ContainedType> extends Functor<ContainedType> { default <ArgType, ReturnType> Function<Functor<ArgType>, Functor<ReturnType>> fmap( final Function<ArgType, ReturnType> func) { return argumentFunctor -> { - if (!(argumentFunctor instanceof IHolder<?>)) { + if(!(argumentFunctor instanceof IHolder<?>)) { final String msg = "This functor only supports mapping over instances of IHolder"; throw new IllegalArgumentException(msg); @@ -72,21 +71,19 @@ public interface IHolder<ContainedType> extends Functor<ContainedType> { * Lifts a function to bind over this holder. * * @param <NewType> - * The type of the functions return. + * The type of the functions return. * * @param func - * The function to lift over the holder. + * The function to lift over the holder. * - * @return - * The function lifted over the holder. + * @return The function lifted over the holder. */ public <NewType> Function<ContainedType, IHolder<NewType>> lift(Function<ContainedType, NewType> func); /** * Make this holder lazy. * - * @return - * A lazy version of this holder. + * @return A lazy version of this holder. */ public default IHolder<ContainedType> makeLazy() { return new WrappedLazy<>(this); @@ -95,8 +92,7 @@ public interface IHolder<ContainedType> extends Functor<ContainedType> { /** * Make this holder a list. * - * @return - * A list version of this holder. + * @return A list version of this holder. */ public default IHolder<ContainedType> makeList() { return new BoundListHolder<>(new FunctionalList<>(this)); @@ -105,8 +101,7 @@ public interface IHolder<ContainedType> extends Functor<ContainedType> { /** * Make this holder optional. * - * @return - * An optional version of this holder. + * @return An optional version of this holder. */ public default IHolder<ContainedType> makeOptional() { return new WrappedOption<>(this); @@ -119,13 +114,12 @@ public interface IHolder<ContainedType> extends Functor<ContainedType> { * Does not change the internal state of this holder. * * @param <MappedType> - * The type of the mapped value. + * The type of the mapped value. * * @param mapper - * The function to do mapping with. + * The function to do mapping with. * - * @return - * A holder with the mapped value + * @return A holder with the mapped value */ public <MappedType> IHolder<MappedType> map(Function<ContainedType, MappedType> mapper); @@ -133,10 +127,9 @@ public interface IHolder<ContainedType> extends Functor<ContainedType> { * Replace the held value with a new one. * * @param newValue - * The value to hold instead. + * The value to hold instead. * - * @return - * The holder itself. + * @return The holder itself. */ public default IHolder<ContainedType> replace(final ContainedType newValue) { return transform(oldValue -> { @@ -148,10 +141,9 @@ public interface IHolder<ContainedType> extends Functor<ContainedType> { * Transform the value held in this holder. * * @param transformer - * The function to transform the value with. + * The function to transform the value with. * - * @return - * The holder itself, for easy chaining. + * @return The holder itself, for easy chaining. */ public IHolder<ContainedType> transform(UnaryOperator<ContainedType> transformer); @@ -160,13 +152,12 @@ public interface IHolder<ContainedType> extends Functor<ContainedType> { * held. * * @param <UnwrappedType> - * The type of the unwrapped value. + * The type of the unwrapped value. * * @param unwrapper - * The function to use to unwrap the value. + * The function to use to unwrap the value. * - * @return - * The unwrapped held value. + * @return The unwrapped held value. */ public <UnwrappedType> UnwrappedType unwrap(Function<ContainedType, UnwrappedType> unwrapper); } diff --git a/base/src/main/java/bjc/utils/data/IPair.java b/base/src/main/java/bjc/utils/data/IPair.java index 75b092d..1c864d1 100644 --- a/base/src/main/java/bjc/utils/data/IPair.java +++ b/base/src/main/java/bjc/utils/data/IPair.java @@ -12,10 +12,10 @@ import bjc.utils.funcdata.theory.Bifunctor; * @author ben * * @param <LeftType> - * The type of the left side of the pair. + * The type of the left side of the pair. * * @param <RightType> - * The type of the right side of the pair. + * The type of the right side of the pair. * */ public interface IPair<LeftType, RightType> extends Bifunctor<LeftType, RightType> { @@ -23,16 +23,15 @@ public interface IPair<LeftType, RightType> extends Bifunctor<LeftType, RightTyp * Bind a function across the values in this pair. * * @param <BoundLeft> - * The type of the bound left. + * The type of the bound left. * * @param <BoundRight> - * The type of the bound right. + * The type of the bound right. * * @param binder - * The function to bind with. + * The function to bind with. * - * @return - * The bound pair. + * @return The bound pair. */ public <BoundLeft, BoundRight> IPair<BoundLeft, BoundRight> bind( BiFunction<LeftType, RightType, IPair<BoundLeft, BoundRight>> binder); @@ -41,13 +40,12 @@ public interface IPair<LeftType, RightType> extends Bifunctor<LeftType, RightTyp * Bind a function to the left value in this pair. * * @param <BoundLeft> - * The type of the bound value. + * The type of the bound value. * * @param leftBinder - * The function to use to bind. + * The function to use to bind. * - * @return - * A pair with the left type bound. + * @return A pair with the left type bound. */ public <BoundLeft> IPair<BoundLeft, RightType> bindLeft( Function<LeftType, IPair<BoundLeft, RightType>> leftBinder); @@ -56,13 +54,12 @@ public interface IPair<LeftType, RightType> extends Bifunctor<LeftType, RightTyp * Bind a function to the right value in this pair. * * @param <BoundRight> - * The type of the bound value. + * The type of the bound value. * * @param rightBinder - * The function to use to bind. + * The function to use to bind. * - * @return - * A pair with the right type bound. + * @return A pair with the right type bound. */ public <BoundRight> IPair<LeftType, BoundRight> bindRight( Function<RightType, IPair<LeftType, BoundRight>> rightBinder); @@ -71,16 +68,15 @@ public interface IPair<LeftType, RightType> extends Bifunctor<LeftType, RightTyp * Pairwise combine two pairs together. * * @param <OtherLeft> - * The left type of the other pair. + * The left type of the other pair. * * @param <OtherRight> - * The right type of the other pair. + * The right type of the other pair. * * @param otherPair - * The pair to combine with. + * The pair to combine with. * - * @return - * The pairs, pairwise combined together. + * @return The pairs, pairwise combined together. */ public default <OtherLeft, OtherRight> IPair<IPair<LeftType, OtherLeft>, IPair<RightType, OtherRight>> combine( final IPair<OtherLeft, OtherRight> otherPair) { @@ -91,28 +87,27 @@ public interface IPair<LeftType, RightType> extends Bifunctor<LeftType, RightTyp * Combine the contents of two pairs together. * * @param <OtherLeft> - * The type of the left value of the other pair. + * The type of the left value of the other pair. * * @param <OtherRight> - * The type of the right value of the other pair. + * The type of the right value of the other pair. * * @param <CombinedLeft> - * The type of the left value of the combined pair. + * The type of the left value of the combined pair. * * @param <CombinedRight> - * The type of the right value of the combined pair. + * The type of the right value of the combined pair. * * @param otherPair - * The other pair to combine with. + * The other pair to combine with. * * @param leftCombiner - * The function to combine the left values with. + * The function to combine the left values with. * * @param rightCombiner - * The function to combine the right values with. + * The function to combine the right values with. * - * @return - * A pair with its values combined. + * @return A pair with its values combined. */ public <OtherLeft, OtherRight, CombinedLeft, CombinedRight> IPair<CombinedLeft, CombinedRight> combine( IPair<OtherLeft, OtherRight> otherPair, @@ -124,7 +119,7 @@ public interface IPair<LeftType, RightType> extends Bifunctor<LeftType, RightTyp * pair. * * @param consumer - * The action to perform on the pair. + * The action to perform on the pair. */ public default void doWith(final BiConsumer<LeftType, RightType> consumer) { merge((leftValue, rightValue) -> { @@ -135,10 +130,10 @@ public interface IPair<LeftType, RightType> extends Bifunctor<LeftType, RightTyp } @Override - default <OldLeft, OldRight, NewLeft> LeftBifunctorMap<OldLeft, OldRight, NewLeft> - fmapLeft(final Function<OldLeft, NewLeft> func) { + default <OldLeft, OldRight, NewLeft> LeftBifunctorMap<OldLeft, OldRight, NewLeft> fmapLeft( + final Function<OldLeft, NewLeft> func) { return argumentPair -> { - if (!(argumentPair instanceof IPair<?, ?>)) { + if(!(argumentPair instanceof IPair<?, ?>)) { final String msg = "This function can only be applied to instances of IPair"; throw new IllegalArgumentException(msg); @@ -151,10 +146,10 @@ public interface IPair<LeftType, RightType> extends Bifunctor<LeftType, RightTyp } @Override - default <OldLeft, OldRight, NewRight> RightBifunctorMap<OldLeft, OldRight, NewRight> - fmapRight(final Function<OldRight, NewRight> func) { + default <OldLeft, OldRight, NewRight> RightBifunctorMap<OldLeft, OldRight, NewRight> fmapRight( + final Function<OldRight, NewRight> func) { return argumentPair -> { - if (!(argumentPair instanceof IPair<?, ?>)) { + if(!(argumentPair instanceof IPair<?, ?>)) { final String msg = "This function can only be applied to instances of IPair"; throw new IllegalArgumentException(msg); @@ -169,8 +164,7 @@ public interface IPair<LeftType, RightType> extends Bifunctor<LeftType, RightTyp /** * Get the value on the left side of the pair. * - * @return - * The value on the left side of the pair. + * @return The value on the left side of the pair. */ @Override public default LeftType getLeft() { @@ -180,8 +174,7 @@ public interface IPair<LeftType, RightType> extends Bifunctor<LeftType, RightTyp /** * Get the value on the right side of the pair. * - * @return - * The value on the right side of the pair. + * @return The value on the right side of the pair. */ @Override public default RightType getRight() { @@ -189,19 +182,17 @@ public interface IPair<LeftType, RightType> extends Bifunctor<LeftType, RightTyp } /** - * Transform the value on the left side of the pair. + * Transform the value on the left side of the pair. * * Doesn't modify the pair. * * @param <NewLeft> - * The new type of the left part of the pair. + * The new type of the left part of the pair. * * @param mapper - * The function to use to transform the left part of the - * pair. + * The function to use to transform the left part of the pair. * - * @return - * The pair, with its left part transformed. + * @return The pair, with its left part transformed. */ public <NewLeft> IPair<NewLeft, RightType> mapLeft(Function<LeftType, NewLeft> mapper); @@ -211,14 +202,12 @@ public interface IPair<LeftType, RightType> extends Bifunctor<LeftType, RightTyp * Doesn't modify the pair. * * @param <NewRight> - * The new type of the right part of the pair. + * The new type of the right part of the pair. * * @param mapper - * The function to use to transform the right part of the - * pair. + * The function to use to transform the right part of the pair. * - * @return - * The pair, with its right part transformed. + * @return The pair, with its right part transformed. */ public <NewRight> IPair<LeftType, NewRight> mapRight(Function<RightType, NewRight> mapper); @@ -226,13 +215,12 @@ public interface IPair<LeftType, RightType> extends Bifunctor<LeftType, RightTyp * Merge the two values in this pair into a single value. * * @param <MergedType> - * The type of the single value. + * The type of the single value. * * @param merger - * The function to use for merging. + * The function to use for merging. * - * @return - * The pair, merged into a single value. + * @return The pair, merged into a single value. */ public <MergedType> MergedType merge(BiFunction<LeftType, RightType, MergedType> merger); } diff --git a/base/src/main/java/bjc/utils/data/ITree.java b/base/src/main/java/bjc/utils/data/ITree.java index 450905b..5a4d645 100644 --- a/base/src/main/java/bjc/utils/data/ITree.java +++ b/base/src/main/java/bjc/utils/data/ITree.java @@ -14,7 +14,7 @@ import bjc.utils.functypes.ListFlattener; * @author ben * * @param <ContainedType> - * The type of data contained in the tree nodes. + * The type of data contained in the tree nodes. * */ public interface ITree<ContainedType> { @@ -22,7 +22,7 @@ public interface ITree<ContainedType> { * Append a child to this node. * * @param child - * The child to append to this node. + * The child to append to this node. */ void addChild(ITree<ContainedType> child); @@ -30,7 +30,7 @@ public interface ITree<ContainedType> { * Prepend a child to this node. * * @param child - * The child to prepend to this node. + * The child to prepend to this node. */ void prependChild(ITree<ContainedType> child); @@ -38,24 +38,23 @@ public interface ITree<ContainedType> { * Collapse a tree into a single version. * * @param <NewType> - * The intermediate type being folded. + * The intermediate type being folded. * * @param <ReturnedType> - * The type that is the end result. + * The type that is the end result. * * @param leafTransform - * The function to use to convert leaf values. + * The function to use to convert leaf values. * * @param nodeCollapser - * The function to use to convert internal nodes and - * their children. + * The function to use to convert internal nodes and their + * children. * * @param resultTransformer - * The function to use to convert a state to the returned - * version. + * The function to use to convert a state to the returned + * version. * - * @return - * The final transformed state. + * @return The final transformed state. */ <NewType, ReturnedType> ReturnedType collapse(Function<ContainedType, NewType> leafTransform, Function<ContainedType, ListFlattener<NewType>> nodeCollapser, @@ -65,7 +64,7 @@ public interface ITree<ContainedType> { * Execute a given action for each of this tree's children. * * @param action - * The action to execute for each child. + * The action to execute for each child. */ void doForChildren(Consumer<ITree<ContainedType>> action); @@ -74,14 +73,13 @@ public interface ITree<ContainedType> { * those trees into a single tree. * * @param mapper - * The function to use to map values into trees. + * The function to use to map values into trees. * - * @return - * A tree, with some nodes expanded into trees. + * @return A tree, with some nodes expanded into trees. */ default ITree<ContainedType> flatMapTree(final Function<ContainedType, ITree<ContainedType>> mapper) { return topDownTransform(dat -> TopDownTransformResult.PUSHDOWN, node -> { - if (node.getChildrenCount() > 0) { + if(node.getChildrenCount() > 0) { final ITree<ContainedType> parent = node.transformHead(mapper); node.doForChildren(parent::addChild); @@ -97,10 +95,9 @@ public interface ITree<ContainedType> { * Get the specified child of this tree. * * @param childNo - * The number of the child to get. + * The number of the child to get. * - * @return - * The specified child of this tree. + * @return The specified child of this tree. */ default ITree<ContainedType> getChild(final int childNo) { return transformChild(childNo, child -> child); @@ -109,16 +106,14 @@ public interface ITree<ContainedType> { /** * Get a count of the number of direct children this node has. * - * @return - * The number of direct children this node has. + * @return The number of direct children this node has. */ int getChildrenCount(); /** * Get the data stored in this node. * - * @return - * The data stored in this node. + * @return The data stored in this node. */ default ContainedType getHead() { return transformHead(head -> head); @@ -128,16 +123,15 @@ public interface ITree<ContainedType> { * Rebuild the tree with the same structure, but different nodes. * * @param <MappedType> - * The type of the new tree. + * The type of the new tree. * * @param leafTransformer - * The function to use to transform leaf tokens. + * The function to use to transform leaf tokens. * * @param internalTransformer - * The function to use to transform internal tokens. + * The function to use to transform internal tokens. * - * @return - * The tree, with the nodes changed. + * @return The tree, with the nodes changed. */ <MappedType> ITree<MappedType> rebuildTree(Function<ContainedType, MappedType> leafTransformer, Function<ContainedType, MappedType> internalTransformer); @@ -146,10 +140,10 @@ public interface ITree<ContainedType> { * Transform some of the nodes in this tree. * * @param nodePicker - * The predicate to use to pick nodes to transform. + * The predicate to use to pick nodes to transform. * * @param transformer - * The function to use to transform picked nodes. + * The function to use to transform picked nodes. */ void selectiveTransform(Predicate<ContainedType> nodePicker, UnaryOperator<ContainedType> transformer); @@ -157,13 +151,12 @@ public interface ITree<ContainedType> { * Do a top-down transform of the tree. * * @param transformPicker - * The function to use to pick how to progress. + * The function to use to pick how to progress. * * @param transformer - * The function used to transform picked subtrees. + * The function used to transform picked subtrees. * - * @return - * The tree with the transform applied to picked subtrees. + * @return The tree with the transform applied to picked subtrees. */ ITree<ContainedType> topDownTransform(Function<ContainedType, TopDownTransformResult> transformPicker, UnaryOperator<ITree<ContainedType>> transformer); @@ -172,20 +165,19 @@ public interface ITree<ContainedType> { * Transform one of this nodes children. * * @param <TransformedType> - * The type of the transformed value. + * The type of the transformed value. * * @param childNo - * The number of the child to transform. + * The number of the child to transform. * * @param transformer - * The function to use to transform the value. + * The function to use to transform the value. * - * @return - * The transformed value. + * @return The transformed value. * * @throws IllegalArgumentException - * if the childNo is out of bounds (0 <= childNo <= - * childCount()). + * if the childNo is out of bounds (0 <= childNo <= + * childCount()). */ <TransformedType> TransformedType transformChild(int childNo, Function<ITree<ContainedType>, TransformedType> transformer); @@ -194,13 +186,12 @@ public interface ITree<ContainedType> { * Transform the value that is the head of this node. * * @param <TransformedType> - * The type of the transformed value. + * The type of the transformed value. * * @param transformer - * The function to use to transform the value. + * The function to use to transform the value. * - * @return - * The transformed value. + * @return The transformed value. */ <TransformedType> TransformedType transformHead(Function<ContainedType, TransformedType> transformer); @@ -208,13 +199,12 @@ public interface ITree<ContainedType> { * Transform the tree into a tree with a different type of token. * * @param <MappedType> - * The type of the new tree. + * The type of the new tree. * * @param transformer - * The function to use to transform tokens. + * The function to use to transform tokens. * - * @return - * A tree with the token types transformed. + * @return A tree with the token types transformed. */ default <MappedType> ITree<MappedType> transformTree(final Function<ContainedType, MappedType> transformer) { return rebuildTree(transformer, transformer); @@ -224,10 +214,10 @@ public interface ITree<ContainedType> { * Perform an action on each part of the tree. * * @param linearizationMethod - * The way to traverse the tree. + * The way to traverse the tree. * * @param action - * The action to perform on each tree node. + * The action to perform on each tree node. */ void traverse(TreeLinearizationMethod linearizationMethod, Consumer<ContainedType> action); @@ -235,11 +225,10 @@ public interface ITree<ContainedType> { * Find the farthest to right child that satisfies the given predicate. * * @param childPred - * The predicate to satisfy. + * The predicate to satisfy. * - * @return - * The index of the right-most child that satisfies the predicate, - * or -1 if one doesn't exist. + * @return The index of the right-most child that satisfies the + * predicate, or -1 if one doesn't exist. */ int revFind(Predicate<ITree<ContainedType>> childPred); } diff --git a/base/src/main/java/bjc/utils/data/Identity.java b/base/src/main/java/bjc/utils/data/Identity.java index 3acb5aa..44ddc31 100644 --- a/base/src/main/java/bjc/utils/data/Identity.java +++ b/base/src/main/java/bjc/utils/data/Identity.java @@ -9,7 +9,7 @@ import java.util.function.UnaryOperator; * @author ben * * @param <ContainedType> - * The type contained in the holder. + * The type contained in the holder. */ public class Identity<ContainedType> implements IHolder<ContainedType> { /* The held value. */ @@ -24,7 +24,7 @@ public class Identity<ContainedType> implements IHolder<ContainedType> { * Create a holder holding the specified value. * * @param value - * The value to hold. + * The value to hold. */ public Identity(final ContainedType value) { heldValue = value; @@ -47,15 +47,15 @@ public class Identity<ContainedType> implements IHolder<ContainedType> { @Override public boolean equals(final Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (!(obj instanceof Identity)) return false; + if(this == obj) return true; + if(obj == null) return false; + if(!(obj instanceof Identity)) return false; final Identity<?> other = (Identity<?>) obj; - if (heldValue == null) { - if (other.heldValue != null) return false; - } else if (!heldValue.equals(other.heldValue)) return false; + if(heldValue == null) { + if(other.heldValue != null) return false; + } else if(!heldValue.equals(other.heldValue)) return false; return true; } @@ -93,10 +93,9 @@ public class Identity<ContainedType> implements IHolder<ContainedType> { * Create a new identity container. * * @param val - * The contained value. + * The contained value. * - * @return - * A new identity container. + * @return A new identity container. */ public static <ContainedType> Identity<ContainedType> id(final ContainedType val) { return new Identity<>(val); @@ -105,8 +104,7 @@ public class Identity<ContainedType> implements IHolder<ContainedType> { /** * Create a new empty identity container. * - * @return - * A new empty identity container. + * @return A new empty identity container. */ public static <ContainedType> Identity<ContainedType> id() { return new Identity<>(); diff --git a/base/src/main/java/bjc/utils/data/LazyPair.java b/base/src/main/java/bjc/utils/data/LazyPair.java index 548a09e..0500486 100644 --- a/base/src/main/java/bjc/utils/data/LazyPair.java +++ b/base/src/main/java/bjc/utils/data/LazyPair.java @@ -13,40 +13,40 @@ import bjc.utils.data.internals.HalfBoundLazyPair; * @author ben * * @param <LeftType> - * The type on the left side of the pair. + * The type on the left side of the pair. * * @param <RightType> - * The type on the right side of the pair. + * The type on the right side of the pair. */ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> { /* The supplier for the left value. */ - private Supplier<LeftType> leftSupplier; + private Supplier<LeftType> leftSupplier; /* The left value. */ private LeftType leftValue; /* Whether the left value has been created. */ - private boolean leftMaterialized; + private boolean leftMaterialized; /* The supplier for the right value. */ private Supplier<RightType> rightSupplier; /* The right value. */ private RightType rightValue; /* Whether the right value has been created. */ - private boolean rightMaterialized; + private boolean rightMaterialized; /** * Create a new lazy pair, using the set values. * * @param leftVal - * The value for the left side of the pair. + * The value for the left side of the pair. * * @param rightVal - * The value for the right side of the pair. + * The value for the right side of the pair. */ public LazyPair(final LeftType leftVal, final RightType rightVal) { - leftValue = leftVal; + leftValue = leftVal; rightValue = rightVal; - leftMaterialized = true; + leftMaterialized = true; rightMaterialized = true; } @@ -54,17 +54,17 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> * Create a new lazy pair from the given value sources. * * @param leftSupp - * The source for a value on the left side of the pair. + * The source for a value on the left side of the pair. * * @param rightSupp - * The source for a value on the right side of the pair. + * The source for a value on the right side of the pair. */ public LazyPair(final Supplier<LeftType> leftSupp, final Supplier<RightType> rightSupp) { /* Use single suppliers to catch double-instantiation bugs. */ - leftSupplier = new SingleSupplier<>(leftSupp); + leftSupplier = new SingleSupplier<>(leftSupp); rightSupplier = new SingleSupplier<>(rightSupp); - leftMaterialized = false; + leftMaterialized = false; rightMaterialized = false; } @@ -78,7 +78,7 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> public <BoundLeft> IPair<BoundLeft, RightType> bindLeft( final Function<LeftType, IPair<BoundLeft, RightType>> leftBinder) { final Supplier<LeftType> leftSupp = () -> { - if (leftMaterialized) return leftValue; + if(leftMaterialized) return leftValue; return leftSupplier.get(); }; @@ -90,7 +90,7 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> public <BoundRight> IPair<LeftType, BoundRight> bindRight( final Function<RightType, IPair<LeftType, BoundRight>> rightBinder) { final Supplier<RightType> rightSupp = () -> { - if (rightMaterialized) return rightValue; + if(rightMaterialized) return rightValue; return rightSupplier.get(); }; @@ -105,7 +105,7 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> final BiFunction<RightType, OtherRight, CombinedRight> rightCombiner) { return otherPair.bind((otherLeft, otherRight) -> { return bind((leftVal, rightVal) -> { - final CombinedLeft left = leftCombiner.apply(leftVal, otherLeft); + final CombinedLeft left = leftCombiner.apply(leftVal, otherLeft); final CombinedRight right = rightCombiner.apply(rightVal, otherRight); return new LazyPair<>(left, right); @@ -115,7 +115,7 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> @Override public LeftType getLeft() { - if (!leftMaterialized) { + if(!leftMaterialized) { leftValue = leftSupplier.get(); leftMaterialized = true; @@ -126,7 +126,7 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> @Override public RightType getRight() { - if (!rightMaterialized) { + if(!rightMaterialized) { rightValue = rightSupplier.get(); rightMaterialized = true; @@ -138,13 +138,13 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> @Override public <NewLeft> IPair<NewLeft, RightType> mapLeft(final Function<LeftType, NewLeft> mapper) { final Supplier<NewLeft> leftSupp = () -> { - if (leftMaterialized) return mapper.apply(leftValue); + if(leftMaterialized) return mapper.apply(leftValue); return mapper.apply(leftSupplier.get()); }; final Supplier<RightType> rightSupp = () -> { - if (rightMaterialized) return rightValue; + if(rightMaterialized) return rightValue; return rightSupplier.get(); }; @@ -155,13 +155,13 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> @Override public <NewRight> IPair<LeftType, NewRight> mapRight(final Function<RightType, NewRight> mapper) { final Supplier<LeftType> leftSupp = () -> { - if (leftMaterialized) return leftValue; + if(leftMaterialized) return leftValue; return leftSupplier.get(); }; final Supplier<NewRight> rightSupp = () -> { - if (rightMaterialized) return mapper.apply(rightValue); + if(rightMaterialized) return mapper.apply(rightValue); return mapper.apply(rightSupplier.get()); }; @@ -171,13 +171,13 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> @Override public <MergedType> MergedType merge(final BiFunction<LeftType, RightType, MergedType> merger) { - if (!leftMaterialized) { + if(!leftMaterialized) { leftValue = leftSupplier.get(); leftMaterialized = true; } - if (!rightMaterialized) { + if(!rightMaterialized) { rightValue = rightSupplier.get(); rightMaterialized = true; @@ -191,13 +191,13 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> String leftVal; String rightVal; - if (leftMaterialized) { + if(leftMaterialized) { leftVal = leftValue.toString(); } else { leftVal = "(un-materialized)"; } - if (rightMaterialized) { + if(rightMaterialized) { rightVal = rightValue.toString(); } else { rightVal = "(un-materialized)"; @@ -221,26 +221,28 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> @Override public boolean equals(final Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (!(obj instanceof LazyPair<?, ?>)) return false; + if(this == obj) return true; + if(obj == null) return false; + if(!(obj instanceof LazyPair<?, ?>)) return false; final LazyPair<?, ?> other = (LazyPair<?, ?>) obj; - if (leftMaterialized != other.leftMaterialized) return false; - - if (leftMaterialized) { - if (leftValue == null) { - if (other.leftValue != null) return false; - } else if (!leftValue.equals(other.leftValue)) return false; - } else return false; - - if (rightMaterialized != other.rightMaterialized) return false; - if (rightMaterialized) { - if (rightValue == null) { - if (other.rightValue != null) return false; - } else if (!rightValue.equals(other.rightValue)) return false; - } else return false; + if(leftMaterialized != other.leftMaterialized) return false; + + if(leftMaterialized) { + if(leftValue == null) { + if(other.leftValue != null) return false; + } else if(!leftValue.equals(other.leftValue)) return false; + } else + return false; + + if(rightMaterialized != other.rightMaterialized) return false; + if(rightMaterialized) { + if(rightValue == null) { + if(other.rightValue != null) return false; + } else if(!rightValue.equals(other.rightValue)) return false; + } else + return false; return true; } diff --git a/base/src/main/java/bjc/utils/data/ListHolder.java b/base/src/main/java/bjc/utils/data/ListHolder.java index 4564466..dbcdf6e 100644 --- a/base/src/main/java/bjc/utils/data/ListHolder.java +++ b/base/src/main/java/bjc/utils/data/ListHolder.java @@ -13,7 +13,7 @@ import bjc.utils.funcdata.IList; * @author ben * * @param <ContainedType> - * The type of contained value. + * The type of contained value. */ public class ListHolder<ContainedType> implements IHolder<ContainedType> { private IList<ContainedType> heldValues; @@ -22,14 +22,14 @@ public class ListHolder<ContainedType> implements IHolder<ContainedType> { * Create a new list holder. * * @param values - * The possible values for the computation. + * The possible values for the computation. */ @SafeVarargs public ListHolder(final ContainedType... values) { heldValues = new FunctionalList<>(); - if (values != null) { - for (final ContainedType containedValue : values) { + if(values != null) { + for(final ContainedType containedValue : values) { heldValues.add(containedValue); } } @@ -90,15 +90,15 @@ public class ListHolder<ContainedType> implements IHolder<ContainedType> { @Override public boolean equals(final Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (!(obj instanceof ListHolder<?>)) return false; + if(this == obj) return true; + if(obj == null) return false; + if(!(obj instanceof ListHolder<?>)) return false; final ListHolder<?> other = (ListHolder<?>) obj; - if (heldValues == null) { - if (other.heldValues != null) return false; - } else if (!heldValues.equals(other.heldValues)) return false; + if(heldValues == null) { + if(other.heldValues != null) return false; + } else if(!heldValues.equals(other.heldValues)) return false; return true; } diff --git a/base/src/main/java/bjc/utils/data/Option.java b/base/src/main/java/bjc/utils/data/Option.java index 6eae21f..7869946 100644 --- a/base/src/main/java/bjc/utils/data/Option.java +++ b/base/src/main/java/bjc/utils/data/Option.java @@ -9,7 +9,7 @@ import java.util.function.UnaryOperator; * @author ben * * @param <ContainedType> - * The type of the value that may or may not be held. + * The type of the value that may or may not be held. */ public class Option<ContainedType> implements IHolder<ContainedType> { private ContainedType held; @@ -18,7 +18,7 @@ public class Option<ContainedType> implements IHolder<ContainedType> { * Create a new optional, using the given initial value. * * @param seed - * The initial value for the optional. + * The initial value for the optional. */ public Option(final ContainedType seed) { held = seed; @@ -26,7 +26,7 @@ public class Option<ContainedType> implements IHolder<ContainedType> { @Override public <BoundType> IHolder<BoundType> bind(final Function<ContainedType, IHolder<BoundType>> binder) { - if (held == null) return new Option<>(null); + if(held == null) return new Option<>(null); return binder.apply(held); } @@ -40,14 +40,14 @@ public class Option<ContainedType> implements IHolder<ContainedType> { @Override public <MappedType> IHolder<MappedType> map(final Function<ContainedType, MappedType> mapper) { - if (held == null) return new Option<>(null); + if(held == null) return new Option<>(null); return new Option<>(mapper.apply(held)); } @Override public IHolder<ContainedType> transform(final UnaryOperator<ContainedType> transformer) { - if (held != null) { + if(held != null) { held = transformer.apply(held); } @@ -56,7 +56,7 @@ public class Option<ContainedType> implements IHolder<ContainedType> { @Override public <UnwrappedType> UnwrappedType unwrap(final Function<ContainedType, UnwrappedType> unwrapper) { - if (held == null) return null; + if(held == null) return null; return unwrapper.apply(held); } @@ -78,15 +78,15 @@ public class Option<ContainedType> implements IHolder<ContainedType> { @Override public boolean equals(final Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (!(obj instanceof Option<?>)) return false; + if(this == obj) return true; + if(obj == null) return false; + if(!(obj instanceof Option<?>)) return false; final Option<?> other = (Option<?>) obj; - if (held == null) { - if (other.held != null) return false; - } else if (!held.equals(other.held)) return false; + if(held == null) { + if(other.held != null) return false; + } else if(!held.equals(other.held)) return false; return true; } diff --git a/base/src/main/java/bjc/utils/data/Pair.java b/base/src/main/java/bjc/utils/data/Pair.java index fb81e17..40e4849 100644 --- a/base/src/main/java/bjc/utils/data/Pair.java +++ b/base/src/main/java/bjc/utils/data/Pair.java @@ -9,10 +9,10 @@ import java.util.function.Function; * @author ben * * @param <LeftType> - * The type of the left value. + * The type of the left value. * * @param <RightType> - * The type of the right value. + * The type of the right value. */ public class Pair<LeftType, RightType> implements IPair<LeftType, RightType> { /* The left value. */ @@ -29,20 +29,20 @@ public class Pair<LeftType, RightType> implements IPair<LeftType, RightType> { * Create a new pair with both sides set to the specified values. * * @param left - * The value of the left side. + * The value of the left side. * * @param right - * The value of the right side. + * The value of the right side. */ public Pair(final LeftType left, final RightType right) { - leftValue = left; + leftValue = left; rightValue = right; } @Override public <BoundLeft, BoundRight> IPair<BoundLeft, BoundRight> bind( final BiFunction<LeftType, RightType, IPair<BoundLeft, BoundRight>> binder) { - if (binder == null) throw new NullPointerException("Binder must not be null."); + if(binder == null) throw new NullPointerException("Binder must not be null."); return binder.apply(leftValue, rightValue); } @@ -50,7 +50,7 @@ public class Pair<LeftType, RightType> implements IPair<LeftType, RightType> { @Override public <BoundLeft> IPair<BoundLeft, RightType> bindLeft( final Function<LeftType, IPair<BoundLeft, RightType>> leftBinder) { - if (leftBinder == null) throw new NullPointerException("Binder must not be null"); + if(leftBinder == null) throw new NullPointerException("Binder must not be null"); return leftBinder.apply(leftValue); } @@ -58,7 +58,7 @@ public class Pair<LeftType, RightType> implements IPair<LeftType, RightType> { @Override public <BoundRight> IPair<LeftType, BoundRight> bindRight( final Function<RightType, IPair<LeftType, BoundRight>> rightBinder) { - if (rightBinder == null) throw new NullPointerException("Binder must not be null"); + if(rightBinder == null) throw new NullPointerException("Binder must not be null"); return rightBinder.apply(rightValue); } @@ -69,7 +69,7 @@ public class Pair<LeftType, RightType> implements IPair<LeftType, RightType> { final BiFunction<LeftType, OtherLeft, CombinedLeft> leftCombiner, final BiFunction<RightType, OtherRight, CombinedRight> rightCombiner) { return otherPair.bind((otherLeft, otherRight) -> { - final CombinedLeft left = leftCombiner.apply(leftValue, otherLeft); + final CombinedLeft left = leftCombiner.apply(leftValue, otherLeft); final CombinedRight right = rightCombiner.apply(rightValue, otherRight); return new Pair<>(left, right); @@ -78,21 +78,21 @@ public class Pair<LeftType, RightType> implements IPair<LeftType, RightType> { @Override public <NewLeft> IPair<NewLeft, RightType> mapLeft(final Function<LeftType, NewLeft> mapper) { - if (mapper == null) throw new NullPointerException("Mapper must not be null"); + if(mapper == null) throw new NullPointerException("Mapper must not be null"); return new Pair<>(mapper.apply(leftValue), rightValue); } @Override public <NewRight> IPair<LeftType, NewRight> mapRight(final Function<RightType, NewRight> mapper) { - if (mapper == null) throw new NullPointerException("Mapper must not be null"); + if(mapper == null) throw new NullPointerException("Mapper must not be null"); return new Pair<>(leftValue, mapper.apply(rightValue)); } @Override public <MergedType> MergedType merge(final BiFunction<LeftType, RightType, MergedType> merger) { - if (merger == null) throw new NullPointerException("Merger must not be null"); + if(merger == null) throw new NullPointerException("Merger must not be null"); return merger.apply(leftValue, rightValue); } @@ -115,19 +115,19 @@ public class Pair<LeftType, RightType> implements IPair<LeftType, RightType> { @Override public boolean equals(final Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (!(obj instanceof Pair<?, ?>)) return false; + if(this == obj) return true; + if(obj == null) return false; + if(!(obj instanceof Pair<?, ?>)) return false; final Pair<?, ?> other = (Pair<?, ?>) obj; - if (leftValue == null) { - if (other.leftValue != null) return false; - } else if (!leftValue.equals(other.leftValue)) return false; + if(leftValue == null) { + if(other.leftValue != null) return false; + } else if(!leftValue.equals(other.leftValue)) return false; - if (rightValue == null) { - if (other.rightValue != null) return false; - } else if (!rightValue.equals(other.rightValue)) return false; + if(rightValue == null) { + if(other.rightValue != null) return false; + } else if(!rightValue.equals(other.rightValue)) return false; return true; } diff --git a/base/src/main/java/bjc/utils/data/SingleIterator.java b/base/src/main/java/bjc/utils/data/SingleIterator.java index 1241a68..561cd0b 100644 --- a/base/src/main/java/bjc/utils/data/SingleIterator.java +++ b/base/src/main/java/bjc/utils/data/SingleIterator.java @@ -8,7 +8,7 @@ import java.util.Iterator; * @author EVE * * @param <T> - * The type of the item. + * The type of the item. */ public class SingleIterator<T> implements Iterator<T> { /* The item being held. */ @@ -20,7 +20,7 @@ public class SingleIterator<T> implements Iterator<T> { * Create a iterator that yields a single item. * * @param item - * The item to yield. + * The item to yield. */ public SingleIterator(final T item) { itm = item; diff --git a/base/src/main/java/bjc/utils/data/SingleSupplier.java b/base/src/main/java/bjc/utils/data/SingleSupplier.java index 60f9136..8054d33 100644 --- a/base/src/main/java/bjc/utils/data/SingleSupplier.java +++ b/base/src/main/java/bjc/utils/data/SingleSupplier.java @@ -10,7 +10,7 @@ import java.util.function.Supplier; * @author ben * * @param <T> - * The supplied type + * The supplied type */ public class SingleSupplier<T> implements Supplier<T> { /* The next supplier ID. */ @@ -25,10 +25,9 @@ public class SingleSupplier<T> implements Supplier<T> { /* * The place where the supplier was instantiated. * - * @NOTE - * This is both slow to create, and generally bad practice to keep - * exceptions around without throwing them. However, it is very - * useful to find where the first instantiation was. + * @NOTE This is both slow to create, and generally bad practice to keep + * exceptions around without throwing them. However, it is very useful + * to find where the first instantiation was. */ private Exception instSite; @@ -36,7 +35,7 @@ public class SingleSupplier<T> implements Supplier<T> { * Create a new single supplier from an existing value. * * @param supp - * The supplier to give a single value from. + * The supplier to give a single value from. */ public SingleSupplier(final Supplier<T> supp) { source = supp; @@ -48,7 +47,7 @@ public class SingleSupplier<T> implements Supplier<T> { @Override public T get() { - if (gotten == true) { + if(gotten == true) { final String msg = String.format( "Attempted to retrieve value more than once from single supplier #%d", id); @@ -63,7 +62,7 @@ public class SingleSupplier<T> implements Supplier<T> { try { throw new IllegalStateException("Previous instantiation here."); - } catch (final IllegalStateException isex) { + } catch(final IllegalStateException isex) { instSite = isex; } diff --git a/base/src/main/java/bjc/utils/data/Toggle.java b/base/src/main/java/bjc/utils/data/Toggle.java index a1467e4..4e7b7d8 100644 --- a/base/src/main/java/bjc/utils/data/Toggle.java +++ b/base/src/main/java/bjc/utils/data/Toggle.java @@ -6,23 +6,21 @@ package bjc.utils.data; * @author EVE * * @param <E> - * The value stored in the toggle. + * The value stored in the toggle. */ public interface Toggle<E> { /** * Retrieve the currently-aligned value of this toggle, and swap the * value to the new one. * - * @return - * The previously-aligned value. + * @return The previously-aligned value. */ E get(); /** * Retrieve the currently-aligned value without altering the alignment. * - * @return - * The currently-aligned value. + * @return The currently-aligned value. */ E peek(); @@ -30,7 +28,7 @@ public interface Toggle<E> { * Change the alignment of the toggle. * * @param isLeft - * Whether the toggle should be left-aligned or not. + * Whether the toggle should be left-aligned or not. */ void set(boolean isLeft); } diff --git a/base/src/main/java/bjc/utils/data/TopDownTransformIterator.java b/base/src/main/java/bjc/utils/data/TopDownTransformIterator.java index c6b7d31..8f3e40c 100644 --- a/base/src/main/java/bjc/utils/data/TopDownTransformIterator.java +++ b/base/src/main/java/bjc/utils/data/TopDownTransformIterator.java @@ -50,7 +50,7 @@ public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<C } public void addYield(final Iterator<ITree<ContainedType>> src) { - if (curYield != null) { + if(curYield != null) { toYield.push(curYield); } @@ -63,51 +63,54 @@ public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<C } public ITree<ContainedType> flushYields(final ITree<ContainedType> val) { - if (curYield != null) { + if(curYield != null) { toYield.add(new SingleIterator<>(val)); - if (curYield.hasNext()) + if(curYield.hasNext()) return curYield.next(); else { - while (toYield.size() != 0 && !curYield.hasNext()) { + while(toYield.size() != 0 && !curYield.hasNext()) { curYield = toYield.pop(); } - if (toYield.size() == 0 && !curYield.hasNext()) { + if(toYield.size() == 0 && !curYield.hasNext()) { curYield = null; return val; - } else return curYield.next(); + } else + return curYield.next(); } - } else return val; + } else + return val; } @Override public ITree<ContainedType> next() { - if (done) throw new NoSuchElementException(); + if(done) throw new NoSuchElementException(); - if (curYield != null) { - if (curYield.hasNext()) + if(curYield != null) { + if(curYield.hasNext()) return curYield.next(); else { - while (toYield.size() != 0 && !curYield.hasNext()) { + while(toYield.size() != 0 && !curYield.hasNext()) { curYield = toYield.pop(); } - if (toYield.size() == 0 && !curYield.hasNext()) { + if(toYield.size() == 0 && !curYield.hasNext()) { curYield = null; - } else return curYield.next(); + } else + return curYield.next(); } } - if (initial) { + if(initial) { final TopDownTransformResult res = picker.apply(preParent.getHead()); - switch (res) { + switch(res) { case PASSTHROUGH: postParent = new Tree<>(preParent.getHead()); - if (preParent.getChildrenCount() != 0) { - for (int i = 0; i < preParent.getChildrenCount(); i++) { + if(preParent.getChildrenCount() != 0) { + for(int i = 0; i < preParent.getChildrenCount(); i++) { preChildren.add(preParent.getChild(i)); } @@ -127,8 +130,8 @@ public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<C preParent = transform.apply(preParent, this::addYield); return flushYields(preParent); case PUSHDOWN: - if (preParent.getChildrenCount() != 0) { - for (int i = 0; i < preParent.getChildrenCount(); i++) { + if(preParent.getChildrenCount() != 0) { + for(int i = 0; i < preParent.getChildrenCount(); i++) { preChildren.add(preParent.getChild(i)); } @@ -144,8 +147,8 @@ public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<C postParent = new Tree<>(intRes.getHead()); - if (intRes.getChildrenCount() != 0) { - for (int i = 0; i < intRes.getChildrenCount(); i++) { + if(intRes.getChildrenCount() != 0) { + for(int i = 0; i < intRes.getChildrenCount(); i++) { preChildren.add(intRes.getChild(i)); } @@ -159,13 +162,13 @@ public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<C throw new IllegalArgumentException("Unknown result type " + res); } - if (res != RTRANSFORM) { + if(res != RTRANSFORM) { initial = false; } } - if (curChild == null || !curChild.hasNext()) { - if (preChildren.size() != 0) { + if(curChild == null || !curChild.hasNext()) { + if(preChildren.size() != 0) { curChild = new TopDownTransformIterator<>(picker, transform, preChildren.pop()); final ITree<ContainedType> res = curChild.next(); @@ -176,12 +179,12 @@ public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<C } else { ITree<ContainedType> res = null; - if (postParent == null) { + if(postParent == null) { res = new Tree<>(preParent.getHead()); System.out.println("\t\tTRACE: adding nodes " + postChildren + " to " + res); - for (final ITree<ContainedType> child : postChildren) { + for(final ITree<ContainedType> child : postChildren) { res.addChild(child); } @@ -191,7 +194,7 @@ public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<C res = postParent; System.out.println("\t\tTRACE: adding nodes " + postChildren + " to " + res); - for (final ITree<ContainedType> child : postChildren) { + for(final ITree<ContainedType> child : postChildren) { res.addChild(child); } } diff --git a/base/src/main/java/bjc/utils/data/TransformIterator.java b/base/src/main/java/bjc/utils/data/TransformIterator.java index 5a6ac85..9ce3b20 100644 --- a/base/src/main/java/bjc/utils/data/TransformIterator.java +++ b/base/src/main/java/bjc/utils/data/TransformIterator.java @@ -9,10 +9,10 @@ import java.util.function.Function; * @author EVE * * @param <S> - * The source iterator type. + * The source iterator type. * * @param <D> - * The destination iterator type. + * The destination iterator type. */ public class TransformIterator<S, D> implements Iterator<D> { /* Our source of values. */ @@ -24,10 +24,10 @@ public class TransformIterator<S, D> implements Iterator<D> { * Create a new transform iterator. * * @param source - * The source iterator to use. + * The source iterator to use. * * @param transform - * The transform to apply. + * The transform to apply. */ public TransformIterator(final Iterator<S> source, final Function<S, D> transform) { this.source = source; diff --git a/base/src/main/java/bjc/utils/data/Tree.java b/base/src/main/java/bjc/utils/data/Tree.java index 386153b..6b7e03a 100644 --- a/base/src/main/java/bjc/utils/data/Tree.java +++ b/base/src/main/java/bjc/utils/data/Tree.java @@ -16,7 +16,7 @@ import bjc.utils.functypes.ListFlattener; * @author ben * * @param <ContainedType> - * The type contained in the tree. + * The type contained in the tree. */ public class Tree<ContainedType> implements ITree<ContainedType> { /* The data/label for this node. */ @@ -26,17 +26,16 @@ public class Tree<ContainedType> implements ITree<ContainedType> { private IList<ITree<ContainedType>> children; /* Whether this node has children. */ - /* @NOTE - * Why have both this boolean and childCount? Why not just do a - * childCount == 0 - * whenever you'd check hasChildren? + /* + * @NOTE Why have both this boolean and childCount? Why not just do a + * childCount == 0 whenever you'd check hasChildren? */ private boolean hasChildren; /* The number of children this node has. */ - private int childCount = 0; + private int childCount = 0; /* The ID of this node. */ - private int ID; + private int ID; /* The next ID to assign to a node. */ private static int nextID = 0; @@ -44,7 +43,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { * Create a new leaf node in a tree. * * @param leaf - * The data to store as a leaf node. + * The data to store as a leaf node. */ public Tree(final ContainedType leaf) { data = leaf; @@ -58,10 +57,10 @@ public class Tree<ContainedType> implements ITree<ContainedType> { * Create a new tree node with the specified children. * * @param leaf - * The data to hold in this node. + * The data to hold in this node. * * @param childrn - * A list of children for this node. + * A list of children for this node. */ public Tree(final ContainedType leaf, final IList<ITree<ContainedType>> childrn) { this(leaf); @@ -77,10 +76,10 @@ public class Tree<ContainedType> implements ITree<ContainedType> { * Create a new tree node with the specified children. * * @param leaf - * The data to hold in this node. + * The data to hold in this node. * * @param childrn - * A list of children for this node. + * A list of children for this node. */ @SafeVarargs public Tree(final ContainedType leaf, final ITree<ContainedType>... childrn) { @@ -92,7 +91,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { children = new FunctionalList<>(); - for (final ITree<ContainedType> child : childrn) { + for(final ITree<ContainedType> child : childrn) { children.add(child); childCount++; @@ -101,7 +100,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { @Override public void addChild(final ITree<ContainedType> child) { - if (hasChildren == false) { + if(hasChildren == false) { hasChildren = true; children = new FunctionalList<>(); @@ -114,7 +113,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { @Override public void prependChild(final ITree<ContainedType> child) { - if (hasChildren == false) { + if(hasChildren == false) { hasChildren = true; children = new FunctionalList<>(); @@ -127,7 +126,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { @Override public void doForChildren(final Consumer<ITree<ContainedType>> action) { - if (childCount > 0) { + if(childCount > 0) { children.forEach(action); } } @@ -139,11 +138,11 @@ public class Tree<ContainedType> implements ITree<ContainedType> { @Override public int revFind(final Predicate<ITree<ContainedType>> childPred) { - if (childCount == 0) { + if(childCount == 0) { return -1; } else { - for (int i = childCount - 1; i >= 0; i--) { - if (childPred.test(getChild(i))) return i; + for(int i = childCount - 1; i >= 0; i--) { + if(childPred.test(getChild(i))) return i; } return -1; @@ -152,10 +151,10 @@ public class Tree<ContainedType> implements ITree<ContainedType> { @Override public void traverse(final TreeLinearizationMethod linearizationMethod, final Consumer<ContainedType> action) { - if (hasChildren) { - switch (linearizationMethod) { + if(hasChildren) { + switch(linearizationMethod) { case INORDER: - if (childCount != 2) { + if(childCount != 2) { final String msg = "Can only do in-order traversal for binary trees."; throw new IllegalArgumentException(msg); @@ -195,7 +194,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { @Override public ITree<ContainedType> flatMapTree(final Function<ContainedType, ITree<ContainedType>> mapper) { - if (hasChildren) { + if(hasChildren) { final ITree<ContainedType> flatMappedData = mapper.apply(data); final IList<ITree<ContainedType>> mappedChildren = children @@ -212,14 +211,13 @@ public class Tree<ContainedType> implements ITree<ContainedType> { /* * Do a collapse of this tree. * - * @NOTE - * Why is this protected? I can't see any good reason someone'd - * want to override it. + * @NOTE Why is this protected? I can't see any good reason someone'd + * want to override it. */ protected <NewType> NewType internalCollapse(final Function<ContainedType, NewType> leafTransform, final Function<ContainedType, ListFlattener<NewType>> nodeCollapser) { - if (hasChildren) { + if(hasChildren) { final Function<IList<NewType>, NewType> nodeTransformer = nodeCollapser.apply(data); final IList<NewType> collapsedChildren = children.map(child -> { @@ -236,7 +234,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { } protected void internalToString(final StringBuilder builder, final int indentLevel, final boolean initial) { - for (int i = 0; i < indentLevel; i++) { + for(int i = 0; i < indentLevel; i++) { builder.append(">\t"); } @@ -246,14 +244,14 @@ public class Tree<ContainedType> implements ITree<ContainedType> { builder.append(data == null ? "(null)" : data.toString()); builder.append("\n"); - if (hasChildren) { + if(hasChildren) { children.forEach(child -> { - if (child instanceof Tree<?>) { + if(child instanceof Tree<?>) { final Tree<ContainedType> kid = (Tree<ContainedType>) child; kid.internalToString(builder, indentLevel + 1, false); } else { - for (int i = 0; i < indentLevel + 1; i++) { + for(int i = 0; i < indentLevel + 1; i++) { builder.append(">\t"); } @@ -268,7 +266,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { @Override public <MappedType> ITree<MappedType> rebuildTree(final Function<ContainedType, MappedType> leafTransformer, final Function<ContainedType, MappedType> operatorTransformer) { - if (hasChildren) { + if(hasChildren) { final IList<ITree<MappedType>> mappedChildren = children.map(child -> { return child.rebuildTree(leafTransformer, operatorTransformer); }); @@ -283,7 +281,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { @Override public void selectiveTransform(final Predicate<ContainedType> nodePicker, final UnaryOperator<ContainedType> transformer) { - if (hasChildren) { + if(hasChildren) { children.forEach(child -> child.selectiveTransform(nodePicker, transformer)); } else { data = transformer.apply(data); @@ -296,11 +294,11 @@ public class Tree<ContainedType> implements ITree<ContainedType> { final UnaryOperator<ITree<ContainedType>> transformer) { final TopDownTransformResult transformResult = transformPicker.apply(data); - switch (transformResult) { + switch(transformResult) { case PASSTHROUGH: ITree<ContainedType> result = new Tree<>(data); - if (hasChildren) { + if(hasChildren) { children.forEach(child -> { final ITree<ContainedType> kid = child.topDownTransform(transformPicker, transformer); @@ -319,7 +317,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { case PUSHDOWN: result = new Tree<>(data); - if (hasChildren) { + if(hasChildren) { children.forEach(child -> { final ITree<ContainedType> kid = child.topDownTransform(transformPicker, transformer); @@ -351,7 +349,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { @Override public <TransformedType> TransformedType transformChild(final int childNo, final Function<ITree<ContainedType>, TransformedType> transformer) { - if (childNo < 0 || childNo > childCount - 1) { + if(childNo < 0 || childNo > childCount - 1) { final String msg = String.format("Child index #%d is invalid", childNo); throw new IllegalArgumentException(msg); @@ -394,21 +392,21 @@ public class Tree<ContainedType> implements ITree<ContainedType> { @Override public boolean equals(final Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (!(obj instanceof Tree<?>)) return false; + if(this == obj) return true; + if(obj == null) return false; + if(!(obj instanceof Tree<?>)) return false; final Tree<?> other = (Tree<?>) obj; - if (data == null) { - if (other.data != null) return false; - } else if (!data.equals(other.data)) return false; + if(data == null) { + if(other.data != null) return false; + } else if(!data.equals(other.data)) return false; - if (childCount != other.childCount) return false; + if(childCount != other.childCount) return false; - if (children == null) { - if (other.children != null) return false; - } else if (!children.equals(other.children)) return false; + if(children == null) { + if(other.children != null) return false; + } else if(!children.equals(other.children)) return false; return true; } diff --git a/base/src/main/java/bjc/utils/data/ValueToggle.java b/base/src/main/java/bjc/utils/data/ValueToggle.java index 54c7a57..09f314c 100644 --- a/base/src/main/java/bjc/utils/data/ValueToggle.java +++ b/base/src/main/java/bjc/utils/data/ValueToggle.java @@ -6,13 +6,13 @@ package bjc.utils.data; * @author EVE * * @param <E> - * The type of value to toggle between. + * The type of value to toggle between. */ public class ValueToggle<E> implements Toggle<E> { /* Our left value. */ - private final E lft; + private final E lft; /* Our right value. */ - private final E rght; + private final E rght; /* Our alignment. */ private final BooleanToggle alignment; @@ -22,10 +22,10 @@ public class ValueToggle<E> implements Toggle<E> { * All toggles start right-aligned. * * @param left - * The value when the toggle is left-aligned. + * The value when the toggle is left-aligned. * * @param right - * The value when the toggle is right-aligned. + * The value when the toggle is right-aligned. */ public ValueToggle(final E left, final E right) { lft = left; @@ -37,7 +37,7 @@ public class ValueToggle<E> implements Toggle<E> { @Override public E get() { - if (alignment.get()) { + if(alignment.get()) { return lft; } else { return rght; @@ -46,7 +46,7 @@ public class ValueToggle<E> implements Toggle<E> { @Override public E peek() { - if (alignment.peek()) { + if(alignment.peek()) { return lft; } else { return rght; diff --git a/base/src/main/java/bjc/utils/data/internals/BoundLazy.java b/base/src/main/java/bjc/utils/data/internals/BoundLazy.java index a1c2ea0..f4e8f7e 100644 --- a/base/src/main/java/bjc/utils/data/internals/BoundLazy.java +++ b/base/src/main/java/bjc/utils/data/internals/BoundLazy.java @@ -32,13 +32,13 @@ public class BoundLazy<OldType, BoundContainedType> implements IHolder<BoundCont private final IList<UnaryOperator<BoundContainedType>> actions = new FunctionalList<>(); /** - * Create a new bound lazy value. + * Create a new bound lazy value. * * @param supp - * The supplier of the old value. + * The supplier of the old value. * * @param binder - * The function to use to bind the old value to the new one. + * The function to use to bind the old value to the new one. */ public BoundLazy(final Supplier<IHolder<OldType>> supp, final Function<OldType, IHolder<BoundContainedType>> binder) { @@ -48,7 +48,7 @@ public class BoundLazy<OldType, BoundContainedType> implements IHolder<BoundCont @Override public <BoundType> IHolder<BoundType> bind(final Function<BoundContainedType, IHolder<BoundType>> bindr) { - if (bindr == null) throw new NullPointerException("Binder must not be null"); + if(bindr == null) throw new NullPointerException("Binder must not be null"); /* Prepare a list of pending actions. */ final IList<UnaryOperator<BoundContainedType>> pendingActions = new FunctionalList<>(); @@ -59,7 +59,7 @@ public class BoundLazy<OldType, BoundContainedType> implements IHolder<BoundCont IHolder<BoundContainedType> oldHolder = boundHolder; /* Bind the value if it hasn't been bound before. */ - if (!holderBound) { + if(!holderBound) { oldHolder = oldSupplier.get().unwrap(binder); } @@ -75,7 +75,7 @@ public class BoundLazy<OldType, BoundContainedType> implements IHolder<BoundCont @Override public <NewType> Function<BoundContainedType, IHolder<NewType>> lift( final Function<BoundContainedType, NewType> func) { - if (func == null) throw new NullPointerException("Function to lift must not be null"); + if(func == null) throw new NullPointerException("Function to lift must not be null"); return (val) -> { return new Lazy<>(func.apply(val)); @@ -84,7 +84,7 @@ public class BoundLazy<OldType, BoundContainedType> implements IHolder<BoundCont @Override public <MappedType> IHolder<MappedType> map(final Function<BoundContainedType, MappedType> mapper) { - if (mapper == null) throw new NullPointerException("Mapper must not be null"); + if(mapper == null) throw new NullPointerException("Mapper must not be null"); /* Prepare a list of pending actions. */ final IList<UnaryOperator<BoundContainedType>> pendingActions = new FunctionalList<>(); @@ -95,7 +95,7 @@ public class BoundLazy<OldType, BoundContainedType> implements IHolder<BoundCont IHolder<BoundContainedType> oldHolder = boundHolder; /* Bound the value if it hasn't been bound. */ - if (!holderBound) { + if(!holderBound) { oldHolder = oldSupplier.get().unwrap(binder); } @@ -110,14 +110,14 @@ public class BoundLazy<OldType, BoundContainedType> implements IHolder<BoundCont @Override public String toString() { - if (holderBound) return boundHolder.toString(); + if(holderBound) return boundHolder.toString(); return "(unmaterialized)"; } @Override public IHolder<BoundContainedType> transform(final UnaryOperator<BoundContainedType> transformer) { - if (transformer == null) throw new NullPointerException("Transformer must not be null"); + if(transformer == null) throw new NullPointerException("Transformer must not be null"); actions.add(transformer); @@ -126,9 +126,9 @@ public class BoundLazy<OldType, BoundContainedType> implements IHolder<BoundCont @Override public <UnwrappedType> UnwrappedType unwrap(final Function<BoundContainedType, UnwrappedType> unwrapper) { - if (unwrapper == null) throw new NullPointerException("Unwrapper must not be null"); + if(unwrapper == null) throw new NullPointerException("Unwrapper must not be null"); - if (!holderBound) { + if(!holderBound) { boundHolder = oldSupplier.get().unwrap(binder::apply); } diff --git a/base/src/main/java/bjc/utils/data/internals/BoundLazyPair.java b/base/src/main/java/bjc/utils/data/internals/BoundLazyPair.java index 401f5d5..2ef0e4c 100644 --- a/base/src/main/java/bjc/utils/data/internals/BoundLazyPair.java +++ b/base/src/main/java/bjc/utils/data/internals/BoundLazyPair.java @@ -34,13 +34,14 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai * Create a new bound lazy pair. * * @param leftSupp - * The supplier for the left value. + * The supplier for the left value. * * @param rightSupp - * The supplier for the right value. + * The supplier for the right value. * * @param bindr - * The function to use to bind the left and right into a new pair. + * The function to use to bind the left and right into a new + * pair. */ public BoundLazyPair(final Supplier<OldLeft> leftSupp, final Supplier<OldRight> rightSupp, final BiFunction<OldLeft, OldRight, IPair<NewLeft, NewRight>> bindr) { @@ -52,13 +53,13 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai @Override public <BoundLeft, BoundRight> IPair<BoundLeft, BoundRight> bind( final BiFunction<NewLeft, NewRight, IPair<BoundLeft, BoundRight>> bindr) { - if (bindr == null) throw new NullPointerException("Binder must not be null"); + if(bindr == null) throw new NullPointerException("Binder must not be null"); final IHolder<IPair<NewLeft, NewRight>> newPair = new Identity<>(boundPair); - final IHolder<Boolean> newPairMade = new Identity<>(pairBound); + final IHolder<Boolean> newPairMade = new Identity<>(pairBound); final Supplier<NewLeft> leftSupp = () -> { - if (!newPairMade.getValue()) { + if(!newPairMade.getValue()) { /* * If the pair hasn't been bound before, bind * it. @@ -72,7 +73,7 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai }; final Supplier<NewRight> rightSupp = () -> { - if (!newPairMade.getValue()) { + if(!newPairMade.getValue()) { /* * If the pair hasn't been bound before, bind * it. @@ -91,12 +92,12 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai @Override public <BoundLeft> IPair<BoundLeft, NewRight> bindLeft( final Function<NewLeft, IPair<BoundLeft, NewRight>> leftBinder) { - if (leftBinder == null) throw new NullPointerException("Left binder must not be null"); + if(leftBinder == null) throw new NullPointerException("Left binder must not be null"); final Supplier<NewLeft> leftSupp = () -> { IPair<NewLeft, NewRight> newPair = boundPair; - if (!pairBound) { + if(!pairBound) { /* * If the pair hasn't been bound before, bind * it. @@ -113,12 +114,12 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai @Override public <BoundRight> IPair<NewLeft, BoundRight> bindRight( final Function<NewRight, IPair<NewLeft, BoundRight>> rightBinder) { - if (rightBinder == null) throw new NullPointerException("Right binder must not be null"); + if(rightBinder == null) throw new NullPointerException("Right binder must not be null"); final Supplier<NewRight> rightSupp = () -> { IPair<NewLeft, NewRight> newPair = boundPair; - if (!pairBound) { + if(!pairBound) { /* * If the pair hasn't been bound before, bind * it. @@ -137,17 +138,17 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai final IPair<OtherLeft, OtherRight> otherPair, final BiFunction<NewLeft, OtherLeft, CombinedLeft> leftCombiner, final BiFunction<NewRight, OtherRight, CombinedRight> rightCombiner) { - if (otherPair == null) { + if(otherPair == null) { throw new NullPointerException("Other pair must not be null"); - } else if (leftCombiner == null) { + } else if(leftCombiner == null) { throw new NullPointerException("Left combiner must not be null"); - } else if (rightCombiner == null) { + } else if(rightCombiner == null) { throw new NullPointerException("Right combiner must not be null"); } return otherPair.bind((otherLeft, otherRight) -> { return bind((leftVal, rightVal) -> { - CombinedLeft cLeft = leftCombiner.apply(leftVal, otherLeft); + CombinedLeft cLeft = leftCombiner.apply(leftVal, otherLeft); CombinedRight cRight = rightCombiner.apply(rightVal, otherRight); return new LazyPair<>(cLeft, cRight); @@ -157,10 +158,10 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai @Override public <NewLeftType> IPair<NewLeftType, NewRight> mapLeft(final Function<NewLeft, NewLeftType> mapper) { - if (mapper == null) throw new NullPointerException("Mapper must not be null"); + if(mapper == null) throw new NullPointerException("Mapper must not be null"); final Supplier<NewLeftType> leftSupp = () -> { - if (!pairBound) { + if(!pairBound) { final NewLeft leftVal = binder.apply(leftSupplier.get(), rightSupplier.get()).getLeft(); return mapper.apply(leftVal); @@ -170,7 +171,7 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai }; final Supplier<NewRight> rightSupp = () -> { - if (!pairBound) return binder.apply(leftSupplier.get(), rightSupplier.get()).getRight(); + if(!pairBound) return binder.apply(leftSupplier.get(), rightSupplier.get()).getRight(); return boundPair.getRight(); }; @@ -180,16 +181,16 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai @Override public <NewRightType> IPair<NewLeft, NewRightType> mapRight(final Function<NewRight, NewRightType> mapper) { - if (mapper == null) throw new NullPointerException("Mapper must not be null"); + if(mapper == null) throw new NullPointerException("Mapper must not be null"); final Supplier<NewLeft> leftSupp = () -> { - if (!pairBound) return binder.apply(leftSupplier.get(), rightSupplier.get()).getLeft(); + if(!pairBound) return binder.apply(leftSupplier.get(), rightSupplier.get()).getLeft(); return boundPair.getLeft(); }; final Supplier<NewRightType> rightSupp = () -> { - if (!pairBound) { + if(!pairBound) { final NewRight rightVal = binder.apply(leftSupplier.get(), rightSupplier.get()) .getRight(); @@ -204,9 +205,9 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai @Override public <MergedType> MergedType merge(final BiFunction<NewLeft, NewRight, MergedType> merger) { - if (merger == null) throw new NullPointerException("Merger must not be null"); + if(merger == null) throw new NullPointerException("Merger must not be null"); - if (!pairBound) { + if(!pairBound) { /* * If the pair isn't bound yet, bind it. */ @@ -220,7 +221,7 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai @Override public String toString() { - if (pairBound) return boundPair.toString(); + if(pairBound) return boundPair.toString(); return "(un-materialized)"; } diff --git a/base/src/main/java/bjc/utils/data/internals/BoundListHolder.java b/base/src/main/java/bjc/utils/data/internals/BoundListHolder.java index 31178da..613f8e9 100644 --- a/base/src/main/java/bjc/utils/data/internals/BoundListHolder.java +++ b/base/src/main/java/bjc/utils/data/internals/BoundListHolder.java @@ -21,7 +21,7 @@ public class BoundListHolder<ContainedType> implements IHolder<ContainedType> { * Create a new list of holders. * * @param toHold - * The list of holders to, well, hold. + * The list of holders to, well, hold. */ public BoundListHolder(final IList<IHolder<ContainedType>> toHold) { heldHolders = toHold; @@ -29,7 +29,7 @@ public class BoundListHolder<ContainedType> implements IHolder<ContainedType> { @Override public <BoundType> IHolder<BoundType> bind(final Function<ContainedType, IHolder<BoundType>> binder) { - if (binder == null) throw new NullPointerException("Binder must not be null"); + if(binder == null) throw new NullPointerException("Binder must not be null"); final IList<IHolder<BoundType>> boundHolders = heldHolders.map((containedHolder) -> { return containedHolder.bind(binder); @@ -40,7 +40,7 @@ public class BoundListHolder<ContainedType> implements IHolder<ContainedType> { @Override public <NewType> Function<ContainedType, IHolder<NewType>> lift(final Function<ContainedType, NewType> func) { - if (func == null) throw new NullPointerException("Function to lift must not be null"); + if(func == null) throw new NullPointerException("Function to lift must not be null"); return (val) -> { return new ListHolder<>(func.apply(val)); @@ -49,7 +49,7 @@ public class BoundListHolder<ContainedType> implements IHolder<ContainedType> { @Override public <MappedType> IHolder<MappedType> map(final Function<ContainedType, MappedType> mapper) { - if (mapper == null) throw new NullPointerException("Mapper must not be null"); + if(mapper == null) throw new NullPointerException("Mapper must not be null"); final IList<IHolder<MappedType>> mappedHolders = heldHolders.map((containedHolder) -> { return containedHolder.map(mapper); @@ -60,7 +60,7 @@ public class BoundListHolder<ContainedType> implements IHolder<ContainedType> { @Override public IHolder<ContainedType> transform(final UnaryOperator<ContainedType> transformer) { - if (transformer == null) throw new NullPointerException("Transformer must not be null"); + if(transformer == null) throw new NullPointerException("Transformer must not be null"); heldHolders.forEach((containedHolder) -> { containedHolder.transform(transformer); @@ -71,11 +71,10 @@ public class BoundListHolder<ContainedType> implements IHolder<ContainedType> { @Override public <UnwrappedType> UnwrappedType unwrap(final Function<ContainedType, UnwrappedType> unwrapper) { - if (unwrapper == null) throw new NullPointerException("Unwrapper must not be null"); + if(unwrapper == null) throw new NullPointerException("Unwrapper must not be null"); /* - * @NOTE - * Is there another way we could want to do this? + * @NOTE Is there another way we could want to do this? */ return heldHolders.randItem().unwrap(unwrapper); } diff --git a/base/src/main/java/bjc/utils/data/internals/HalfBoundLazyPair.java b/base/src/main/java/bjc/utils/data/internals/HalfBoundLazyPair.java index 5467255..4803bc2 100644 --- a/base/src/main/java/bjc/utils/data/internals/HalfBoundLazyPair.java +++ b/base/src/main/java/bjc/utils/data/internals/HalfBoundLazyPair.java @@ -31,18 +31,18 @@ public class HalfBoundLazyPair<OldType, NewLeft, NewRight> implements IPair<NewL private final Function<OldType, IPair<NewLeft, NewRight>> binder; /* The new bound pair. */ - private IPair<NewLeft, NewRight> boundPair; + private IPair<NewLeft, NewRight> boundPair; /* Has the pair been bound yet or not? */ - private boolean pairBound; + private boolean pairBound; /** * Create a new half-bound lazy pair. * * @param oldSupp - * The supplier of the old value. + * The supplier of the old value. * * @param bindr - * The function to use to create the pair from the old value. + * The function to use to create the pair from the old value. */ public HalfBoundLazyPair(final Supplier<OldType> oldSupp, final Function<OldType, IPair<NewLeft, NewRight>> bindr) { @@ -57,7 +57,7 @@ public class HalfBoundLazyPair<OldType, NewLeft, NewRight> implements IPair<NewL final IHolder<Boolean> newPairMade = new Identity<>(pairBound); final Supplier<NewLeft> leftSupp = () -> { - if (!newPairMade.getValue()) { + if(!newPairMade.getValue()) { /* Bind the pair if it hasn't been bound yet. */ newPair.replace(binder.apply(oldSupplier.get())); newPairMade.replace(true); @@ -67,7 +67,7 @@ public class HalfBoundLazyPair<OldType, NewLeft, NewRight> implements IPair<NewL }; final Supplier<NewRight> rightSupp = () -> { - if (!newPairMade.getValue()) { + if(!newPairMade.getValue()) { /* Bind the pair if it hasn't been bound yet. */ newPair.replace(binder.apply(oldSupplier.get())); newPairMade.replace(true); @@ -85,7 +85,7 @@ public class HalfBoundLazyPair<OldType, NewLeft, NewRight> implements IPair<NewL final Supplier<NewLeft> leftSupp = () -> { IPair<NewLeft, NewRight> newPair = boundPair; - if (!pairBound) { + if(!pairBound) { newPair = binder.apply(oldSupplier.get()); } @@ -101,7 +101,7 @@ public class HalfBoundLazyPair<OldType, NewLeft, NewRight> implements IPair<NewL final Supplier<NewRight> rightSupp = () -> { IPair<NewLeft, NewRight> newPair = boundPair; - if (!pairBound) { + if(!pairBound) { newPair = binder.apply(oldSupplier.get()); } @@ -118,7 +118,7 @@ public class HalfBoundLazyPair<OldType, NewLeft, NewRight> implements IPair<NewL final BiFunction<NewRight, OtherRight, CombinedRight> rightCombiner) { return otherPair.bind((otherLeft, otherRight) -> { return bind((leftVal, rightVal) -> { - CombinedLeft cLeft = leftCombiner.apply(leftVal, otherLeft); + CombinedLeft cLeft = leftCombiner.apply(leftVal, otherLeft); CombinedRight cRight = rightCombiner.apply(rightVal, otherRight); return new LazyPair<>(cLeft, cRight); @@ -129,7 +129,7 @@ public class HalfBoundLazyPair<OldType, NewLeft, NewRight> implements IPair<NewL @Override public <NewLeftType> IPair<NewLeftType, NewRight> mapLeft(final Function<NewLeft, NewLeftType> mapper) { final Supplier<NewLeftType> leftSupp = () -> { - if (pairBound) return mapper.apply(boundPair.getLeft()); + if(pairBound) return mapper.apply(boundPair.getLeft()); final NewLeft leftVal = binder.apply(oldSupplier.get()).getLeft(); @@ -137,7 +137,7 @@ public class HalfBoundLazyPair<OldType, NewLeft, NewRight> implements IPair<NewL }; final Supplier<NewRight> rightSupp = () -> { - if (pairBound) return boundPair.getRight(); + if(pairBound) return boundPair.getRight(); return binder.apply(oldSupplier.get()).getRight(); }; @@ -148,13 +148,13 @@ public class HalfBoundLazyPair<OldType, NewLeft, NewRight> implements IPair<NewL @Override public <NewRightType> IPair<NewLeft, NewRightType> mapRight(final Function<NewRight, NewRightType> mapper) { final Supplier<NewLeft> leftSupp = () -> { - if (pairBound) return boundPair.getLeft(); + if(pairBound) return boundPair.getLeft(); return binder.apply(oldSupplier.get()).getLeft(); }; final Supplier<NewRightType> rightSupp = () -> { - if (pairBound) return mapper.apply(boundPair.getRight()); + if(pairBound) return mapper.apply(boundPair.getRight()); final NewRight rightVal = binder.apply(oldSupplier.get()).getRight(); @@ -166,7 +166,7 @@ public class HalfBoundLazyPair<OldType, NewLeft, NewRight> implements IPair<NewL @Override public <MergedType> MergedType merge(final BiFunction<NewLeft, NewRight, MergedType> merger) { - if (!pairBound) { + if(!pairBound) { boundPair = binder.apply(oldSupplier.get()); pairBound = true; diff --git a/base/src/main/java/bjc/utils/data/internals/WrappedLazy.java b/base/src/main/java/bjc/utils/data/internals/WrappedLazy.java index a5c8130..57f9302 100644 --- a/base/src/main/java/bjc/utils/data/internals/WrappedLazy.java +++ b/base/src/main/java/bjc/utils/data/internals/WrappedLazy.java @@ -19,13 +19,13 @@ public class WrappedLazy<ContainedType> implements IHolder<ContainedType> { * Create a new wrapped lazy value. * * @param wrappedHolder - * The holder to make lazy. + * The holder to make lazy. */ public WrappedLazy(final IHolder<ContainedType> wrappedHolder) { held = new Lazy<>(wrappedHolder); } - /* + /* * This has an extra parameter, because otherwise it erases to the same * as the public one. * diff --git a/base/src/main/java/bjc/utils/data/internals/WrappedOption.java b/base/src/main/java/bjc/utils/data/internals/WrappedOption.java index 872295f..6260ce4 100644 --- a/base/src/main/java/bjc/utils/data/internals/WrappedOption.java +++ b/base/src/main/java/bjc/utils/data/internals/WrappedOption.java @@ -19,7 +19,7 @@ public class WrappedOption<ContainedType> implements IHolder<ContainedType> { * Create a new wrapped option. * * @param seedValue - * The value to wrap. + * The value to wrap. */ public WrappedOption(final IHolder<ContainedType> seedValue) { held = new Option<>(seedValue); @@ -38,7 +38,7 @@ public class WrappedOption<ContainedType> implements IHolder<ContainedType> { public <BoundType> IHolder<BoundType> bind(final Function<ContainedType, IHolder<BoundType>> binder) { final IHolder<IHolder<BoundType>> newHolder = held.map((containedHolder) -> { return containedHolder.bind((containedValue) -> { - if (containedValue == null) return new Option<>(null); + if(containedValue == null) return new Option<>(null); return binder.apply(containedValue); }); @@ -58,7 +58,7 @@ public class WrappedOption<ContainedType> implements IHolder<ContainedType> { public <MappedType> IHolder<MappedType> map(final Function<ContainedType, MappedType> mapper) { final IHolder<IHolder<MappedType>> newHolder = held.map((containedHolder) -> { return containedHolder.map((containedValue) -> { - if (containedValue == null) return null; + if(containedValue == null) return null; return mapper.apply(containedValue); }); @@ -71,7 +71,7 @@ public class WrappedOption<ContainedType> implements IHolder<ContainedType> { public IHolder<ContainedType> transform(final UnaryOperator<ContainedType> transformer) { held.transform((containedHolder) -> { return containedHolder.transform((containedValue) -> { - if (containedValue == null) return null; + if(containedValue == null) return null; return transformer.apply(containedValue); }); @@ -84,7 +84,7 @@ public class WrappedOption<ContainedType> implements IHolder<ContainedType> { public <UnwrappedType> UnwrappedType unwrap(final Function<ContainedType, UnwrappedType> unwrapper) { return held.unwrap((containedHolder) -> { return containedHolder.unwrap((containedValue) -> { - if (containedValue == null) return null; + if(containedValue == null) return null; return unwrapper.apply(containedValue); }); diff --git a/base/src/main/java/bjc/utils/esodata/AbbrevMap.java b/base/src/main/java/bjc/utils/esodata/AbbrevMap.java index 64f542a..59888c0 100644 --- a/base/src/main/java/bjc/utils/esodata/AbbrevMap.java +++ b/base/src/main/java/bjc/utils/esodata/AbbrevMap.java @@ -168,7 +168,9 @@ public class AbbrevMap { */ public String[] deabbrev(final String abbrev) { if(abbrevMap.containsKey(abbrev)) { - return new String[] { abbrevMap.get(abbrev) }; + return new String[] { + abbrevMap.get(abbrev) + }; } return ambMap.get(abbrev).toArray(new String[0]); diff --git a/base/src/main/java/bjc/utils/esodata/Directory.java b/base/src/main/java/bjc/utils/esodata/Directory.java index 4b25cda..b0abd7c 100644 --- a/base/src/main/java/bjc/utils/esodata/Directory.java +++ b/base/src/main/java/bjc/utils/esodata/Directory.java @@ -1,114 +1,107 @@ -package bjc.utils.esodata;
-
-/**
- * Represents a hierarchical map.
- *
- * What's useful about this is that you can hand sub-directories to people and
- * be able to ensure that they can't write outside of it.
- *
- * @param <K>
- * The key type of the map.
- * @param <V>
- * The value type of the map.
- */
-public interface Directory<K, V> {
- /**
- * Retrieves a given sub-directory.
- *
- * @param key
- * The key to retrieve the sub-directory for.
- *
- * @return
- * The sub-directory under that name.
- *
- * @throws IllegalArgumentException
- * If the given sub-directory doesn't exist.
- */
- Directory<K, V> getSubdirectory(K key);
-
- /**
- * Check if a given sub-directory exists.
- *
- * @param key
- * The key to look for the sub-directory under.
- *
- * @return
- * Whether or not a sub-directory of that name exists.
- */
- boolean hasSubdirectory(K key);
-
- /**
- * Insert a sub-directory into the dictionary.
- *
- * @param key
- * The name of the new sub-directory
- * @param value
- * The sub-directory to insert
- *
- * @return
- * The old sub-directory attached to this key, or null if such a
- * sub-directory didn't exist
- */
- Directory<K, V> putSubdirectory(K key, Directory<K, V> value);
-
- /**
- * Create a new sub-directory.
- *
- * Will fail if a sub-directory of that name already exists.
- *
- * @param key
- * The name of the new sub-directory.
- *
- * @return
- * The new sub-directory, or null if one by that name already
- * exists.
- */
- default Directory<K, V> newSubdirectory(final K key) {
- if (hasSubdirectory(key)) return null;
-
- final Directory<K, V> dir = new SimpleDirectory<>();
-
- putSubdirectory(key, dir);
-
- return dir;
- }
-
- /**
- * Check if the directory contains a data-item under the given key.
- *
- * @param key
- * The key to check for.
- *
- * @return
- * Whether or not there is a data item for the given key.
- */
- boolean containsKey(K key);
-
- /**
- * Retrieve a given data-item from the directory.
- *
- * @param key
- * The key to retrieve data for.
- *
- * @return
- * The value for the given key.
- *
- * @throws IllegalArgumentException
- * If no value exists for the given key.
- */
- V getKey(K key);
-
- /**
- * Insert a data-item into the directory.
- *
- * @param key
- * The key to insert into.
- *
- * @param val
- * The value to insert.
- *
- * @return
- * The old value of key, or null if such a value didn't exist.
- */
- V putKey(K key, V val);
-}
+package bjc.utils.esodata; + +/** + * Represents a hierarchical map. + * + * What's useful about this is that you can hand sub-directories to people and + * be able to ensure that they can't write outside of it. + * + * @param <K> + * The key type of the map. + * @param <V> + * The value type of the map. + */ +public interface Directory<K, V> { + /** + * Retrieves a given sub-directory. + * + * @param key + * The key to retrieve the sub-directory for. + * + * @return The sub-directory under that name. + * + * @throws IllegalArgumentException + * If the given sub-directory doesn't exist. + */ + Directory<K, V> getSubdirectory(K key); + + /** + * Check if a given sub-directory exists. + * + * @param key + * The key to look for the sub-directory under. + * + * @return Whether or not a sub-directory of that name exists. + */ + boolean hasSubdirectory(K key); + + /** + * Insert a sub-directory into the dictionary. + * + * @param key + * The name of the new sub-directory + * @param value + * The sub-directory to insert + * + * @return The old sub-directory attached to this key, or null if such a + * sub-directory didn't exist + */ + Directory<K, V> putSubdirectory(K key, Directory<K, V> value); + + /** + * Create a new sub-directory. + * + * Will fail if a sub-directory of that name already exists. + * + * @param key + * The name of the new sub-directory. + * + * @return The new sub-directory, or null if one by that name already + * exists. + */ + default Directory<K, V> newSubdirectory(final K key) { + if(hasSubdirectory(key)) return null; + + final Directory<K, V> dir = new SimpleDirectory<>(); + + putSubdirectory(key, dir); + + return dir; + } + + /** + * Check if the directory contains a data-item under the given key. + * + * @param key + * The key to check for. + * + * @return Whether or not there is a data item for the given key. + */ + boolean containsKey(K key); + + /** + * Retrieve a given data-item from the directory. + * + * @param key + * The key to retrieve data for. + * + * @return The value for the given key. + * + * @throws IllegalArgumentException + * If no value exists for the given key. + */ + V getKey(K key); + + /** + * Insert a data-item into the directory. + * + * @param key + * The key to insert into. + * + * @param val + * The value to insert. + * + * @return The old value of key, or null if such a value didn't exist. + */ + V putKey(K key, V val); +} diff --git a/base/src/main/java/bjc/utils/esodata/DoubleTape.java b/base/src/main/java/bjc/utils/esodata/DoubleTape.java index a0031ec..bfc58a4 100644 --- a/base/src/main/java/bjc/utils/esodata/DoubleTape.java +++ b/base/src/main/java/bjc/utils/esodata/DoubleTape.java @@ -20,15 +20,15 @@ package bjc.utils.esodata; * Flip refers to the entire tape for 'obvious' reasons. * * @param <T> - * The element type of the tape. + * The element type of the tape. * * @author bjculkin */ public class DoubleTape<T> implements Tape<T> { /* The front-side of the tape. */ - private Tape<T> front; + private Tape<T> front; /* The back-side of the tape. */ - private Tape<T> back; + private Tape<T> back; /** Create a new empty double-sided tape that doesn't autoextend. */ public DoubleTape() { @@ -40,7 +40,7 @@ public class DoubleTape<T> implements Tape<T> { * auto-extension policy. * * @param autoExtnd - * Whether or not to auto-extend the tape to the right w/ nulls. + * Whether or not to auto-extend the tape to the right w/ nulls. */ public DoubleTape(final boolean autoExtnd) { front = new SingleTape<>(autoExtnd); @@ -107,7 +107,7 @@ public class DoubleTape<T> implements Tape<T> { public boolean left(final int amt) { final boolean succ = front.left(amt); - if (succ) { + if(succ) { back.right(amt); } @@ -123,7 +123,7 @@ public class DoubleTape<T> implements Tape<T> { public boolean right(final int amt) { final boolean succ = front.right(amt); - if (succ) { + if(succ) { back.left(amt); } @@ -160,19 +160,19 @@ public class DoubleTape<T> implements Tape<T> { @Override public boolean equals(final Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (!(obj instanceof DoubleTape<?>)) return false; + if(this == obj) return true; + if(obj == null) return false; + if(!(obj instanceof DoubleTape<?>)) return false; final DoubleTape<?> other = (DoubleTape<?>) obj; - if (back == null) { - if (other.back != null) return false; - } else if (!back.equals(other.back)) return false; + if(back == null) { + if(other.back != null) return false; + } else if(!back.equals(other.back)) return false; - if (front == null) { - if (other.front != null) return false; - } else if (!front.equals(other.front)) return false; + if(front == null) { + if(other.front != null) return false; + } else if(!front.equals(other.front)) return false; return true; } diff --git a/base/src/main/java/bjc/utils/esodata/PushdownMap.java b/base/src/main/java/bjc/utils/esodata/PushdownMap.java index 18a9b46..e010fee 100644 --- a/base/src/main/java/bjc/utils/esodata/PushdownMap.java +++ b/base/src/main/java/bjc/utils/esodata/PushdownMap.java @@ -17,10 +17,10 @@ import bjc.utils.funcdata.IMap; * @author EVE * * @param <KeyType> - * The key of the map. + * The key of the map. * * @param <ValueType> - * The values in the map. + * The values in the map. */ public class PushdownMap<KeyType, ValueType> implements IMap<KeyType, ValueType> { /* Our backing storage. */ @@ -84,17 +84,16 @@ public class PushdownMap<KeyType, ValueType> implements IMap<KeyType, ValueType> @Override public <V2> IMap<KeyType, V2> transform(final Function<ValueType, V2> transformer) { /* - * @NOTE - * Can and should we support this? - * More to the point, maybe this should be a map sub-type - * that does what it needs to? + * @NOTE Can and should we support this? More to the point, + * maybe this should be a map sub-type that does what it needs + * to? */ throw new UnsupportedOperationException("Cannot transform pushdown maps."); } @Override public ValueType put(final KeyType key, final ValueType val) { - if (backing.containsKey(key)) { + if(backing.containsKey(key)) { final Stack<ValueType> stk = backing.get(key); final ValueType vl = stk.top(); @@ -115,7 +114,7 @@ public class PushdownMap<KeyType, ValueType> implements IMap<KeyType, ValueType> public ValueType remove(final KeyType key) { final Stack<ValueType> stk = backing.get(key); - if (stk.size() > 1) { + if(stk.size() > 1) { return stk.pop(); } else { return backing.remove(key).top(); @@ -139,15 +138,15 @@ public class PushdownMap<KeyType, ValueType> implements IMap<KeyType, ValueType> @Override public boolean equals(final Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (!(obj instanceof PushdownMap<?, ?>)) return false; + if(this == obj) return true; + if(obj == null) return false; + if(!(obj instanceof PushdownMap<?, ?>)) return false; final PushdownMap<?, ?> other = (PushdownMap<?, ?>) obj; - if (backing == null) { - if (other.backing != null) return false; - } else if (!backing.equals(other.backing)) return false; + if(backing == null) { + if(other.backing != null) return false; + } else if(!backing.equals(other.backing)) return false; return true; } diff --git a/base/src/main/java/bjc/utils/esodata/QueueStack.java b/base/src/main/java/bjc/utils/esodata/QueueStack.java index be393a3..c0cbc7d 100644 --- a/base/src/main/java/bjc/utils/esodata/QueueStack.java +++ b/base/src/main/java/bjc/utils/esodata/QueueStack.java @@ -9,7 +9,7 @@ import java.util.LinkedList; * Basically, a stack that actually acts like a queue. * * @param <T> - * The datatype stored in the stack. + * The datatype stored in the stack. * * @author Ben Culkin */ @@ -29,14 +29,14 @@ public class QueueStack<T> extends Stack<T> { @Override public T pop() { - if (backing.isEmpty()) throw new StackUnderflowException(); + if(backing.isEmpty()) throw new StackUnderflowException(); return backing.remove(); } @Override public T top() { - if (backing.isEmpty()) throw new StackUnderflowException(); + if(backing.isEmpty()) throw new StackUnderflowException(); return backing.peek(); } @@ -74,15 +74,15 @@ public class QueueStack<T> extends Stack<T> { @Override public boolean equals(final Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (!(obj instanceof QueueStack<?>)) return false; + if(this == obj) return true; + if(obj == null) return false; + if(!(obj instanceof QueueStack<?>)) return false; final QueueStack<?> other = (QueueStack<?>) obj; - if (backing == null) { - if (other.backing != null) return false; - } else if (!backing.equals(other.backing)) return false; + if(backing == null) { + if(other.backing != null) return false; + } else if(!backing.equals(other.backing)) return false; return true; } diff --git a/base/src/main/java/bjc/utils/esodata/SimpleDirectory.java b/base/src/main/java/bjc/utils/esodata/SimpleDirectory.java index 5e7f480..a3e0a96 100644 --- a/base/src/main/java/bjc/utils/esodata/SimpleDirectory.java +++ b/base/src/main/java/bjc/utils/esodata/SimpleDirectory.java @@ -11,10 +11,10 @@ import bjc.utils.funcdata.IMap; * @author EVE * * @param <K> - * The key type of the directory. + * The key type of the directory. * * @param <V> - * The value type of the directory. + * The value type of the directory. */ public class SimpleDirectory<K, V> implements Directory<K, V> { /* Our sub-directories. */ @@ -25,7 +25,7 @@ public class SimpleDirectory<K, V> implements Directory<K, V> { /** Create a new directory. */ public SimpleDirectory() { children = new FunctionalMap<>(); - data = new FunctionalMap<>(); + data = new FunctionalMap<>(); } @Override @@ -71,19 +71,19 @@ public class SimpleDirectory<K, V> implements Directory<K, V> { @Override public boolean equals(final Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (!(obj instanceof SimpleDirectory<?, ?>)) return false; + if(this == obj) return true; + if(obj == null) return false; + if(!(obj instanceof SimpleDirectory<?, ?>)) return false; final SimpleDirectory<?, ?> other = (SimpleDirectory<?, ?>) obj; - if (children == null) { - if (other.children != null) return false; - } else if (!children.equals(other.children)) return false; + if(children == null) { + if(other.children != null) return false; + } else if(!children.equals(other.children)) return false; - if (data == null) { - if (other.data != null) return false; - } else if (!data.equals(other.data)) return false; + if(data == null) { + if(other.data != null) return false; + } else if(!data.equals(other.data)) return false; return true; } diff --git a/base/src/main/java/bjc/utils/esodata/SimpleStack.java b/base/src/main/java/bjc/utils/esodata/SimpleStack.java index 72fb343..8bc7e1e 100644 --- a/base/src/main/java/bjc/utils/esodata/SimpleStack.java +++ b/base/src/main/java/bjc/utils/esodata/SimpleStack.java @@ -7,7 +7,7 @@ import java.util.LinkedList; * Simple implementation of a stack. * * @param <T> - * The datatype stored in the stack. + * The datatype stored in the stack. * * @author Ben Culkin */ @@ -27,14 +27,14 @@ public class SimpleStack<T> extends Stack<T> { @Override public T pop() { - if (backing.isEmpty()) throw new StackUnderflowException(); + if(backing.isEmpty()) throw new StackUnderflowException(); return backing.pop(); } @Override public T top() { - if (backing.isEmpty()) throw new StackUnderflowException(); + if(backing.isEmpty()) throw new StackUnderflowException(); return backing.peek(); } @@ -67,15 +67,15 @@ public class SimpleStack<T> extends Stack<T> { @Override public boolean equals(final Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (!(obj instanceof SimpleStack<?>)) return false; + if(this == obj) return true; + if(obj == null) return false; + if(!(obj instanceof SimpleStack<?>)) return false; final SimpleStack<?> other = (SimpleStack<?>) obj; - if (backing == null) { - if (other.backing != null) return false; - } else if (!backing.equals(other.backing)) return false; + if(backing == null) { + if(other.backing != null) return false; + } else if(!backing.equals(other.backing)) return false; return true; } diff --git a/base/src/main/java/bjc/utils/esodata/SingleTape.java b/base/src/main/java/bjc/utils/esodata/SingleTape.java index ae9b746..57ee99a 100644 --- a/base/src/main/java/bjc/utils/esodata/SingleTape.java +++ b/base/src/main/java/bjc/utils/esodata/SingleTape.java @@ -15,20 +15,20 @@ import java.util.ArrayList; * policy. * * @param <T> - * The element type of the tape. + * The element type of the tape. * * @author bjculkin */ public class SingleTape<T> implements Tape<T> { - /* @NOTE - * Does this stuff still need to be protected? We're not trying to - * use inheritance to implement tape types any more, so I don't see - * any reason to not have it be private. + /* + * @NOTE Does this stuff still need to be protected? We're not trying to + * use inheritance to implement tape types any more, so I don't see any + * reason to not have it be private. */ /* Our backing store. */ - protected ArrayList<T> backing; + protected ArrayList<T> backing; /* Our position in the list. */ - protected int pos; + protected int pos; /* Whether to auto-extend the list on the left with nulls. */ protected boolean autoExtend; @@ -57,7 +57,7 @@ public class SingleTape<T> implements Tape<T> { * policy. * * @param autoExtnd - * Whether or not to auto-extend the tape to the right w/ nulls. + * Whether or not to auto-extend the tape to the right w/ nulls. */ public SingleTape(final boolean autoExtnd) { autoExtend = autoExtnd; @@ -92,7 +92,7 @@ public class SingleTape<T> implements Tape<T> { @Override public void insertAfter(final T itm) { - if (pos == backing.size() - 1) { + if(pos == backing.size() - 1) { backing.add(itm); } else { backing.add(pos + 1, itm); @@ -102,7 +102,7 @@ public class SingleTape<T> implements Tape<T> { @Override public T remove() { final T res = backing.remove(pos); - if (pos != 0) { + if(pos != 0) { pos -= 1; } return res; @@ -125,7 +125,7 @@ public class SingleTape<T> implements Tape<T> { @Override public boolean left(final int amt) { - if (pos - amt < 0) return false; + if(pos - amt < 0) return false; pos -= amt; return true; @@ -138,12 +138,13 @@ public class SingleTape<T> implements Tape<T> { @Override public boolean right(final int amt) { - if (pos + amt >= backing.size() - 1) { - if (autoExtend) { - while (pos + amt >= backing.size() - 1) { + if(pos + amt >= backing.size() - 1) { + if(autoExtend) { + while(pos + amt >= backing.size() - 1) { backing.add(null); } - } else return false; + } else + return false; } pos += amt; @@ -167,15 +168,15 @@ public class SingleTape<T> implements Tape<T> { @Override public boolean equals(final Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (!(obj instanceof SingleTape<?>)) return false; + if(this == obj) return true; + if(obj == null) return false; + if(!(obj instanceof SingleTape<?>)) return false; final SingleTape<?> other = (SingleTape<?>) obj; - if (backing == null) { - if (other.backing != null) return false; - } else if (!backing.equals(other.backing)) return false; + if(backing == null) { + if(other.backing != null) return false; + } else if(!backing.equals(other.backing)) return false; return true; } diff --git a/base/src/main/java/bjc/utils/esodata/SpaghettiStack.java b/base/src/main/java/bjc/utils/esodata/SpaghettiStack.java index f445f75..8f2924b 100644 --- a/base/src/main/java/bjc/utils/esodata/SpaghettiStack.java +++ b/base/src/main/java/bjc/utils/esodata/SpaghettiStack.java @@ -8,7 +8,7 @@ import java.util.stream.Stream; * parent stack. * * @param <T> - * The datatype stored in the stack. + * The datatype stored in the stack. * * @author Ben Culkin */ @@ -22,7 +22,7 @@ class SpaghettiStack<T> extends Stack<T> { * Create a new empty spaghetti stack, off of the specified parent. * * @param par - * The parent stack + * The parent stack */ public SpaghettiStack(final Stack<T> par) { backing = new SimpleStack<>(); @@ -37,14 +37,14 @@ class SpaghettiStack<T> extends Stack<T> { @Override public T pop() { - if (backing.empty()) return parent.pop(); + if(backing.empty()) return parent.pop(); return backing.pop(); } @Override public T top() { - if (backing.empty()) return parent.top(); + if(backing.empty()) return parent.top(); return backing.top(); } @@ -78,19 +78,19 @@ class SpaghettiStack<T> extends Stack<T> { @Override public boolean equals(final Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (!(obj instanceof SpaghettiStack<?>)) return false; + if(this == obj) return true; + if(obj == null) return false; + if(!(obj instanceof SpaghettiStack<?>)) return false; final SpaghettiStack<?> other = (SpaghettiStack<?>) obj; - if (backing == null) { - if (other.backing != null) return false; - } else if (!backing.equals(other.backing)) return false; + if(backing == null) { + if(other.backing != null) return false; + } else if(!backing.equals(other.backing)) return false; - if (parent == null) { - if (other.parent != null) return false; - } else if (!parent.equals(other.parent)) return false; + if(parent == null) { + if(other.parent != null) return false; + } else if(!parent.equals(other.parent)) return false; return true; } diff --git a/base/src/main/java/bjc/utils/esodata/Stack.java b/base/src/main/java/bjc/utils/esodata/Stack.java index 9bb61dc..5c923c3 100644 --- a/base/src/main/java/bjc/utils/esodata/Stack.java +++ b/base/src/main/java/bjc/utils/esodata/Stack.java @@ -21,7 +21,7 @@ import java.util.function.Consumer; * </p> * * @param <T> - * The datatype stored in the stack. + * The datatype stored in the stack. * * @author Ben Culkin */ @@ -41,15 +41,14 @@ public abstract class Stack<T> { * Push an element onto the stack. * * @param elm - * The element to insert. + * The element to insert. */ public abstract void push(T elm); /** * Pop an element off of the stack. * - * @return - * The element on top of the stack. + * @return The element on top of the stack. */ public abstract T pop(); @@ -57,32 +56,28 @@ public abstract class Stack<T> { * Retrieve the top element of this stack without removing it from the * stack. * - * @return - * The top element of this stack. + * @return The top element of this stack. */ public abstract T top(); /** * Get the number of elements in the stack. * - * @return - * the number of elements in the stack. + * @return the number of elements in the stack. */ public abstract int size(); /** * Check if the stack is empty. * - * @return - * Whether or not the stack is empty. + * @return Whether or not the stack is empty. */ public abstract boolean empty(); /** * Create a spaghetti stack branching off of this one. * - * @return - * A spaghetti stack with this stack as a parent. + * @return A spaghetti stack with this stack as a parent. */ public Stack<T> spaghettify() { return new SpaghettiStack<>(this); @@ -96,10 +91,10 @@ public abstract class Stack<T> { * Drop n items from the stack. * * @param n - * The number of items to drop. + * The number of items to drop. */ public void drop(final int n) { - for (int i = 0; i < n; i++) { + for(int i = 0; i < n; i++) { pop(); } } @@ -113,7 +108,7 @@ public abstract class Stack<T> { * Delete n items below the current one. * * @param n - * The number of items below the top to delete. + * The number of items below the top to delete. */ public void nip(final int n) { final T elm = pop(); @@ -132,20 +127,20 @@ public abstract class Stack<T> { * Replicate the top n items of the stack m times. * * @param n - * The number of items to duplicate. + * The number of items to duplicate. * * @param m - * The number of times to duplicate items. + * The number of times to duplicate items. */ public void multidup(final int n, final int m) { final List<T> lst = new ArrayList<>(n); - for (int i = n; i > 0; i--) { + for(int i = n; i > 0; i--) { lst.set(i - 1, pop()); } - for (int i = 0; i < m; i++) { - for (final T elm : lst) { + for(int i = 0; i < m; i++) { + for(final T elm : lst) { push(elm); } } @@ -155,7 +150,7 @@ public abstract class Stack<T> { * Duplicate the top n items of the stack. * * @param n - * The number of items to duplicate. + * The number of items to duplicate. */ public void dup(final int n) { multidup(n, 2); @@ -170,27 +165,27 @@ public abstract class Stack<T> { * Replicate the n elements below the top one m times. * * @param n - * The number of items to duplicate. + * The number of items to duplicate. * * @param m - * The number of times to duplicate items. + * The number of times to duplicate items. */ public void multiover(final int n, final int m) { final List<T> lst = new ArrayList<>(n); final T elm = pop(); - for (int i = n; i > 0; i--) { + for(int i = n; i > 0; i--) { lst.set(i - 1, pop()); } - for (final T nelm : lst) { + for(final T nelm : lst) { push(nelm); } push(elm); - for (int i = 1; i < m; i++) { - for (final T nelm : lst) { + for(int i = 1; i < m; i++) { + for(final T nelm : lst) { push(nelm); } } @@ -200,7 +195,7 @@ public abstract class Stack<T> { * Duplicate the n elements below the top one. * * @param n - * The number of items to duplicate. + * The number of items to duplicate. */ public void over(final int n) { multiover(n, 2); @@ -275,9 +270,8 @@ public abstract class Stack<T> { push(y); } - /* - * :StackCombinators - * Add a general rotate/roll operator. + /* + * :StackCombinators Add a general rotate/roll operator. */ /* @@ -288,21 +282,21 @@ public abstract class Stack<T> { * Hides the top n elements on the stack from an action. * * @param n - * The number of elements to hide. + * The number of elements to hide. * * @param action - * The action to hide the elements from + * The action to hide the elements from */ public void dip(final int n, final Consumer<Stack<T>> action) { final List<T> elms = new ArrayList<>(n); - for (int i = n; i > 0; i--) { + for(int i = n; i > 0; i--) { elms.set(i - 1, pop()); } action.accept(this); - for (final T elm : elms) { + for(final T elm : elms) { push(elm); } } @@ -311,26 +305,25 @@ public abstract class Stack<T> { * Hide the top element of the stack from an action. * * @param action - * The action to hide the top from + * The action to hide the top from */ public void dip(final Consumer<Stack<T>> action) { dip(1, action); } /** - * Copy the top n elements on the stack, replacing them once an action is - * done. + * Copy the top n elements on the stack, replacing them once an action + * is done. * * @param n - * The number of elements to copy. + * The number of elements to copy. * * @param action - * The action to execute. + * The action to execute. */ public void keep(final int n, final Consumer<Stack<T>> action) { /* - * @NOTE - * Is this correct? + * @NOTE Is this correct? */ dup(n); dip(n, action); @@ -340,20 +333,20 @@ public abstract class Stack<T> { * Apply all the actions in a list to the top n elements of the stack. * * @param n - * The number of elements to give to cons. + * The number of elements to give to cons. * * @param actions - * The actions to execute. + * The actions to execute. */ public void multicleave(final int n, final List<Consumer<Stack<T>>> actions) { final List<T> elms = new ArrayList<>(n); - for (int i = n; i > 0; i--) { + for(int i = n; i > 0; i--) { elms.set(i - 1, pop()); } - for (final Consumer<Stack<T>> action : actions) { - for (final T elm : elms) { + for(final Consumer<Stack<T>> action : actions) { + for(final T elm : elms) { push(elm); } @@ -365,7 +358,7 @@ public abstract class Stack<T> { * Apply all the actions in a list to the top element of the stack. * * @param actions - * The actions to execute. + * The actions to execute. */ public void cleave(final List<Consumer<Stack<T>>> actions) { multicleave(1, actions); @@ -375,18 +368,18 @@ public abstract class Stack<T> { * Apply every action in a list of actions to n arguments. * * @param n - * The number of parameters each action takes. + * The number of parameters each action takes. * * @param actions - * The actions to execute. + * The actions to execute. */ public void multispread(final int n, final List<Consumer<Stack<T>>> actions) { final List<List<T>> nelms = new ArrayList<>(actions.size()); - for (int i = actions.size(); i > 0; i--) { + for(int i = actions.size(); i > 0; i--) { final List<T> elms = new ArrayList<>(n); - for (int j = n; j > 0; j--) { + for(int j = n; j > 0; j--) { elms.set(j, pop()); } @@ -394,8 +387,8 @@ public abstract class Stack<T> { } int i = 0; - for (final List<T> elms : nelms) { - for (final T elm : elms) { + for(final List<T> elms : nelms) { + for(final T elm : elms) { push(elm); } @@ -409,7 +402,7 @@ public abstract class Stack<T> { * the stack. * * @param conses - * The actions to execute. + * The actions to execute. */ public void spread(final List<Consumer<Stack<T>>> conses) { multispread(1, conses); @@ -419,18 +412,18 @@ public abstract class Stack<T> { * Apply an action to the first m groups of n arguments. * * @param n - * The number of arguments cons takes. + * The number of arguments cons takes. * * @param m - * The number of time to call cons. + * The number of time to call cons. * * @param action - * The action to execute. + * The action to execute. */ public void multiapply(final int n, final int m, final Consumer<Stack<T>> action) { final List<Consumer<Stack<T>>> actions = new ArrayList<>(m); - for (int i = 0; i < m; i++) { + for(int i = 0; i < m; i++) { actions.add(action); } @@ -441,10 +434,10 @@ public abstract class Stack<T> { * Apply an action n times to the corresponding elements in the stack. * * @param n - * The number of times to execute cons. + * The number of times to execute cons. * * @param action - * The action to execute. + * The action to execute. */ public void apply(final int n, final Consumer<Stack<T>> action) { multiapply(1, n, action); @@ -457,8 +450,7 @@ public abstract class Stack<T> { /** * Get an array representing this stack. * - * @return - * The stack as an array. + * @return The stack as an array. */ public abstract T[] toArray(); } diff --git a/base/src/main/java/bjc/utils/esodata/Tape.java b/base/src/main/java/bjc/utils/esodata/Tape.java index dab027f..91a404a 100644 --- a/base/src/main/java/bjc/utils/esodata/Tape.java +++ b/base/src/main/java/bjc/utils/esodata/Tape.java @@ -8,7 +8,7 @@ package bjc.utils.esodata; * unbounded to the right, but in practice bounded by available memory. * * @param <T> - * The element type of the tape. + * The element type of the tape. * * @author bjculkin */ @@ -16,8 +16,7 @@ public interface Tape<T> { /** * Get the item the tape is currently on. * - * @return - * The item the tape is on. + * @return The item the tape is on. */ T item(); @@ -25,23 +24,21 @@ public interface Tape<T> { * Set the item the tape is currently on. * * @param itm - * The new value for the tape item. + * The new value for the tape item. */ void item(T itm); /** * Get the current number of elements in the tape. * - * @return - * The current number of elements in the tape. + * @return The current number of elements in the tape. */ int size(); /** * Get the position of the current item. * - * @return - * The position of the current item. + * @return The position of the current item. */ int position(); @@ -49,7 +46,7 @@ public interface Tape<T> { * Insert an element before the current item. * * @param itm - * The item to add. + * The item to add. */ void insertBefore(T itm); @@ -57,7 +54,7 @@ public interface Tape<T> { * Insert an element after the current item. * * @param itm - * The item to insert. + * The item to insert. */ void insertAfter(T itm); @@ -67,8 +64,7 @@ public interface Tape<T> { * Also moves the cursor back one step if possible to maintain relative * position. * - * @return - * The removed item. + * @return The removed item. */ T remove(); @@ -83,8 +79,7 @@ public interface Tape<T> { * * The cursor can't go past zero. * - * @return - * True if the cursor was moved left. + * @return True if the cursor was moved left. */ boolean left(); @@ -95,18 +90,16 @@ public interface Tape<T> { * that would exceed zero don't move the cursor at all. * * @param amt - * The amount to attempt to move the cursor left. + * The amount to attempt to move the cursor left. * - * @return - * True if the cursor was moved left. + * @return True if the cursor was moved left. */ boolean left(int amt); /** * Move the cursor one space right. * - * @return - * Whether the cursor was moved right. + * @return Whether the cursor was moved right. */ boolean right(); @@ -114,18 +107,16 @@ public interface Tape<T> { * Move the cursor the specified amount right. * * @param amt - * The amount to move the cursor right by. + * The amount to move the cursor right by. * - * @return - * Whether the cursor was moved right. + * @return Whether the cursor was moved right. */ boolean right(int amt); /** * Is this tape double sided? * - * @return - * Whether or not this tape is double-sided. + * @return Whether or not this tape is double-sided. */ boolean isDoubleSided(); } diff --git a/base/src/main/java/bjc/utils/esodata/TapeChanger.java b/base/src/main/java/bjc/utils/esodata/TapeChanger.java index 08f56c1..2623ad3 100644 --- a/base/src/main/java/bjc/utils/esodata/TapeChanger.java +++ b/base/src/main/java/bjc/utils/esodata/TapeChanger.java @@ -10,13 +10,13 @@ package bjc.utils.esodata; * either return null/false. * * @param <T> - * The element type of the tapes. + * The element type of the tapes. */ public class TapeChanger<T> implements Tape<T> { /* Our list of tapes. */ private Tape<Tape<T>> tapes; /* The current tape. */ - private Tape<T> currentTape; + private Tape<T> currentTape; /** Create a new empty tape changer. */ public TapeChanger() { @@ -27,10 +27,10 @@ public class TapeChanger<T> implements Tape<T> { * Create a new tape changer with the specified tapes. * * @param current - * The tape to mount first. + * The tape to mount first. * * @param others - * The tapes to put in this tape changer. + * The tapes to put in this tape changer. */ @SafeVarargs public TapeChanger(final Tape<T> current, final Tape<T>... others) { @@ -38,7 +38,7 @@ public class TapeChanger<T> implements Tape<T> { tapes.insertBefore(current); - for (final Tape<T> tp : others) { + for(final Tape<T> tp : others) { tapes.insertAfter(tp); tapes.right(); } @@ -49,63 +49,63 @@ public class TapeChanger<T> implements Tape<T> { @Override public T item() { - if (currentTape == null) return null; + if(currentTape == null) return null; return currentTape.item(); } @Override public void item(final T itm) { - if (currentTape == null) return; + if(currentTape == null) return; currentTape.item(itm); } @Override public int size() { - if (currentTape == null) return 0; + if(currentTape == null) return 0; return currentTape.size(); } @Override public int position() { - if (currentTape == null) return 0; + if(currentTape == null) return 0; return currentTape.position(); } @Override public void insertBefore(final T itm) { - if (currentTape == null) return; + if(currentTape == null) return; currentTape.insertBefore(itm); } @Override public void insertAfter(final T itm) { - if (currentTape == null) return; + if(currentTape == null) return; currentTape.insertAfter(itm); } @Override public T remove() { - if (currentTape == null) return null; + if(currentTape == null) return null; return currentTape.remove(); } @Override public void first() { - if (currentTape == null) return; + if(currentTape == null) return; currentTape.first(); } @Override public void last() { - if (currentTape == null) return; + if(currentTape == null) return; currentTape.last(); } @@ -117,7 +117,7 @@ public class TapeChanger<T> implements Tape<T> { @Override public boolean left(final int amt) { - if (currentTape == null) return false; + if(currentTape == null) return false; return currentTape.left(amt); } @@ -129,7 +129,7 @@ public class TapeChanger<T> implements Tape<T> { @Override public boolean right(final int amt) { - if (currentTape == null) return false; + if(currentTape == null) return false; return currentTape.right(amt); } @@ -143,16 +143,16 @@ public class TapeChanger<T> implements Tape<T> { * If the current tape is not double-sided, does nothing. */ public void flip() { - if (currentTape == null) return; + if(currentTape == null) return; - if (currentTape.isDoubleSided()) { + if(currentTape.isDoubleSided()) { ((DoubleTape<T>) currentTape).flip(); } } @Override public boolean isDoubleSided() { - if (currentTape == null) return false; + if(currentTape == null) return false; return currentTape.isDoubleSided(); } @@ -160,8 +160,7 @@ public class TapeChanger<T> implements Tape<T> { /** * Check if a tape is currently loaded. * - * @return - * Whether or not a tape is loaded. + * @return Whether or not a tape is loaded. */ public boolean isLoaded() { return currentTape != null; @@ -173,13 +172,12 @@ public class TapeChanger<T> implements Tape<T> { * Attempting to load a tape that isn't there won't eject the current * tape. * - * @return - * Whether or not the next tape was loaded. + * @return Whether or not the next tape was loaded. */ public boolean nextTape() { final boolean succ = tapes.right(); - if (succ) { + if(succ) { currentTape = tapes.item(); } @@ -192,13 +190,12 @@ public class TapeChanger<T> implements Tape<T> { * Attempting to load a tape that isn't there won't eject the current * tape. * - * @return - * Whether or not the previous tape was loaded. + * @return Whether or not the previous tape was loaded. */ public boolean prevTape() { final boolean succ = tapes.left(); - if (succ) { + if(succ) { currentTape = tapes.item(); } @@ -213,7 +210,7 @@ public class TapeChanger<T> implements Tape<T> { * The specified tape is loaded. * * @param tp - * The tape to insert and load. + * The tape to insert and load. */ public void insertTape(final Tape<T> tp) { tapes.insertAfter(tp); @@ -229,11 +226,10 @@ public class TapeChanger<T> implements Tape<T> { * * Loads the previous tape, if there is one. * - * @return - * The removed tape. + * @return The removed tape. */ public Tape<T> removeTape() { - if (currentTape == null) return null; + if(currentTape == null) return null; final Tape<T> tp = tapes.remove(); currentTape = tapes.item(); @@ -253,8 +249,7 @@ public class TapeChanger<T> implements Tape<T> { /** * Get how many tapes are currently in the changer. * - * @return - * How many tapes are currently in the changer. + * @return How many tapes are currently in the changer. */ public int tapeCount() { return tapes.size(); @@ -271,19 +266,19 @@ public class TapeChanger<T> implements Tape<T> { @Override public boolean equals(final Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (!(obj instanceof TapeChanger<?>)) return false; + if(this == obj) return true; + if(obj == null) return false; + if(!(obj instanceof TapeChanger<?>)) return false; final TapeChanger<?> other = (TapeChanger<?>) obj; - if (currentTape == null) { - if (other.currentTape != null) return false; - } else if (!currentTape.equals(other.currentTape)) return false; + if(currentTape == null) { + if(other.currentTape != null) return false; + } else if(!currentTape.equals(other.currentTape)) return false; - if (tapes == null) { - if (other.tapes != null) return false; - } else if (!tapes.equals(other.tapes)) return false; + if(tapes == null) { + if(other.tapes != null) return false; + } else if(!tapes.equals(other.tapes)) return false; return true; } diff --git a/base/src/main/java/bjc/utils/esodata/TapeLibrary.java b/base/src/main/java/bjc/utils/esodata/TapeLibrary.java index 00e2e99..4ebfd6c 100644 --- a/base/src/main/java/bjc/utils/esodata/TapeLibrary.java +++ b/base/src/main/java/bjc/utils/esodata/TapeLibrary.java @@ -13,13 +13,13 @@ import java.util.Map; * either return null/false. * * @param <T> - * The element type of the tapes. + * The element type of the tapes. */ public class TapeLibrary<T> implements Tape<T> { /* Our backing store of tapes. */ private final Map<String, Tape<T>> tapes; /* The current tape. */ - private Tape<T> currentTape; + private Tape<T> currentTape; /** Create a new empty tape library. */ public TapeLibrary() { @@ -28,63 +28,63 @@ public class TapeLibrary<T> implements Tape<T> { @Override public T item() { - if (currentTape == null) return null; + if(currentTape == null) return null; return currentTape.item(); } @Override public void item(final T itm) { - if (currentTape == null) return; + if(currentTape == null) return; currentTape.item(itm); } @Override public int size() { - if (currentTape == null) return 0; + if(currentTape == null) return 0; return currentTape.size(); } @Override public int position() { - if (currentTape == null) return 0; + if(currentTape == null) return 0; return currentTape.position(); } @Override public void insertBefore(final T itm) { - if (currentTape == null) return; + if(currentTape == null) return; currentTape.insertBefore(itm); } @Override public void insertAfter(final T itm) { - if (currentTape == null) return; + if(currentTape == null) return; currentTape.insertAfter(itm); } @Override public T remove() { - if (currentTape == null) return null; + if(currentTape == null) return null; return currentTape.remove(); } @Override public void first() { - if (currentTape == null) return; + if(currentTape == null) return; currentTape.first(); } @Override public void last() { - if (currentTape == null) return; + if(currentTape == null) return; currentTape.last(); } @@ -96,7 +96,7 @@ public class TapeLibrary<T> implements Tape<T> { @Override public boolean left(final int amt) { - if (currentTape == null) return false; + if(currentTape == null) return false; return currentTape.left(amt); } @@ -108,7 +108,7 @@ public class TapeLibrary<T> implements Tape<T> { @Override public boolean right(final int amt) { - if (currentTape == null) return false; + if(currentTape == null) return false; return currentTape.right(amt); } @@ -122,16 +122,16 @@ public class TapeLibrary<T> implements Tape<T> { * If the current tape is not double-sided, does nothing. */ public void flip() { - if (currentTape == null) return; + if(currentTape == null) return; - if (currentTape.isDoubleSided()) { + if(currentTape.isDoubleSided()) { ((DoubleTape<T>) currentTape).flip(); } } @Override public boolean isDoubleSided() { - if (currentTape == null) return false; + if(currentTape == null) return false; return currentTape.isDoubleSided(); } @@ -139,8 +139,7 @@ public class TapeLibrary<T> implements Tape<T> { /** * Check if a tape is currently loaded. * - * @return - * Whether or not a tape is loaded. + * @return Whether or not a tape is loaded. */ public boolean isLoaded() { return currentTape != null; @@ -153,13 +152,12 @@ public class TapeLibrary<T> implements Tape<T> { * tape. * * @param label - * The label of the tape to load. + * The label of the tape to load. * - * @return - * Whether or not the next tape was loaded. + * @return Whether or not the next tape was loaded. */ public boolean switchTape(final String label) { - if (tapes.containsKey(label)) { + if(tapes.containsKey(label)) { currentTape = tapes.get(label); return true; } @@ -177,10 +175,10 @@ public class TapeLibrary<T> implements Tape<T> { * Adding a duplicate tape will overwrite any existing types. * * @param label - * The label of the tape to add. + * The label of the tape to add. * * @param tp - * The tape to insert and load. + * The tape to insert and load. */ public void insertTape(final String label, final Tape<T> tp) { tapes.put(label, tp); @@ -194,10 +192,9 @@ public class TapeLibrary<T> implements Tape<T> { * Does nothing if there is not a tape of that name loaded. * * @param label - * The tape to remove. + * The tape to remove. * - * @return - * The removed tape. + * @return The removed tape. */ public Tape<T> removeTape(final String label) { return tapes.remove(label); @@ -215,8 +212,7 @@ public class TapeLibrary<T> implements Tape<T> { /** * Get how many tapes are currently in the library. * - * @return - * How many tapes are currently in the library. + * @return How many tapes are currently in the library. */ public int tapeCount() { return tapes.size(); @@ -226,10 +222,9 @@ public class TapeLibrary<T> implements Tape<T> { * Check if a specific tape is loaded into the library. * * @param label - * The tape to check for. + * The tape to check for. * - * @return - * Whether or not a tape of that name exists + * @return Whether or not a tape of that name exists */ public boolean hasTape(final String label) { return tapes.containsKey(label); @@ -248,19 +243,19 @@ public class TapeLibrary<T> implements Tape<T> { @Override public boolean equals(final Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (!(obj instanceof TapeLibrary<?>)) return false; + if(this == obj) return true; + if(obj == null) return false; + if(!(obj instanceof TapeLibrary<?>)) return false; final TapeLibrary<?> other = (TapeLibrary<?>) obj; - if (currentTape == null) { - if (other.currentTape != null) return false; - } else if (!currentTape.equals(other.currentTape)) return false; + if(currentTape == null) { + if(other.currentTape != null) return false; + } else if(!currentTape.equals(other.currentTape)) return false; - if (tapes == null) { - if (other.tapes != null) return false; - } else if (!tapes.equals(other.tapes)) return false; + if(tapes == null) { + if(other.tapes != null) return false; + } else if(!tapes.equals(other.tapes)) return false; return true; } diff --git a/base/src/main/java/bjc/utils/esodata/UnifiedDirectory.java b/base/src/main/java/bjc/utils/esodata/UnifiedDirectory.java index ed71512..75d3440 100644 --- a/base/src/main/java/bjc/utils/esodata/UnifiedDirectory.java +++ b/base/src/main/java/bjc/utils/esodata/UnifiedDirectory.java @@ -11,10 +11,10 @@ import bjc.utils.funcdata.IMap; * @author EVE * * @param <K> - * The key type of the directory. + * The key type of the directory. * * @param <V> - * The value type of the directory. + * The value type of the directory. */ public class UnifiedDirectory<K, V> implements Directory<K, V> { /* Our directory children. */ @@ -40,7 +40,7 @@ public class UnifiedDirectory<K, V> implements Directory<K, V> { @Override public Directory<K, V> putSubdirectory(final K key, final Directory<K, V> val) { - if (data.containsKey(key)) { + if(data.containsKey(key)) { final String msg = String.format("Key %s is already used for data", key); throw new IllegalArgumentException(msg); @@ -61,7 +61,7 @@ public class UnifiedDirectory<K, V> implements Directory<K, V> { @Override public V putKey(final K key, final V val) { - if (children.containsKey(key)) { + if(children.containsKey(key)) { final String msg = String.format("Key %s is already used for sub-directories.", key); throw new IllegalArgumentException(msg); @@ -81,19 +81,19 @@ public class UnifiedDirectory<K, V> implements Directory<K, V> { @Override public boolean equals(final Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (!(obj instanceof UnifiedDirectory<?, ?>)) return false; + if(this == obj) return true; + if(obj == null) return false; + if(!(obj instanceof UnifiedDirectory<?, ?>)) return false; final UnifiedDirectory<?, ?> other = (UnifiedDirectory<?, ?>) obj; - if (children == null) { - if (other.children != null) return false; - } else if (!children.equals(other.children)) return false; + if(children == null) { + if(other.children != null) return false; + } else if(!children.equals(other.children)) return false; - if (data == null) { - if (other.data != null) return false; - } else if (!data.equals(other.data)) return false; + if(data == null) { + if(other.data != null) return false; + } else if(!data.equals(other.data)) return false; return true; } diff --git a/base/src/main/java/bjc/utils/exceptions/FileNotChosenException.java b/base/src/main/java/bjc/utils/exceptions/FileNotChosenException.java index 501da5d..44bef61 100644 --- a/base/src/main/java/bjc/utils/exceptions/FileNotChosenException.java +++ b/base/src/main/java/bjc/utils/exceptions/FileNotChosenException.java @@ -20,7 +20,7 @@ public class FileNotChosenException extends IOException { * Create a new exception with the given cause. * * @param cause - * The cause of why the exception was thrown. + * The cause of why the exception was thrown. */ public FileNotChosenException(final String cause) { super(cause); diff --git a/base/src/main/java/bjc/utils/exceptions/PragmaFormatException.java b/base/src/main/java/bjc/utils/exceptions/PragmaFormatException.java index 362ab27..12bc6e4 100644 --- a/base/src/main/java/bjc/utils/exceptions/PragmaFormatException.java +++ b/base/src/main/java/bjc/utils/exceptions/PragmaFormatException.java @@ -20,7 +20,7 @@ public class PragmaFormatException extends InputMismatchException { * Create a new exception with the given message. * * @param message - * The message to explain why the exception was thrown. + * The message to explain why the exception was thrown. */ public PragmaFormatException(final String message) { super(message); diff --git a/base/src/main/java/bjc/utils/exceptions/UnknownPragmaException.java b/base/src/main/java/bjc/utils/exceptions/UnknownPragmaException.java index dded214..cbb2822 100644 --- a/base/src/main/java/bjc/utils/exceptions/UnknownPragmaException.java +++ b/base/src/main/java/bjc/utils/exceptions/UnknownPragmaException.java @@ -15,7 +15,7 @@ public class UnknownPragmaException extends InputMismatchException { * Create a new exception with the given cause. * * @param cause - * The cause for throwing this exception. + * The cause for throwing this exception. */ public UnknownPragmaException(final String cause) { super(cause); diff --git a/base/src/main/java/bjc/utils/funcdata/ExtendedMap.java b/base/src/main/java/bjc/utils/funcdata/ExtendedMap.java index 0c6389e..a2ace67 100644 --- a/base/src/main/java/bjc/utils/funcdata/ExtendedMap.java +++ b/base/src/main/java/bjc/utils/funcdata/ExtendedMap.java @@ -13,10 +13,10 @@ import bjc.utils.funcutils.ListUtils; * @author Ben Culkin * * @param <KeyType> - * The type of the keys of the map. + * The type of the keys of the map. * * @param <ValueType> - * The type of the values of the map. + * The type of the values of the map. */ class ExtendedMap<KeyType, ValueType> implements IMap<KeyType, ValueType> { /* The map we delegate lookups to. */ @@ -28,10 +28,10 @@ class ExtendedMap<KeyType, ValueType> implements IMap<KeyType, ValueType> { * Create a new extended map. * * @param delegate - * The map to lookup things in. + * The map to lookup things in. * * @param store - * The map to store things in. + * The map to store things in. */ public ExtendedMap(final IMap<KeyType, ValueType> delegate, final IMap<KeyType, ValueType> store) { this.delegate = delegate; @@ -45,7 +45,7 @@ class ExtendedMap<KeyType, ValueType> implements IMap<KeyType, ValueType> { @Override public boolean containsKey(final KeyType key) { - if (store.containsKey(key)) return true; + if(store.containsKey(key)) return true; return delegate.containsKey(key); } @@ -78,7 +78,7 @@ class ExtendedMap<KeyType, ValueType> implements IMap<KeyType, ValueType> { @Override public ValueType get(final KeyType key) { - if (store.containsKey(key)) return store.get(key); + if(store.containsKey(key)) return store.get(key); return delegate.get(key); } @@ -105,7 +105,7 @@ class ExtendedMap<KeyType, ValueType> implements IMap<KeyType, ValueType> { @Override public ValueType remove(final KeyType key) { - if (!store.containsKey(key)) return delegate.remove(key); + if(!store.containsKey(key)) return delegate.remove(key); return store.remove(key); } @@ -126,18 +126,18 @@ class ExtendedMap<KeyType, ValueType> implements IMap<KeyType, ValueType> { @Override public boolean equals(final Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (!(obj instanceof ExtendedMap)) return false; + if(this == obj) return true; + if(obj == null) return false; + if(!(obj instanceof ExtendedMap)) return false; final ExtendedMap<?, ?> other = (ExtendedMap<?, ?>) obj; - if (delegate == null) { - if (other.delegate != null) return false; - } else if (!delegate.equals(other.delegate)) return false; - if (store == null) { - if (other.store != null) return false; - } else if (!store.equals(other.store)) return false; + if(delegate == null) { + if(other.delegate != null) return false; + } else if(!delegate.equals(other.delegate)) return false; + if(store == null) { + if(other.store != null) return false; + } else if(!store.equals(other.store)) return false; return true; } diff --git a/base/src/main/java/bjc/utils/funcdata/FunctionalList.java b/base/src/main/java/bjc/utils/funcdata/FunctionalList.java index 4cae085..c730424 100644 --- a/base/src/main/java/bjc/utils/funcdata/FunctionalList.java +++ b/base/src/main/java/bjc/utils/funcdata/FunctionalList.java @@ -27,7 +27,7 @@ import bjc.utils.data.Pair; * @author ben * * @param <E> - * The type in this list + * The type in this list */ public class FunctionalList<E> implements Cloneable, IList<E> { /* The list used as a backing store */ @@ -44,13 +44,13 @@ public class FunctionalList<E> implements Cloneable, IList<E> { * Takes O(n) time, where n is the number of items specified * * @param items - * The items to put into this functional list. + * The items to put into this functional list. */ @SafeVarargs public FunctionalList(final E... items) { wrapped = new ArrayList<>(items.length); - for (final E item : items) { + for(final E item : items) { wrapped.add(item); } } @@ -59,7 +59,7 @@ public class FunctionalList<E> implements Cloneable, IList<E> { * Create a new functional list with the specified size. * * @param size - * The size of the backing list . + * The size of the backing list . */ private FunctionalList(final int size) { wrapped = new ArrayList<>(size); @@ -71,10 +71,10 @@ public class FunctionalList<E> implements Cloneable, IList<E> { * Takes O(1) time, since it doesn't copy the list. * * @param backing - * The list to use as a backing list. + * The list to use as a backing list. */ public FunctionalList(final List<E> backing) { - if (backing == null) throw new NullPointerException("Backing list must be non-null"); + if(backing == null) throw new NullPointerException("Backing list must be non-null"); wrapped = backing; } @@ -86,10 +86,10 @@ public class FunctionalList<E> implements Cloneable, IList<E> { @Override public boolean allMatch(final Predicate<E> predicate) { - if (predicate == null) throw new NullPointerException("Predicate must be non-null"); + if(predicate == null) throw new NullPointerException("Predicate must be non-null"); - for (final E item : wrapped) { - if (!predicate.test(item)) + for(final E item : wrapped) { + if(!predicate.test(item)) /* We've found a non-matching item. */ return false; } @@ -100,10 +100,10 @@ public class FunctionalList<E> implements Cloneable, IList<E> { @Override public boolean anyMatch(final Predicate<E> predicate) { - if (predicate == null) throw new NullPointerException("Predicate must be not null"); + if(predicate == null) throw new NullPointerException("Predicate must be not null"); - for (final E item : wrapped) { - if (predicate.test(item)) + for(final E item : wrapped) { + if(predicate.test(item)) /* We've found a matching item. */ return true; } @@ -117,14 +117,13 @@ public class FunctionalList<E> implements Cloneable, IList<E> { * * Takes O(n) time, where n is the number of elements in the list. * - * @return - * A copy of the list. + * @return A copy of the list. */ @Override public IList<E> clone() { final IList<E> cloned = new FunctionalList<>(); - for (final E element : wrapped) { + for(final E element : wrapped) { cloned.add(element); } @@ -133,9 +132,9 @@ public class FunctionalList<E> implements Cloneable, IList<E> { @Override public <T, F> IList<F> combineWith(final IList<T> rightList, final BiFunction<E, T, F> itemCombiner) { - if (rightList == null) { + if(rightList == null) { throw new NullPointerException("Target combine list must not be null"); - } else if (itemCombiner == null) { + } else if(itemCombiner == null) { throw new NullPointerException("Combiner must not be null"); } @@ -144,7 +143,7 @@ public class FunctionalList<E> implements Cloneable, IList<E> { /* Get the iterator for the other list. */ final Iterator<T> rightIterator = rightList.toIterable().iterator(); - for (final Iterator<E> leftIterator = wrapped.iterator(); leftIterator.hasNext() + for(final Iterator<E> leftIterator = wrapped.iterator(); leftIterator.hasNext() && rightIterator.hasNext();) { /* Add the transformed items to the result list. */ final E leftVal = leftIterator.next(); @@ -164,22 +163,21 @@ public class FunctionalList<E> implements Cloneable, IList<E> { @Override public E first() { - if (wrapped.size() < 1) - throw new NoSuchElementException("Attempted to get first element of empty list"); + if(wrapped.size() < 1) throw new NoSuchElementException("Attempted to get first element of empty list"); return wrapped.get(0); } @Override public <T> IList<T> flatMap(final Function<E, IList<T>> expander) { - if (expander == null) throw new NullPointerException("Expander must not be null"); + if(expander == null) throw new NullPointerException("Expander must not be null"); final IList<T> returned = new FunctionalList<>(this.wrapped.size()); forEach(element -> { final IList<T> expandedElement = expander.apply(element); - if (expandedElement == null) throw new NullPointerException("Expander returned null list"); + if(expandedElement == null) throw new NullPointerException("Expander returned null list"); /* Add each element to the returned list. */ expandedElement.forEach(returned::add); @@ -190,16 +188,19 @@ public class FunctionalList<E> implements Cloneable, IList<E> { @Override public void forEach(final Consumer<? super E> action) { - if (action == null) throw new NullPointerException("Action is null"); + if(action == null) throw new NullPointerException("Action is null"); wrapped.forEach(action); } @Override public void forEachIndexed(final BiConsumer<Integer, E> indexedAction) { - if (indexedAction == null) throw new NullPointerException("Action must not be null"); + if(indexedAction == null) throw new NullPointerException("Action must not be null"); - /* This is held b/c ref'd variables must be final/effectively final. */ + /* + * This is held b/c ref'd variables must be final/effectively + * final. + */ final IHolder<Integer> currentIndex = new Identity<>(0); wrapped.forEach((element) -> { @@ -219,8 +220,7 @@ public class FunctionalList<E> implements Cloneable, IList<E> { /** * Get the internal backing list. * - * @return - * The backing list this list is based off of. + * @return The backing list this list is based off of. */ public List<E> getInternal() { return wrapped; @@ -228,13 +228,16 @@ public class FunctionalList<E> implements Cloneable, IList<E> { @Override public IList<E> getMatching(final Predicate<E> predicate) { - if (predicate == null) throw new NullPointerException("Predicate must not be null"); + if(predicate == null) throw new NullPointerException("Predicate must not be null"); final IList<E> returned = new FunctionalList<>(); wrapped.forEach((element) -> { - if (predicate.test(element)) { - /* The item matches, so add it to the returned list. */ + if(predicate.test(element)) { + /* + * The item matches, so add it to the returned + * list. + */ returned.add(element); } }); @@ -259,7 +262,7 @@ public class FunctionalList<E> implements Cloneable, IList<E> { @Override public <T> IList<T> map(final Function<E, T> elementTransformer) { - if (elementTransformer == null) throw new NullPointerException("Transformer must be not null"); + if(elementTransformer == null) throw new NullPointerException("Transformer must be not null"); final IList<T> returned = new FunctionalList<>(this.wrapped.size()); @@ -278,7 +281,7 @@ public class FunctionalList<E> implements Cloneable, IList<E> { @Override public IList<IList<E>> partition(final int numberPerPartition) { - if (numberPerPartition < 1 || numberPerPartition > wrapped.size()) { + if(numberPerPartition < 1 || numberPerPartition > wrapped.size()) { final String fmt = "%s is an invalid partition size. Must be between 1 and %d"; final String msg = String.format(fmt, numberPerPartition, wrapped.size()); @@ -291,7 +294,7 @@ public class FunctionalList<E> implements Cloneable, IList<E> { final IHolder<IList<E>> currentPartition = new Identity<>(new FunctionalList<>()); this.forEach(element -> { - if (isPartitionFull(numberPerPartition, currentPartition)) { + if(isPartitionFull(numberPerPartition, currentPartition)) { /* Add the partition to the list. */ returned.add(currentPartition.unwrap(partition -> partition)); @@ -313,7 +316,7 @@ public class FunctionalList<E> implements Cloneable, IList<E> { @Override public E randItem(final Function<Integer, Integer> rnd) { - if (rnd == null) throw new NullPointerException("Random source must not be null"); + if(rnd == null) throw new NullPointerException("Random source must not be null"); final int randomIndex = rnd.apply(wrapped.size()); @@ -323,9 +326,9 @@ public class FunctionalList<E> implements Cloneable, IList<E> { @Override public <T, F> F reduceAux(final T initialValue, final BiFunction<E, T, T> stateAccumulator, final Function<T, F> resultTransformer) { - if (stateAccumulator == null) { + if(stateAccumulator == null) { throw new NullPointerException("Accumulator must not be null"); - } else if (resultTransformer == null) { + } else if(resultTransformer == null) { throw new NullPointerException("Transformer must not be null"); } @@ -343,7 +346,7 @@ public class FunctionalList<E> implements Cloneable, IList<E> { @Override public boolean removeIf(final Predicate<E> removePredicate) { - if (removePredicate == null) throw new NullPointerException("Predicate must be non-null"); + if(removePredicate == null) throw new NullPointerException("Predicate must be non-null"); return wrapped.removeIf(removePredicate); } @@ -363,7 +366,7 @@ public class FunctionalList<E> implements Cloneable, IList<E> { /* Search our internal list. */ final int foundIndex = Collections.binarySearch(wrapped, searchKey, comparator); - if (foundIndex >= 0) { + if(foundIndex >= 0) { /* We found a matching element. */ return wrapped.get(foundIndex); } @@ -396,19 +399,19 @@ public class FunctionalList<E> implements Cloneable, IList<E> { public String toString() { final int lSize = getSize(); - if (lSize == 0) return "()"; + if(lSize == 0) return "()"; final StringBuilder sb = new StringBuilder("("); final Iterator<E> itr = toIterable().iterator(); final E itm = itr.next(); int i = 0; - if (lSize == 1) return "(" + itm + ")"; + if(lSize == 1) return "(" + itm + ")"; - for (final E item : toIterable()) { + for(final E item : toIterable()) { sb.append(item.toString()); - if (i < lSize - 1) { + if(i < lSize - 1) { sb.append(", "); } diff --git a/base/src/main/java/bjc/utils/funcdata/FunctionalMap.java b/base/src/main/java/bjc/utils/funcdata/FunctionalMap.java index 1218833..115005c 100644 --- a/base/src/main/java/bjc/utils/funcdata/FunctionalMap.java +++ b/base/src/main/java/bjc/utils/funcdata/FunctionalMap.java @@ -14,10 +14,10 @@ import bjc.utils.data.IPair; * @author ben * * @param <KeyType> - * The type of the map's keys. + * The type of the map's keys. * * @param <ValueType> - * The type of the map's values. + * The type of the map's values. */ public class FunctionalMap<KeyType, ValueType> implements IMap<KeyType, ValueType> { /* Our backing store. */ @@ -32,13 +32,13 @@ public class FunctionalMap<KeyType, ValueType> implements IMap<KeyType, ValueTyp * Create a new functional map with the specified entries. * * @param entries - * The entries to put into the map. + * The entries to put into the map. */ @SafeVarargs public FunctionalMap(final IPair<KeyType, ValueType>... entries) { this(); - for (final IPair<KeyType, ValueType> entry : entries) { + for(final IPair<KeyType, ValueType> entry : entries) { entry.doWith((key, val) -> { wrappedMap.put(key, val); }); @@ -49,10 +49,10 @@ public class FunctionalMap<KeyType, ValueType> implements IMap<KeyType, ValueTyp * Create a new functional map wrapping the specified map. * * @param wrap - * The map to wrap. + * The map to wrap. */ public FunctionalMap(final Map<KeyType, ValueType> wrap) { - if (wrap == null) throw new NullPointerException("Map to wrap must not be null"); + if(wrap == null) throw new NullPointerException("Map to wrap must not be null"); wrappedMap = wrap; } @@ -89,9 +89,9 @@ public class FunctionalMap<KeyType, ValueType> implements IMap<KeyType, ValueTyp @Override public ValueType get(final KeyType key) { - if (key == null) throw new NullPointerException("Key must not be null"); + if(key == null) throw new NullPointerException("Key must not be null"); - if (!wrappedMap.containsKey(key)) { + if(!wrappedMap.containsKey(key)) { final String msg = String.format("Key %s is not present in the map", key); throw new IllegalArgumentException(msg); @@ -118,14 +118,14 @@ public class FunctionalMap<KeyType, ValueType> implements IMap<KeyType, ValueTyp @Override public <MappedValue> IMap<KeyType, MappedValue> transform(final Function<ValueType, MappedValue> transformer) { - if (transformer == null) throw new NullPointerException("Transformer must not be null"); + if(transformer == null) throw new NullPointerException("Transformer must not be null"); return new TransformedValueMap<>(this, transformer); } @Override public ValueType put(final KeyType key, final ValueType val) { - if (key == null) throw new NullPointerException("Key must not be null"); + if(key == null) throw new NullPointerException("Key must not be null"); return wrappedMap.put(key, val); } @@ -161,15 +161,15 @@ public class FunctionalMap<KeyType, ValueType> implements IMap<KeyType, ValueTyp @Override public boolean equals(final Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (!(obj instanceof FunctionalMap)) return false; + if(this == obj) return true; + if(obj == null) return false; + if(!(obj instanceof FunctionalMap)) return false; final FunctionalMap<?, ?> other = (FunctionalMap<?, ?>) obj; - if (wrappedMap == null) { - if (other.wrappedMap != null) return false; - } else if (!wrappedMap.equals(other.wrappedMap)) return false; + if(wrappedMap == null) { + if(other.wrappedMap != null) return false; + } else if(!wrappedMap.equals(other.wrappedMap)) return false; return true; } } diff --git a/base/src/main/java/bjc/utils/funcdata/FunctionalStringTokenizer.java b/base/src/main/java/bjc/utils/funcdata/FunctionalStringTokenizer.java index 384572d..4935e3d 100644 --- a/base/src/main/java/bjc/utils/funcdata/FunctionalStringTokenizer.java +++ b/base/src/main/java/bjc/utils/funcdata/FunctionalStringTokenizer.java @@ -14,13 +14,12 @@ public class FunctionalStringTokenizer { * Create a new tokenizer from the specified string. * * @param strang - * The string to create a tokenizer from. + * The string to create a tokenizer from. * - * @return - * A new tokenizer that splits the provided string on spaces. + * @return A new tokenizer that splits the provided string on spaces. */ public static FunctionalStringTokenizer fromString(final String strang) { - if (strang == null) throw new NullPointerException("String to tokenize must be non-null"); + if(strang == null) throw new NullPointerException("String to tokenize must be non-null"); return new FunctionalStringTokenizer(new StringTokenizer(strang, " ")); } @@ -32,10 +31,10 @@ public class FunctionalStringTokenizer { * Create a functional string tokenizer from a given string. * * @param inp - * The string to tokenize. + * The string to tokenize. */ public FunctionalStringTokenizer(final String inp) { - if (inp == null) throw new NullPointerException("String to tokenize must be non-null"); + if(inp == null) throw new NullPointerException("String to tokenize must be non-null"); this.input = new StringTokenizer(inp); } @@ -45,15 +44,15 @@ public class FunctionalStringTokenizer { * separators. * * @param input - * The string to tokenize. + * The string to tokenize. * * @param seperators - * The set of separating tokens to use for splitting. + * The set of separating tokens to use for splitting. */ public FunctionalStringTokenizer(final String input, final String seperators) { - if (input == null) { + if(input == null) { throw new NullPointerException("String to tokenize must not be null"); - } else if (seperators == null) { + } else if(seperators == null) { throw new NullPointerException("Tokens to split on must not be null"); } @@ -64,10 +63,10 @@ public class FunctionalStringTokenizer { * Create a functional string tokenizer from a non-functional one. * * @param toWrap - * The non-functional string tokenizer to wrap. + * The non-functional string tokenizer to wrap. */ public FunctionalStringTokenizer(final StringTokenizer toWrap) { - if (toWrap == null) throw new NullPointerException("Wrapped tokenizer must not be null"); + if(toWrap == null) throw new NullPointerException("Wrapped tokenizer must not be null"); this.input = toWrap; } @@ -76,12 +75,12 @@ public class FunctionalStringTokenizer { * Execute a provided action for each of the remaining tokens. * * @param action - * The action to execute for each token. + * The action to execute for each token. */ public void forEachToken(final Consumer<String> action) { - if (action == null) throw new NullPointerException("Action must not be null"); + if(action == null) throw new NullPointerException("Action must not be null"); - while (input.hasMoreTokens()) { + while(input.hasMoreTokens()) { action.accept(input.nextToken()); } } @@ -89,8 +88,7 @@ public class FunctionalStringTokenizer { /** * Get the string tokenizer encapsulated by this tokenizer. * - * @return - * The encapsulated tokenizer. + * @return The encapsulated tokenizer. */ public StringTokenizer getInternal() { return input; @@ -99,8 +97,7 @@ public class FunctionalStringTokenizer { /** * Check if this tokenizer has more tokens. * - * @return - * Whether or not this tokenizer has more tokens. + * @return Whether or not this tokenizer has more tokens. */ public boolean hasMoreTokens() { return input.hasMoreTokens(); @@ -109,12 +106,11 @@ public class FunctionalStringTokenizer { /** * Return the next token from the tokenizer. * - * @return - * The next token from the tokenizer, or null if no more tokens are - * available. + * @return The next token from the tokenizer, or null if no more tokens + * are available. */ public String nextToken() { - if (input.hasMoreTokens()) { + if(input.hasMoreTokens()) { /* Return the next available token. */ return input.nextToken(); } @@ -126,8 +122,7 @@ public class FunctionalStringTokenizer { /** * Convert this tokenizer into a list of strings. * - * @return - * This tokenizer, converted into a list of strings. + * @return This tokenizer, converted into a list of strings. */ public IList<String> toList() { return toList((final String element) -> element); @@ -138,16 +133,15 @@ public class FunctionalStringTokenizer { * the input from this tokenizer. * * @param <E> - * The type of the converted tokens. + * The type of the converted tokens. * * @param transformer - * The function to use to convert tokens. + * The function to use to convert tokens. * - * @return - * A list containing all of the converted tokens. + * @return A list containing all of the converted tokens. */ public <E> IList<E> toList(final Function<String, E> transformer) { - if (transformer == null) throw new NullPointerException("Transformer must not be null"); + if(transformer == null) throw new NullPointerException("Transformer must not be null"); final IList<E> returned = new FunctionalList<>(); diff --git a/base/src/main/java/bjc/utils/funcdata/IList.java b/base/src/main/java/bjc/utils/funcdata/IList.java index 4dd2b1a..cfda68d 100644 --- a/base/src/main/java/bjc/utils/funcdata/IList.java +++ b/base/src/main/java/bjc/utils/funcdata/IList.java @@ -18,17 +18,16 @@ import bjc.utils.functypes.ID; * @author ben * * @param <ContainedType> - * The type in this list + * The type in this list */ public interface IList<ContainedType> extends Iterable<ContainedType> { /** * Add an item to this list. * * @param item - * The item to add to this list. + * The item to add to this list. * - * @return - * Whether the item was added to the list successfully.. + * @return Whether the item was added to the list successfully.. */ boolean add(ContainedType item); @@ -36,10 +35,10 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Add all of the elements in the provided list to this list. * * @param items - * The list of items to add. + * The list of items to add. * - * @return - * True if every item was successfully added to the list, false otherwise. + * @return True if every item was successfully added to the list, false + * otherwise. */ default boolean addAll(final IList<ContainedType> items) { return items.map(this::add).anyMatch(bl -> bl == false); @@ -49,17 +48,16 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Add all of the elements in the provided array to this list. * * @param items - * The array of items to add. + * The array of items to add. * - * @return - * True if every item was successfully added to the list, false - * otherwise. + * @return True if every item was successfully added to the list, false + * otherwise. */ @SuppressWarnings("unchecked") default boolean addAll(final ContainedType... items) { boolean succ = true; - for (final ContainedType item : items) { + for(final ContainedType item : items) { final boolean addSucc = add(item); succ = succ ? addSucc : false; @@ -73,11 +71,10 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * predicate. * * @param matcher - * The predicate to use for checking. + * The predicate to use for checking. * - * @return - * Whether all of the elements of the list match the specified - * predicate. + * @return Whether all of the elements of the list match the specified + * predicate. */ boolean allMatch(Predicate<ContainedType> matcher); @@ -85,10 +82,10 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Check if any of the elements in this list match the specified list. * * @param matcher - * The predicate to use for checking. + * The predicate to use for checking. * - * @return - * Whether any element in the list matches the provided predicate. + * @return Whether any element in the list matches the provided + * predicate. */ boolean anyMatch(Predicate<ContainedType> matcher); @@ -96,16 +93,15 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Reduce the contents of this list using a collector. * * @param <StateType> - * The intermediate accumulation type. + * The intermediate accumulation type. * * @param <ReducedType> - * The final, reduced type. + * The final, reduced type. * * @param collector - * The collector to use for reduction. + * The collector to use for reduction. * - * @return - * The reduced list. + * @return The reduced list. */ default <StateType, ReducedType> ReducedType collect( final Collector<ContainedType, StateType, ReducedType> collector) { @@ -130,19 +126,18 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * list and the combined one. * * @param <OtherType> - * The type of the second list. + * The type of the second list. * * @param <CombinedType> - * The type of the combined list. + * The type of the combined list. * * @param list - * The list to combine with. + * The list to combine with. * * @param combiner - * The function to use for combining element pairs. + * The function to use for combining element pairs. * - * @return - * A new list containing the merged pairs of lists. + * @return A new list containing the merged pairs of lists. */ <OtherType, CombinedType> IList<CombinedType> combineWith(IList<OtherType> list, BiFunction<ContainedType, OtherType, CombinedType> combiner); @@ -151,18 +146,16 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Check if the list contains the specified item. * * @param item - * The item to see if it is contained. + * The item to see if it is contained. * - * @return - * Whether or not the specified item is in the list. + * @return Whether or not the specified item is in the list. */ boolean contains(ContainedType item); /** * Get the first element in the list. * - * @return - * The first element in this list. + * @return The first element in this list. */ ContainedType first(); @@ -173,14 +166,13 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Does not change the underlying list. * * @param <MappedType> - * The type of the flattened list. + * The type of the flattened list. * * @param expander - * The function to apply to each member of the list. + * The function to apply to each member of the list. * - * @return - * A new list containing the flattened results of applying the - * provided function. + * @return A new list containing the flattened results of applying the + * provided function. */ <MappedType> IList<MappedType> flatMap(Function<ContainedType, IList<MappedType>> expander); @@ -188,7 +180,7 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Apply a given action for each member of the list. * * @param action - * The action to apply to each member of the list. + * The action to apply to each member of the list. */ @Override void forEach(Consumer<? super ContainedType> action); @@ -197,7 +189,8 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Apply a given function to each element in the list and its index. * * @param action - * The function to apply to each element in the list and its index. + * The function to apply to each element in the list and its + * index. */ void forEachIndexed(BiConsumer<Integer, ContainedType> action); @@ -205,10 +198,9 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Retrieve a value in the list by its index. * * @param index - * The index to retrieve a value from. + * The index to retrieve a value from. * - * @return - * The value at the specified index in the list. + * @return The value at the specified index in the list. */ ContainedType getByIndex(int index); @@ -216,26 +208,23 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Retrieve a list containing all elements matching a predicate. * * @param predicate - * The predicate to match by. + * The predicate to match by. * - * @return - * A list containing all elements that match the predicate. + * @return A list containing all elements that match the predicate. */ IList<ContainedType> getMatching(Predicate<ContainedType> predicate); /** * Retrieve the size of the wrapped list. * - * @return - * The size of the wrapped list. + * @return The size of the wrapped list. */ int getSize(); /** * Check if this list is empty. * - * @return - * Whether or not this list is empty. + * @return Whether or not this list is empty. */ boolean isEmpty(); @@ -246,13 +235,12 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Does not change the underlying list. * * @param <MappedType> - * The type of the transformed list. + * The type of the transformed list. * * @param transformer - * The function to apply to each element in the list. + * The function to apply to each element in the list. * - * @return - * A new list containing the mapped elements of this list. + * @return A new list containing the mapped elements of this list. */ <MappedType> IList<MappedType> map(Function<ContainedType, MappedType> transformer); @@ -260,13 +248,13 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Zip two lists into a list of pairs. * * @param <OtherType> - * The type of the second list. + * The type of the second list. * * @param list - * The list to use as the left side of the pair. + * The list to use as the left side of the pair. * - * @return - * A list containing pairs of this element and the specified list. + * @return A list containing pairs of this element and the specified + * list. */ <OtherType> IList<IPair<ContainedType, OtherType>> pairWith(IList<OtherType> list); @@ -274,12 +262,11 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Partition this list into a list of sublists. * * @param partitionSize - * The size of elements to put into each one of the sublists. - * - * @return - * A list partitioned into partitions of size partitionSize. The last - * partition may not be completely full if the size of the list is - * not a multiple of partitionSize. + * The size of elements to put into each one of the sublists. + * + * @return A list partitioned into partitions of size partitionSize. The + * last partition may not be completely full if the size of the + * list is not a multiple of partitionSize. */ IList<IList<ContainedType>> partition(int partitionSize); @@ -287,7 +274,7 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Prepend an item to the list. * * @param item - * The item to prepend to the list. + * The item to prepend to the list. */ void prepend(ContainedType item); @@ -295,11 +282,11 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Prepend an array of items to the list. * * @param items - * The items to prepend to the list. + * The items to prepend to the list. */ @SuppressWarnings("unchecked") default void prependAll(final ContainedType... items) { - for (final ContainedType item : items) { + for(final ContainedType item : items) { prepend(item); } } @@ -308,8 +295,7 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Select a random item from the list, using a default random number * generator. * - * @return - * A random item from the list + * @return A random item from the list */ default ContainedType randItem() { return randItem(num -> (int) (Math.random() * num)); @@ -320,10 +306,9 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * generator. * * @param rnd - * The random number generator to use. + * The random number generator to use. * - * @return - * A random element from this list. + * @return A random element from this list. */ ContainedType randItem(Function<Integer, Integer> rnd); @@ -331,25 +316,24 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Reduce this list to a single value, using a accumulative approach. * * @param <StateType> - * The in-between type of the values + * The in-between type of the values * * @param <ReducedType> - * The final value type + * The final value type * * @param initial - * The initial value of the accumulative state. + * The initial value of the accumulative state. * * @param accumulator - * The function to use to combine a list element with the - * accumulative state. + * The function to use to combine a list element with the + * accumulative state. * * @param transformer - * The function to use to convert the accumulative state into a - * final result. + * The function to use to convert the accumulative state into a + * final result. * - * @return - * A single value condensed from this list and transformed into its - * final state. + * @return A single value condensed from this list and transformed into + * its final state. */ <StateType, ReducedType> ReducedType reduceAux(StateType initial, BiFunction<ContainedType, StateType, StateType> accumulator, @@ -359,17 +343,16 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Reduce this list to a single value, using a accumulative approach. * * @param <StateType> - * The in-between type of the values. + * The in-between type of the values. * * @param initial - * The initial value of the accumulative state. + * The initial value of the accumulative state. * * @param accumulator - * The function to use to combine a list element with the - * accumulative state. + * The function to use to combine a list element with the + * accumulative state. * - * @return - * A single value condensed from this list. + * @return A single value condensed from this list. */ default <StateType> StateType reduceAux(StateType initial, BiFunction<ContainedType, StateType, StateType> accumulator) { @@ -380,10 +363,9 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Remove all elements that match a given predicate. * * @param predicate - * The predicate to use to determine elements to delete. + * The predicate to use to determine elements to delete. * - * @return - * Whether there was anything that satisfied the predicate. + * @return Whether there was anything that satisfied the predicate. */ boolean removeIf(Predicate<ContainedType> predicate); @@ -391,7 +373,7 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Remove all parameters that match a given parameter. * * @param element - * The object to remove all matching copies of. + * The object to remove all matching copies of. */ void removeMatching(ContainedType element); @@ -406,14 +388,13 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * hand. * * @param key - * The key to search for. + * The key to search for. * * @param comparator - * The way to compare elements for searching. Pass null to use the - * natural ordering for E. + * The way to compare elements for searching. Pass null to use + * the natural ordering for E. * - * @return - * The element if it is in this list, or null if it is not. + * @return The element if it is in this list, or null if it is not. */ ContainedType search(ContainedType key, Comparator<ContainedType> comparator); @@ -424,16 +405,15 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Does change the underlying list. * * @param comparator - * The way to compare elements for sorting. Pass null to use E's - * natural ordering + * The way to compare elements for sorting. Pass null to use E's + * natural ordering */ void sort(Comparator<ContainedType> comparator); /** * Get the tail of this list (the list without the first element). * - * @return - * The list without the first element. + * @return The list without the first element. */ IList<ContainedType> tail(); @@ -441,18 +421,16 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Convert this list into an array. * * @param type - * The type of array to return. + * The type of array to return. * - * @return - * The list, as an array. + * @return The list, as an array. */ ContainedType[] toArray(ContainedType[] type); /** * Convert the list into a Iterable. * - * @return - * An iterable view onto the list. + * @return An iterable view onto the list. */ Iterable<ContainedType> toIterable(); diff --git a/base/src/main/java/bjc/utils/funcdata/IMap.java b/base/src/main/java/bjc/utils/funcdata/IMap.java index 35dc64b..9449898 100644 --- a/base/src/main/java/bjc/utils/funcdata/IMap.java +++ b/base/src/main/java/bjc/utils/funcdata/IMap.java @@ -10,17 +10,17 @@ import java.util.function.Function; * @author ben * * @param <KeyType> - * The type of this map's keys. + * The type of this map's keys. * * @param <ValueType> - * The type of this map's values. + * The type of this map's values. */ public interface IMap<KeyType, ValueType> { /** * Execute an action for each entry in the map. * * @param action - * The action to execute for each entry in the map. + * The action to execute for each entry in the map. */ void forEach(BiConsumer<KeyType, ValueType> action); @@ -28,7 +28,7 @@ public interface IMap<KeyType, ValueType> { * Perform an action for each key in the map. * * @param action - * The action to perform on each key in the map. + * The action to perform on each key in the map. */ default void forEachKey(final Consumer<KeyType> action) { forEach((key, val) -> action.accept(key)); @@ -38,7 +38,7 @@ public interface IMap<KeyType, ValueType> { * Perform an action for each value in the map. * * @param action - * The action to perform on each value in the map. + * The action to perform on each value in the map. */ default void forEachValue(final Consumer<ValueType> action) { forEach((key, val) -> action.accept(val)); @@ -48,10 +48,9 @@ public interface IMap<KeyType, ValueType> { * Check if this map contains the specified key. * * @param key - * The key to check. + * The key to check. * - * @return - * Whether or not the map contains the key. + * @return Whether or not the map contains the key. */ boolean containsKey(KeyType key); @@ -59,10 +58,9 @@ public interface IMap<KeyType, ValueType> { * Get the value assigned to the given key. * * @param key - * The key to look for a value under. + * The key to look for a value under. * - * @return - * The value of the key. + * @return The value of the key. */ ValueType get(KeyType key); @@ -71,14 +69,13 @@ public interface IMap<KeyType, ValueType> { * doesn't exist. * * @param key - * The key to attempt to retrieve. + * The key to attempt to retrieve. * * @param defaultValue - * The value to return if the key doesn't exist. + * The value to return if the key doesn't exist. * - * @return - * The value associated with the key, or the default value if the - * key doesn't exist. + * @return The value associated with the key, or the default value if + * the key doesn't exist. */ default ValueType getOrDefault(final KeyType key, final ValueType defaultValue) { try { @@ -96,18 +93,17 @@ public interface IMap<KeyType, ValueType> { * Add an entry to the map. * * @param key - * The key to put the value under. + * The key to put the value under. * * @param val - * The value to add. + * The value to add. * - * @return - * The previous value of the key in the map, or null if the key - * wasn't in the map. However, note that it may also return null if - * the key was set to null. + * @return The previous value of the key in the map, or null if the key + * wasn't in the map. However, note that it may also return null + * if the key was set to null. * * @throws UnsupportedOperationException - * If the map implementation doesn't support modifying the map. + * If the map implementation doesn't support modifying the map. */ ValueType put(KeyType key, ValueType val); @@ -119,17 +115,16 @@ public interface IMap<KeyType, ValueType> { /** * Get the number of entries in this map. * - * @return - * The number of entries in this map. + * @return The number of entries in this map. */ default int size() { return keyList().getSize(); } - /* @NOTE - * Do we want this to be the semantics for transform, or do we want - * to go to semantics using something like Isomorphism, or doing a - * one-time bulk conversion of the values? + /* + * @NOTE Do we want this to be the semantics for transform, or do we + * want to go to semantics using something like Isomorphism, or doing a + * one-time bulk conversion of the values? */ /** * Transform the values returned by this map. @@ -139,13 +134,12 @@ public interface IMap<KeyType, ValueType> { * likely not work as expected. * * @param <V2> - * The new type of returned values. + * The new type of returned values. * * @param transformer - * The function to use to transform values. + * The function to use to transform values. * - * @return - * The map where each value will be transformed after lookup. + * @return The map where each value will be transformed after lookup. */ default <V2> IMap<KeyType, V2> transform(final Function<ValueType, V2> transformer) { return new TransformedValueMap<>(this, transformer); @@ -155,8 +149,7 @@ public interface IMap<KeyType, ValueType> { * Extends this map, creating a new map that will delegate queries to * the map, but store any added values itself. * - * @return - * An extended map. + * @return An extended map. */ IMap<KeyType, ValueType> extend(); @@ -164,34 +157,31 @@ public interface IMap<KeyType, ValueType> { * Remove the value bound to the key. * * @param key - * The key to remove from the map. + * The key to remove from the map. * - * @return - * The previous value for the key in the map, or null if the key - * wasn't in the class. NOTE: Just because you received null, - * doesn't mean the map wasn't changed. It may mean that someone - * put a null value for that key into the map. + * @return The previous value for the key in the map, or null if the key + * wasn't in the class. NOTE: Just because you received null, + * doesn't mean the map wasn't changed. It may mean that someone + * put a null value for that key into the map. */ ValueType remove(KeyType key); /** * Get a list of all the keys in this map. * - * @return - * A list of all the keys in this map. + * @return A list of all the keys in this map. */ IList<KeyType> keyList(); /** * Get a list of the values in this map. * - * @return - * A list of values in this map. + * @return A list of values in this map. */ default IList<ValueType> valueList() { final IList<ValueType> returns = new FunctionalList<>(); - for (final KeyType key : keyList()) { + for(final KeyType key : keyList()) { returns.add(get(key)); } diff --git a/base/src/main/java/bjc/utils/funcdata/SentryList.java b/base/src/main/java/bjc/utils/funcdata/SentryList.java index 1040328..a6a960a 100644 --- a/base/src/main/java/bjc/utils/funcdata/SentryList.java +++ b/base/src/main/java/bjc/utils/funcdata/SentryList.java @@ -8,7 +8,7 @@ import java.util.List; * @author bjculkin * * @param <T> - * The type of item in the list. + * The type of item in the list. */ public class SentryList<T> extends FunctionalList<T> { /** Create a new sentry list. */ @@ -20,7 +20,7 @@ public class SentryList<T> extends FunctionalList<T> { * Create a new sentry list backed by an existing list. * * @param backing - * The backing list. + * The backing list. */ public SentryList(final List<T> backing) { super(backing); @@ -30,7 +30,7 @@ public class SentryList<T> extends FunctionalList<T> { public boolean add(final T item) { final boolean val = super.add(item); - if (val) { + if(val) { System.out.println("Added item (" + item + ") to list"); } diff --git a/base/src/main/java/bjc/utils/funcdata/TransformedValueMap.java b/base/src/main/java/bjc/utils/funcdata/TransformedValueMap.java index a8cb762..d6d85dd 100644 --- a/base/src/main/java/bjc/utils/funcdata/TransformedValueMap.java +++ b/base/src/main/java/bjc/utils/funcdata/TransformedValueMap.java @@ -10,18 +10,18 @@ import java.util.function.Function; * @author ben * * @param <OldKey> - * The type of the map's keys + * The type of the map's keys * * @param <OldValue> - * The type of the map's values + * The type of the map's values * * @param <NewValue> - * The type of the transformed values + * The type of the transformed values * */ final class TransformedValueMap<OldKey, OldValue, NewValue> implements IMap<OldKey, NewValue> { /* Our backing map. */ - private final IMap<OldKey, OldValue> backing; + private final IMap<OldKey, OldValue> backing; /* Our transforming function. */ private final Function<OldValue, NewValue> transformer; @@ -29,10 +29,10 @@ final class TransformedValueMap<OldKey, OldValue, NewValue> implements IMap<OldK * Create a new transformed-value loop. * * @param backingMap - * The map to use as backing. + * The map to use as backing. * * @param transform - * The function to use for the transform. + * The function to use for the transform. */ public TransformedValueMap(final IMap<OldKey, OldValue> backingMap, final Function<OldValue, NewValue> transform) { diff --git a/base/src/main/java/bjc/utils/funcdata/bst/BinarySearchTree.java b/base/src/main/java/bjc/utils/funcdata/bst/BinarySearchTree.java index f9dc4a2..6631834 100644 --- a/base/src/main/java/bjc/utils/funcdata/bst/BinarySearchTree.java +++ b/base/src/main/java/bjc/utils/funcdata/bst/BinarySearchTree.java @@ -14,7 +14,7 @@ import bjc.utils.funcdata.IList; * @author ben * * @param <T> - * The data type stored in the node. + * The data type stored in the node. */ public class BinarySearchTree<T> { /* The comparator for use in ordering items */ @@ -30,10 +30,10 @@ public class BinarySearchTree<T> { * Create a new tree using the specified way to compare elements. * * @param cmp - * The thing to use for comparing elements + * The thing to use for comparing elements */ public BinarySearchTree(final Comparator<T> cmp) { - if (cmp == null) throw new NullPointerException("Comparator must not be null"); + if(cmp == null) throw new NullPointerException("Comparator must not be null"); elementCount = 0; comparator = cmp; @@ -43,12 +43,12 @@ public class BinarySearchTree<T> { * Add a node to the binary search tree. * * @param element - * The data to add to the binary search tree. + * The data to add to the binary search tree. */ public void addNode(final T element) { elementCount++; - if (root == null) { + if(root == null) { root = new BinarySearchTreeNode<>(element, null, null); } else { root.add(element, comparator); @@ -59,16 +59,15 @@ public class BinarySearchTree<T> { * Check if an adjusted pivot falls with the bounds of a list. * * @param elements - * The list to get bounds from. + * The list to get bounds from. * * @param pivot - * The pivot. + * The pivot. * * @param pivotAdjustment - * The distance from the pivot. + * The distance from the pivot. * - * @return - * Whether the adjusted pivot is with the list. + * @return Whether the adjusted pivot is with the list. */ private boolean adjustedPivotInBounds(final IList<T> elements, final int pivot, final int pivotAdjustment) { return ((pivot - pivotAdjustment) >= 0) && ((pivot + pivotAdjustment) < elements.getSize()); @@ -93,8 +92,8 @@ public class BinarySearchTree<T> { int pivotAdjustment = 0; /* Add elements until there aren't any left. */ - while (adjustedPivotInBounds(elements, pivot, pivotAdjustment)) { - if (root == null) { + while(adjustedPivotInBounds(elements, pivot, pivotAdjustment)) { + if(root == null) { /* Create a new root element. */ root = new BinarySearchTreeNode<>(elements.getByIndex(pivot), null, null); } else { @@ -111,9 +110,9 @@ public class BinarySearchTree<T> { } /* Add any trailing unbalanced elements. */ - if (pivot - pivotAdjustment >= 0) { + if(pivot - pivotAdjustment >= 0) { root.add(elements.getByIndex(pivot - pivotAdjustment), comparator); - } else if (pivot + pivotAdjustment < elements.getSize()) { + } else if(pivot + pivotAdjustment < elements.getSize()) { root.add(elements.getByIndex(pivot + pivotAdjustment), comparator); } } @@ -125,7 +124,7 @@ public class BinarySearchTree<T> { * invoked, and are not included in traversals/finds. * * @param element - * The node to delete + * The node to delete */ public void deleteNode(final T element) { elementCount--; @@ -136,8 +135,7 @@ public class BinarySearchTree<T> { /** * Get the root of the tree. * - * @return - * The root of the tree. + * @return The root of the tree. */ public ITreePart<T> getRoot() { return root; @@ -147,7 +145,7 @@ public class BinarySearchTree<T> { * Check if a node is in the tree. * * @param element - * The node to check the presence of for the tree.. + * The node to check the presence of for the tree.. * * @return Whether or not the node is in the tree. */ @@ -159,15 +157,15 @@ public class BinarySearchTree<T> { * Traverse the tree in a specified way until the function fails. * * @param linearizationMethod - * The way to linearize the tree for traversal. + * The way to linearize the tree for traversal. * * @param traversalPredicate - * The function to use until it fails. + * The function to use until it fails. */ public void traverse(final TreeLinearizationMethod linearizationMethod, final Predicate<T> traversalPredicate) { - if (linearizationMethod == null) { + if(linearizationMethod == null) { throw new NullPointerException("Linearization method must not be null"); - } else if (traversalPredicate == null) { + } else if(traversalPredicate == null) { throw new NullPointerException("Predicate must not be nulls"); } @@ -210,16 +208,16 @@ public class BinarySearchTree<T> { @Override public boolean equals(final Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (!(obj instanceof BinarySearchTree<?>)) return false; + if(this == obj) return true; + if(obj == null) return false; + if(!(obj instanceof BinarySearchTree<?>)) return false; final BinarySearchTree<?> other = (BinarySearchTree<?>) obj; - if (elementCount != other.elementCount) return false; - if (root == null) { - if (other.root != null) return false; - } else if (!root.equals(other.root)) return false; + if(elementCount != other.elementCount) return false; + if(root == null) { + if(other.root != null) return false; + } else if(!root.equals(other.root)) return false; return true; } diff --git a/base/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeLeaf.java b/base/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeLeaf.java index 46f597e..762288f 100644 --- a/base/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeLeaf.java +++ b/base/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeLeaf.java @@ -11,7 +11,7 @@ import java.util.function.Predicate; * @author ben * * @param <T> - * The data stored in the tree. + * The data stored in the tree. */ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { /** The data held in this tree leaf */ @@ -24,7 +24,7 @@ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { * Create a new leaf holding the specified data. * * @param element - * The data for the leaf to hold. + * The data for the leaf to hold. */ public BinarySearchTreeLeaf(final T element) { data = element; @@ -37,7 +37,7 @@ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { @Override public <E> E collapse(final Function<T, E> leafTransformer, final BiFunction<E, E, E> branchCollapser) { - if (leafTransformer == null) throw new NullPointerException("Transformer must not be null"); + if(leafTransformer == null) throw new NullPointerException("Transformer must not be null"); return leafTransformer.apply(data); } @@ -54,16 +54,16 @@ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { @Override public void delete(final T element, final Comparator<T> comparator) { - if (data.equals(element)) { + if(data.equals(element)) { isDeleted = true; } } @Override public boolean directedWalk(final DirectedWalkFunction<T> treeWalker) { - if (treeWalker == null) throw new NullPointerException("Tree walker must not be null"); + if(treeWalker == null) throw new NullPointerException("Tree walker must not be null"); - switch (treeWalker.walk(data)) { + switch(treeWalker.walk(data)) { case SUCCESS: return true; /* We don't have any children to care about. */ @@ -78,7 +78,7 @@ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { @Override public boolean forEach(final TreeLinearizationMethod linearizationMethod, final Predicate<T> traversalPredicate) { - if (traversalPredicate == null) throw new NullPointerException("Predicate must not be null"); + if(traversalPredicate == null) throw new NullPointerException("Predicate must not be null"); return traversalPredicate.test(data); } @@ -99,16 +99,16 @@ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { @Override public boolean equals(final Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (!(obj instanceof BinarySearchTreeLeaf<?>)) return false; + if(this == obj) return true; + if(obj == null) return false; + if(!(obj instanceof BinarySearchTreeLeaf<?>)) return false; final BinarySearchTreeLeaf<?> other = (BinarySearchTreeLeaf<?>) obj; - if (data == null) { - if (other.data != null) return false; - } else if (!data.equals(other.data)) return false; - if (isDeleted != other.isDeleted) return false; + if(data == null) { + if(other.data != null) return false; + } else if(!data.equals(other.data)) return false; + if(isDeleted != other.isDeleted) return false; return true; } diff --git a/base/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeNode.java b/base/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeNode.java index 3124474..eb7b6b5 100644 --- a/base/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeNode.java +++ b/base/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeNode.java @@ -16,7 +16,7 @@ import java.util.function.Predicate; * @author ben * * @param <T> - * The data type stored in the tree. + * The data type stored in the tree. */ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { /* The left child of this node */ @@ -29,13 +29,13 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { * Create a new node with the specified data and children. * * @param element - * The data to store in this node. + * The data to store in this node. * * @param lft - * The left child of this node. + * The left child of this node. * * @param rght - * The right child of this node. + * The right child of this node. */ public BinarySearchTreeNode(final T element, final ITreePart<T> lft, final ITreePart<T> rght) { super(element); @@ -45,23 +45,24 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { @Override public void add(final T element, final Comparator<T> comparator) { - if (comparator == null) throw new NullPointerException("Comparator must not be null"); + if(comparator == null) throw new NullPointerException("Comparator must not be null"); - switch (comparator.compare(data, element)) { + switch(comparator.compare(data, element)) { case -1: - if (left == null) { + if(left == null) { left = new BinarySearchTreeNode<>(element, null, null); } else { left.add(element, comparator); } break; case 0: - if (isDeleted) { + if(isDeleted) { isDeleted = false; - } else throw new IllegalArgumentException("Can't add duplicate values"); + } else + throw new IllegalArgumentException("Can't add duplicate values"); break; case 1: - if (right == null) { + if(right == null) { right = new BinarySearchTreeNode<>(element, null, null); } else { right.add(element, comparator); @@ -74,15 +75,15 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { @Override public <E> E collapse(final Function<T, E> nodeCollapser, final BiFunction<E, E, E> branchCollapser) { - if (nodeCollapser == null || branchCollapser == null) + if(nodeCollapser == null || branchCollapser == null) throw new NullPointerException("Collapser must not be null"); final E collapsedNode = nodeCollapser.apply(data); - if (left != null) { + if(left != null) { final E collapsedLeftBranch = left.collapse(nodeCollapser, branchCollapser); - if (right != null) { + if(right != null) { final E collapsedRightBranch = right.collapse(nodeCollapser, branchCollapser); final E collapsedBranches = branchCollapser.apply(collapsedLeftBranch, @@ -94,7 +95,7 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { return branchCollapser.apply(collapsedNode, collapsedLeftBranch); } - if (right != null) { + if(right != null) { final E collapsedRightBranch = right.collapse(nodeCollapser, branchCollapser); return branchCollapser.apply(collapsedNode, collapsedRightBranch); @@ -105,10 +106,10 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { @Override public boolean contains(final T element, final Comparator<T> comparator) { - if (comparator == null) throw new NullPointerException("Comparator must not be null"); + if(comparator == null) throw new NullPointerException("Comparator must not be null"); return directedWalk(currentElement -> { - switch (comparator.compare(element, currentElement)) { + switch(comparator.compare(element, currentElement)) { case -1: return LEFT; case 0: @@ -123,10 +124,10 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { @Override public void delete(final T element, final Comparator<T> comparator) { - if (comparator == null) throw new NullPointerException("Comparator must not be null"); + if(comparator == null) throw new NullPointerException("Comparator must not be null"); directedWalk(currentElement -> { - switch (comparator.compare(data, element)) { + switch(comparator.compare(data, element)) { case -1: return left == null ? FAILURE : LEFT; case 0: @@ -142,9 +143,9 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { @Override public boolean directedWalk(final DirectedWalkFunction<T> treeWalker) { - if (treeWalker == null) throw new NullPointerException("Walker must not be null"); + if(treeWalker == null) throw new NullPointerException("Walker must not be null"); - switch (treeWalker.walk(data)) { + switch(treeWalker.walk(data)) { case SUCCESS: return true; case LEFT: @@ -160,13 +161,13 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { @Override public boolean forEach(final TreeLinearizationMethod linearizationMethod, final Predicate<T> traversalPredicate) { - if (linearizationMethod == null) { + if(linearizationMethod == null) { throw new NullPointerException("Linearization method must not be null"); - } else if (traversalPredicate == null) { + } else if(traversalPredicate == null) { throw new NullPointerException("Predicate must not be null"); } - switch (linearizationMethod) { + switch(linearizationMethod) { case PREORDER: return preorderTraverse(linearizationMethod, traversalPredicate); case INORDER: @@ -174,7 +175,8 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { case POSTORDER: return postorderTraverse(linearizationMethod, traversalPredicate); default: - String msg = String.format("Passed an incorrect TreeLinearizationMethod %s. WAT", linearizationMethod); + String msg = String.format("Passed an incorrect TreeLinearizationMethod %s. WAT", + linearizationMethod); throw new IllegalArgumentException(msg); } @@ -183,11 +185,11 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { /* Do an in-order traversal. */ private boolean inorderTraverse(final TreeLinearizationMethod linearizationMethod, final Predicate<T> traversalPredicate) { - if (!traverseLeftBranch(linearizationMethod, traversalPredicate)) return false; + if(!traverseLeftBranch(linearizationMethod, traversalPredicate)) return false; - if (!traverseElement(traversalPredicate)) return false; + if(!traverseElement(traversalPredicate)) return false; - if (!traverseRightBranch(linearizationMethod, traversalPredicate)) return false; + if(!traverseRightBranch(linearizationMethod, traversalPredicate)) return false; return true; } @@ -195,11 +197,11 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { /* Do a post-order traversal. */ private boolean postorderTraverse(final TreeLinearizationMethod linearizationMethod, final Predicate<T> traversalPredicate) { - if (!traverseLeftBranch(linearizationMethod, traversalPredicate)) return false; + if(!traverseLeftBranch(linearizationMethod, traversalPredicate)) return false; - if (!traverseRightBranch(linearizationMethod, traversalPredicate)) return false; + if(!traverseRightBranch(linearizationMethod, traversalPredicate)) return false; - if (!traverseElement(traversalPredicate)) return false; + if(!traverseElement(traversalPredicate)) return false; return true; @@ -208,11 +210,11 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { /* Do a pre-order traversal. */ private boolean preorderTraverse(final TreeLinearizationMethod linearizationMethod, final Predicate<T> traversalPredicate) { - if (!traverseElement(traversalPredicate)) return false; + if(!traverseElement(traversalPredicate)) return false; - if (!traverseLeftBranch(linearizationMethod, traversalPredicate)) return false; + if(!traverseLeftBranch(linearizationMethod, traversalPredicate)) return false; - if (!traverseRightBranch(linearizationMethod, traversalPredicate)) return false; + if(!traverseRightBranch(linearizationMethod, traversalPredicate)) return false; return true; } @@ -221,7 +223,7 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { private boolean traverseElement(final Predicate<T> traversalPredicate) { boolean nodeSuccesfullyTraversed; - if (isDeleted) { + if(isDeleted) { nodeSuccesfullyTraversed = true; } else { nodeSuccesfullyTraversed = traversalPredicate.test(data); @@ -235,7 +237,7 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { final Predicate<T> traversalPredicate) { boolean leftSuccesfullyTraversed; - if (left == null) { + if(left == null) { leftSuccesfullyTraversed = true; } else { leftSuccesfullyTraversed = left.forEach(linearizationMethod, traversalPredicate); @@ -249,7 +251,7 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { final Predicate<T> traversalPredicate) { boolean rightSuccesfullyTraversed; - if (right == null) { + if(right == null) { rightSuccesfullyTraversed = true; } else { rightSuccesfullyTraversed = right.forEach(linearizationMethod, traversalPredicate); @@ -274,19 +276,19 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { @Override public boolean equals(final Object obj) { - if (this == obj) return true; - if (!super.equals(obj)) return false; - if (!(obj instanceof BinarySearchTreeNode<?>)) return false; + if(this == obj) return true; + if(!super.equals(obj)) return false; + if(!(obj instanceof BinarySearchTreeNode<?>)) return false; final BinarySearchTreeNode<?> other = (BinarySearchTreeNode<?>) obj; - if (left == null) { - if (other.left != null) return false; - } else if (!left.equals(other.left)) return false; + if(left == null) { + if(other.left != null) return false; + } else if(!left.equals(other.left)) return false; - if (right == null) { - if (other.right != null) return false; - } else if (!right.equals(other.right)) return false; + if(right == null) { + if(other.right != null) return false; + } else if(!right.equals(other.right)) return false; return true; } diff --git a/base/src/main/java/bjc/utils/funcdata/bst/DirectedWalkFunction.java b/base/src/main/java/bjc/utils/funcdata/bst/DirectedWalkFunction.java index fdf86d7..e341320 100644 --- a/base/src/main/java/bjc/utils/funcdata/bst/DirectedWalkFunction.java +++ b/base/src/main/java/bjc/utils/funcdata/bst/DirectedWalkFunction.java @@ -6,7 +6,7 @@ package bjc.utils.funcdata.bst; * @author ben * * @param <T> - * The type of element stored in the walked tree + * The type of element stored in the walked tree */ @FunctionalInterface public interface DirectedWalkFunction<T> { @@ -36,10 +36,9 @@ public interface DirectedWalkFunction<T> { * Perform a directed walk on a node of a tree. * * @param element - * The data stored in the node currently being visited. + * The data stored in the node currently being visited. * - * @return - * The way the function wants the walk to go next. + * @return The way the function wants the walk to go next. */ public DirectedWalkResult walk(T element); } diff --git a/base/src/main/java/bjc/utils/funcdata/bst/ITreePart.java b/base/src/main/java/bjc/utils/funcdata/bst/ITreePart.java index a2ce71f..f9b3d4a 100644 --- a/base/src/main/java/bjc/utils/funcdata/bst/ITreePart.java +++ b/base/src/main/java/bjc/utils/funcdata/bst/ITreePart.java @@ -11,18 +11,18 @@ import java.util.function.Predicate; * @author ben * * @param <T> - * The data contained in this part of the tree. + * The data contained in this part of the tree. */ public interface ITreePart<T> { /** * Add a element below this tree part somewhere. * * @param element - * The element to add below this tree part + * The element to add below this tree part * * @param comparator - * The thing to use for comparing values to find where to - * insert the tree part. + * The thing to use for comparing values to find where to insert + * the tree part. */ public void add(T element, Comparator<T> comparator); @@ -32,17 +32,16 @@ public interface ITreePart<T> { * Does not change the underlying tree. * * @param <E> - * The type of the final collapsed value + * The type of the final collapsed value * * @param nodeCollapser - * The function to use to transform data into mapped form. + * The function to use to transform data into mapped form. * * @param branchCollapser - * The function to use to collapse data in mapped form into a - * single value. + * The function to use to collapse data in mapped form into a + * single value. * - * @return - * A single value from collapsing the tree. + * @return A single value from collapsing the tree. */ public <E> E collapse(Function<T, E> nodeCollapser, BiFunction<E, E, E> branchCollapser); @@ -50,22 +49,20 @@ public interface ITreePart<T> { * Check if this tre part or below it contains the specified data item. * * @param element - * The data item to look for. + * The data item to look for. * * @param comparator - * The comparator to use to search for the data item. + * The comparator to use to search for the data item. * - * @return - * Whether or not the given item is contained in this tree part or - * its children. + * @return Whether or not the given item is contained in this tree part + * or its children. */ public boolean contains(T element, Comparator<T> comparator); /** * Get the data associated with this tree part. * - * @return - * The data associated with this tree part. + * @return The data associated with this tree part. */ public T data(); @@ -73,10 +70,10 @@ public interface ITreePart<T> { * Remove the given node from this tree part and any of its children. * * @param element - * The data item to remove. + * The data item to remove. * * @param comparator - * The comparator to use to search for the data item. + * The comparator to use to search for the data item. */ public void delete(T element, Comparator<T> comparator); @@ -84,11 +81,9 @@ public interface ITreePart<T> { * Execute a directed walk through the tree. * * @param walker - * The function to use to direct the walk through the - * tree. + * The function to use to direct the walk through the tree. * - * @return - * Whether the directed walk finished successfully. + * @return Whether the directed walk finished successfully. */ public boolean directedWalk(DirectedWalkFunction<T> walker); @@ -97,14 +92,13 @@ public interface ITreePart<T> { * completes for. * * @param linearizationMethod - * The way to linearize the tree for executing. + * The way to linearize the tree for executing. * * @param predicate - * The predicate to apply to each element, where it returning false - * terminates traversal early. + * The predicate to apply to each element, where it returning + * false terminates traversal early. * - * @return - * Whether the traversal finished succesfully. + * @return Whether the traversal finished succesfully. */ public boolean forEach(TreeLinearizationMethod linearizationMethod, Predicate<T> predicate); } diff --git a/base/src/main/java/bjc/utils/funcdata/theory/Bifunctor.java b/base/src/main/java/bjc/utils/funcdata/theory/Bifunctor.java index a94a7b5..4bbc154 100644 --- a/base/src/main/java/bjc/utils/funcdata/theory/Bifunctor.java +++ b/base/src/main/java/bjc/utils/funcdata/theory/Bifunctor.java @@ -8,10 +8,10 @@ import java.util.function.Function; * @author ben * * @param <LeftType> - * The type stored on the 'left' of the pair. + * The type stored on the 'left' of the pair. * * @param <RightType> - * The type stored on the 'right' of the pair. + * The type stored on the 'right' of the pair. */ public interface Bifunctor<LeftType, RightType> { /** @@ -19,17 +19,17 @@ public interface Bifunctor<LeftType, RightType> { * * @author EVE * - * @param <OldLeft> - * The old left type. + * @param <OldLeft> + * The old left type. * * @param <OldRight> - * The old right type. + * The old right type. * * @param <NewLeft> - * The new left type. + * The new left type. * * @param <NewRight> - * The new right type. + * The new right type. */ public interface BifunctorMap<OldLeft, OldRight, NewLeft, NewRight> extends Function<Bifunctor<OldLeft, OldRight>, Bifunctor<NewLeft, NewRight>> { @@ -42,13 +42,13 @@ public interface Bifunctor<LeftType, RightType> { * @author EVE * * @param <OldLeft> - * The old left type. + * The old left type. * * @param <OldRight> - * The old right type. + * The old right type. * * @param <NewLeft> - * The new left type. + * The new left type. */ public interface LeftBifunctorMap<OldLeft, OldRight, NewLeft> extends BifunctorMap<OldLeft, OldRight, NewLeft, OldRight> { @@ -61,13 +61,13 @@ public interface Bifunctor<LeftType, RightType> { * @author EVE * * @param <OldLeft> - * The old left type. + * The old left type. * * @param <OldRight> - * The old right type. + * The old right type. * * @param <NewRight> - * The new right type. + * The new right type. */ public interface RightBifunctorMap<OldLeft, OldRight, NewRight> extends BifunctorMap<OldLeft, OldRight, OldLeft, NewRight> { @@ -79,25 +79,24 @@ public interface Bifunctor<LeftType, RightType> { * parts of a pair. * * @param <OldLeft> - * The old left type of the pair. + * The old left type of the pair. * * @param <OldRight> - * The old right type of the pair. + * The old right type of the pair. * * @param <NewLeft> - * The new left type of the pair. + * The new left type of the pair. * * @param <NewRight> - * The new right type of the pair. + * The new right type of the pair. * * @param leftFunc - * The function that maps over the left of the pair. + * The function that maps over the left of the pair. * * @param rightFunc - * The function that maps over the right of the pair. + * The function that maps over the right of the pair. * - * @return - * A function that maps over both parts of the pair. + * @return A function that maps over both parts of the pair. */ public default <OldLeft, OldRight, NewLeft, NewRight> BifunctorMap<OldLeft, OldRight, NewLeft, NewRight> bimap( final Function<OldLeft, NewLeft> leftFunc, final Function<OldRight, NewRight> rightFunc) { @@ -118,19 +117,18 @@ public interface Bifunctor<LeftType, RightType> { * Lift a function to operate over the left part of this pair. * * @param <OldLeft> - * The old left type of the pair. + * The old left type of the pair. * * @param <OldRight> - * The old right type of the pair. + * The old right type of the pair. * * @param <NewLeft> - * The new left type of the pair. + * The new left type of the pair. * * @param func - * The function to lift to work over the left side of the pair. + * The function to lift to work over the left side of the pair. * - * @return - * The function lifted to work over the left side of bifunctors. + * @return The function lifted to work over the left side of bifunctors. */ public <OldLeft, OldRight, NewLeft> LeftBifunctorMap<OldLeft, OldRight, NewLeft> fmapLeft( Function<OldLeft, NewLeft> func); @@ -139,20 +137,19 @@ public interface Bifunctor<LeftType, RightType> { * Lift a function to operate over the right part of this pair. * * @param <OldLeft> - * The old left type of the pair. + * The old left type of the pair. * * @param <OldRight> - * The old right type of the pair. + * The old right type of the pair. * * @param <NewRight> - * The new right type of the pair. + * The new right type of the pair. * * @param func - * The function to lift to work over the right side of - * the pair. + * The function to lift to work over the right side of the pair. * - * @return - * The function lifted to work over the right side of bifunctors. + * @return The function lifted to work over the right side of + * bifunctors. */ public <OldLeft, OldRight, NewRight> RightBifunctorMap<OldLeft, OldRight, NewRight> fmapRight( Function<OldRight, NewRight> func); @@ -160,16 +157,14 @@ public interface Bifunctor<LeftType, RightType> { /** * Get the value contained on the left of this bifunctor. * - * @return - * The value on the left side of this bifunctor. + * @return The value on the left side of this bifunctor. */ public LeftType getLeft(); /** * Get the value contained on the right of this bifunctor. * - * @return - * The value on the right of this bifunctor. + * @return The value on the right of this bifunctor. */ public RightType getRight(); } diff --git a/base/src/main/java/bjc/utils/funcdata/theory/Functor.java b/base/src/main/java/bjc/utils/funcdata/theory/Functor.java index 9efa883..13852e6 100644 --- a/base/src/main/java/bjc/utils/funcdata/theory/Functor.java +++ b/base/src/main/java/bjc/utils/funcdata/theory/Functor.java @@ -9,7 +9,7 @@ import java.util.function.Function; * @author ben * * @param <ContainedType> - * The value inside the functor. + * The value inside the functor. */ public interface Functor<ContainedType> { /** @@ -20,17 +20,16 @@ public interface Functor<ContainedType> { * on instances of the type of functor you called fmap on.. * * @param <ArgType> - * The argument of the function. + * The argument of the function. * * @param <ReturnType> - * The return type of the function. + * The return type of the function. * * @param func - * The function to convert. + * The function to convert. * - * @return - * The passed in function converted to work over a particular - * type of functors. + * @return The passed in function converted to work over a particular + * type of functors. */ public <ArgType, ReturnType> Function<Functor<ArgType>, Functor<ReturnType>> fmap( Function<ArgType, ReturnType> func); @@ -38,8 +37,7 @@ public interface Functor<ContainedType> { /** * Retrieve the thing inside this functor. * - * @return - * The thing inside this functor. + * @return The thing inside this functor. */ public ContainedType getValue(); } diff --git a/base/src/main/java/bjc/utils/functypes/ID.java b/base/src/main/java/bjc/utils/functypes/ID.java index 4090410..62e7909 100644 --- a/base/src/main/java/bjc/utils/functypes/ID.java +++ b/base/src/main/java/bjc/utils/functypes/ID.java @@ -1,20 +1,19 @@ -package bjc.utils.functypes;
-
-import java.util.function.UnaryOperator;
-
-/**
- * Identity function.
- *
- * @author bjculkin
- */
-public class ID {
- /**
- * Create an identity function.
- *
- * @return
- * A identity function.
- */
- public static <A> UnaryOperator<A> id() {
- return (x) -> x;
- }
-}
+package bjc.utils.functypes; + +import java.util.function.UnaryOperator; + +/** + * Identity function. + * + * @author bjculkin + */ +public class ID { + /** + * Create an identity function. + * + * @return A identity function. + */ + public static <A> UnaryOperator<A> id() { + return (x) -> x; + } +} diff --git a/base/src/main/java/bjc/utils/functypes/ListFlattener.java b/base/src/main/java/bjc/utils/functypes/ListFlattener.java index 7d0ef63..bdf0a09 100644 --- a/base/src/main/java/bjc/utils/functypes/ListFlattener.java +++ b/base/src/main/java/bjc/utils/functypes/ListFlattener.java @@ -10,7 +10,7 @@ import bjc.utils.funcdata.IList; * @author bjculkin * * @param <S> - * The type of value in the list. + * The type of value in the list. */ public interface ListFlattener<S> extends Function<IList<S>, S> { diff --git a/base/src/main/java/bjc/utils/funcutils/CollectorUtils.java b/base/src/main/java/bjc/utils/funcutils/CollectorUtils.java index 2da5967..419c216 100644 --- a/base/src/main/java/bjc/utils/funcutils/CollectorUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/CollectorUtils.java @@ -15,28 +15,27 @@ public class CollectorUtils { * Create a collector that applies two collectors at once. * * @param <InitialType> - * The type of the collection to collect from. + * The type of the collection to collect from. * * @param <AuxType1> - * The intermediate type of the first collector. + * The intermediate type of the first collector. * * @param <AuxType2> - * The intermediate type of the second collector. + * The intermediate type of the second collector. * * @param <FinalType1> - * The final type of the first collector. + * The final type of the first collector. * * @param <FinalType2> - * The final type of the second collector. + * The final type of the second collector. * * @param first - * The first collector to use. + * The first collector to use. * * @param second - * The second collector to use. + * The second collector to use. * - * @return - * A collector that functions as mentioned above. + * @return A collector that functions as mentioned above. */ public static <InitialType, AuxType1, AuxType2, FinalType1, FinalType2> Collector<InitialType, IHolder<IPair<AuxType1, AuxType2>>, IPair<FinalType1, FinalType2>> compoundCollect( final Collector<InitialType, AuxType1, FinalType1> first, diff --git a/base/src/main/java/bjc/utils/funcutils/CompoundCollector.java b/base/src/main/java/bjc/utils/funcutils/CompoundCollector.java index 928c3f4..53b4b8d 100644 --- a/base/src/main/java/bjc/utils/funcutils/CompoundCollector.java +++ b/base/src/main/java/bjc/utils/funcutils/CompoundCollector.java @@ -12,7 +12,7 @@ import bjc.utils.data.IPair; import bjc.utils.data.Identity; import bjc.utils.data.Pair; -/** +/** * Implementation of a collecter that uses two collectors. * * @author Ben Culkin @@ -22,7 +22,7 @@ final class CompoundCollector<InitialType, AuxType1, AuxType2, FinalType1, Final /* Our characteristics. */ private final Set<java.util.stream.Collector.Characteristics> characteristicSet; - /* The first collector. */ + /* The first collector. */ private final Collector<InitialType, AuxType1, FinalType1> first; /* The second collector. */ private final Collector<InitialType, AuxType2, FinalType2> second; @@ -31,10 +31,10 @@ final class CompoundCollector<InitialType, AuxType1, AuxType2, FinalType1, Final * Create a collector that uses two collectors. * * @param first - * The first collector. + * The first collector. * * @param second - * The second collector. + * The second collector. */ public CompoundCollector(final Collector<InitialType, AuxType1, FinalType1> first, final Collector<InitialType, AuxType2, FinalType2> second) { @@ -48,7 +48,7 @@ final class CompoundCollector<InitialType, AuxType1, AuxType2, FinalType1, Final @Override public BiConsumer<IHolder<IPair<AuxType1, AuxType2>>, InitialType> accumulator() { - final BiConsumer<AuxType1, InitialType> firstAccumulator = first.accumulator(); + final BiConsumer<AuxType1, InitialType> firstAccumulator = first.accumulator(); final BiConsumer<AuxType2, InitialType> secondAccumulator = second.accumulator(); return (state, value) -> { @@ -68,7 +68,7 @@ final class CompoundCollector<InitialType, AuxType1, AuxType2, FinalType1, Final @Override public BinaryOperator<IHolder<IPair<AuxType1, AuxType2>>> combiner() { - final BinaryOperator<AuxType1> firstCombiner = first.combiner(); + final BinaryOperator<AuxType1> firstCombiner = first.combiner(); final BinaryOperator<AuxType2> secondCombiner = second.combiner(); return (leftState, rightState) -> { @@ -85,7 +85,7 @@ final class CompoundCollector<InitialType, AuxType1, AuxType2, FinalType1, Final return state -> { return state.unwrap(pair -> { return pair.bind((left, right) -> { - final FinalType1 finalLeft = first.finisher().apply(left); + final FinalType1 finalLeft = first.finisher().apply(left); final FinalType2 finalRight = second.finisher().apply(right); return new Pair<>(finalLeft, finalRight); @@ -97,7 +97,7 @@ final class CompoundCollector<InitialType, AuxType1, AuxType2, FinalType1, Final @Override public Supplier<IHolder<IPair<AuxType1, AuxType2>>> supplier() { return () -> { - final AuxType1 initialLeft = first.supplier().get(); + final AuxType1 initialLeft = first.supplier().get(); final AuxType2 initialRight = second.supplier().get(); return new Identity<>(new Pair<>(initialLeft, initialRight)); diff --git a/base/src/main/java/bjc/utils/funcutils/EnumUtils.java b/base/src/main/java/bjc/utils/funcutils/EnumUtils.java index 2039b97..20c5972 100644 --- a/base/src/main/java/bjc/utils/funcutils/EnumUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/EnumUtils.java @@ -16,19 +16,19 @@ public class EnumUtils { * Do an action for a random number of enum values. * * @param <E> - * The type of the enum. + * The type of the enum. * * @param clasz - * The enum class. + * The enum class. * * @param nValues - * The number of values to execute the action on. + * The number of values to execute the action on. * * @param action - * The action to perform on random values. + * The action to perform on random values. * * @param rnd - * The source of randomness to use. + * The source of randomness to use. */ public static <E extends Enum<E>> void doForValues(final Class<E> clasz, final int nValues, final Consumer<E> action, final Random rnd) { @@ -38,7 +38,7 @@ public class EnumUtils { final int randomValueCount = enumValues.length - nValues; - for (int i = 0; i <= randomValueCount; i++) { + for(int i = 0; i <= randomValueCount; i++) { final E rDir = valueList.randItem(rnd::nextInt); valueList.removeMatching(rDir); @@ -51,16 +51,15 @@ public class EnumUtils { * Get a random value from an enum. * * @param <E> - * The type of the enum. + * The type of the enum. * * @param clasz - * The class of the enum. + * The class of the enum. * * @param rnd - * The random source to use. + * The random source to use. * - * @return - * A random value from the specified enum. + * @return A random value from the specified enum. */ public static <E extends Enum<E>> E getRandomValue(final Class<E> clasz, final Random rnd) { final E[] enumValues = clasz.getEnumConstants(); diff --git a/base/src/main/java/bjc/utils/funcutils/FileUtils.java b/base/src/main/java/bjc/utils/funcutils/FileUtils.java index 6b897df..0fd3db0 100644 --- a/base/src/main/java/bjc/utils/funcutils/FileUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/FileUtils.java @@ -13,27 +13,26 @@ import java.util.function.BiPredicate; */ public class FileUtils { /* - * @NOTE - * If it becomes necessary, write another overload - * for this with all the buttons and knobs from - * walkFileTree. + * @NOTE If it becomes necessary, write another overload for this with + * all the buttons and knobs from walkFileTree. */ /** * Traverse a directory recursively. This is a depth-first traversal. * * @param root - * The directory to start the traversal at. + * The directory to start the traversal at. * * @param predicate - * The predicate to determine whether or not to traverse - * a directory. + * The predicate to determine whether or not to traverse a + * directory. * * @param action - * The action to invoke upon each file in the directory. Returning - * true means to continue the traversal, returning false stops it. + * The action to invoke upon each file in the directory. + * Returning true means to continue the traversal, returning + * false stops it. * * @throws IOException - * If the walk throws an exception. + * If the walk throws an exception. * */ public static void traverseDirectory(final Path root, final BiPredicate<Path, BasicFileAttributes> predicate, diff --git a/base/src/main/java/bjc/utils/funcutils/FunctionalFileVisitor.java b/base/src/main/java/bjc/utils/funcutils/FunctionalFileVisitor.java index b0dd162..fb2a697 100644 --- a/base/src/main/java/bjc/utils/funcutils/FunctionalFileVisitor.java +++ b/base/src/main/java/bjc/utils/funcutils/FunctionalFileVisitor.java @@ -14,18 +14,18 @@ import java.util.function.BiPredicate; */ final class FunctionalFileVisitor extends SimpleFileVisitor<Path> { /* Our predicate to pick files. */ - private final BiPredicate<Path, BasicFileAttributes> predicate; + private final BiPredicate<Path, BasicFileAttributes> predicate; /* Our action to aply to files. */ - private final BiPredicate<Path, BasicFileAttributes> action; + private final BiPredicate<Path, BasicFileAttributes> action; /** * Create a new file visitor, powered by functions. * * @param predicate - * The predicate to use to pick which files to traverse. + * The predicate to use to pick which files to traverse. * * @param action - * The function to execute on every file. + * The function to execute on every file. */ public FunctionalFileVisitor(final BiPredicate<Path, BasicFileAttributes> predicate, final BiPredicate<Path, BasicFileAttributes> action) { @@ -35,14 +35,14 @@ final class FunctionalFileVisitor extends SimpleFileVisitor<Path> { @Override public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { - if (predicate.test(dir, attrs)) return FileVisitResult.CONTINUE; + if(predicate.test(dir, attrs)) return FileVisitResult.CONTINUE; return FileVisitResult.SKIP_SUBTREE; } @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { - if (action.test(file, attrs)) return FileVisitResult.CONTINUE; + if(action.test(file, attrs)) return FileVisitResult.CONTINUE; return FileVisitResult.TERMINATE; } diff --git a/base/src/main/java/bjc/utils/funcutils/GroupPartIteration.java b/base/src/main/java/bjc/utils/funcutils/GroupPartIteration.java index 9e4b43a..a406c1c 100644 --- a/base/src/main/java/bjc/utils/funcutils/GroupPartIteration.java +++ b/base/src/main/java/bjc/utils/funcutils/GroupPartIteration.java @@ -12,19 +12,19 @@ import bjc.utils.funcdata.IList; * @author ben * * @param <E> - * The type of element in the list being partitioned + * The type of element in the list being partitioned */ final class GroupPartIteration<E> implements Consumer<E> { /* The list we're returning. */ private final IList<IList<E>> returnedList; /* The current partition of the list. */ - public IList<E> currentPartition; + public IList<E> currentPartition; /* The items rejected from the current partition. */ private final IList<E> rejectedItems; /* The number of items in the current partition. */ - private int numberInCurrentPartition; + private int numberInCurrentPartition; /* The number of items in each partition. */ private final int numberPerPartition; @@ -35,17 +35,18 @@ final class GroupPartIteration<E> implements Consumer<E> { * Create a new group partitioning iteration. * * @param returned - * The list containing all of the existing partitions. + * The list containing all of the existing partitions. * * @param rejects - * The items that have been rejected from a partition for being too - * large. + * The items that have been rejected from a partition for being + * too large. * * @param nPerPart - * The combined value of items that should go into each partition. + * The combined value of items that should go into each + * partition. * * @param eleCount - * The function to use to determine the value of an item. + * The function to use to determine the value of an item. */ public GroupPartIteration(final IList<IList<E>> returned, final IList<E> rejects, final int nPerPart, final Function<E, Integer> eleCount) { @@ -62,7 +63,7 @@ final class GroupPartIteration<E> implements Consumer<E> { public void accept(final E value) { final boolean shouldStartPartition = numberInCurrentPartition >= numberPerPartition; - if (shouldStartPartition) { + if(shouldStartPartition) { returnedList.add(currentPartition); currentPartition = new FunctionalList<>(); @@ -70,10 +71,10 @@ final class GroupPartIteration<E> implements Consumer<E> { } else { final int currentElementCount = elementCounter.apply(value); - final boolean shouldReject = - (numberInCurrentPartition + currentElementCount) >= numberPerPartition; + final boolean shouldReject = (numberInCurrentPartition + + currentElementCount) >= numberPerPartition; - if (shouldReject) { + if(shouldReject) { rejectedItems.add(value); } else { currentPartition.add(value); diff --git a/base/src/main/java/bjc/utils/funcutils/IBuilder.java b/base/src/main/java/bjc/utils/funcutils/IBuilder.java index 6cbb838..f8dd2fc 100644 --- a/base/src/main/java/bjc/utils/funcutils/IBuilder.java +++ b/base/src/main/java/bjc/utils/funcutils/IBuilder.java @@ -6,18 +6,17 @@ package bjc.utils.funcutils; * @author ben * * @param <E> - * The type of object being built. + * The type of object being built. */ public interface IBuilder<E> { /** * Build the object this builder is building. * - * @return - * The built object. + * @return The built object. * * @throws IllegalStateException - * If the data in the builder cannot be built into its - * corresponding object at this point in time. + * If the data in the builder cannot be built into its + * corresponding object at this point in time. */ public E build(); @@ -25,7 +24,7 @@ public interface IBuilder<E> { * Reset the state of this builder to its initial state. * * @throws UnsupportedOperationException - * If the builder doesn't support resetting its state. + * If the builder doesn't support resetting its state. */ public default void reset() { throw new UnsupportedOperationException("Builder doesn't support state resetting"); diff --git a/base/src/main/java/bjc/utils/funcutils/Isomorphism.java b/base/src/main/java/bjc/utils/funcutils/Isomorphism.java index d86ee9f..9559540 100644 --- a/base/src/main/java/bjc/utils/funcutils/Isomorphism.java +++ b/base/src/main/java/bjc/utils/funcutils/Isomorphism.java @@ -8,25 +8,25 @@ import java.util.function.Function; * @author bjculkin * * @param <S> - * The source type of the isomorphism. + * The source type of the isomorphism. * * @param <D> - * The destination type of isomorphism. + * The destination type of isomorphism. */ public class Isomorphism<S, D> { /* The function to the destination type. */ - private Function<S, D> toFunc; + private Function<S, D> toFunc; /* The function to the source type. */ - private Function<D, S> fromFunc; + private Function<D, S> fromFunc; /** * Create a new isomorphism. * * @param to - * The 'forward' function, from the source to the definition. + * The 'forward' function, from the source to the definition. * * @param from - * The 'backward' function, from the definition to the source. + * The 'backward' function, from the definition to the source. */ public Isomorphism(Function<S, D> to, Function<D, S> from) { toFunc = to; @@ -37,10 +37,9 @@ public class Isomorphism<S, D> { * Apply the isomorphism forward. * * @param val - * The source value. + * The source value. * - * @return - * The destination value. + * @return The destination value. */ public D to(S val) { return toFunc.apply(val); @@ -50,10 +49,9 @@ public class Isomorphism<S, D> { * Apply the isomorphism backward. * * @param val - * The destination value. + * The destination value. * - * @return - * The source value. + * @return The source value. */ public S from(D val) { return fromFunc.apply(val); diff --git a/base/src/main/java/bjc/utils/funcutils/LambdaLock.java b/base/src/main/java/bjc/utils/funcutils/LambdaLock.java index 2506d53..0130a77 100644 --- a/base/src/main/java/bjc/utils/funcutils/LambdaLock.java +++ b/base/src/main/java/bjc/utils/funcutils/LambdaLock.java @@ -26,7 +26,7 @@ public class LambdaLock { * Create a new lambda-enabled lock. * * @param lck - * The lock to wrap. + * The lock to wrap. */ public LambdaLock(final ReadWriteLock lck) { readLock = lck.readLock(); @@ -37,10 +37,9 @@ public class LambdaLock { * Execute an action with the read lock taken. * * @param supp - * The action to call. + * The action to call. * - * @return - * The result of the action. + * @return The result of the action. */ public <T> T read(final Supplier<T> supp) { readLock.lock(); @@ -56,10 +55,9 @@ public class LambdaLock { * Execute an action with the write lock taken. * * @param supp - * The action to call. + * The action to call. * - * @return - * The result of the action. + * @return The result of the action. */ public <T> T write(final Supplier<T> supp) { writeLock.lock(); @@ -75,7 +73,7 @@ public class LambdaLock { * Execute an action with the read lock taken. * * @param action - * The action to call. + * The action to call. */ public void read(final Runnable action) { readLock.lock(); @@ -91,7 +89,7 @@ public class LambdaLock { * Execute an action with the write lock taken. * * @param action - * The action to call. + * The action to call. */ public void write(final Runnable action) { writeLock.lock(); diff --git a/base/src/main/java/bjc/utils/funcutils/ListUtils.java b/base/src/main/java/bjc/utils/funcutils/ListUtils.java index 2441a80..20ae7b2 100644 --- a/base/src/main/java/bjc/utils/funcutils/ListUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/ListUtils.java @@ -23,13 +23,12 @@ public class ListUtils { * spaces. * * @param input - * The list of tokens to collapse. + * The list of tokens to collapse. * - * @return - * The collapsed string of tokens. + * @return The collapsed string of tokens. */ public static String collapseTokens(final IList<String> input) { - if (input == null) throw new NullPointerException("Input must not be null"); + if(input == null) throw new NullPointerException("Input must not be null"); return collapseTokens(input, ""); } @@ -39,33 +38,32 @@ public class ListUtils { * separator after each token. * * @param input - * The list of tokens to collapse. + * The list of tokens to collapse. * * @param seperator - * The separator to use for separating tokens. + * The separator to use for separating tokens. * - * @return - * The collapsed string of tokens. + * @return The collapsed string of tokens. */ public static String collapseTokens(final IList<String> input, final String seperator) { - if (input == null) { + if(input == null) { throw new NullPointerException("Input must not be null"); - } else if (seperator == null) { + } else if(seperator == null) { throw new NullPointerException("Seperator must not be null"); } - if (input.getSize() < 1) { + if(input.getSize() < 1) { return ""; - } else if (input.getSize() == 1) { + } else if(input.getSize() == 1) { return input.first(); } else { final StringBuilder state = new StringBuilder(); int i = 1; - for (final String itm : input.toIterable()) { + for(final String itm : input.toIterable()) { state.append(itm); - if (i != input.getSize()) { + if(i != input.getSize()) { state.append(seperator); } @@ -80,21 +78,20 @@ public class ListUtils { * Select a number of random items from the list without replacement. * * @param <E> - * The type of items to select. + * The type of items to select. * * @param list - * The list to select from. + * The list to select from. * * @param number - * The number of items to selet. + * The number of items to selet. * * @param rng - * A function that creates a random number from 0 to the - * desired number. + * A function that creates a random number from 0 to the desired + * number. * - * @return - * A new list containing the desired number of items randomly - * selected from the specified list without replacement. + * @return A new list containing the desired number of items randomly + * selected from the specified list without replacement. */ public static <E> IList<E> drawWithoutReplacement(final IList<E> list, final int number, final Function<Integer, Integer> rng) { @@ -105,7 +102,7 @@ public class ListUtils { final Iterator<E> itr = list.toIterable().iterator(); E element = null; - for (final int index = 0; itr.hasNext(); element = itr.next()) { + for(final int index = 0; itr.hasNext(); element = itr.next()) { /* n - m */ final int winningChance = number - selected.getSize(); @@ -113,7 +110,7 @@ public class ListUtils { final int totalChance = total - (index - 1); /* Probability of selecting the t+1'th element */ - if (NumberUtils.isProbable(winningChance, totalChance, rng)) { + if(NumberUtils.isProbable(winningChance, totalChance, rng)) { selected.add(element); } } @@ -125,27 +122,26 @@ public class ListUtils { * Select a number of random items from the list, with replacement. * * @param <E> - * The type of items to select. + * The type of items to select. * * @param list - * The list to select from. + * The list to select from. * * @param number - * The number of items to select. + * The number of items to select. * * @param rng - * A function that creates a random number from 0 to the - * desired number. + * A function that creates a random number from 0 to the desired + * number. * - * @return - * A new list containing the desired number of items randomly - * selected from the specified list. + * @return A new list containing the desired number of items randomly + * selected from the specified list. */ public static <E> IList<E> drawWithReplacement(final IList<E> list, final int number, final Function<Integer, Integer> rng) { final IList<E> selected = new FunctionalList<>(new ArrayList<>(number)); - for (int i = 0; i < number; i++) { + for(int i = 0; i < number; i++) { selected.add(list.randItem(rng)); } @@ -157,27 +153,26 @@ public class ListUtils { * for more than one element in a partition. * * @param <E> - * The type of elements in the list to partition. + * The type of elements in the list to partition. * * @param input - * The list to partition. + * The list to partition. * * @param counter - * The function to determine the count for each element for. + * The function to determine the count for each element for. * * @param partitionSize - * The number of elements to put in each partition. + * The number of elements to put in each partition. * - * @return - * A list partitioned according to the above rules. + * @return A list partitioned according to the above rules. */ public static <E> IList<IList<E>> groupPartition(final IList<E> input, final Function<E, Integer> counter, final int partitionSize) { - if (input == null) { + if(input == null) { throw new NullPointerException("Input list must not be null"); - } else if (counter == null) { + } else if(counter == null) { throw new NullPointerException("Counter must not be null"); - } else if (partitionSize < 1 || partitionSize > input.getSize()) { + } else if(partitionSize < 1 || partitionSize > input.getSize()) { final String fmt = "%d is not a valid partition size. Must be between 1 and %d"; final String msg = String.format(fmt, partitionSize, input.getSize()); @@ -193,20 +188,20 @@ public class ListUtils { final GroupPartIteration<E> it = new GroupPartIteration<>(returned, rejected, partitionSize, counter); /* Run up to a certain number of passes. */ - for (int numberOfIterations = 0; numberOfIterations < MAX_NTRIESPART + for(int numberOfIterations = 0; numberOfIterations < MAX_NTRIESPART && !rejected.isEmpty(); numberOfIterations++) { input.forEach(it); - if (rejected.isEmpty()) { + if(rejected.isEmpty()) { /* Nothing was rejected, so we're done. */ return returned; } } - final String fmt = "Heuristic (more than %d iterations of partitioning) detected an unpartitionable list. (%s)\nThe following elements were not partitioned: %s\nCurrent group in formation: %s\nPreviously formed groups: %s\n"; - final String msg = String.format(fmt, MAX_NTRIESPART, input.toString(), rejected.toString(), it.currentPartition.toString(), returned.toString()); + final String msg = String.format(fmt, MAX_NTRIESPART, input.toString(), rejected.toString(), + it.currentPartition.toString(), returned.toString()); throw new IllegalArgumentException(msg); } @@ -215,20 +210,19 @@ public class ListUtils { * Merge the contents of a bunch of lists together into a single list. * * @param <E> - * The type of value in this lists. + * The type of value in this lists. * * @param lists - * The values in the lists to merge. + * The values in the lists to merge. * - * @return - * A list containing all the elements of the lists. + * @return A list containing all the elements of the lists. */ @SafeVarargs public static <E> IList<E> mergeLists(final IList<E>... lists) { final IList<E> returned = new FunctionalList<>(); - for (final IList<E> list : lists) { - for (final E itm : list.toIterable()) { + for(final IList<E> list : lists) { + for(final E itm : list.toIterable()) { returned.add(itm); } } @@ -240,25 +234,24 @@ public class ListUtils { * Pad the provided list out to the desired size. * * @param <E> - * The type of elements in the list. + * The type of elements in the list. * * @param list - * The list to pad out. + * The list to pad out. * * @param counter - * The function to count elements with. + * The function to count elements with. * * @param size - * The desired size of the list. + * The desired size of the list. * * @param padder - * The function to get elements to pad with. + * The function to get elements to pad with. * - * @return - * The list, padded to the desired size. + * @return The list, padded to the desired size. * * @throws IllegalArgumentException - * If the list couldn't be padded to the desired size. + * If the list couldn't be padded to the desired size. */ public static <E> IList<E> padList(final IList<E> list, final Function<E, Integer> counter, final int size, final Supplier<E> padder) { @@ -266,22 +259,22 @@ public class ListUtils { final IList<E> returned = new FunctionalList<>(); - for (final E itm : list.toIterable()) { + for(final E itm : list.toIterable()) { count += counter.apply(itm); returned.add(itm); } - if (count % size != 0) { + if(count % size != 0) { /* We need to pad */ int needed = count % size; int threshold = 0; - while (needed > 0 && threshold <= MAX_NTRIESPART) { + while(needed > 0 && threshold <= MAX_NTRIESPART) { final E val = padder.get(); final int newCount = counter.apply(val); - if (newCount <= needed) { + if(newCount <= needed) { returned.add(val); threshold = 0; @@ -292,10 +285,11 @@ public class ListUtils { } } - if (threshold > MAX_NTRIESPART) { + if(threshold > MAX_NTRIESPART) { final String fmt = "Heuristic (more than %d iterations of attempting to pad) detected an unpaddable list. (%s)\nPartially padded list: %S"; - final String msg = String.format(fmt, MAX_NTRIESPART, list.toString(), returned.toString()); + final String msg = String.format(fmt, MAX_NTRIESPART, list.toString(), + returned.toString()); throw new IllegalArgumentException(msg); } diff --git a/base/src/main/java/bjc/utils/funcutils/NumberUtils.java b/base/src/main/java/bjc/utils/funcutils/NumberUtils.java index c3d52fa..c29fafe 100644 --- a/base/src/main/java/bjc/utils/funcutils/NumberUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/NumberUtils.java @@ -12,23 +12,22 @@ public class NumberUtils { * Compute the falling factorial of a number. * * @param value - * The number to compute. + * The number to compute. * * @param power - * The power to do the falling factorial for. + * The power to do the falling factorial for. * - * @return - * The falling factorial of the number to the power. + * @return The falling factorial of the number to the power. */ public static int fallingFactorial(final int value, final int power) { - if (power == 0) { + if(power == 0) { return 1; - } else if (power == 1) { + } else if(power == 1) { return value; } else { int result = 1; - for (int currentSub = 0; currentSub < power + 1; currentSub++) { + for(int currentSub = 0; currentSub < power + 1; currentSub++) { result *= value - currentSub; } @@ -40,13 +39,13 @@ public class NumberUtils { * Evaluates a linear probability distribution. * * @param winning - * The number of winning possibilities. + * The number of winning possibilities. * * @param total - * The number of total possibilities. + * The number of total possibilities. * * @param rng - * The function to use to generate a random possibility. + * The function to use to generate a random possibility. * * @return Whether or not a random possibility was a winning one. */ @@ -58,16 +57,15 @@ public class NumberUtils { * Check if a number is in an inclusive range. * * @param min - * The minimum value of the range. + * The minimum value of the range. * * @param max - * The maximum value of the range. + * The maximum value of the range. * * @param i - * The number to check. + * The number to check. * - * @return - * Whether the number is in the range. + * @return Whether the number is in the range. */ public static boolean between(final int min, final int max, final int i) { return i >= min && i <= max; diff --git a/base/src/main/java/bjc/utils/funcutils/StringUtils.java b/base/src/main/java/bjc/utils/funcutils/StringUtils.java index ba4ebca..fa7e59e 100644 --- a/base/src/main/java/bjc/utils/funcutils/StringUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/StringUtils.java @@ -17,19 +17,18 @@ public class StringUtils { * expression. * * @param input - * The string to check. + * The string to check. * * @param rRegex - * The regex to see if the string only contains matches of. + * The regex to see if the string only contains matches of. * - * @return - * Whether or not the string consists only of multiple matches of - * the provided regex. + * @return Whether or not the string consists only of multiple matches + * of the provided regex. */ public static boolean containsOnly(final String input, final String rRegex) { - if (input == null) + if(input == null) throw new NullPointerException("Input must not be null"); - else if (rRegex == null) throw new NullPointerException("Regex must not be null"); + else if(rRegex == null) throw new NullPointerException("Regex must not be null"); /* * This regular expression is fairly simple. @@ -46,13 +45,13 @@ public class StringUtils { * Indent the string being built in a StringBuilder n levels. * * @param builder - * The builder to indent in. + * The builder to indent in. * * @param levels - * The number of levels to indent. + * The number of levels to indent. */ public static void indentNLevels(final StringBuilder builder, final int levels) { - for (int i = 0; i < levels; i++) { + for(int i = 0; i < levels; i++) { builder.append("\t"); } } @@ -62,14 +61,13 @@ public class StringUtils { * empty. * * @param <ContainedType> - * The type in the deque. + * The type in the deque. * * @param queue - * The deque to print. + * The deque to print. * - * @return - * A string version of the deque, with allowance for an empty - * deque. + * @return A string version of the deque, with allowance for an empty + * deque. */ public static <ContainedType> String printDeque(final Deque<ContainedType> queue) { return queue.isEmpty() ? "(none)" : queue.toString(); @@ -79,26 +77,26 @@ public class StringUtils { * Converts a sequence to an English list. * * @param objects - * The sequence to convert to an English list. + * The sequence to convert to an English list. * * @param join - * The string to use for separating the last element from the rest. + * The string to use for separating the last element from the + * rest. * * @param comma - * The string to use as a comma + * The string to use as a comma * - * @return - * The sequence as an English list. + * @return The sequence as an English list. */ public static String toEnglishList(final Object[] objects, final String join, final String comma) { - if (objects == null) throw new NullPointerException("Sequence must not be null"); + if(objects == null) throw new NullPointerException("Sequence must not be null"); final StringBuilder sb = new StringBuilder(); final String joiner = join; final String coma = comma; - switch (objects.length) { + switch(objects.length) { case 0: /* Empty list. */ break; @@ -114,7 +112,7 @@ public class StringUtils { break; default: /* Three or more items. */ - for (int i = 0; i < objects.length - 1; i++) { + for(int i = 0; i < objects.length - 1; i++) { sb.append(objects[i].toString()); sb.append(coma + " "); } @@ -137,13 +135,13 @@ public class StringUtils { * Converts a sequence to an English list. * * @param objects - * The sequence to convert to an English list. + * The sequence to convert to an English list. * * @param join - * The string to use for separating the last element from the rest. + * The string to use for separating the last element from the + * rest. * - * @return - * The sequence as an English list. + * @return The sequence as an English list. */ public static String toEnglishList(final Object[] objects, final String join) { return toEnglishList(objects, join, ","); @@ -153,16 +151,15 @@ public class StringUtils { * Converts a sequence to an English list. * * @param objects - * The sequence to convert to an English list. + * The sequence to convert to an English list. * * @param and - * Whether to use 'and' or 'or'. + * Whether to use 'and' or 'or'. * - * @return - * The sequence as an English list. + * @return The sequence as an English list. */ public static String toEnglishList(final Object[] objects, final boolean and) { - if (and) { + if(and) { return toEnglishList(objects, "and"); } else { return toEnglishList(objects, "or"); @@ -173,17 +170,16 @@ public class StringUtils { * Count the number of graphemes in a string. * * @param value - * The string to check. + * The string to check. * - * @return - * The number of graphemes in the string. + * @return The number of graphemes in the string. */ public static int graphemeCount(final String value) { final BreakIterator it = BreakIterator.getCharacterInstance(); it.setText(value); int count = 0; - while (it.next() != BreakIterator.DONE) { + while(it.next() != BreakIterator.DONE) { count++; } @@ -194,14 +190,14 @@ public class StringUtils { * Count the number of times a pattern matches in a given string. * * @param value - * The string to count occurances in. + * The string to count occurances in. * * @param pattern - * The pattern to count occurances of. + * The pattern to count occurances of. */ public static int countMatches(final String value, final String pattern) { Matcher mat = Pattern.compile(pattern).matcher(value); - + int num = 0; while(mat.find()) num += 1; diff --git a/base/src/main/java/bjc/utils/funcutils/TreeUtils.java b/base/src/main/java/bjc/utils/funcutils/TreeUtils.java index 3308fb8..1bdd7b3 100644 --- a/base/src/main/java/bjc/utils/funcutils/TreeUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/TreeUtils.java @@ -29,7 +29,8 @@ public class TreeUtils { } /* Find a path in a tree. */ - private static <T> void findPath(ITree<T> subtree, LinkedList<T> path, Predicate<T> leafMarker, IList<IList<T>> paths) { + private static <T> void findPath(ITree<T> subtree, LinkedList<T> path, Predicate<T> leafMarker, + IList<IList<T>> paths) { if(subtree.getChildrenCount() == 0 && leafMarker.test(subtree.getHead())) { /* We're at a matching leaf node. Add it. */ IList<T> finalPath = new FunctionalList<>(); diff --git a/base/src/main/java/bjc/utils/funcutils/TriConsumer.java b/base/src/main/java/bjc/utils/funcutils/TriConsumer.java index a41cde0..7b15097 100644 --- a/base/src/main/java/bjc/utils/funcutils/TriConsumer.java +++ b/base/src/main/java/bjc/utils/funcutils/TriConsumer.java @@ -6,13 +6,13 @@ package bjc.utils.funcutils; * @author EVE * * @param <A> - * Type of the first argument. + * Type of the first argument. * * @param <B> - * Type of the second argument. + * Type of the second argument. * * @param <C> - * Type of the third argument. + * Type of the third argument. */ @FunctionalInterface public interface TriConsumer<A, B, C> { @@ -20,13 +20,13 @@ public interface TriConsumer<A, B, C> { * Perform the action. * * @param a - * The first parameter. + * The first parameter. * * @param b - * The second parameter. + * The second parameter. * * @param c - * The third parameter. + * The third parameter. */ public void accept(A a, B b, C c); } diff --git a/base/src/main/java/bjc/utils/gen/RandomGrammar.java b/base/src/main/java/bjc/utils/gen/RandomGrammar.java index 978accb..b418c79 100644 --- a/base/src/main/java/bjc/utils/gen/RandomGrammar.java +++ b/base/src/main/java/bjc/utils/gen/RandomGrammar.java @@ -9,7 +9,7 @@ import bjc.utils.funcdata.IList; * @author ben * * @param <E> - * The type of grammar elements to use. + * The type of grammar elements to use. */ public class RandomGrammar<E> extends WeightedGrammar<E> { /** Create a new random grammar. */ @@ -21,14 +21,14 @@ public class RandomGrammar<E> extends WeightedGrammar<E> { * Add cases to a specified rule. * * @param rule - * The name of the rule to add cases to. + * The name of the rule to add cases to. * * @param cases - * The cases to add for this rule. + * The cases to add for this rule. */ @SafeVarargs public final void addCases(final E rule, final IList<E>... cases) { - for (final IList<E> currentCase : cases) { + for(final IList<E> currentCase : cases) { super.addCase(rule, 1, currentCase); } } @@ -37,16 +37,16 @@ public class RandomGrammar<E> extends WeightedGrammar<E> { * Create a rule with the specified name and cases. * * @param rule - * The name of the rule to add. + * The name of the rule to add. * * @param cases - * The cases to add for this rule. + * The cases to add for this rule. */ @SafeVarargs public final void makeRule(final E rule, final IList<E>... cases) { super.addRule(rule); - for (final IList<E> currentCase : cases) { + for(final IList<E> currentCase : cases) { super.addCase(rule, 1, currentCase); } } @@ -55,13 +55,13 @@ public class RandomGrammar<E> extends WeightedGrammar<E> { * Create a rule with the specified name and cases. * * @param rule - * The name of the rule to add. + * The name of the rule to add. * * @param cases - * The cases to add for this rule. + * The cases to add for this rule. */ public void makeRule(final E rule, final IList<IList<E>> cases) { - if (cases == null) throw new NullPointerException("Cases must not be null"); + if(cases == null) throw new NullPointerException("Cases must not be null"); super.addRule(rule); diff --git a/base/src/main/java/bjc/utils/gen/WeightedGrammar.java b/base/src/main/java/bjc/utils/gen/WeightedGrammar.java index 1fbba02..472c3a3 100644 --- a/base/src/main/java/bjc/utils/gen/WeightedGrammar.java +++ b/base/src/main/java/bjc/utils/gen/WeightedGrammar.java @@ -19,7 +19,7 @@ import bjc.utils.funcdata.IMap; * @author ben * * @param <E> - * The values that make up sentences of this grammar. + * The values that make up sentences of this grammar. */ public class WeightedGrammar<E> { /** The initial rule of the grammar */ @@ -55,12 +55,12 @@ public class WeightedGrammar<E> { * randomness. * * @param source - * The source of randomness to use + * The source of randomness to use */ public WeightedGrammar(final Random source) { this(); - if (source == null) throw new NullPointerException("Source of randomness must be non-null"); + if(source == null) throw new NullPointerException("Source of randomness must be non-null"); rng = source; } @@ -69,10 +69,10 @@ public class WeightedGrammar<E> { * Configure the action to perform on special tokens. * * @param marker - * The marker to find special tokens. + * The marker to find special tokens. * * @param action - * The action to take on those tokens. + * The action to take on those tokens. */ public void configureSpecial(final Predicate<E> marker, final BiFunction<E, WeightedGrammar<E>, IList<E>> action) { @@ -84,15 +84,15 @@ public class WeightedGrammar<E> { * Adds a special rule to the grammar. * * @param ruleName - * The name of the special rule. + * The name of the special rule. * * @param cse - * The case for the rule. + * The case for the rule. */ public void addSpecialRule(final E ruleName, final Supplier<IList<E>> cse) { - if (ruleName == null) { + if(ruleName == null) { throw new NullPointerException("Rule name must not be null"); - } else if (cse == null) { + } else if(cse == null) { throw new NullPointerException("Case must not be null"); } @@ -103,18 +103,18 @@ public class WeightedGrammar<E> { * Add a case to an already existing rule. * * @param ruleName - * The rule to add a case to. + * The rule to add a case to. * * @param probability - * The probability for this rule to be chosen. + * The probability for this rule to be chosen. * * @param cse - * The case being added. + * The case being added. */ public void addCase(final E ruleName, final int probability, final IList<E> cse) { - if (ruleName == null) { + if(ruleName == null) { throw new NullPointerException("Rule name must be not null"); - } else if (cse == null) { + } else if(cse == null) { throw new NullPointerException("Case body must not be null"); } @@ -125,24 +125,23 @@ public class WeightedGrammar<E> { * Add a alias for an existing subgrammar. * * @param name - * The name of the subgrammar to alias. + * The name of the subgrammar to alias. * * @param alias - * The alias of the subgrammar. + * The alias of the subgrammar. * - * @return - * Whether the alias was succesfully created. + * @return Whether the alias was succesfully created. */ public boolean addGrammarAlias(final E name, final E alias) { - if (name == null) { + if(name == null) { throw new NullPointerException("Subgrammar name must not be null"); - } else if (alias == null) { + } else if(alias == null) { throw new NullPointerException("Subgrammar alias must not be null"); } - if (subgrammars.containsKey(alias)) return false; + if(subgrammars.containsKey(alias)) return false; - if (subgrammars.containsKey(name)) { + if(subgrammars.containsKey(name)) { subgrammars.put(alias, subgrammars.get(name)); return true; } @@ -154,17 +153,16 @@ public class WeightedGrammar<E> { * Add a new rule with no cases. * * @param name - * The name of the rule to add. + * The name of the rule to add. * - * @return - * Whether or not the rule was successfully added. + * @return Whether or not the rule was successfully added. */ public boolean addRule(final E name) { - if (rng == null) { + if(rng == null) { rng = new Random(); } - if (name == null) throw new NullPointerException("Rule name must not be null"); + if(name == null) throw new NullPointerException("Rule name must not be null"); return addRule(name, new WeightedRandom<>(rng)); } @@ -173,22 +171,21 @@ public class WeightedGrammar<E> { * Add a new rule with a set of cases. * * @param name - * The name of the rule to add. + * The name of the rule to add. * * @param cases - * The set of cases for the rule. + * The set of cases for the rule. * - * @return - * Whether or not the rule was succesfully added. + * @return Whether or not the rule was succesfully added. */ public boolean addRule(final E name, final WeightedRandom<IList<E>> cases) { - if (name == null) { + if(name == null) { throw new NullPointerException("Name must not be null"); - } else if (cases == null) { + } else if(cases == null) { throw new NullPointerException("Cases must not be null"); } - if (rules.containsKey(name)) return false; + if(rules.containsKey(name)) return false; rules.put(name, cases); return true; @@ -198,22 +195,21 @@ public class WeightedGrammar<E> { * Add a subgrammar. * * @param name - * The name of the subgrammar. + * The name of the subgrammar. * * @param subgrammar - * The subgrammar to add. + * The subgrammar to add. * - * @return - * Whether or not the subgrammar was succesfully added. + * @return Whether or not the subgrammar was succesfully added. */ public boolean addSubgrammar(final E name, final WeightedGrammar<E> subgrammar) { - if (name == null) { + if(name == null) { throw new NullPointerException("Subgrammar name must not be null"); - } else if (subgrammar == null) { + } else if(subgrammar == null) { throw new NullPointerException("Subgrammar must not be null"); } - if (subgrammars.containsKey(name)) return false; + if(subgrammars.containsKey(name)) return false; subgrammars.put(name, subgrammar); return true; @@ -223,10 +219,10 @@ public class WeightedGrammar<E> { * Remove a rule with the specified name. * * @param name - * The name of the rule to remove. + * The name of the rule to remove. */ public void deleteRule(final E name) { - if (name == null) throw new NullPointerException("Rule name must not be null"); + if(name == null) throw new NullPointerException("Rule name must not be null"); rules.remove(name); } @@ -235,10 +231,10 @@ public class WeightedGrammar<E> { * Remove a subgrammar with the specified name. * * @param name - * The name of the subgrammar to remove. + * The name of the subgrammar to remove. */ public void deleteSubgrammar(final E name) { - if (name == null) throw new NullPointerException("Rule name must not be null"); + if(name == null) throw new NullPointerException("Rule name must not be null"); subgrammars.remove(name); } @@ -249,19 +245,18 @@ public class WeightedGrammar<E> { * Only generates sentences one layer deep. * * @param ruleName - * The rule to test. + * The rule to test. * - * @return - * A set of sentences generated by the specified rule. + * @return A set of sentences generated by the specified rule. */ public IList<IList<E>> generateDebugValues(final E ruleName) { - if (ruleName == null) throw new NullPointerException("Rule name must not be null"); + if(ruleName == null) throw new NullPointerException("Rule name must not be null"); final IList<IList<E>> returnedList = new FunctionalList<>(); final WeightedRandom<IList<E>> ruleGenerator = rules.get(ruleName); - for (int i = 0; i < 10; i++) { + for(int i = 0; i < 10; i++) { returnedList.add(ruleGenerator.generateValue()); } @@ -272,27 +267,27 @@ public class WeightedGrammar<E> { * Generate a generic sentence from a initial rule. * * @param <T> - * The type of the transformed output + * The type of the transformed output * * @param initRules - * The initial rule to start with. + * The initial rule to start with. * * @param tokenTransformer - * The function to transform grammar output into something. + * The function to transform grammar output into something. * * @param spacer - * The spacer element to add in between output tokens. + * The spacer element to add in between output tokens. * - * @return - * A randomly generated sentence from the specified initial rule. + * @return A randomly generated sentence from the specified initial + * rule. */ public <T> IList<T> generateGenericValues(final E initRules, final Function<E, T> tokenTransformer, final T spacer) { - if (initRules == null) { + if(initRules == null) { throw new NullPointerException("Initial rule must not be null"); - } else if (tokenTransformer == null) { + } else if(tokenTransformer == null) { throw new NullPointerException("Transformer must not be null"); - } else if (spacer == null) { + } else if(spacer == null) { throw new NullPointerException("Spacer must not be null"); } @@ -300,43 +295,42 @@ public class WeightedGrammar<E> { IList<E> genRules = new FunctionalList<>(initRules); - if (specialMarker != null) { - if (specialMarker.test(initRules)) { + if(specialMarker != null) { + if(specialMarker.test(initRules)) { genRules = specialAction.apply(initRules, this); } } /* - * @NOTE - * Can this loop be simplified in some way? + * @NOTE Can this loop be simplified in some way? */ - for (final E initRule : genRules.toIterable()) { - if (specialRules.containsKey(initRule)) { - for (final E rulePart : specialRules.get(initRule).get().toIterable()) { + for(final E initRule : genRules.toIterable()) { + if(specialRules.containsKey(initRule)) { + for(final E rulePart : specialRules.get(initRule).get().toIterable()) { final Iterable<T> generatedRuleParts = generateGenericValues(rulePart, tokenTransformer, spacer).toIterable(); - for (final T generatedRulePart : generatedRuleParts) { + for(final T generatedRulePart : generatedRuleParts) { returnedList.add(generatedRulePart); returnedList.add(spacer); } } - } else if (subgrammars.containsKey(initRule)) { + } else if(subgrammars.containsKey(initRule)) { final Iterable<T> ruleParts = subgrammars.get(initRule) .generateGenericValues(initRule, tokenTransformer, spacer).toIterable(); - for (final T rulePart : ruleParts) { + for(final T rulePart : ruleParts) { returnedList.add(rulePart); returnedList.add(spacer); } - } else if (rules.containsKey(initRule)) { + } else if(rules.containsKey(initRule)) { final Iterable<E> ruleParts = rules.get(initRule).generateValue().toIterable(); - for (final E rulePart : ruleParts) { + for(final E rulePart : ruleParts) { final Iterable<T> generatedRuleParts = generateGenericValues(rulePart, tokenTransformer, spacer).toIterable(); - for (final T generatedRulePart : generatedRuleParts) { + for(final T generatedRulePart : generatedRuleParts) { returnedList.add(generatedRulePart); returnedList.add(spacer); } @@ -344,7 +338,7 @@ public class WeightedGrammar<E> { } else { final T transformedToken = tokenTransformer.apply(initRule); - if (transformedToken == null) + if(transformedToken == null) throw new NullPointerException("Transformer created null token"); returnedList.add(transformedToken); @@ -359,14 +353,13 @@ public class WeightedGrammar<E> { * Generate a random list of grammar elements from a given initial rule. * * @param initRule - * The initial rule to start with. + * The initial rule to start with. * * @param spacer - * The item to use to space the list. + * The item to use to space the list. * - * @return - * A list of random grammar elements generated by the specified - * rule. + * @return A list of random grammar elements generated by the specified + * rule. */ public IList<E> generateListValues(final E initRule, final E spacer) { final IList<E> retList = generateGenericValues(initRule, strang -> strang, spacer); @@ -377,8 +370,7 @@ public class WeightedGrammar<E> { /** * Get the initial rule of this grammar. * - * @return - * The initial rule of this grammar. + * @return The initial rule of this grammar. */ public String getInitialRule() { return initialRule; @@ -387,8 +379,7 @@ public class WeightedGrammar<E> { /** * Returns the number of rules in this grammar. * - * @return - * The number of rules in this grammar. + * @return The number of rules in this grammar. */ public int getRuleCount() { return rules.size(); @@ -397,8 +388,7 @@ public class WeightedGrammar<E> { /** * Returns a set containing all of the rules in this grammar. * - * @return - * The set of all rule names in this grammar. + * @return The set of all rule names in this grammar. */ public IList<E> getRuleNames() { final IList<E> ruleNames = new FunctionalList<>(); @@ -413,13 +403,12 @@ public class WeightedGrammar<E> { * Get the subgrammar with the specified name. * * @param name - * The name of the subgrammar to get. + * The name of the subgrammar to get. * - * @return - * The subgrammar with the specified name. + * @return The subgrammar with the specified name. */ public WeightedGrammar<E> getSubgrammar(final E name) { - if (name == null) throw new NullPointerException("Subgrammar name must not be null"); + if(name == null) throw new NullPointerException("Subgrammar name must not be null"); return subgrammars.get(name); } @@ -427,8 +416,7 @@ public class WeightedGrammar<E> { /** * Check if this grammar has an initial rule * - * @return - * Whether or not this grammar has an initial rule + * @return Whether or not this grammar has an initial rule */ public boolean hasInitialRule() { return initialRule != null && !initialRule.equalsIgnoreCase(""); @@ -438,10 +426,9 @@ public class WeightedGrammar<E> { * Check if this grammar has a given rule. * * @param ruleName - * The rule to check for. + * The rule to check for. * - * @return - * Whether or not the grammar has a rule by that name. + * @return Whether or not the grammar has a rule by that name. */ public boolean hasRule(final E ruleName) { return rules.containsKey(ruleName) || specialRules.containsKey(ruleName); @@ -451,24 +438,24 @@ public class WeightedGrammar<E> { * Prefix a given rule with a token multiple times. * * @param ruleName - * The name of the rule to prefix. + * The name of the rule to prefix. * * @param prefixToken - * The token to prefix to the rules. + * The token to prefix to the rules. * * @param additionalProbability - * The additional probability of the tokens. + * The additional probability of the tokens. * * @param numberOfTimes - * The number of times to prefix the token. + * The number of times to prefix the token. */ public void multiPrefixRule(final E ruleName, final E prefixToken, final int additionalProbability, final int numberOfTimes) { - if (ruleName == null) + if(ruleName == null) throw new NullPointerException("Rule name must not be null"); - else if (prefixToken == null) + else if(prefixToken == null) throw new NullPointerException("Prefix token must not be null"); - else if (numberOfTimes < 1) + else if(numberOfTimes < 1) throw new IllegalArgumentException("Number of times to prefix must be positive."); final WeightedRandom<IList<E>> rule = rules.get(ruleName); @@ -476,24 +463,23 @@ public class WeightedGrammar<E> { final IList<IPair<Integer, IList<E>>> newResults = new FunctionalList<>(); /* - * @NOTE - * Can this be simplified? + * @NOTE Can this be simplified? */ rule.getValues().forEach((pair) -> { final IList<IList<E>> newRule = new FunctionalList<>(); - for (int i = 1; i <= numberOfTimes; i++) { + for(int i = 1; i <= numberOfTimes; i++) { final IList<E> newCase = pair.merge((left, right) -> { final IList<E> returnVal = new FunctionalList<>(); - for (final E val : right.toIterable()) { + for(final E val : right.toIterable()) { returnVal.add(val); } return returnVal; }); - for (int j = 1; j <= i; j++) { + for(int j = 1; j <= i; j++) { newCase.prepend(prefixToken); } @@ -519,19 +505,18 @@ public class WeightedGrammar<E> { * given token. * * @param additionalProbability - * The amount to adjust the probability by. + * The amount to adjust the probability by. * * @param ruleName - * The name of the rule to prefix. + * The name of the rule to prefix. * * @param prefixToken - * The token to prefix to the rule. + * The token to prefix to the rule. */ public void prefixRule(final E ruleName, final E prefixToken, final int additionalProbability) { - if (ruleName == null) { + if(ruleName == null) { throw new NullPointerException("Rule name must not be null"); - } - else if (prefixToken == null) { + } else if(prefixToken == null) { throw new NullPointerException("Prefix token must not be null"); } @@ -543,7 +528,7 @@ public class WeightedGrammar<E> { final IList<E> newCase = pair.merge((left, right) -> { final IList<E> returnVal = new FunctionalList<>(); - for (final E val : right.toIterable()) { + for(final E val : right.toIterable()) { returnVal.add(val); } @@ -562,7 +547,7 @@ public class WeightedGrammar<E> { * Set the initial rule of the grammar. * * @param initRule - * The initial rule of this grammar. + * The initial rule of this grammar. */ public void setInitialRule(final String initRule) { this.initialRule = initRule; @@ -572,18 +557,18 @@ public class WeightedGrammar<E> { * Suffix a token to a rule. * * @param ruleName - * The rule to suffix. + * The rule to suffix. * * @param suffixToken - * The token to prefix to the rule. + * The token to prefix to the rule. * * @param additionalProbability - * Additional probability of the prefixed rule. + * Additional probability of the prefixed rule. */ public void suffixRule(final E ruleName, final E suffixToken, final int additionalProbability) { - if (ruleName == null) { + if(ruleName == null) { throw new NullPointerException("Rule name must not be null"); - } else if (suffixToken == null) { + } else if(suffixToken == null) { throw new NullPointerException("Prefix token must not be null"); } @@ -595,7 +580,7 @@ public class WeightedGrammar<E> { final IList<E> newCase = par.merge((left, right) -> { final IList<E> returnVal = new FunctionalList<>(); - for (final E val : right.toIterable()) { + for(final E val : right.toIterable()) { returnVal.add(val); } diff --git a/base/src/main/java/bjc/utils/gen/WeightedRandom.java b/base/src/main/java/bjc/utils/gen/WeightedRandom.java index abba36a..be8b8c2 100644 --- a/base/src/main/java/bjc/utils/gen/WeightedRandom.java +++ b/base/src/main/java/bjc/utils/gen/WeightedRandom.java @@ -15,7 +15,7 @@ import bjc.utils.funcdata.IList; * @author ben * * @param <E> - * The type of values that are randomly selected. + * The type of values that are randomly selected. */ public class WeightedRandom<E> { /* The list of probabilities for each result */ @@ -33,13 +33,13 @@ public class WeightedRandom<E> { * randomness. * * @param src - * The source of randomness to use. + * The source of randomness to use. */ public WeightedRandom(final Random src) { probabilities = new FunctionalList<>(); results = new FunctionalList<>(); - if (src == null) throw new NullPointerException("Source of randomness must not be null"); + if(src == null) throw new NullPointerException("Source of randomness must not be null"); source = src; } @@ -48,10 +48,10 @@ public class WeightedRandom<E> { * Add a probability for a specific result to be given. * * @param chance - * The chance to get this result. + * The chance to get this result. * * @param result - * The result to get when the chance comes up. + * The result to get when the chance comes up. */ public void addProbability(final int chance, final E result) { probabilities.add(chance); @@ -63,17 +63,16 @@ public class WeightedRandom<E> { /** * Generate a weighted random value. * - * @return - * A random value selected in a weighted fashion. + * @return A random value selected in a weighted fashion. */ public E generateValue() { - final IHolder<Integer> value = new Identity<>(source.nextInt(totalChance)); - final IHolder<E> current = new Identity<>(); + final IHolder<Integer> value = new Identity<>(source.nextInt(totalChance)); + final IHolder<E> current = new Identity<>(); final IHolder<Boolean> picked = new Identity<>(true); probabilities.forEachIndexed((index, probability) -> { - if (picked.unwrap(bool -> bool)) { - if (value.unwrap((number) -> number < probability)) { + if(picked.unwrap(bool -> bool)) { + if(value.unwrap((number) -> number < probability)) { current.transform((result) -> results.getByIndex(index)); picked.transform((bool) -> false); @@ -89,8 +88,7 @@ public class WeightedRandom<E> { /** * Return a list of values that can be generated by this generator * - * @return - * A list of all the values that can be generated + * @return A list of all the values that can be generated */ public IList<E> getResults() { return results; @@ -100,8 +98,7 @@ public class WeightedRandom<E> { * Return a list containing values that can be generated paired with the * probability of those values being generated * - * @return - * A list of pairs of values and value probabilities + * @return A list of pairs of values and value probabilities */ public IList<IPair<Integer, E>> getValues() { return probabilities.pairWith(results); diff --git a/base/src/main/java/bjc/utils/graph/AdjacencyMap.java b/base/src/main/java/bjc/utils/graph/AdjacencyMap.java index 1598b25..965eccc 100644 --- a/base/src/main/java/bjc/utils/graph/AdjacencyMap.java +++ b/base/src/main/java/bjc/utils/graph/AdjacencyMap.java @@ -20,25 +20,24 @@ import bjc.utils.funcutils.FuncUtils; * @author ben * * @param <T> - * The type of the nodes in the graph + * The type of the nodes in the graph */ public class AdjacencyMap<T> { /** * Create an adjacency map from a stream of text * * @param stream - * The stream of text to read in + * The stream of text to read in * - * @return - * An adjacency map defined by the text + * @return An adjacency map defined by the text */ public static AdjacencyMap<Integer> fromStream(final InputStream stream) { - if (stream == null) throw new NullPointerException("Input source must not be null"); + if(stream == null) throw new NullPointerException("Input source must not be null"); /* Create the adjacency map. */ AdjacencyMap<Integer> adjacency; - try (Scanner input = new Scanner(stream)) { + try(Scanner input = new Scanner(stream)) { input.useDelimiter("\n"); int vertexCount; @@ -48,8 +47,8 @@ public class AdjacencyMap<T> { try { /* First, read in number of vertices. */ vertexCount = Integer.parseInt(possible); - } catch (final NumberFormatException nfex) { - String msg = String.format( + } catch(final NumberFormatException nfex) { + String msg = String.format( "The first line must contain the number of vertices. %s is not a valid number", possible); @@ -60,7 +59,7 @@ public class AdjacencyMap<T> { throw imex; } - if (vertexCount <= 0) + if(vertexCount <= 0) throw new InputMismatchException("The number of vertices must be greater than 0"); final IList<Integer> vertices = new FunctionalList<>(); @@ -84,7 +83,7 @@ public class AdjacencyMap<T> { final IHolder<Integer> row, final String strang) { final String[] parts = strang.split(" "); - if (parts.length != vertexCount) { + if(parts.length != vertexCount) { String msg = String.format("Must specify a weight for all %d vertices", vertexCount); throw new InputMismatchException(msg); @@ -92,12 +91,12 @@ public class AdjacencyMap<T> { int column = 0; - for (final String part : parts) { + for(final String part : parts) { int weight; try { weight = Integer.parseInt(part); - } catch (final NumberFormatException nfex) { + } catch(final NumberFormatException nfex) { String msg = String.format("%d is not a valid weight.", part); final InputMismatchException imex = new InputMismatchException(msg); @@ -121,10 +120,10 @@ public class AdjacencyMap<T> { * Create a new map from a set of vertices * * @param vertices - * The set of vertices to create a map from + * The set of vertices to create a map from */ public AdjacencyMap(final IList<T> vertices) { - if (vertices == null) throw new NullPointerException("Vertices must not be null"); + if(vertices == null) throw new NullPointerException("Vertices must not be null"); vertices.forEach(vertex -> { final IMap<T, Integer> row = new FunctionalMap<>(); @@ -140,8 +139,7 @@ public class AdjacencyMap<T> { /** * Check if the graph is directed * - * @return - * Whether or not the graph is directed + * @return Whether or not the graph is directed */ public boolean isDirected() { final IHolder<Boolean> result = new Identity<>(true); @@ -150,7 +148,7 @@ public class AdjacencyMap<T> { sourceValue.forEach((targetKey, targetValue) -> { final int inverseValue = adjacency.get(targetKey).get(sourceKey); - if (targetValue != inverseValue) { + if(targetValue != inverseValue) { result.replace(false); } }); @@ -163,24 +161,24 @@ public class AdjacencyMap<T> { * Set the weight of an edge. * * @param source - * The source node of the edge. + * The source node of the edge. * @param target - * The target node of the edge. + * The target node of the edge. * @param weight - * The weight of the edge. + * The weight of the edge. */ public void setWeight(final T source, final T target, final int weight) { - if (source == null) { + if(source == null) { throw new NullPointerException("Source vertex must not be null"); - } else if (target == null) { + } else if(target == null) { throw new NullPointerException("Target vertex must not be null"); } - if (!adjacency.containsKey(source)) { + if(!adjacency.containsKey(source)) { String msg = String.format("Source vertex %s isn't present in map", source); throw new IllegalArgumentException(msg); - } else if (!adjacency.containsKey(target)) { + } else if(!adjacency.containsKey(target)) { String msg = String.format("Target vertex %s isn't present in map", target); throw new IllegalArgumentException(msg); @@ -192,8 +190,7 @@ public class AdjacencyMap<T> { /** * Convert this to a different graph representation. * - * @return - * The new representation of this graph. + * @return The new representation of this graph. */ public Graph<T> toGraph() { final Graph<T> ret = new Graph<>(); @@ -211,10 +208,10 @@ public class AdjacencyMap<T> { * Convert an adjacency map back into a stream. * * @param sink - * The stream to convert to. + * The stream to convert to. */ public void toStream(final OutputStream sink) { - if (sink == null) throw new NullPointerException("Output source must not be null"); + if(sink == null) throw new NullPointerException("Output source must not be null"); final PrintStream outputPrinter = new PrintStream(sink); diff --git a/base/src/main/java/bjc/utils/graph/Edge.java b/base/src/main/java/bjc/utils/graph/Edge.java index 9236464..e7e7b36 100644 --- a/base/src/main/java/bjc/utils/graph/Edge.java +++ b/base/src/main/java/bjc/utils/graph/Edge.java @@ -6,10 +6,10 @@ package bjc.utils.graph; * @author ben * * @param <T> - * The type of the nodes in the graph. + * The type of the nodes in the graph. */ public class Edge<T> { - /* The distance from initial to terminal node. */ + /* The distance from initial to terminal node. */ private final int distance; /* The initial and terminal nodes of this edge. */ @@ -19,18 +19,18 @@ public class Edge<T> { * Create a new edge with set parameters. * * @param initial - * The initial node of the edge. + * The initial node of the edge. * * @param terminal - * The terminal node of the edge. + * The terminal node of the edge. * * @param distance - * The distance between initial and terminal edge. + * The distance between initial and terminal edge. */ public Edge(final T initial, final T terminal, final int distance) { - if (initial == null) { + if(initial == null) { throw new NullPointerException("Initial node must not be null"); - } else if (terminal == null) { + } else if(terminal == null) { throw new NullPointerException("Terminal node must not be null"); } @@ -41,24 +41,24 @@ public class Edge<T> { @Override public boolean equals(final Object obj) { - if (this == obj) + if(this == obj) return true; - else if (obj == null) + else if(obj == null) return false; - else if (getClass() != obj.getClass()) + else if(getClass() != obj.getClass()) return false; else { final Edge<?> other = (Edge<?>) obj; - if (distance != other.distance) + if(distance != other.distance) return false; - else if (source == null) { - if (other.source != null) return false; - } else if (!source.equals(other.source)) + else if(source == null) { + if(other.source != null) return false; + } else if(!source.equals(other.source)) return false; - else if (target == null) { - if (other.target != null) return false; - } else if (!target.equals(other.target)) return false; + else if(target == null) { + if(other.target != null) return false; + } else if(!target.equals(other.target)) return false; return true; } @@ -67,9 +67,8 @@ public class Edge<T> { /** * Get the distance in this edge. * - * @return - * The distance between the initial and terminal nodes of this - * edge. + * @return The distance between the initial and terminal nodes of this + * edge. */ public int getDistance() { return distance; @@ -78,8 +77,7 @@ public class Edge<T> { /** * Get the initial node of an edge. * - * @return - * The initial node of this edge. + * @return The initial node of this edge. */ public T getSource() { return source; @@ -88,8 +86,7 @@ public class Edge<T> { /** * Get the target node of an edge. * - * @return - * The target node of this edge. + * @return The target node of this edge. */ public T getTarget() { return target; @@ -110,8 +107,8 @@ public class Edge<T> { @Override public String toString() { - String msg = String.format("source vertex %s to target vertex %s with distance: %s", - source, target, distance); + String msg = String.format("source vertex %s to target vertex %s with distance: %s", source, target, + distance); return msg; } diff --git a/base/src/main/java/bjc/utils/graph/Graph.java b/base/src/main/java/bjc/utils/graph/Graph.java index d00dbae..83c2dc2 100644 --- a/base/src/main/java/bjc/utils/graph/Graph.java +++ b/base/src/main/java/bjc/utils/graph/Graph.java @@ -22,20 +22,19 @@ import bjc.utils.funcdata.IMap; * @author ben * * @param <T> - * The label for vertices. + * The label for vertices. */ public class Graph<T> { /** * Create a graph from a list of edges. * * @param <E> - * The type of data stored in the edges. + * The type of data stored in the edges. * * @param edges - * The list of edges to build from. + * The list of edges to build from. * - * @return - * A graph built from the provided edge-list. + * @return A graph built from the provided edge-list. */ public static <E> Graph<E> fromEdgeList(final List<Edge<E>> edges) { final Graph<E> g = new Graph<>(); @@ -59,27 +58,27 @@ public class Graph<T> { * Add a edge to the graph. * * @param source - * The source vertex for this edge. + * The source vertex for this edge. * * @param target - * The target vertex for this edge. + * The target vertex for this edge. * * @param distance - * The distance from the source vertex to the target vertex. + * The distance from the source vertex to the target vertex. * * @param directed - * Whether or not the edge is directed or not. + * Whether or not the edge is directed or not. */ public void addEdge(final T source, final T target, final int distance, final boolean directed) { /* Can't add edges with a null source or target. */ - if (source == null) { + if(source == null) { throw new NullPointerException("The source vertex cannot be null"); - } else if (target == null) { + } else if(target == null) { throw new NullPointerException("The target vertex cannot be null"); } /* Initialize adjacency list for vertices if necessary. */ - if (!backing.containsKey(source)) { + if(!backing.containsKey(source)) { backing.put(source, new FunctionalMap<T, Integer>()); } @@ -87,8 +86,8 @@ public class Graph<T> { backing.get(source).put(target, distance); /* Handle possible directed edges. */ - if (!directed) { - if (!backing.containsKey(target)) { + if(!directed) { + if(!backing.containsKey(target)) { backing.put(target, new FunctionalMap<T, Integer>()); } @@ -101,24 +100,24 @@ public class Graph<T> { * conditions. * * @param source - * The vertex to test edges for. + * The vertex to test edges for. * * @param matcher - * The conditions an edge must match. + * The conditions an edge must match. * * @param action - * The action to execute for matching edges. + * The action to execute for matching edges. */ public void forAllEdgesMatchingAt(final T source, final BiPredicate<T, Integer> matcher, final BiConsumer<T, Integer> action) { - if (matcher == null) { + if(matcher == null) { throw new NullPointerException("Matcher must not be null"); - } else if (action == null) { + } else if(action == null) { throw new NullPointerException("Action must not be null"); } getEdges(source).forEach((target, weight) -> { - if (matcher.test(target, weight)) { + if(matcher.test(target, weight)) { action.accept(target, weight); } }); @@ -128,15 +127,14 @@ public class Graph<T> { * Get all the edges that begin at a particular source vertex. * * @param source - * The vertex to use as a source. - * @return - * All of the edges with the specified vertex as a source. + * The vertex to use as a source. + * @return All of the edges with the specified vertex as a source. */ public IMap<T, Integer> getEdges(final T source) { /* Can't find edges for a null source. */ - if (source == null) + if(source == null) throw new NullPointerException("The source cannot be null."); - else if (!backing.containsKey(source)) + else if(!backing.containsKey(source)) throw new IllegalArgumentException("Vertex " + source + " is not in graph"); return backing.get(source); @@ -145,8 +143,7 @@ public class Graph<T> { /** * Get the initial vertex of the graph. * - * @return - * The initial vertex of the graph. + * @return The initial vertex of the graph. */ public T getInitial() { return backing.keyList().first(); @@ -158,8 +155,7 @@ public class Graph<T> { * If the graph is non-connected, this will lead to unpredictable * results. * - * @return - * A list of edges that constitute the MST. + * @return A list of edges that constitute the MST. */ public List<Edge<T>> getMinimumSpanningTree() { /* Set of all of the currently available edges. */ @@ -178,7 +174,7 @@ public class Graph<T> { visited.add(source.getValue()); /* Make sure we visit all the nodes. */ - while (visited.size() != getVertexCount()) { + while(visited.size() != getVertexCount()) { /* Grab all edges adjacent to the provided edge. */ forAllEdgesMatchingAt(source.getValue(), (target, weight) -> { @@ -194,9 +190,9 @@ public class Graph<T> { /* * Only consider edges where we haven't visited the - * target of the edge. + * target of the edge. */ - while (visited.contains(minimum.getValue().getTarget())) { + while(visited.contains(minimum.getValue().getTarget())) { minimum.transform((edge) -> available.poll()); } @@ -216,8 +212,7 @@ public class Graph<T> { /** * Get the count of the vertices in this graph. * - * @return - * A count of the vertices in this graph. + * @return A count of the vertices in this graph. */ public int getVertexCount() { return backing.size(); @@ -226,8 +221,7 @@ public class Graph<T> { /** * Get all of the vertices in this graph. * - * @return - * A unmodifiable set of all the vertices in the graph. + * @return A unmodifiable set of all the vertices in the graph. */ public IList<T> getVertices() { return backing.keyList(); @@ -237,27 +231,27 @@ public class Graph<T> { * Remove the edge starting at the source and ending at the target. * * @param source - * The source vertex for the edge. + * The source vertex for the edge. * * @param target - * The target vertex for the edge. + * The target vertex for the edge. */ public void removeEdge(final T source, final T target) { /* Can't remove things w/ null vertices. */ - if (source == null) { + if(source == null) { throw new NullPointerException("The source vertex cannot be null"); - } else if (target == null) { + } else if(target == null) { throw new NullPointerException("The target vertex cannot be null"); } /* Can't remove if one vertice doesn't exists. */ - if (!backing.containsKey(source)) { + if(!backing.containsKey(source)) { String msg = String.format("vertex %s does not exist", source); throw new NoSuchElementException(msg); } - if (!backing.containsKey(target)) { + if(!backing.containsKey(target)) { String msg = String.format("vertex %s does not exist", target); throw new NoSuchElementException(msg); @@ -265,7 +259,8 @@ public class Graph<T> { backing.get(source).remove(target); - /* Uncomment this to turn the graph undirected + /* + * Uncomment this to turn the graph undirected * * graph.get(target).remove(source); */ @@ -274,8 +269,7 @@ public class Graph<T> { /** * Convert a graph into a adjacency map/matrix. * - * @return - * A adjacency map representing this graph. + * @return A adjacency map representing this graph. */ public AdjacencyMap<T> toAdjacencyMap() { final AdjacencyMap<T> adjacency = new AdjacencyMap<>(backing.keyList()); diff --git a/base/src/main/java/bjc/utils/gui/ExtensionFileFilter.java b/base/src/main/java/bjc/utils/gui/ExtensionFileFilter.java index 7c487eb..6696c92 100644 --- a/base/src/main/java/bjc/utils/gui/ExtensionFileFilter.java +++ b/base/src/main/java/bjc/utils/gui/ExtensionFileFilter.java @@ -26,7 +26,7 @@ public class ExtensionFileFilter extends FileFilter { * Create a new filter only showing files with the specified extensions. * * @param exts - * The extensions to show in this filter. + * The extensions to show in this filter. */ public ExtensionFileFilter(final List<String> exts) { extensions = new FunctionalList<>(exts); @@ -36,7 +36,7 @@ public class ExtensionFileFilter extends FileFilter { * Create a new filter only showing files with the specified extensions. * * @param exts - * The extensions to show in this filter. + * The extensions to show in this filter. */ public ExtensionFileFilter(final String... exts) { extensions = new FunctionalList<>(exts); @@ -44,7 +44,7 @@ public class ExtensionFileFilter extends FileFilter { @Override public boolean accept(final File pathname) { - if (pathname == null) throw new NullPointerException("Pathname must not be null"); + if(pathname == null) throw new NullPointerException("Pathname must not be null"); return extensions.anyMatch(pathname.getName()::endsWith); } diff --git a/base/src/main/java/bjc/utils/gui/SimpleDialogs.java b/base/src/main/java/bjc/utils/gui/SimpleDialogs.java index 59eb1c3..b7763a2 100644 --- a/base/src/main/java/bjc/utils/gui/SimpleDialogs.java +++ b/base/src/main/java/bjc/utils/gui/SimpleDialogs.java @@ -25,15 +25,15 @@ public class SimpleDialogs { * Get a bounded integer from the user. * * @param parent - * The parent component for the dialogs. + * The parent component for the dialogs. * @param title - * The title for the dialogs. + * The title for the dialogs. * @param prompt - * The prompt to tell the user what to enter. + * The prompt to tell the user what to enter. * @param lowerBound - * The lower integer bound to accept. + * The lower integer bound to accept. * @param upperBound - * The upper integer bound to accept. + * The upper integer bound to accept. * @return A int within the specified bounds. */ public static int getBoundedInt(final Component parent, final String title, final String prompt, @@ -43,7 +43,7 @@ public class SimpleDialogs { final int value = Integer.parseInt(strang); return value < upperBound && value > lowerBound; - } catch (final NumberFormatException nfex) { + } catch(final NumberFormatException nfex) { // We don't care about the specifics of the // exception, just // that this value isn't good @@ -56,26 +56,26 @@ public class SimpleDialogs { * Asks the user to pick an option from a series of choices. * * @param <E> - * The type of choices for the user to pick + * The type of choices for the user to pick * * @param parent - * The parent frame for this dialog + * The parent frame for this dialog * @param title - * The title of this dialog + * The title of this dialog * @param question - * The question being asked + * The question being asked * @param choices - * The available choices for the question + * The available choices for the question * @return The choice the user picked, or null if they didn't pick one */ @SuppressWarnings("unchecked") public static <E> E getChoice(final Frame parent, final String title, final String question, final E... choices) { - if (parent == null) + if(parent == null) throw new NullPointerException("Parent must not be null"); - else if (title == null) + else if(title == null) throw new NullPointerException("Title must not be null"); - else if (question == null) throw new NullPointerException("Question must not be null"); + else if(question == null) throw new NullPointerException("Question must not be null"); final JDialog chooser = new JDialog(parent, title, true); chooser.setLayout(new VLayout(2)); @@ -112,11 +112,11 @@ public class SimpleDialogs { * Get a integer from the user * * @param parent - * The parent component for dialogs. + * The parent component for dialogs. * @param title - * The title for dialogs. + * The title for dialogs. * @param prompt - * The prompt to tell the user what to enter. + * The prompt to tell the user what to enter. * @return A int. */ public static int getInt(final Component parent, final String title, final String prompt) { @@ -124,7 +124,7 @@ public class SimpleDialogs { try { Integer.parseInt(strang); return true; - } catch (final NumberFormatException nfex) { + } catch(final NumberFormatException nfex) { // We don't care about this exception, just mark // the value // as not good @@ -137,19 +137,19 @@ public class SimpleDialogs { * Get a string from the user * * @param parent - * The parent component for dialogs. + * The parent component for dialogs. * @param title - * The title for the dialogs. + * The title for the dialogs. * @param prompt - * The prompt to tell the user what to enter. + * The prompt to tell the user what to enter. * @return A string. */ public static String getString(final Component parent, final String title, final String prompt) { - if (parent == null) + if(parent == null) throw new NullPointerException("Parent must not be null"); - else if (title == null) + else if(title == null) throw new NullPointerException("Title must not be null"); - else if (prompt == null) throw new NullPointerException("Prompt must not be null"); + else if(prompt == null) throw new NullPointerException("Prompt must not be null"); return JOptionPane.showInputDialog(parent, prompt, title, JOptionPane.QUESTION_MESSAGE); } @@ -158,29 +158,29 @@ public class SimpleDialogs { * Get a value parsable from a string from the user. * * @param <E> - * The type of the value parsed from the string + * The type of the value parsed from the string * * @param parent - * The parent component for dialogs. + * The parent component for dialogs. * @param title - * The title for dialogs. + * The title for dialogs. * @param prompt - * The prompt to tell the user what to enter. + * The prompt to tell the user what to enter. * @param validator - * A predicate to determine if a input is valid. + * A predicate to determine if a input is valid. * @param transformer - * The function to transform the string into a value. + * The function to transform the string into a value. * @return The value parsed from a string. */ public static <E> E getValue(final Component parent, final String title, final String prompt, final Predicate<String> validator, final Function<String, E> transformer) { - if (validator == null) + if(validator == null) throw new NullPointerException("Validator must not be null"); - else if (transformer == null) throw new NullPointerException("Transformer must not be null"); + else if(transformer == null) throw new NullPointerException("Transformer must not be null"); String input = getString(parent, title, prompt); - while (!validator.test(input)) { + while(!validator.test(input)) { showError(parent, "I/O Error", "Please enter a valid value"); input = getString(parent, title, prompt); @@ -193,11 +193,11 @@ public class SimpleDialogs { * Get a whole number from the user. * * @param parent - * The parent component for dialogs. + * The parent component for dialogs. * @param title - * The title for dialogs. + * The title for dialogs. * @param prompt - * The prompt to tell the user what to enter. + * The prompt to tell the user what to enter. * @return A whole number. */ public static int getWhole(final Component parent, final String title, final String prompt) { @@ -208,19 +208,19 @@ public class SimpleDialogs { * Ask the user a Yes/No question. * * @param parent - * The parent component for dialogs. + * The parent component for dialogs. * @param title - * The title for dialogs. + * The title for dialogs. * @param question - * The question to ask the user. + * The question to ask the user. * @return True if the user said yes, false otherwise. */ public static boolean getYesNo(final Component parent, final String title, final String question) { - if (parent == null) + if(parent == null) throw new NullPointerException("Parent must not be null"); - else if (title == null) + else if(title == null) throw new NullPointerException("Title must not be null"); - else if (question == null) throw new NullPointerException("Question must not be null"); + else if(question == null) throw new NullPointerException("Question must not be null"); final int result = JOptionPane.showConfirmDialog(parent, question, title, JOptionPane.YES_NO_OPTION); @@ -231,18 +231,18 @@ public class SimpleDialogs { * Show a error message to the user * * @param parent - * The parent component for dialogs. + * The parent component for dialogs. * @param title - * The title for dialogs. + * The title for dialogs. * @param message - * The error to show the user. + * The error to show the user. */ public static void showError(final Component parent, final String title, final String message) { - if (parent == null) + if(parent == null) throw new NullPointerException("Parent must not be null"); - else if (title == null) + else if(title == null) throw new NullPointerException("Title must not be null"); - else if (message == null) throw new NullPointerException("Error message must not be null"); + else if(message == null) throw new NullPointerException("Error message must not be null"); JOptionPane.showMessageDialog(parent, message, title, JOptionPane.ERROR_MESSAGE); } @@ -251,18 +251,18 @@ public class SimpleDialogs { * Show an informative message to the user * * @param parent - * The parent for this dialog + * The parent for this dialog * @param title - * Show the title for this dialog + * Show the title for this dialog * @param message - * Show the message for this dialog + * Show the message for this dialog */ public static void showMessage(final Component parent, final String title, final String message) { - if (parent == null) + if(parent == null) throw new NullPointerException("Parent must not be null"); - else if (title == null) + else if(title == null) throw new NullPointerException("Title must not be null"); - else if (message == null) throw new NullPointerException("Message must not be null"); + else if(message == null) throw new NullPointerException("Message must not be null"); JOptionPane.showMessageDialog(parent, title, message, JOptionPane.INFORMATION_MESSAGE); } diff --git a/base/src/main/java/bjc/utils/gui/SimpleFileChooser.java b/base/src/main/java/bjc/utils/gui/SimpleFileChooser.java index 7da0bd8..2bdd792 100644 --- a/base/src/main/java/bjc/utils/gui/SimpleFileChooser.java +++ b/base/src/main/java/bjc/utils/gui/SimpleFileChooser.java @@ -17,18 +17,18 @@ import bjc.utils.exceptions.FileNotChosenException; */ public class SimpleFileChooser { private static File doOpenFile(final Component parent, final String title, final JFileChooser files) { - if (title == null) throw new NullPointerException("Title must not be null"); + if(title == null) throw new NullPointerException("Title must not be null"); files.setDialogTitle(title); boolean success = false; - while (!success) { + while(!success) { try { maybeDoOpenFile(parent, files); success = true; - } catch (final FileNotChosenException fncx) { + } catch(final FileNotChosenException fncx) { // We don't care about specifics SimpleDialogs.showError(parent, "I/O Error", "Please pick a file to open"); } @@ -38,18 +38,18 @@ public class SimpleFileChooser { } private static File doSaveFile(final Component parent, final String title, final JFileChooser files) { - if (title == null) throw new NullPointerException("Title must not be null"); + if(title == null) throw new NullPointerException("Title must not be null"); files.setDialogTitle(title); final boolean success = false; - while (!success) { + while(!success) { try { maybeDoSaveFile(parent, files); return files.getSelectedFile(); - } catch (final FileNotChosenException fncex) { + } catch(final FileNotChosenException fncex) { // We don't care about specifics SimpleDialogs.showError(parent, "I/O Error", "Please pick a file to save to"); } @@ -61,9 +61,9 @@ public class SimpleFileChooser { * until they pick a file. * * @param parent - * The component to use as the parent for the dialog. + * The component to use as the parent for the dialog. * @param title - * The title of the dialog to prompt with. + * The title of the dialog to prompt with. * @return The file the user has chosen. */ public static File getOpenFile(final Component parent, final String title) { @@ -77,11 +77,11 @@ public class SimpleFileChooser { * until they pick a file. * * @param parent - * The component to use as the parent for the dialog. + * The component to use as the parent for the dialog. * @param title - * The title of the dialog to prompt with. + * The title of the dialog to prompt with. * @param extensions - * The list of file extensions the file should have. + * The list of file extensions the file should have. * @return The file the user has chosen. */ public static File getOpenFile(final Component parent, final String title, final String... extensions) { @@ -96,9 +96,9 @@ public class SimpleFileChooser { * Prompt the user with a "Save File..." dialog. * * @param parent - * The component to use as the parent for the dialog. + * The component to use as the parent for the dialog. * @param title - * The title of the dialog to prompt with. + * The title of the dialog to prompt with. * @return The file the user chose. */ public static File getSaveFile(final Component parent, final String title) { @@ -111,11 +111,11 @@ public class SimpleFileChooser { * Prompt the user with a "Save File..." dialog. * * @param parent - * The component to use as the parent for the dialog. + * The component to use as the parent for the dialog. * @param title - * The title of the dialog to prompt with. + * The title of the dialog to prompt with. * @param extensions - * The extensions of the files the user can choose. + * The extensions of the files the user can choose. * @return The file the user chose. */ public static File getSaveFile(final Component parent, final String title, final String... extensions) { @@ -128,44 +128,44 @@ public class SimpleFileChooser { private static void maybeDoOpenFile(final Component parent, final JFileChooser files) throws FileNotChosenException { - if (parent == null) + if(parent == null) throw new NullPointerException("Parent must not be null"); - else if (files == null) throw new NullPointerException("File chooser must not be null"); + else if(files == null) throw new NullPointerException("File chooser must not be null"); final int result = files.showSaveDialog(parent); - if (result != JFileChooser.APPROVE_OPTION) throw new FileNotChosenException(); + if(result != JFileChooser.APPROVE_OPTION) throw new FileNotChosenException(); } private static void maybeDoSaveFile(final Component parent, final JFileChooser files) throws FileNotChosenException { - if (parent == null) + if(parent == null) throw new NullPointerException("Parent must not be null"); - else if (files == null) throw new NullPointerException("File chooser must not be null"); + else if(files == null) throw new NullPointerException("File chooser must not be null"); final int result = files.showSaveDialog(parent); - if (result != JFileChooser.APPROVE_OPTION) throw new FileNotChosenException(); + if(result != JFileChooser.APPROVE_OPTION) throw new FileNotChosenException(); } /** * Prompt the user with a "Open File..." dialog. * * @param parent - * The component to use as the parent for the dialog. + * The component to use as the parent for the dialog. * @param title - * The title of the dialog to prompt with. + * The title of the dialog to prompt with. * @return The file if the user chose one or null if they didn't. */ public static File maybeOpenFile(final Component parent, final String title) { - if (title == null) throw new NullPointerException("Title must not be null"); + if(title == null) throw new NullPointerException("Title must not be null"); final JFileChooser files = new JFileChooser(); files.setDialogTitle(title); try { maybeDoOpenFile(parent, files); - } catch (final FileNotChosenException fncex) { + } catch(final FileNotChosenException fncex) { // We don't care about specifics } @@ -176,20 +176,20 @@ public class SimpleFileChooser { * Prompt the user with a "Save File..." dialog. * * @param parent - * The component to use as the parent for the dialog. + * The component to use as the parent for the dialog. * @param title - * The title of the dialog to prompt with. + * The title of the dialog to prompt with. * @return The file if the user chose one or null if they didn't. */ public static File maybeSaveFile(final Component parent, final String title) { - if (title == null) throw new NullPointerException("Title must not be null"); + if(title == null) throw new NullPointerException("Title must not be null"); final JFileChooser files = new JFileChooser(); files.setDialogTitle(title); try { maybeDoSaveFile(parent, files); - } catch (final FileNotChosenException fncex) { + } catch(final FileNotChosenException fncex) { // We don't care about specifics } diff --git a/base/src/main/java/bjc/utils/gui/SimpleInternalDialogs.java b/base/src/main/java/bjc/utils/gui/SimpleInternalDialogs.java index 5237557..ef56011 100644 --- a/base/src/main/java/bjc/utils/gui/SimpleInternalDialogs.java +++ b/base/src/main/java/bjc/utils/gui/SimpleInternalDialogs.java @@ -19,15 +19,15 @@ public class SimpleInternalDialogs { * Get a bounded integer from the user. * * @param parent - * The parent component for the dialogs. + * The parent component for the dialogs. * @param title - * The title for the dialogs. + * The title for the dialogs. * @param prompt - * The prompt to tell the user what to enter. + * The prompt to tell the user what to enter. * @param lowerBound - * The lower integer bound to accept. + * The lower integer bound to accept. * @param upperBound - * The upper integer bound to accept. + * The upper integer bound to accept. * @return A int within the specified bounds. */ public static int getBoundedInt(final Component parent, final String title, final String prompt, @@ -37,7 +37,7 @@ public class SimpleInternalDialogs { final int value = Integer.parseInt(strang); return value < upperBound && value > lowerBound; - } catch (final NumberFormatException nfex) { + } catch(final NumberFormatException nfex) { // We don't care about the specifics of the // exception, just // that this value isn't good @@ -50,11 +50,11 @@ public class SimpleInternalDialogs { * Get a integer from the user * * @param parent - * The parent component for dialogs. + * The parent component for dialogs. * @param title - * The title for dialogs. + * The title for dialogs. * @param prompt - * The prompt to tell the user what to enter. + * The prompt to tell the user what to enter. * @return A int. */ public static int getInt(final Component parent, final String title, final String prompt) { @@ -62,7 +62,7 @@ public class SimpleInternalDialogs { try { Integer.parseInt(strang); return true; - } catch (final NumberFormatException nfex) { + } catch(final NumberFormatException nfex) { // We don't care about this exception, just mark // the value // as not good @@ -75,19 +75,19 @@ public class SimpleInternalDialogs { * Get a string from the user * * @param parent - * The parent component for dialogs. + * The parent component for dialogs. * @param title - * The title for the dialogs. + * The title for the dialogs. * @param prompt - * The prompt to tell the user what to enter. + * The prompt to tell the user what to enter. * @return A string. */ public static String getString(final Component parent, final String title, final String prompt) { - if (parent == null) + if(parent == null) throw new NullPointerException("Parent must not be null"); - else if (title == null) + else if(title == null) throw new NullPointerException("Title must not be null"); - else if (prompt == null) throw new NullPointerException("Prompt must not be null"); + else if(prompt == null) throw new NullPointerException("Prompt must not be null"); return JOptionPane.showInternalInputDialog(parent, prompt, title, JOptionPane.QUESTION_MESSAGE); } @@ -96,29 +96,29 @@ public class SimpleInternalDialogs { * Get a value parsable from a string from the user. * * @param <E> - * The type of the value parsed from the string + * The type of the value parsed from the string * * @param parent - * The parent component for dialogs. + * The parent component for dialogs. * @param title - * The title for dialogs. + * The title for dialogs. * @param prompt - * The prompt to tell the user what to enter. + * The prompt to tell the user what to enter. * @param validator - * A predicate to determine if a input is valid. + * A predicate to determine if a input is valid. * @param transformer - * The function to transform the string into a value. + * The function to transform the string into a value. * @return The value parsed from a string. */ public static <E> E getValue(final Component parent, final String title, final String prompt, final Predicate<String> validator, final Function<String, E> transformer) { - if (validator == null) + if(validator == null) throw new NullPointerException("Validator must not be null"); - else if (transformer == null) throw new NullPointerException("Transformer must not be null"); + else if(transformer == null) throw new NullPointerException("Transformer must not be null"); String strang = getString(parent, title, prompt); - while (!validator.test(strang)) { + while(!validator.test(strang)) { showError(parent, "I/O Error", "Please enter a valid value"); strang = getString(parent, title, prompt); @@ -131,11 +131,11 @@ public class SimpleInternalDialogs { * Get a whole number from the user. * * @param parent - * The parent component for dialogs. + * The parent component for dialogs. * @param title - * The title for dialogs. + * The title for dialogs. * @param prompt - * The prompt to tell the user what to enter. + * The prompt to tell the user what to enter. * @return A whole number. */ public static int getWhole(final Component parent, final String title, final String prompt) { @@ -146,19 +146,19 @@ public class SimpleInternalDialogs { * Ask the user a Yes/No question. * * @param parent - * The parent component for dialogs. + * The parent component for dialogs. * @param title - * The title for dialogs. + * The title for dialogs. * @param question - * The question to ask the user. + * The question to ask the user. * @return True if the user said yes, false otherwise. */ public static boolean getYesNo(final Component parent, final String title, final String question) { - if (parent == null) + if(parent == null) throw new NullPointerException("Parent must not be null"); - else if (title == null) + else if(title == null) throw new NullPointerException("Title must not be null"); - else if (question == null) throw new NullPointerException("Question must not be null"); + else if(question == null) throw new NullPointerException("Question must not be null"); final int result = JOptionPane.showInternalConfirmDialog(parent, question, title, JOptionPane.YES_NO_OPTION); @@ -170,18 +170,18 @@ public class SimpleInternalDialogs { * Show a error message to the user * * @param parent - * The parent component for dialogs. + * The parent component for dialogs. * @param title - * The title for dialogs. + * The title for dialogs. * @param message - * The error to show the user. + * The error to show the user. */ public static void showError(final Component parent, final String title, final String message) { - if (parent == null) + if(parent == null) throw new NullPointerException("Parent must not be null"); - else if (title == null) + else if(title == null) throw new NullPointerException("Title must not be null"); - else if (message == null) throw new NullPointerException("Error message must not be null"); + else if(message == null) throw new NullPointerException("Error message must not be null"); JOptionPane.showInternalMessageDialog(parent, message, title, JOptionPane.ERROR_MESSAGE); } @@ -190,18 +190,18 @@ public class SimpleInternalDialogs { * Show an informative message to the user * * @param parent - * The parent for this dialog + * The parent for this dialog * @param title - * Show the title for this dialog + * Show the title for this dialog * @param message - * Show the message for this dialog + * Show the message for this dialog */ public static void showMessage(final Component parent, final String title, final String message) { - if (parent == null) + if(parent == null) throw new NullPointerException("Parent must not be null"); - else if (title == null) + else if(title == null) throw new NullPointerException("Title must not be null"); - else if (message == null) throw new NullPointerException("Message must not be null"); + else if(message == null) throw new NullPointerException("Message must not be null"); JOptionPane.showInternalMessageDialog(parent, title, message, JOptionPane.INFORMATION_MESSAGE); } diff --git a/base/src/main/java/bjc/utils/gui/SimpleInternalFrame.java b/base/src/main/java/bjc/utils/gui/SimpleInternalFrame.java index afb498e..5c7983c 100644 --- a/base/src/main/java/bjc/utils/gui/SimpleInternalFrame.java +++ b/base/src/main/java/bjc/utils/gui/SimpleInternalFrame.java @@ -22,7 +22,7 @@ public class SimpleInternalFrame extends JInternalFrame { * Create a new blank internal frame with a specific title * * @param title - * The title of the internal frame + * The title of the internal frame */ public SimpleInternalFrame(final String title) { super(title); diff --git a/base/src/main/java/bjc/utils/gui/SimpleJList.java b/base/src/main/java/bjc/utils/gui/SimpleJList.java index 411d0db..31c995c 100644 --- a/base/src/main/java/bjc/utils/gui/SimpleJList.java +++ b/base/src/main/java/bjc/utils/gui/SimpleJList.java @@ -15,14 +15,14 @@ public class SimpleJList { * Create a new JList from a given list. * * @param <E> - * The type of data in the JList + * The type of data in the JList * * @param source - * The list to populate the JList with. + * The list to populate the JList with. * @return A JList populated with the elements from ls. */ public static <E> JList<E> buildFromList(final Iterable<E> source) { - if (source == null) throw new NullPointerException("Source must not be null"); + if(source == null) throw new NullPointerException("Source must not be null"); return new JList<>(buildModel(source)); } @@ -31,14 +31,14 @@ public class SimpleJList { * Create a new list model from a given list. * * @param <E> - * The type of data in the list model + * The type of data in the list model * * @param source - * The list to fill the list model from. + * The list to fill the list model from. * @return A list model populated with the elements from ls. */ public static <E> ListModel<E> buildModel(final Iterable<E> source) { - if (source == null) throw new NullPointerException("Source must not be null"); + if(source == null) throw new NullPointerException("Source must not be null"); final DefaultListModel<E> defaultModel = new DefaultListModel<>(); diff --git a/base/src/main/java/bjc/utils/gui/SimpleTitledBorder.java b/base/src/main/java/bjc/utils/gui/SimpleTitledBorder.java index 9b01507..bddb564 100644 --- a/base/src/main/java/bjc/utils/gui/SimpleTitledBorder.java +++ b/base/src/main/java/bjc/utils/gui/SimpleTitledBorder.java @@ -17,7 +17,7 @@ public class SimpleTitledBorder extends TitledBorder { * Create a new border with the specified title. * * @param title - * The title for the border. + * The title for the border. */ public SimpleTitledBorder(final String title) { super(new EtchedBorder(), title); diff --git a/base/src/main/java/bjc/utils/gui/TextAreaOutputStream.java b/base/src/main/java/bjc/utils/gui/TextAreaOutputStream.java index fbc58ed..0beb1e2 100644 --- a/base/src/main/java/bjc/utils/gui/TextAreaOutputStream.java +++ b/base/src/main/java/bjc/utils/gui/TextAreaOutputStream.java @@ -18,7 +18,7 @@ public class TextAreaOutputStream extends OutputStream { * Create a new output stream attached to a textarea * * @param console - * The textarea to write to + * The textarea to write to */ public TextAreaOutputStream(final JTextArea console) { this.textArea = console; @@ -28,7 +28,7 @@ public class TextAreaOutputStream extends OutputStream { public void write(final int b) throws IOException { textArea.append("" + (char) b); - if (b == '\n') { + if(b == '\n') { textArea.repaint(); } } diff --git a/base/src/main/java/bjc/utils/gui/awt/ExtensionFileFilter.java b/base/src/main/java/bjc/utils/gui/awt/ExtensionFileFilter.java index 5998345..ae424b4 100644 --- a/base/src/main/java/bjc/utils/gui/awt/ExtensionFileFilter.java +++ b/base/src/main/java/bjc/utils/gui/awt/ExtensionFileFilter.java @@ -22,10 +22,10 @@ public class ExtensionFileFilter implements FilenameFilter { * Create a new filter only showing files with the specified extensions. * * @param exts - * The extensions to show in this filter. + * The extensions to show in this filter. */ public ExtensionFileFilter(final List<String> exts) { - if (exts == null) throw new NullPointerException("Extensions must not be null"); + if(exts == null) throw new NullPointerException("Extensions must not be null"); extensions = new FunctionalList<>(exts); } @@ -34,7 +34,7 @@ public class ExtensionFileFilter implements FilenameFilter { * Create a new filter only showing files with the specified extensions. * * @param exts - * The extensions to show in this filter. + * The extensions to show in this filter. */ public ExtensionFileFilter(final String... exts) { extensions = new FunctionalList<>(exts); diff --git a/base/src/main/java/bjc/utils/gui/awt/SimpleFileDialog.java b/base/src/main/java/bjc/utils/gui/awt/SimpleFileDialog.java index e9236fe..daea7cd 100644 --- a/base/src/main/java/bjc/utils/gui/awt/SimpleFileDialog.java +++ b/base/src/main/java/bjc/utils/gui/awt/SimpleFileDialog.java @@ -19,13 +19,12 @@ public class SimpleFileDialog { * Prompt the user to pick a file to open. * * @param parent - * The parent of the file picker. + * The parent of the file picker. * * @param title - * The title of the file picker. + * The title of the file picker. * - * @return - * The file the user picked. + * @return The file the user picked. */ public static File getOpenFile(final Frame parent, final String title) { return getOpenFile(parent, title, (String[]) null); @@ -35,34 +34,33 @@ public class SimpleFileDialog { * Prompt the user to pick a file to open. * * @param parent - * The parent of the file picker. + * The parent of the file picker. * * @param title - * The title of the file picker. + * The title of the file picker. * * @param extensions - * The extensions to accept as valid. + * The extensions to accept as valid. * - * @return - * The file the user picked. + * @return The file the user picked. */ public static File getOpenFile(final Frame parent, final String title, final String... extensions) { - if (parent == null) { + if(parent == null) { throw new NullPointerException("Parent must not be null"); - } else if (title == null) { + } else if(title == null) { throw new NullPointerException("Title must not be null"); } final FileDialog chooser = new FileDialog(parent, title, FileDialog.LOAD); - if (extensions != null) { + if(extensions != null) { final FilenameFilter filter = new ExtensionFileFilter(extensions); chooser.setFilenameFilter(filter); } chooser.setVisible(true); - while (chooser.getFile() == null) { + while(chooser.getFile() == null) { SimpleDialogs.showError(parent, "File I/O Error", "Please choose a file to open."); chooser.setVisible(true); } @@ -74,26 +72,24 @@ public class SimpleFileDialog { * Prompt the user to pick a file to open. * * @param parent - * The parent of the file picker. + * The parent of the file picker. * * @param title - * The title of the file picker. + * The title of the file picker. * * @param extensions - * The extensions to accept as valid. + * The extensions to accept as valid. * - * @return - * The file the user picked. + * @return The file the user picked. */ public static File[] getOpenFiles(final Frame parent, final String title, final String... extensions) { - if (parent == null) + if(parent == null) throw new NullPointerException("Parent must not be null"); - else if (title == null) - throw new NullPointerException("Title must not be null"); + else if(title == null) throw new NullPointerException("Title must not be null"); final FileDialog chooser = new FileDialog(parent, title, FileDialog.LOAD); - if (extensions != null) { + if(extensions != null) { final FilenameFilter filter = new ExtensionFileFilter(extensions); chooser.setFilenameFilter(filter); } @@ -101,7 +97,7 @@ public class SimpleFileDialog { chooser.setMultipleMode(true); chooser.setVisible(true); - while (chooser.getFile() == null) { + while(chooser.getFile() == null) { SimpleDialogs.showError(parent, "File I/O Error", "Please choose a file to open."); chooser.setVisible(true); } @@ -113,13 +109,12 @@ public class SimpleFileDialog { * Prompt the user to pick a file to save * * @param parent - * The parent of the file picker + * The parent of the file picker * * @param title - * The title of the file picker + * The title of the file picker * - * @return - * The file the user picked + * @return The file the user picked */ public static File getSaveFile(final Frame parent, final String title) { return getSaveFile(parent, title, (String[]) null); @@ -129,33 +124,31 @@ public class SimpleFileDialog { * Prompt the user to pick a file to save * * @param parent - * The parent of the file picker + * The parent of the file picker * * @param title - * The title of the file picker + * The title of the file picker * * @param extensions - * The extensions to accept as valid + * The extensions to accept as valid * - * @return - * The file the user picked + * @return The file the user picked */ public static File getSaveFile(final Frame parent, final String title, final String... extensions) { - if (parent == null) + if(parent == null) throw new NullPointerException("Parent must not be null"); - else if (title == null) - throw new NullPointerException("Title must not be null"); + else if(title == null) throw new NullPointerException("Title must not be null"); final FileDialog chooser = new FileDialog(parent, title, FileDialog.SAVE); - if (extensions != null) { + if(extensions != null) { final FilenameFilter filter = new ExtensionFileFilter(extensions); chooser.setFilenameFilter(filter); } chooser.setVisible(true); - while (chooser.getFile() == null) { + while(chooser.getFile() == null) { SimpleDialogs.showError(parent, "File I/O Error", "Please choose a file to save to."); chooser.setVisible(true); } diff --git a/base/src/main/java/bjc/utils/gui/layout/HLayout.java b/base/src/main/java/bjc/utils/gui/layout/HLayout.java index 6e4f878..c2caa01 100644 --- a/base/src/main/java/bjc/utils/gui/layout/HLayout.java +++ b/base/src/main/java/bjc/utils/gui/layout/HLayout.java @@ -16,7 +16,7 @@ public class HLayout extends GridLayout { * Create a new horizontal layout with the specified number of columns. * * @param columns - * The number of columns in this layout. + * The number of columns in this layout. */ public HLayout(final int columns) { super(1, columns); diff --git a/base/src/main/java/bjc/utils/gui/layout/VLayout.java b/base/src/main/java/bjc/utils/gui/layout/VLayout.java index 6993365..d0f0503 100644 --- a/base/src/main/java/bjc/utils/gui/layout/VLayout.java +++ b/base/src/main/java/bjc/utils/gui/layout/VLayout.java @@ -17,7 +17,7 @@ public class VLayout extends GridLayout { * Create a new vertical layout with the specified number of rows. * * @param rows - * The number of rows. + * The number of rows. */ public VLayout(final int rows) { super(rows, 1); diff --git a/base/src/main/java/bjc/utils/gui/panels/DropdownListPanel.java b/base/src/main/java/bjc/utils/gui/panels/DropdownListPanel.java index 4f71d38..6c57c5a 100644 --- a/base/src/main/java/bjc/utils/gui/panels/DropdownListPanel.java +++ b/base/src/main/java/bjc/utils/gui/panels/DropdownListPanel.java @@ -26,13 +26,13 @@ public class DropdownListPanel extends JPanel { * Create a new dropdown list panel * * @param <T> - * The type of items in the dropdown list + * The type of items in the dropdown list * @param type - * The label of the type of items in the list + * The label of the type of items in the list * @param model - * The model to put items into + * The model to put items into * @param choices - * The items to choose from + * The items to choose from */ public <T> DropdownListPanel(final String type, final DefaultListModel<T> model, final IList<T> choices) { setLayout(new AutosizeLayout()); diff --git a/base/src/main/java/bjc/utils/gui/panels/FormattedInputPanel.java b/base/src/main/java/bjc/utils/gui/panels/FormattedInputPanel.java index 2cecf0c..96f0487 100644 --- a/base/src/main/java/bjc/utils/gui/panels/FormattedInputPanel.java +++ b/base/src/main/java/bjc/utils/gui/panels/FormattedInputPanel.java @@ -15,7 +15,7 @@ import bjc.utils.gui.layout.HLayout; * @author ben * * @param <InputVal> - * The type of value being formatted + * The type of value being formatted */ public class FormattedInputPanel<InputVal> extends JPanel { private static final long serialVersionUID = 5232016563558588031L; @@ -26,13 +26,13 @@ public class FormattedInputPanel<InputVal> extends JPanel { * Create a new formatted input panel * * @param label - * The label for this panel + * The label for this panel * @param length - * The length of this panel + * The length of this panel * @param formatter - * The formatter to use for input + * The formatter to use for input * @param reciever - * The action to call whenever the value changes + * The action to call whenever the value changes */ @SuppressWarnings("unchecked") public FormattedInputPanel(final String label, final int length, final AbstractFormatter formatter, @@ -58,7 +58,7 @@ public class FormattedInputPanel<InputVal> extends JPanel { * Reset the value in this panel to a specified value * * @param value - * The value to set the panel to + * The value to set the panel to */ public void resetValues(final InputVal value) { field.setValue(value); diff --git a/base/src/main/java/bjc/utils/gui/panels/HolderOutputPanel.java b/base/src/main/java/bjc/utils/gui/panels/HolderOutputPanel.java index 653dace..1cf3d88 100644 --- a/base/src/main/java/bjc/utils/gui/panels/HolderOutputPanel.java +++ b/base/src/main/java/bjc/utils/gui/panels/HolderOutputPanel.java @@ -25,11 +25,11 @@ public class HolderOutputPanel extends JPanel { * Create a new display panel, backed by a holder * * @param lab - * The label to attach to this field + * The label to attach to this field * @param valueHolder - * The holder to get the value from + * The holder to get the value from * @param nDelay - * The delay in ms between value updates + * The delay in ms between value updates */ public HolderOutputPanel(final String lab, final IHolder<String> valueHolder, final int nDelay) { this.val = valueHolder; diff --git a/base/src/main/java/bjc/utils/gui/panels/ListParameterPanel.java b/base/src/main/java/bjc/utils/gui/panels/ListParameterPanel.java index cca73d5..f8d9b72 100644 --- a/base/src/main/java/bjc/utils/gui/panels/ListParameterPanel.java +++ b/base/src/main/java/bjc/utils/gui/panels/ListParameterPanel.java @@ -20,7 +20,7 @@ import bjc.utils.gui.layout.VLayout; * @author ben * * @param <E> - * The type of data stored in the list + * The type of data stored in the list */ public class ListParameterPanel<E> extends JPanel { // Version id for serialization @@ -30,11 +30,11 @@ public class ListParameterPanel<E> extends JPanel { * Create a new panel using the specified actions for doing things * * @param add - * The action that provides items + * The action that provides items * @param edit - * The action that edits items + * The action that edits items * @param remove - * The action that removes items + * The action that removes items */ public ListParameterPanel(final Supplier<E> add, final Consumer<E> edit, final Consumer<E> remove) { this(add, edit, remove, null); @@ -44,13 +44,13 @@ public class ListParameterPanel<E> extends JPanel { * Create a new panel using the specified actions for doing things * * @param add - * The action that provides items + * The action that provides items * @param edit - * The action that edits items + * The action that edits items * @param remove - * The action that removes items + * The action that removes items * @param defaults - * The default values to put in the list + * The default values to put in the list */ public ListParameterPanel(final Supplier<E> add, final Consumer<E> edit, final Consumer<E> remove, final IList<E> defaults) { @@ -58,7 +58,7 @@ public class ListParameterPanel<E> extends JPanel { JList<E> list; - if (defaults != null) { + if(defaults != null) { list = SimpleJList.buildFromList(defaults.toIterable()); } else { list = new JList<>(new DefaultListModel<>()); @@ -70,15 +70,15 @@ public class ListParameterPanel<E> extends JPanel { int numButtons = 0; - if (add != null) { + if(add != null) { numButtons++; } - if (edit != null) { + if(edit != null) { numButtons++; } - if (remove != null) { + if(remove != null) { numButtons++; } @@ -86,7 +86,7 @@ public class ListParameterPanel<E> extends JPanel { JButton addParam = null; - if (add != null) { + if(add != null) { addParam = new JButton("Add..."); addParam.addActionListener((event) -> { final DefaultListModel<E> model = (DefaultListModel<E>) list.getModel(); @@ -97,7 +97,7 @@ public class ListParameterPanel<E> extends JPanel { JButton editParam = null; - if (edit != null) { + if(edit != null) { editParam = new JButton("Edit..."); editParam.addActionListener((event) -> { edit.accept(list.getSelectedValue()); @@ -106,7 +106,7 @@ public class ListParameterPanel<E> extends JPanel { JButton removeParam = null; - if (remove != null) { + if(remove != null) { removeParam = new JButton("Remove..."); removeParam.addActionListener((event) -> { final DefaultListModel<E> model = (DefaultListModel<E>) list.getModel(); @@ -115,15 +115,15 @@ public class ListParameterPanel<E> extends JPanel { }); } - if (add != null) { + if(add != null) { buttonPanel.add(addParam); } - if (edit != null) { + if(edit != null) { buttonPanel.add(editParam); } - if (remove != null) { + if(remove != null) { buttonPanel.add(removeParam); } diff --git a/base/src/main/java/bjc/utils/gui/panels/SimpleInputPanel.java b/base/src/main/java/bjc/utils/gui/panels/SimpleInputPanel.java index 65c533d..301a183 100644 --- a/base/src/main/java/bjc/utils/gui/panels/SimpleInputPanel.java +++ b/base/src/main/java/bjc/utils/gui/panels/SimpleInputPanel.java @@ -24,16 +24,16 @@ public class SimpleInputPanel extends JPanel { * Create a new input panel * * @param label - * The label for the field + * The label for the field * @param columns - * The number of columns of text input to take + * The number of columns of text input to take */ public SimpleInputPanel(final String label, final int columns) { setLayout(new BorderLayout()); final JLabel inputLabel = new JLabel(label); - if (columns < 1) { + if(columns < 1) { inputValue = new JTextField(); } else { inputValue = new JTextField(columns); diff --git a/base/src/main/java/bjc/utils/gui/panels/SimpleListPanel.java b/base/src/main/java/bjc/utils/gui/panels/SimpleListPanel.java index edc1797..628d146 100644 --- a/base/src/main/java/bjc/utils/gui/panels/SimpleListPanel.java +++ b/base/src/main/java/bjc/utils/gui/panels/SimpleListPanel.java @@ -28,7 +28,7 @@ public class SimpleListPanel extends JPanel { final Consumer<String> onFailure, final JTextField addItemField) { final String potentialItem = addItemField.getText(); - if (verifier == null || verifier.test(potentialItem)) { + if(verifier == null || verifier.test(potentialItem)) { model.addElement(potentialItem); } else { onFailure.accept(potentialItem); @@ -41,13 +41,13 @@ public class SimpleListPanel extends JPanel { * Create a new list panel * * @param type - * The type of things in the list + * The type of things in the list * @param model - * The model to put items into + * The model to put items into * @param verifier - * The predicate to use to verify items + * The predicate to use to verify items * @param onFailure - * The function to call when an item doesn't verify + * The function to call when an item doesn't verify */ public SimpleListPanel(final String type, final DefaultListModel<String> model, final Predicate<String> verifier, final Consumer<String> onFailure) { diff --git a/base/src/main/java/bjc/utils/gui/panels/SimpleSpinnerPanel.java b/base/src/main/java/bjc/utils/gui/panels/SimpleSpinnerPanel.java index 6106182..2628c39 100644 --- a/base/src/main/java/bjc/utils/gui/panels/SimpleSpinnerPanel.java +++ b/base/src/main/java/bjc/utils/gui/panels/SimpleSpinnerPanel.java @@ -25,9 +25,9 @@ public class SimpleSpinnerPanel extends JPanel { * Create a new spinner panel * * @param label - * The label for the spinner + * The label for the spinner * @param model - * The model to attach to the spinner + * The model to attach to the spinner */ public SimpleSpinnerPanel(final String label, final SpinnerModel model) { setLayout(new BorderLayout()); diff --git a/base/src/main/java/bjc/utils/gui/panels/SliderInputPanel.java b/base/src/main/java/bjc/utils/gui/panels/SliderInputPanel.java index e6a6da4..ff4c161 100644 --- a/base/src/main/java/bjc/utils/gui/panels/SliderInputPanel.java +++ b/base/src/main/java/bjc/utils/gui/panels/SliderInputPanel.java @@ -38,12 +38,13 @@ public class SliderInputPanel extends JPanel { try { final int val = Integer.parseInt(text); - if (val < minValue) + if(val < minValue) throw new ParseException("Value must be greater than " + minValue, 0); - else if (val > maxValue) + else if(val > maxValue) throw new ParseException("Value must be smaller than " + maxValue, 0); - else return val; - } catch (final NumberFormatException nfex) { + else + return val; + } catch(final NumberFormatException nfex) { final ParseException pex = new ParseException("Value must be a valid integer", 0); pex.initCause(nfex); @@ -54,7 +55,7 @@ public class SliderInputPanel extends JPanel { @Override public String valueToString(final Object value) throws ParseException { - if (value == null) return Integer.toString(initValue); + if(value == null) return Integer.toString(initValue); return Integer.toString((Integer) value); } @@ -86,9 +87,9 @@ public class SliderInputPanel extends JPanel { * middle * * @param min - * The minimum value of the slider + * The minimum value of the slider * @param max - * The maximum value of the slider + * The maximum value of the slider */ public SliderSettings(final int min, final int max) { this(min, max, (min + max) / 2); @@ -98,11 +99,11 @@ public class SliderInputPanel extends JPanel { * Create a new set of slider sttings * * @param min - * The minimum slider value + * The minimum slider value * @param max - * The maximum slider value + * The maximum slider value * @param init - * Th initial slider value + * Th initial slider value */ public SliderSettings(final int min, final int max, final int init) { minValue = min; @@ -120,15 +121,15 @@ public class SliderInputPanel extends JPanel { * Create a new slider input panel * * @param lab - * The label for the field + * The label for the field * @param settings - * The settings for slider values + * The settings for slider values * @param majorTick - * The setting for where to place big ticks + * The setting for where to place big ticks * @param minorTick - * The setting for where to place small ticks + * The setting for where to place small ticks * @param action - * The action to execute for a given value + * The action to execute for a given value */ public SliderInputPanel(final String lab, final SliderSettings settings, final int majorTick, final int minorTick, final Consumer<Integer> action) { @@ -145,7 +146,7 @@ public class SliderInputPanel extends JPanel { slider.setPaintLabels(true); slider.addChangeListener((event) -> { - if (slider.getValueIsAdjusting()) { + if(slider.getValueIsAdjusting()) { // Do nothing } else { final int val = slider.getValue(); @@ -161,7 +162,7 @@ public class SliderInputPanel extends JPanel { field.addPropertyChangeListener("value", (event) -> { final Object value = field.getValue(); - if (value == null) { + if(value == null) { // Do nothing } else { slider.setValue((Integer) value); @@ -177,7 +178,7 @@ public class SliderInputPanel extends JPanel { * Reset the values in this panel to a specified value * * @param value - * The value to reset the fields to + * The value to reset the fields to */ public void resetValues(final int value) { slider.setValue(value); diff --git a/base/src/main/java/bjc/utils/ioutils/Prompter.java b/base/src/main/java/bjc/utils/ioutils/Prompter.java index a6ec4c0..b318222 100644 --- a/base/src/main/java/bjc/utils/ioutils/Prompter.java +++ b/base/src/main/java/bjc/utils/ioutils/Prompter.java @@ -19,10 +19,10 @@ public final class Prompter implements Runnable { * Create a new prompter using the specified prompt. * * @param prompt - * The prompt to present. + * The prompt to present. * * @param output - * The stream to print the prompt on. + * The stream to print the prompt on. */ public Prompter(final String prompt, final PrintStream output) { promt = prompt; @@ -34,7 +34,7 @@ public final class Prompter implements Runnable { * Set the prompt this prompter uses. * * @param prompt - * The prompt this prompter uses. + * The prompt this prompter uses. */ public void setPrompt(final String prompt) { promt = prompt; diff --git a/base/src/main/java/bjc/utils/ioutils/RegexStringEditor.java b/base/src/main/java/bjc/utils/ioutils/RegexStringEditor.java index 71f6782..e11d4b4 100644 --- a/base/src/main/java/bjc/utils/ioutils/RegexStringEditor.java +++ b/base/src/main/java/bjc/utils/ioutils/RegexStringEditor.java @@ -25,13 +25,13 @@ public class RegexStringEditor { * the action to the string matched by the pattern. * * @param input - * The input string to process. + * The input string to process. * * @param patt - * The pattern to match the string against. + * The pattern to match the string against. * * @param action - * The action to transform matches with. + * The action to transform matches with. * * @return The string, with matches replaced with the action. */ @@ -44,13 +44,13 @@ public class RegexStringEditor { * applying the action to the strings between the patterns. * * @param input - * The input string to process. + * The input string to process. * * @param patt - * The pattern to match the string against. + * The pattern to match the string against. * * @param action - * The action to transform matches with. + * The action to transform matches with. * * @return The string, with strings between the matches replaced with * the action. @@ -64,16 +64,16 @@ public class RegexStringEditor { * Execute actions between and on matches of a regular expression. * * @param input - * The input string. + * The input string. * * @param rPatt - * The pattern to match against the string. + * The pattern to match against the string. * * @param betweenAction - * The function to execute between matches of the string. + * The function to execute between matches of the string. * * @param onAction - * The function to execute on matches of the string. + * The function to execute on matches of the string. * * @return The string, with both actions applied. */ @@ -102,16 +102,16 @@ public class RegexStringEditor { * Execute actions between and on matches of a regular expression. * * @param input - * The input string. + * The input string. * * @param rPatt - * The pattern to match against the string. + * The pattern to match against the string. * * @param betweenAction - * The function to execute between matches of the string. + * The function to execute between matches of the string. * * @param onAction - * The function to execute on matches of the string. + * The function to execute on matches of the string. * * @return The string, with both actions applied. */ @@ -133,10 +133,10 @@ public class RegexStringEditor { * Separate a string into match/non-match segments. * * @param input - * The string to separate. + * The string to separate. * * @param rPatt - * The pattern to use for separation. + * The pattern to use for separation. * * @return The string, as a list of match/non-match segments, * starting/ending with a non-match segment. @@ -153,7 +153,7 @@ public class RegexStringEditor { /* * For every match. */ - while (matcher.find()) { + while(matcher.find()) { final String match = matcher.group(); /* @@ -183,20 +183,20 @@ public class RegexStringEditor { * Apply an operation to a string if it matches a regular expression. * * @param input - * The input string. + * The input string. * * @param patt - * The pattern to match against it. + * The pattern to match against it. * * @param action - * The action to execute if it matches. + * The action to execute if it matches. * * @return The string, modified by the action if the pattern matched. */ public static String ifMatches(final String input, final Pattern patt, final UnaryOperator<String> action) { final Matcher matcher = patt.matcher(input); - if (matcher.matches()) { + if(matcher.matches()) { return action.apply(input); } else { return input; @@ -207,13 +207,13 @@ public class RegexStringEditor { * Apply an operation to a string if it matches a regular expression. * * @param input - * The input string. + * The input string. * * @param patt - * The pattern to match against it. + * The pattern to match against it. * * @param action - * The action to execute if it doesn't match. + * The action to execute if it doesn't match. * * @return The string, modified by the action if the pattern didn't * match. @@ -221,7 +221,7 @@ public class RegexStringEditor { public static String ifNotMatches(final String input, final Pattern patt, final UnaryOperator<String> action) { final Matcher matcher = patt.matcher(input); - if (matcher.matches()) { + if(matcher.matches()) { return input; } else { return action.apply(input); diff --git a/base/src/main/java/bjc/utils/ioutils/RuleBasedConfigReader.java b/base/src/main/java/bjc/utils/ioutils/RuleBasedConfigReader.java index 7c5205b..9e4bbb6 100644 --- a/base/src/main/java/bjc/utils/ioutils/RuleBasedConfigReader.java +++ b/base/src/main/java/bjc/utils/ioutils/RuleBasedConfigReader.java @@ -22,30 +22,30 @@ import bjc.utils.funcdata.IMap; * @author ben * * @param <E> - * The type of the state object to use + * The type of the state object to use * */ public class RuleBasedConfigReader<E> { - /* Function to execute when starting a rule. - * Takes the tokenizer, and a pair of the read token and application state + /* + * Function to execute when starting a rule. Takes the tokenizer, and a + * pair of the read token and application state */ private BiConsumer<FunctionalStringTokenizer, IPair<String, E>> start; /* - * Function to use when continuing a rule - * Takes a tokenizer and application state + * Function to use when continuing a rule Takes a tokenizer and + * application state */ private BiConsumer<FunctionalStringTokenizer, E> continueRule; /* - * Function to use when ending a rule - * Takes an application state + * Function to use when ending a rule Takes an application state */ private Consumer<E> end; /* - * Map of pragma names to pragma actions - * Pragma actions are functions taking a tokenizer and application state + * Map of pragma names to pragma actions Pragma actions are functions + * taking a tokenizer and application state */ private final IMap<String, BiConsumer<FunctionalStringTokenizer, E>> pragmas; @@ -53,11 +53,11 @@ public class RuleBasedConfigReader<E> { * Create a new rule-based config reader * * @param start - * The action to fire when starting a rule + * The action to fire when starting a rule * @param continueRule - * The action to fire when continuing a rule + * The action to fire when continuing a rule * @param end - * The action to fire when ending a rule + * The action to fire when ending a rule */ public RuleBasedConfigReader(final BiConsumer<FunctionalStringTokenizer, IPair<String, E>> start, final BiConsumer<FunctionalStringTokenizer, E> continueRule, final Consumer<E> end) { @@ -72,22 +72,23 @@ public class RuleBasedConfigReader<E> { * Add a pragma to this reader * * @param name - * The name of the pragma to add + * The name of the pragma to add * @param action - * The function to execute when this pragma is read + * The function to execute when this pragma is read */ public void addPragma(final String name, final BiConsumer<FunctionalStringTokenizer, E> action) { - if (name == null) throw new NullPointerException("Pragma name must not be null"); - else if (action == null) throw new NullPointerException("Pragma action must not be null"); + if(name == null) + throw new NullPointerException("Pragma name must not be null"); + else if(action == null) throw new NullPointerException("Pragma action must not be null"); pragmas.put(name, action); } private void continueRule(final E state, final boolean isRuleOpen, final String line) { // Make sure our input is correct - if (isRuleOpen == false) + if(isRuleOpen == false) throw new InputMismatchException("Cannot continue rule with no rule open"); - else if (continueRule == null) + else if(continueRule == null) throw new InputMismatchException("Rule continuation not supported for current grammar"); /* @@ -100,7 +101,7 @@ public class RuleBasedConfigReader<E> { /* * Ignore blank line without an open rule */ - if (isRuleOpen == false) + if(isRuleOpen == false) /* * Do nothing */ @@ -109,7 +110,7 @@ public class RuleBasedConfigReader<E> { /* * Nothing happens on rule end */ - if (end != null) { + if(end != null) { /* * Process the rule ending */ @@ -127,13 +128,13 @@ public class RuleBasedConfigReader<E> { * Run a stream through this reader * * @param input - * The stream to get input + * The stream to get input * @param initialState - * The initial state of the reader + * The initial state of the reader * @return The final state of the reader */ public E fromStream(final InputStream input, final E initialState) { - if (input == null) throw new NullPointerException("Input stream must not be null"); + if(input == null) throw new NullPointerException("Input stream must not be null"); /* * Application state: We're giving this back later @@ -143,7 +144,7 @@ public class RuleBasedConfigReader<E> { /* * Prepare our input source */ - try (Scanner source = new Scanner(input)) { + try(Scanner source = new Scanner(input)) { source.useDelimiter("\n"); /* * This is true when a rule's open @@ -157,17 +158,17 @@ public class RuleBasedConfigReader<E> { /* * Skip comment lines */ - if (line.startsWith("#") || line.startsWith("//")) + if(line.startsWith("#") || line.startsWith("//")) /* * It's a comment */ return; - else if (line.equals("")) { + else if(line.equals("")) { /* * End the rule */ isRuleOpen.replace(endRule(state, isRuleOpen.getValue())); - } else if (line.startsWith("\t")) { + } else if(line.startsWith("\t")) { /* * Continue the rule */ @@ -191,7 +192,7 @@ public class RuleBasedConfigReader<E> { * Set the action to execute when continuing a rule * * @param continueRule - * The action to execute on continuation of a rule + * The action to execute on continuation of a rule */ public void setContinueRule(final BiConsumer<FunctionalStringTokenizer, E> continueRule) { this.continueRule = continueRule; @@ -201,7 +202,7 @@ public class RuleBasedConfigReader<E> { * Set the action to execute when ending a rule * * @param end - * The action to execute on ending of a rule + * The action to execute on ending of a rule */ public void setEndRule(final Consumer<E> end) { this.end = end; @@ -211,10 +212,10 @@ public class RuleBasedConfigReader<E> { * Set the action to execute when starting a rule * * @param start - * The action to execute on starting of a rule + * The action to execute on starting of a rule */ public void setStartRule(final BiConsumer<FunctionalStringTokenizer, IPair<String, E>> start) { - if (start == null) throw new NullPointerException("Action on rule start must be non-null"); + if(start == null) throw new NullPointerException("Action on rule start must be non-null"); this.start = start; } @@ -233,7 +234,7 @@ public class RuleBasedConfigReader<E> { /* * Handle pragmas */ - if (nextToken.equals("pragma")) { + if(nextToken.equals("pragma")) { /* * Get the pragma name */ @@ -249,7 +250,7 @@ public class RuleBasedConfigReader<E> { /* * Make sure input is correct */ - if (isRuleOpen == true) + if(isRuleOpen == true) throw new InputMismatchException("Nested rules are currently not supported"); /* diff --git a/base/src/main/java/bjc/utils/ioutils/RuleBasedReaderPragmas.java b/base/src/main/java/bjc/utils/ioutils/RuleBasedReaderPragmas.java index e26a7ee..5d19337 100644 --- a/base/src/main/java/bjc/utils/ioutils/RuleBasedReaderPragmas.java +++ b/base/src/main/java/bjc/utils/ioutils/RuleBasedReaderPragmas.java @@ -18,11 +18,11 @@ public class RuleBasedReaderPragmas { * Creates a pragma that takes a single integer argument * * @param <StateType> - * The type of state that goes along with this pragma + * The type of state that goes along with this pragma * @param name - * The name of this pragma, for error message purpose + * The name of this pragma, for error message purpose * @param consumer - * The function to invoke with the parsed integer + * The function to invoke with the parsed integer * @return A pragma that functions as described above. */ public static <StateType> BiConsumer<FunctionalStringTokenizer, StateType> buildInteger(final String name, @@ -31,7 +31,7 @@ public class RuleBasedReaderPragmas { /* * Check our input is correct */ - if (!tokenizer.hasMoreTokens()) { + if(!tokenizer.hasMoreTokens()) { String fmt = "Pragma %s requires one integer argument"; throw new PragmaFormatException(String.format(fmt, name)); @@ -47,13 +47,14 @@ public class RuleBasedReaderPragmas { * Run the pragma */ consumer.accept(Integer.parseInt(token), state); - } catch (final NumberFormatException nfex) { + } catch(final NumberFormatException nfex) { /* * Tell the user their argument isn't correct */ String fmt = "Argument %s to %s pragma isn't a valid integer, and this pragma requires an integer argument."; - final PragmaFormatException pfex = new PragmaFormatException(String.format(fmt, token, name)); + final PragmaFormatException pfex = new PragmaFormatException( + String.format(fmt, token, name)); pfex.initCause(nfex); @@ -67,11 +68,11 @@ public class RuleBasedReaderPragmas { * them all into a single string * * @param <StateType> - * The type of state that goes along with this pragma + * The type of state that goes along with this pragma * @param name - * The name of this pragma, for error message purpose + * The name of this pragma, for error message purpose * @param consumer - * The function to invoke with the parsed string + * The function to invoke with the parsed string * @return A pragma that functions as described above. */ public static <StateType> BiConsumer<FunctionalStringTokenizer, StateType> buildStringCollapser( @@ -80,7 +81,7 @@ public class RuleBasedReaderPragmas { /* * Check our input */ - if (!tokenizer.hasMoreTokens()) { + if(!tokenizer.hasMoreTokens()) { String fmt = "Pragma %s requires one or more string arguments."; throw new PragmaFormatException(String.format(fmt, name)); diff --git a/base/src/main/java/bjc/utils/ioutils/SimpleProperties.java b/base/src/main/java/bjc/utils/ioutils/SimpleProperties.java index e6279c4..7043ed2 100644 --- a/base/src/main/java/bjc/utils/ioutils/SimpleProperties.java +++ b/base/src/main/java/bjc/utils/ioutils/SimpleProperties.java @@ -32,23 +32,23 @@ public class SimpleProperties implements Map<String, String> { * All leading/trailing spaces from the name & body are removed. * * @param is - * The stream to read from. + * The stream to read from. * * @param allowDuplicates - * Whether or not duplicate keys should be allowed. + * Whether or not duplicate keys should be allowed. */ public void loadFrom(final InputStream is, final boolean allowDuplicates) { - try (Scanner scn = new Scanner(is)) { - while (scn.hasNextLine()) { + try(Scanner scn = new Scanner(is)) { + while(scn.hasNextLine()) { final String ln = scn.nextLine().trim(); /* * Skip blank lines/comments */ - if (ln.equals("")) { + if(ln.equals("")) { continue; } - if (ln.startsWith("#")) { + if(ln.startsWith("#")) { continue; } @@ -57,7 +57,7 @@ public class SimpleProperties implements Map<String, String> { /* * Complain about improperly formatted lines. */ - if (sepIdx == -1) { + if(sepIdx == -1) { final String fmt = "Properties must be a name, a space, then the body.\n\tOffending line is '%s'"; final String msg = String.format(fmt, ln); @@ -70,7 +70,7 @@ public class SimpleProperties implements Map<String, String> { /* * Complain about duplicates, if that is wanted. */ - if (!allowDuplicates && containsKey(name)) { + if(!allowDuplicates && containsKey(name)) { final String msg = String.format("Duplicate key '%s'", name); throw new IllegalStateException(msg); @@ -87,7 +87,7 @@ public class SimpleProperties implements Map<String, String> { public void outputProperties() { System.out.println("Read properties:"); - for (final Entry<String, String> entry : entrySet()) { + for(final Entry<String, String> entry : entrySet()) { System.out.printf("\t'%s'\t'%s'\n", entry.getKey(), entry.getValue()); } diff --git a/base/src/main/java/bjc/utils/ioutils/blocks/Block.java b/base/src/main/java/bjc/utils/ioutils/blocks/Block.java index 15f3510..1bf6b46 100644 --- a/base/src/main/java/bjc/utils/ioutils/blocks/Block.java +++ b/base/src/main/java/bjc/utils/ioutils/blocks/Block.java @@ -31,13 +31,13 @@ public class Block { * Create a new block. * * @param blockNo - * The number of this block. + * The number of this block. * @param contents - * The contents of this block. + * The contents of this block. * @param startLine - * The line this block started on. + * The line this block started on. * @param endLine - * The line this block ended. + * The line this block ended. */ public Block(final int blockNo, final String contents, final int startLine, final int endLine) { this.contents = contents; @@ -61,20 +61,20 @@ public class Block { @Override public boolean equals(final Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (!(obj instanceof Block)) return false; + if(this == obj) return true; + if(obj == null) return false; + if(!(obj instanceof Block)) return false; final Block other = (Block) obj; - if (blockNo != other.blockNo) return false; + if(blockNo != other.blockNo) return false; - if (contents == null) { - if (other.contents != null) return false; - } else if (!contents.equals(other.contents)) return false; + if(contents == null) { + if(other.contents != null) return false; + } else if(!contents.equals(other.contents)) return false; - if (endLine != other.endLine) return false; - if (startLine != other.startLine) return false; + if(endLine != other.endLine) return false; + if(startLine != other.startLine) return false; return true; } diff --git a/base/src/main/java/bjc/utils/ioutils/blocks/BlockReader.java b/base/src/main/java/bjc/utils/ioutils/blocks/BlockReader.java index 3c695c6..bf402f5 100644 --- a/base/src/main/java/bjc/utils/ioutils/blocks/BlockReader.java +++ b/base/src/main/java/bjc/utils/ioutils/blocks/BlockReader.java @@ -51,10 +51,10 @@ public interface BlockReader extends AutoCloseable, Iterator<Block> { * Execute an action for each remaining block. * * @param action - * The action to execute for each block + * The action to execute for each block */ default void forEachBlock(final Consumer<Block> action) { - while (hasNext()) { + while(hasNext()) { action.accept(next()); } } diff --git a/base/src/main/java/bjc/utils/ioutils/blocks/BlockReaders.java b/base/src/main/java/bjc/utils/ioutils/blocks/BlockReaders.java index 8bbb89c..f1dfc3c 100644 --- a/base/src/main/java/bjc/utils/ioutils/blocks/BlockReaders.java +++ b/base/src/main/java/bjc/utils/ioutils/blocks/BlockReaders.java @@ -13,10 +13,10 @@ public class BlockReaders { * Create a new simple block reader that works off a regex. * * @param blockDelim - * The regex that separates blocks. + * The regex that separates blocks. * * @param source - * The reader to get blocks from. + * The reader to get blocks from. * * @return A configured simple reader. */ @@ -28,7 +28,7 @@ public class BlockReaders { * Create a new pushback block reader. * * @param src - * The block reader to read blocks from. + * The block reader to read blocks from. * * @return A configured pushback reader. */ @@ -40,10 +40,10 @@ public class BlockReaders { * Create a new triggered block reader. * * @param source - * The block reader to read blocks from. + * The block reader to read blocks from. * * @param action - * The action to execute before reading a block. + * The action to execute before reading a block. * * @return A configured triggered block reader. */ @@ -55,10 +55,10 @@ public class BlockReaders { * Create a new layered block reader. * * @param primary - * The first source to read blocks from. + * The first source to read blocks from. * * @param secondary - * The second source to read blocks from. + * The second source to read blocks from. * * @return A configured layered block reader. */ @@ -70,8 +70,7 @@ public class BlockReaders { * Create a new serial block reader. * * @param readers - * The readers to pull from, in the order to pull from - * them. + * The readers to pull from, in the order to pull from them. * * @return A configured serial block reader. */ diff --git a/base/src/main/java/bjc/utils/ioutils/blocks/LayeredBlockReader.java b/base/src/main/java/bjc/utils/ioutils/blocks/LayeredBlockReader.java index 967a1f2..af138e7 100644 --- a/base/src/main/java/bjc/utils/ioutils/blocks/LayeredBlockReader.java +++ b/base/src/main/java/bjc/utils/ioutils/blocks/LayeredBlockReader.java @@ -17,8 +17,8 @@ public class LayeredBlockReader implements BlockReader { /* * The readers to drain from. */ - private final BlockReader first; - private final BlockReader second; + private final BlockReader first; + private final BlockReader second; /* * The current block number. @@ -29,10 +29,10 @@ public class LayeredBlockReader implements BlockReader { * Create a new layered block reader. * * @param primary - * The first source to read blocks from. + * The first source to read blocks from. * * @param secondary - * The second source to read blocks from. + * The second source to read blocks from. */ public LayeredBlockReader(final BlockReader primary, final BlockReader secondary) { first = primary; @@ -60,7 +60,7 @@ public class LayeredBlockReader implements BlockReader { final boolean gotFirst = first.nextBlock(); final boolean succ = gotFirst ? gotFirst : second.nextBlock(); - if (succ) { + if(succ) { blockNo += 1; } diff --git a/base/src/main/java/bjc/utils/ioutils/blocks/SerialBlockReader.java b/base/src/main/java/bjc/utils/ioutils/blocks/SerialBlockReader.java index c229da1..62db3a8 100644 --- a/base/src/main/java/bjc/utils/ioutils/blocks/SerialBlockReader.java +++ b/base/src/main/java/bjc/utils/ioutils/blocks/SerialBlockReader.java @@ -18,18 +18,17 @@ public class SerialBlockReader implements BlockReader { * Create a new serial block reader. * * @param readers - * The readers to pull from, in the order to pull from - * them. + * The readers to pull from, in the order to pull from them. */ public SerialBlockReader(final BlockReader... readers) { - for (final BlockReader reader : readers) { + for(final BlockReader reader : readers) { readerQueue.add(reader); } } @Override public boolean hasNextBlock() { - if (readerQueue.isEmpty()) return false; + if(readerQueue.isEmpty()) return false; /* * Attempt to get a block from the first reader. @@ -40,10 +39,10 @@ public class SerialBlockReader implements BlockReader { /* * Close/dispose of readers until we get an open one. */ - while (!cont) { + while(!cont) { try { readerQueue.pop().close(); - } catch (final IOException ioex) { + } catch(final IOException ioex) { throw new IllegalStateException("Exception thrown by discarded reader", ioex); } @@ -56,22 +55,23 @@ public class SerialBlockReader implements BlockReader { @Override public Block getBlock() { - if (readerQueue.isEmpty()) + if(readerQueue.isEmpty()) return null; - else return readerQueue.peek().getBlock(); + else + return readerQueue.peek().getBlock(); } @Override public boolean nextBlock() { - if (readerQueue.isEmpty()) return false; + if(readerQueue.isEmpty()) return false; boolean gotBlock = readerQueue.peek().nextBlock(); boolean cont = gotBlock || readerQueue.isEmpty(); - while (!cont) { + while(!cont) { try { readerQueue.pop().close(); - } catch (final IOException ioex) { + } catch(final IOException ioex) { throw new IllegalStateException("Exception thrown by discarded reader", ioex); } @@ -79,7 +79,7 @@ public class SerialBlockReader implements BlockReader { cont = gotBlock || readerQueue.isEmpty(); } - if (cont) { + if(cont) { blockNo += 1; } @@ -93,7 +93,7 @@ public class SerialBlockReader implements BlockReader { @Override public void close() throws IOException { - while (!readerQueue.isEmpty()) { + while(!readerQueue.isEmpty()) { final BlockReader reader = readerQueue.pop(); reader.close(); diff --git a/base/src/main/java/bjc/utils/ioutils/blocks/SimpleBlockReader.java b/base/src/main/java/bjc/utils/ioutils/blocks/SimpleBlockReader.java index 7985de2..6536d0c 100644 --- a/base/src/main/java/bjc/utils/ioutils/blocks/SimpleBlockReader.java +++ b/base/src/main/java/bjc/utils/ioutils/blocks/SimpleBlockReader.java @@ -7,6 +7,7 @@ import java.util.Scanner; import java.util.regex.Pattern; import bjc.utils.funcutils.StringUtils; + /** * Simple implementation of {@link BlockReader} * @@ -30,18 +31,18 @@ public class SimpleBlockReader implements BlockReader { /* * Info about the current block. */ - private int blockNo; - private int lineNo; + private int blockNo; + private int lineNo; /** * Create a new block reader. * * @param blockDelim - * The pattern that separates blocks. Note that the end - * of file is always considered to end a block. + * The pattern that separates blocks. Note that the end of file + * is always considered to end a block. * * @param source - * The source to read blocks from. + * The source to read blocks from. */ public SimpleBlockReader(final String blockDelim, final Reader source) { blockReader = new Scanner(source); @@ -80,7 +81,7 @@ public class SimpleBlockReader implements BlockReader { currBlock = new Block(blockNo, blockContents, blockStartLine, blockEndLine); return true; - } catch (final NoSuchElementException nseex) { + } catch(final NoSuchElementException nseex) { currBlock = null; return false; @@ -101,7 +102,7 @@ public class SimpleBlockReader implements BlockReader { * Set the delimiter used to separate blocks. * * @param delim - * The delimiter used to separate blocks. + * The delimiter used to separate blocks. */ public void setDelimiter(final String delim) { blockReader.useDelimiter(delim); diff --git a/base/src/main/java/bjc/utils/ioutils/blocks/ToggledBlockReader.java b/base/src/main/java/bjc/utils/ioutils/blocks/ToggledBlockReader.java index 8f39b8f..cac0416 100644 --- a/base/src/main/java/bjc/utils/ioutils/blocks/ToggledBlockReader.java +++ b/base/src/main/java/bjc/utils/ioutils/blocks/ToggledBlockReader.java @@ -5,8 +5,8 @@ import java.io.IOException; import bjc.utils.data.BooleanToggle; public class ToggledBlockReader implements BlockReader { - private BlockReader leftSource; - private BlockReader rightSource; + private BlockReader leftSource; + private BlockReader rightSource; /* * We choose the left source when this is true. @@ -16,7 +16,7 @@ public class ToggledBlockReader implements BlockReader { private int blockNo; public ToggledBlockReader(BlockReader left, BlockReader right) { - leftSource = left; + leftSource = left; rightSource = right; blockNo = 0; @@ -26,14 +26,18 @@ public class ToggledBlockReader implements BlockReader { @Override public boolean hasNextBlock() { - if(leftToggle.peek()) return leftSource.hasNextBlock(); - else return rightSource.hasNextBlock(); + if(leftToggle.peek()) + return leftSource.hasNextBlock(); + else + return rightSource.hasNextBlock(); } @Override public Block getBlock() { - if(leftToggle.peek()) return leftSource.getBlock(); - else return rightSource.getBlock(); + if(leftToggle.peek()) + return leftSource.getBlock(); + else + return rightSource.getBlock(); } @Override @@ -54,7 +58,7 @@ public class ToggledBlockReader implements BlockReader { public int getBlockCount() { return blockNo; } - + @Override public void close() throws IOException { leftSource.close(); diff --git a/base/src/main/java/bjc/utils/ioutils/blocks/TriggeredBlockReader.java b/base/src/main/java/bjc/utils/ioutils/blocks/TriggeredBlockReader.java index 3a1e393..a066f9c 100644 --- a/base/src/main/java/bjc/utils/ioutils/blocks/TriggeredBlockReader.java +++ b/base/src/main/java/bjc/utils/ioutils/blocks/TriggeredBlockReader.java @@ -22,10 +22,10 @@ public class TriggeredBlockReader implements BlockReader { * Create a new triggered reader with the specified source/action. * * @param source - * The block reader to read blocks from. + * The block reader to read blocks from. * * @param action - * The action to execute before reading a block. + * The action to execute before reading a block. */ public TriggeredBlockReader(final BlockReader source, final Runnable action) { this.source = source; diff --git a/base/src/main/java/bjc/utils/ioutils/format/AestheticDirective.java b/base/src/main/java/bjc/utils/ioutils/format/AestheticDirective.java index 9cc10d2..16d9d12 100644 --- a/base/src/main/java/bjc/utils/ioutils/format/AestheticDirective.java +++ b/base/src/main/java/bjc/utils/ioutils/format/AestheticDirective.java @@ -10,15 +10,15 @@ class AestheticDirective implements Directive { public void format(StringBuffer sb, Object item, CLModifiers mods, CLParameters params, Tape<Object> tParams, Matcher dirMatcher, CLFormatter fmt) { CLFormatter.checkItem(item, 'A'); - + int mincol = 0, colinc = 1, minpad = 0; char padchar = ' '; - if (params.length() > 1) { + if(params.length() > 1) { mincol = params.getIntDefault(0, "minimum column count", 'A', 0); } - if (params.length() < 4) { + if(params.length() < 4) { throw new IllegalArgumentException( "Must provide either zero, one or four arguments to A directive"); } @@ -29,13 +29,13 @@ class AestheticDirective implements Directive { StringBuilder work = new StringBuilder(); - if (mods.atMod) { - for (int i = 0; i < minpad; i++) { + if(mods.atMod) { + for(int i = 0; i < minpad; i++) { work.append(padchar); } - for (int i = work.length(); i < mincol; i++) { - for (int k = 0; k < colinc; k++) { + for(int i = work.length(); i < mincol; i++) { + for(int k = 0; k < colinc; k++) { work.append(padchar); } } @@ -43,18 +43,18 @@ class AestheticDirective implements Directive { work.append(item.toString()); - if (!mods.atMod) { - for (int i = 0; i < minpad; i++) { + if(!mods.atMod) { + for(int i = 0; i < minpad; i++) { work.append(padchar); } - for (int i = work.length(); i < mincol; i++) { - for (int k = 0; k < colinc; k++) { + for(int i = work.length(); i < mincol; i++) { + for(int k = 0; k < colinc; k++) { work.append(padchar); } } } - + tParams.right(); } diff --git a/base/src/main/java/bjc/utils/ioutils/format/CLParameters.java b/base/src/main/java/bjc/utils/ioutils/format/CLParameters.java index 5bdcbbf..2588446 100644 --- a/base/src/main/java/bjc/utils/ioutils/format/CLParameters.java +++ b/base/src/main/java/bjc/utils/ioutils/format/CLParameters.java @@ -126,7 +126,7 @@ public class CLParameters { return param.charAt(1); } - + /** * Get an optional integer parameter with a default value. * @@ -148,7 +148,7 @@ public class CLParameters { return def; } - + /** * Get a mandatory integer parameter. * diff --git a/base/src/main/java/bjc/utils/ioutils/format/CharacterDirective.java b/base/src/main/java/bjc/utils/ioutils/format/CharacterDirective.java index 7ff74bb..91ddabe 100644 --- a/base/src/main/java/bjc/utils/ioutils/format/CharacterDirective.java +++ b/base/src/main/java/bjc/utils/ioutils/format/CharacterDirective.java @@ -11,7 +11,7 @@ class CharacterDirective implements Directive { public void format(StringBuffer buff, Object parm, CLModifiers mods, CLParameters arrParams, Tape<Object> tParams, Matcher dirMatcher, CLFormatter fmt) { CLFormatter.checkItem(parm, 'C'); - + if(!(parm instanceof Character)) { throw new IllegalFormatConversionException('C', parm.getClass()); } @@ -27,7 +27,7 @@ class CharacterDirective implements Directive { } else { buff.append(ch); } - + tParams.right(); } diff --git a/base/src/main/java/bjc/utils/ioutils/format/EscapeDirective.java b/base/src/main/java/bjc/utils/ioutils/format/EscapeDirective.java index 4f44479..8db3a86 100644 --- a/base/src/main/java/bjc/utils/ioutils/format/EscapeDirective.java +++ b/base/src/main/java/bjc/utils/ioutils/format/EscapeDirective.java @@ -7,8 +7,8 @@ import java.util.regex.Matcher; class EscapeDirective implements Directive { @Override - public void format(StringBuffer sb, Object item, CLModifiers mods, CLParameters params, Tape<Object> formatParams, - Matcher dirMatcher, CLFormatter fmt) { + public void format(StringBuffer sb, Object item, CLModifiers mods, CLParameters params, + Tape<Object> formatParams, Matcher dirMatcher, CLFormatter fmt) { boolean shouldExit; switch(params.length()) { diff --git a/base/src/main/java/bjc/utils/ioutils/format/GotoDirective.java b/base/src/main/java/bjc/utils/ioutils/format/GotoDirective.java index b09053e..767a77e 100644 --- a/base/src/main/java/bjc/utils/ioutils/format/GotoDirective.java +++ b/base/src/main/java/bjc/utils/ioutils/format/GotoDirective.java @@ -7,8 +7,8 @@ import java.util.regex.Matcher; class GotoDirective implements Directive { @Override - public void format(StringBuffer sb, Object item, CLModifiers mods, CLParameters params, Tape<Object> formatParams, - Matcher dirMatcher, CLFormatter fmt) { + public void format(StringBuffer sb, Object item, CLModifiers mods, CLParameters params, + Tape<Object> formatParams, Matcher dirMatcher, CLFormatter fmt) { if(mods.colonMod) { int num = 1; if(params.length() > 1) { diff --git a/base/src/main/java/bjc/utils/ioutils/format/IterationDirective.java b/base/src/main/java/bjc/utils/ioutils/format/IterationDirective.java index e13cb1c..81ce611 100644 --- a/base/src/main/java/bjc/utils/ioutils/format/IterationDirective.java +++ b/base/src/main/java/bjc/utils/ioutils/format/IterationDirective.java @@ -51,11 +51,11 @@ class IterationDirective implements Directive { } int maxItr = Integer.MAX_VALUE; - + if(arrParams.length() > 0) { maxItr = arrParams.getInt(0, "maximum iterations", '{'); } - + if(mods.atMod && mods.colonMod) { } else if(mods.atMod) { diff --git a/base/src/main/java/bjc/utils/ioutils/format/LiteralDirective.java b/base/src/main/java/bjc/utils/ioutils/format/LiteralDirective.java index 77d26cc..5110a9b 100644 --- a/base/src/main/java/bjc/utils/ioutils/format/LiteralDirective.java +++ b/base/src/main/java/bjc/utils/ioutils/format/LiteralDirective.java @@ -6,15 +6,14 @@ import java.util.regex.Matcher; class LiteralDirective implements Directive { - private char directive; - private String lit; + private char directive; + private String lit; public LiteralDirective(String lit, char directive) { this.directive = directive; this.lit = lit; } - @Override public void format(StringBuffer buff, Object item, CLModifiers mods, CLParameters params, Tape<Object> tParams, Matcher dirMatcher, CLFormatter fmt) { diff --git a/base/src/main/java/bjc/utils/ioutils/format/RadixDirective.java b/base/src/main/java/bjc/utils/ioutils/format/RadixDirective.java index 3742582..668a0bd 100644 --- a/base/src/main/java/bjc/utils/ioutils/format/RadixDirective.java +++ b/base/src/main/java/bjc/utils/ioutils/format/RadixDirective.java @@ -12,7 +12,7 @@ class RadixDirective extends GeneralNumberDirective { public void format(StringBuffer buff, Object arg, CLModifiers mods, CLParameters params, Tape<Object> tParams, Matcher dirMatcher, CLFormatter fmt) { CLFormatter.checkItem(arg, 'R'); - + if(!(arg instanceof Number)) { throw new IllegalFormatConversionException('R', arg.getClass()); } @@ -38,7 +38,7 @@ class RadixDirective extends GeneralNumberDirective { handleNumberDirective(buff, mods, params, 0, val, radix); } - + tParams.right(); } } diff --git a/base/src/main/java/bjc/utils/math/Dual.java b/base/src/main/java/bjc/utils/math/Dual.java index 53ddc32..e571519 100644 --- a/base/src/main/java/bjc/utils/math/Dual.java +++ b/base/src/main/java/bjc/utils/math/Dual.java @@ -1,83 +1,78 @@ -package bjc.utils.math;
-
-/**
- * Represents a 'dual' number.
- *
- * Think imaginary numbers, where instead of i, we add a value d such that d^2 =
- * 0.
- */
-public class Dual {
- /**
- * The real part of the dual number.
- */
- public double real;
- /**
- * The dual part of the dual number.
- */
- public double dual;
-
- /**
- * Create a new dual with both parts zero.
- */
- public Dual() {
- real = 0;
- dual = 0;
- }
-
- /**
- * Create a new dual number with a zero dual part.
- *
- * @param real
- * The real part of the number.
- */
- public Dual(double real) {
- this.real = real;
- this.dual = 0;
- }
-
- /**
- * Create a new dual number with a specified dual part.
- *
- * @param real
- * The real part of the number.
- * @param dual
- * The dual part of the number.
- */
- public Dual(double real, double dual) {
- this.real = real;
- this.dual = dual;
- }
-
- @Override
- public String toString() {
- return String.format("<%f, %f>", real, dual);
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- long temp;
- temp = Double.doubleToLongBits(dual);
- result = prime * result + (int) (temp ^ (temp >>> 32));
- temp = Double.doubleToLongBits(real);
- result = prime * result + (int) (temp ^ (temp >>> 32));
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- Dual other = (Dual) obj;
- if (Double.doubleToLongBits(dual) != Double.doubleToLongBits(other.dual))
- return false;
- if (Double.doubleToLongBits(real) != Double.doubleToLongBits(other.real))
- return false;
- return true;
- }
+package bjc.utils.math; + +/** + * Represents a 'dual' number. + * + * Think imaginary numbers, where instead of i, we add a value d such that d^2 = + * 0. + */ +public class Dual { + /** + * The real part of the dual number. + */ + public double real; + /** + * The dual part of the dual number. + */ + public double dual; + + /** + * Create a new dual with both parts zero. + */ + public Dual() { + real = 0; + dual = 0; + } + + /** + * Create a new dual number with a zero dual part. + * + * @param real + * The real part of the number. + */ + public Dual(double real) { + this.real = real; + this.dual = 0; + } + + /** + * Create a new dual number with a specified dual part. + * + * @param real + * The real part of the number. + * @param dual + * The dual part of the number. + */ + public Dual(double real, double dual) { + this.real = real; + this.dual = dual; + } + + @Override + public String toString() { + return String.format("<%f, %f>", real, dual); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + long temp; + temp = Double.doubleToLongBits(dual); + result = prime * result + (int) (temp ^ (temp >>> 32)); + temp = Double.doubleToLongBits(real); + result = prime * result + (int) (temp ^ (temp >>> 32)); + return result; + } + + @Override + public boolean equals(Object obj) { + if(this == obj) return true; + if(obj == null) return false; + if(getClass() != obj.getClass()) return false; + Dual other = (Dual) obj; + if(Double.doubleToLongBits(dual) != Double.doubleToLongBits(other.dual)) return false; + if(Double.doubleToLongBits(real) != Double.doubleToLongBits(other.real)) return false; + return true; + } }
\ No newline at end of file diff --git a/base/src/main/java/bjc/utils/parserutils/DoubleMatcher.java b/base/src/main/java/bjc/utils/parserutils/DoubleMatcher.java index a885808..e045222 100644 --- a/base/src/main/java/bjc/utils/parserutils/DoubleMatcher.java +++ b/base/src/main/java/bjc/utils/parserutils/DoubleMatcher.java @@ -36,7 +36,8 @@ class DoubleMatcher { * Floating point components. */ private static final String rFPLeader = getRegex("fpLeader"); - private static final String rFPNum = applyFormat("fpNumber", rSimpleIntDec, rSimpleDec, rHexString); + private static final String rFPNum = applyFormat("fpNumber", rSimpleIntDec, rSimpleDec, + rHexString); /* * Full double. diff --git a/base/src/main/java/bjc/utils/parserutils/IPrecedent.java b/base/src/main/java/bjc/utils/parserutils/IPrecedent.java index aa366cf..0deab5d 100644 --- a/base/src/main/java/bjc/utils/parserutils/IPrecedent.java +++ b/base/src/main/java/bjc/utils/parserutils/IPrecedent.java @@ -12,7 +12,7 @@ public interface IPrecedent { * Create a new object with set precedence * * @param precedence - * The precedence of the object to handle + * The precedence of the object to handle * @return A new object with set precedence */ public static IPrecedent newSimplePrecedent(final int precedence) { diff --git a/base/src/main/java/bjc/utils/parserutils/ParserException.java b/base/src/main/java/bjc/utils/parserutils/ParserException.java index ae33aba..72e8ac4 100644 --- a/base/src/main/java/bjc/utils/parserutils/ParserException.java +++ b/base/src/main/java/bjc/utils/parserutils/ParserException.java @@ -16,7 +16,7 @@ public class ParserException extends Exception { * Create a new exception with the provided message. * * @param msg - * The message for the exception. + * The message for the exception. */ public ParserException(final String msg) { super(msg); @@ -26,9 +26,9 @@ public class ParserException extends Exception { * Create a new exception with the provided message and cause. * * @param msg - * The message for the exception. + * The message for the exception. * @param cause - * The cause of the exception. + * The cause of the exception. */ public ParserException(final String msg, final Exception cause) { super(msg, cause); diff --git a/base/src/main/java/bjc/utils/parserutils/ShuntingYard.java b/base/src/main/java/bjc/utils/parserutils/ShuntingYard.java index a1b5feb..a0b1249 100644 --- a/base/src/main/java/bjc/utils/parserutils/ShuntingYard.java +++ b/base/src/main/java/bjc/utils/parserutils/ShuntingYard.java @@ -17,7 +17,7 @@ import bjc.utils.funcutils.StringUtils; * @author ben * * @param <TokenType> - * The type of tokens being shunted. + * The type of tokens being shunted. */ public class ShuntingYard<TokenType> { /** @@ -77,11 +77,12 @@ public class ShuntingYard<TokenType> { /* * Handle operators */ - if (operators.containsKey(token)) { - /* - * Pop operators while there isn't a higher precedence one + if(operators.containsKey(token)) { + /* + * Pop operators while there isn't a higher + * precedence one */ - while (!stack.isEmpty() && isHigherPrec(token, stack.peek())) { + while(!stack.isEmpty() && isHigherPrec(token, stack.peek())) { output.add(transformer.apply(stack.pop())); } @@ -89,21 +90,23 @@ public class ShuntingYard<TokenType> { * Put this operator onto the stack */ stack.push(token); - } else if (StringUtils.containsOnly(token, "\\(")) { + } else if(StringUtils.containsOnly(token, "\\(")) { /* - * Handle groups of parenthesis for multiple nesting levels + * Handle groups of parenthesis for multiple + * nesting levels */ stack.push(token); - } else if (StringUtils.containsOnly(token, "\\)")) { + } else if(StringUtils.containsOnly(token, "\\)")) { /* - * Handle groups of parenthesis for multiple nesting levels + * Handle groups of parenthesis for multiple + * nesting levels */ final String swappedToken = token.replace(')', '('); /* * Remove tokens up to a matching parenthesis */ - while (!stack.peek().equals(swappedToken)) { + while(!stack.peek().equals(swappedToken)) { output.add(transformer.apply(stack.pop())); } @@ -129,8 +132,7 @@ public class ShuntingYard<TokenType> { * Create a new shunting yard with a default set of operators. * * @param configureBasics - * Whether or not basic math operators should be - * provided. + * Whether or not basic math operators should be provided. */ public ShuntingYard(final boolean configureBasics) { operators = new FunctionalMap<>(); @@ -138,7 +140,7 @@ public class ShuntingYard<TokenType> { /* * Add basic operators if we're configured to do so */ - if (configureBasics) { + if(configureBasics) { operators.put("+", Operator.ADD); operators.put("-", Operator.SUBTRACT); operators.put("*", Operator.MULTIPLY); @@ -150,10 +152,10 @@ public class ShuntingYard<TokenType> { * Add an operator to the list of shuntable operators. * * @param operator - * The token representing the operator. + * The token representing the operator. * * @param precedence - * The precedence of the operator to add. + * The precedence of the operator to add. */ public void addOp(final String operator, final int precedence) { /* @@ -168,18 +170,18 @@ public class ShuntingYard<TokenType> { * Add an operator to the list of shuntable operators. * * @param operator - * The token representing the operator. + * The token representing the operator. * * @param precedence - * The precedence of the operator. + * The precedence of the operator. */ public void addOp(final String operator, final IPrecedent precedence) { /* * Complain about trying to add an incorrect operator */ - if (operator == null) + if(operator == null) throw new NullPointerException("Operator must not be null"); - else if (precedence == null) throw new NullPointerException("Precedence must not be null"); + else if(precedence == null) throw new NullPointerException("Precedence must not be null"); /* * Add the operator to the ones we handle @@ -196,7 +198,7 @@ public class ShuntingYard<TokenType> { /* * If it doesn't, the left is higher precedence. */ - if (!exists) return false; + if(!exists) return false; /* * Get the precedence of operators @@ -214,10 +216,10 @@ public class ShuntingYard<TokenType> { * Transform a string of tokens from infix notation to postfix. * * @param input - * The string to transform. + * The string to transform. * * @param transformer - * The function to use to transform strings to tokens. + * The function to use to transform strings to tokens. * * @return A list of tokens in postfix notation. */ @@ -225,9 +227,9 @@ public class ShuntingYard<TokenType> { /* * Check our input */ - if (input == null) + if(input == null) throw new NullPointerException("Input must not be null"); - else if (transformer == null) throw new NullPointerException("Transformer must not be null"); + else if(transformer == null) throw new NullPointerException("Transformer must not be null"); /* * Here's what we're handing back @@ -258,14 +260,14 @@ public class ShuntingYard<TokenType> { * Remove an operator from the list of shuntable operators. * * @param operator - * The token representing the operator. If null, remove - * all operators. + * The token representing the operator. If null, remove all + * operators. */ public void removeOp(final String operator) { /* * Check if we want to remove all operators */ - if (operator == null) { + if(operator == null) { operators = new FunctionalMap<>(); } else { operators.remove(operator); diff --git a/base/src/main/java/bjc/utils/parserutils/StringDescaper.java b/base/src/main/java/bjc/utils/parserutils/StringDescaper.java index cb6c86f..59f4760 100644 --- a/base/src/main/java/bjc/utils/parserutils/StringDescaper.java +++ b/base/src/main/java/bjc/utils/parserutils/StringDescaper.java @@ -18,15 +18,15 @@ public class StringDescaper { /* * Patterns and pattern parts. */ - private static String rPossibleEscapeString = getRegex("possibleStringEscape"); - private static Pattern possibleEscapePatt = Pattern.compile(rPossibleEscapeString); + private static String rPossibleEscapeString = getRegex("possibleStringEscape"); + private static Pattern possibleEscapePatt = Pattern.compile(rPossibleEscapeString); - private static String rShortEscape = getRegex("shortFormStringEscape"); - private static String rOctalEscape = getRegex("octalStringEscape"); - private static String rUnicodeEscape = getRegex("unicodeStringEscape"); + private static String rShortEscape = getRegex("shortFormStringEscape"); + private static String rOctalEscape = getRegex("octalStringEscape"); + private static String rUnicodeEscape = getRegex("unicodeStringEscape"); - private String rEscapeString; - private Pattern escapePatt; + private String rEscapeString; + private Pattern escapePatt; // These should be used for something, but I don't recall what //private static String rDoubleQuoteString = applyFormat("doubleQuotes", getRegex("nonStringEscape"), rPossibleEscapeString); @@ -34,15 +34,15 @@ public class StringDescaper { //private static Pattern quotePatt = getCompiledRegex("unescapedQuote"); - private Map<String, String> literalEscapes; - private Map<Pattern, UnaryOperator<String>> specialEscapes; - + private Map<String, String> literalEscapes; + private Map<Pattern, UnaryOperator<String>> specialEscapes; + public StringDescaper() { literalEscapes = new HashMap<>(); specialEscapes = new HashMap<>(); rEscapeString = String.format("\\\\(%1$s|%2$s|%3$s)"); - escapePatt = Pattern.compile(rEscapeString); + escapePatt = Pattern.compile(rEscapeString); } public void addLiteralEscape(String escape, String val) { @@ -61,7 +61,7 @@ public class StringDescaper { Pattern patt = null; try { patt = Pattern.compile(escape); - } catch (PatternSyntaxException psex) { + } catch(PatternSyntaxException psex) { String msg = String.format("Invalid special escape '%s'", escape); IllegalArgumentException iaex = new IllegalArgumentException(msg); @@ -69,7 +69,7 @@ public class StringDescaper { throw psex; } - + if(specialEscapes.containsKey(patt)) { LOGGER.warning(String.format("Shadowing special escape '%s'\n", escape)); } @@ -93,24 +93,25 @@ public class StringDescaper { } /* - * Convert user-defined escapes to a regex for matching. - * We don't need a bar before %4 because the string has it. + * Convert user-defined escapes to a regex for matching. We + * don't need a bar before %4 because the string has it. */ - rEscapeString = String.format("\\(%1$s|%2$s|%3$s%4$s)", rShortEscape, rOctalEscape, rUnicodeEscape, work.toString()); - escapePatt = Pattern.compile(rEscapeString); + rEscapeString = String.format("\\(%1$s|%2$s|%3$s%4$s)", rShortEscape, rOctalEscape, rUnicodeEscape, + work.toString()); + escapePatt = Pattern.compile(rEscapeString); } /** * Replace escape characters with their actual equivalents. * * @param inp - * The string to replace escape sequences in. + * The string to replace escape sequences in. * * @return The string with escape sequences replaced by their equivalent * characters. */ public String descapeString(final String inp) { - if (inp == null) { + if(inp == null) { throw new NullPointerException("Input to descapeString must not be null"); } @@ -121,13 +122,14 @@ public class StringDescaper { final Matcher possibleEscapeFinder = possibleEscapePatt.matcher(inp); final Matcher escapeFinder = escapePatt.matcher(inp); - while (possibleEscapeFinder.find()) { - if (!escapeFinder.find()) { + while(possibleEscapeFinder.find()) { + if(!escapeFinder.find()) { /* - * Found a possible escape that isn't actually an - * escape. + * Found a possible escape that isn't actually + * an escape. */ - final String msg = String.format("Illegal escape sequence '%s' at position %d of string '%s'", + final String msg = String.format( + "Illegal escape sequence '%s' at position %d of string '%s'", possibleEscapeFinder.group(), possibleEscapeFinder.start(), inp); throw new IllegalArgumentException(msg); } @@ -138,7 +140,7 @@ public class StringDescaper { * Convert the escape to a string. */ String escapeRep = ""; - switch (escapeSeq) { + switch(escapeSeq) { case "\\b": escapeRep = "\b"; break; @@ -168,7 +170,7 @@ public class StringDescaper { escapeRep = "\\"; break; default: - if (escapeSeq.startsWith("u")) { + if(escapeSeq.startsWith("u")) { escapeRep = handleUnicodeEscape(escapeSeq.substring(1)); } else if(escapeSeq.startsWith("O")) { escapeRep = handleOctalEscape(escapeSeq.substring(1)); @@ -203,7 +205,7 @@ public class StringDescaper { final int codepoint = Integer.parseInt(seq, 16); return new String(Character.toChars(codepoint)); - } catch (final IllegalArgumentException iaex) { + } catch(final IllegalArgumentException iaex) { final String msg = String.format("'%s' is not a valid Unicode escape sequence'", seq); final IllegalArgumentException reiaex = new IllegalArgumentException(msg); @@ -221,14 +223,15 @@ public class StringDescaper { try { final int codepoint = Integer.parseInt(seq, 8); - if (codepoint > 255) { - final String msg = String.format("'%d' is outside the range of octal escapes', codepoint"); + if(codepoint > 255) { + final String msg = String + .format("'%d' is outside the range of octal escapes', codepoint"); throw new IllegalArgumentException(msg); } return new String(Character.toChars(codepoint)); - } catch (final IllegalArgumentException iaex) { + } catch(final IllegalArgumentException iaex) { final String msg = String.format("'%s' is not a valid octal escape sequence'", seq); final IllegalArgumentException reiaex = new IllegalArgumentException(msg); diff --git a/base/src/main/java/bjc/utils/parserutils/TokenTransformer.java b/base/src/main/java/bjc/utils/parserutils/TokenTransformer.java index 30ccc5a..5a37596 100644 --- a/base/src/main/java/bjc/utils/parserutils/TokenTransformer.java +++ b/base/src/main/java/bjc/utils/parserutils/TokenTransformer.java @@ -30,7 +30,8 @@ final class TokenTransformer<TokenType> implements Consumer<TokenType> { @Override public ConstructorState<TokenType> apply(final ConstructorState<TokenType> pair) { /* - * Replace the current AST with the result of handling an operator + * Replace the current AST with the result of handling + * an operator */ return new ConstructorState<>(pair.bindLeft(queuedASTs -> { return handleOperator(queuedASTs); @@ -46,13 +47,14 @@ final class TokenTransformer<TokenType> implements Consumer<TokenType> { /* * Handle special operators */ - if (isSpecialOperator.test(element)) { + if(isSpecialOperator.test(element)) { newAST = handleSpecialOperator.apply(element).apply(queuedASTs); } else { /* - * Error if we don't have enough for a binary operator + * Error if we don't have enough for a binary + * operator */ - if (queuedASTs.size() < 2) { + if(queuedASTs.size() < 2) { final String msg = String.format( "Attempted to parse binary operator without enough operands\n\tProblem operator is: %s\n\tPossible operand is: %s", element.toString(), queuedASTs.peek().toString()); @@ -108,7 +110,7 @@ final class TokenTransformer<TokenType> implements Consumer<TokenType> { /* * Handle operators */ - if (operatorPredicate.test(element)) { + if(operatorPredicate.test(element)) { initialState.transform(new OperatorHandler(element)); } else { final ITree<TokenType> newAST = new Tree<>(element); @@ -118,7 +120,9 @@ final class TokenTransformer<TokenType> implements Consumer<TokenType> { */ initialState.transform(pair -> { /* - * Transform the pair, ignoring the current AST in favor of the one consisting of the current element + * Transform the pair, ignoring the current AST + * in favor of the one consisting of the current + * element */ return new ConstructorState<>(pair.bindLeft(queue -> { queue.push(newAST); diff --git a/base/src/main/java/bjc/utils/parserutils/TokenUtils.java b/base/src/main/java/bjc/utils/parserutils/TokenUtils.java index cb9ab7b..2a6c0fd 100644 --- a/base/src/main/java/bjc/utils/parserutils/TokenUtils.java +++ b/base/src/main/java/bjc/utils/parserutils/TokenUtils.java @@ -64,13 +64,13 @@ public class TokenUtils { * Splits a string around instances of java-style double-quoted strings. * * @param inp - * The string to split. + * The string to split. * * @return An list containing alternating bits of the string and the * embedded double-quoted strings that separated them. */ public static List<String> removeDQuotedStrings(final String inp) { - if (inp == null) throw new NullPointerException("inp must not be null"); + if(inp == null) throw new NullPointerException("inp must not be null"); /* * What we need for piece-by-piece string building @@ -84,7 +84,7 @@ public class TokenUtils { final Matcher mt = doubleQuotePatt.matcher(inp); final Matcher corr = quotePatt.matcher(inp); - if (corr.find() && !corr.find()) { + if(corr.find() && !corr.find()) { /* * There's a unmatched opening quote with no strings. */ @@ -95,7 +95,7 @@ public class TokenUtils { throw new IllegalArgumentException(msg); } - while (mt.find()) { + while(mt.find()) { /* * Remove the string until the quoted string. */ @@ -120,7 +120,7 @@ public class TokenUtils { mt.appendTail(work); final String tail = work.toString(); - if (tail.contains("\"")) { + if(tail.contains("\"")) { /* * There's a unmatched opening quote with at least one * string. @@ -135,7 +135,7 @@ public class TokenUtils { /* * Only add an empty tail if the string was empty. */ - if (!tail.equals("") || res.isEmpty()) { + if(!tail.equals("") || res.isEmpty()) { res.add(tail); } @@ -146,13 +146,13 @@ public class TokenUtils { * Replace escape characters with their actual equivalents. * * @param inp - * The string to replace escape sequences in. + * The string to replace escape sequences in. * * @return The string with escape sequences replaced by their equivalent * characters. */ public static String descapeString(final String inp) { - if (inp == null) throw new NullPointerException("inp must not be null"); + if(inp == null) throw new NullPointerException("inp must not be null"); /* * Prepare the buffer and escape finder. @@ -161,11 +161,11 @@ public class TokenUtils { final Matcher possibleEscapeFinder = possibleEscapePatt.matcher(inp); final Matcher escapeFinder = escapePatt.matcher(inp); - while (possibleEscapeFinder.find()) { - if (!escapeFinder.find()) { + while(possibleEscapeFinder.find()) { + if(!escapeFinder.find()) { /* - * Found a possible escape that isn't actually an - * escape. + * Found a possible escape that isn't actually + * an escape. */ final String msg = String.format("Illegal escape sequence '%s' at position %d", possibleEscapeFinder.group(), possibleEscapeFinder.start()); @@ -179,7 +179,7 @@ public class TokenUtils { * Convert the escape to a string. */ String escapeRep = ""; - switch (escapeSeq) { + switch(escapeSeq) { case "\\b": escapeRep = "\b"; break; @@ -209,7 +209,7 @@ public class TokenUtils { escapeRep = "\\"; break; default: - if (escapeSeq.startsWith("u")) { + if(escapeSeq.startsWith("u")) { escapeRep = handleUnicodeEscape(escapeSeq.substring(1)); } else { escapeRep = handleOctalEscape(escapeSeq); @@ -232,7 +232,7 @@ public class TokenUtils { final int codepoint = Integer.parseInt(seq, 16); return new String(Character.toChars(codepoint)); - } catch (final IllegalArgumentException iaex) { + } catch(final IllegalArgumentException iaex) { final String msg = String.format("'%s' is not a valid Unicode escape sequence'", seq); final IllegalArgumentException reiaex = new IllegalArgumentException(msg); @@ -250,7 +250,7 @@ public class TokenUtils { try { final int codepoint = Integer.parseInt(seq, 8); - if (codepoint > 255) { + if(codepoint > 255) { final String msg = String .format("'%d' is outside the range of octal escapes', codepoint"); @@ -258,7 +258,7 @@ public class TokenUtils { } return new String(Character.toChars(codepoint)); - } catch (final IllegalArgumentException iaex) { + } catch(final IllegalArgumentException iaex) { final String msg = String.format("'%s' is not a valid octal escape sequence'", seq); final IllegalArgumentException reiaex = new IllegalArgumentException(msg); @@ -274,7 +274,7 @@ public class TokenUtils { * by {@link Double#parseDouble(String)}. * * @param inp - * The string to check. + * The string to check. * @return Whether the string is a valid double or not. */ public static boolean isDouble(final String inp) { @@ -289,14 +289,14 @@ public class TokenUtils { * integers will still cause errors. * * @param inp - * The input to check. + * The input to check. * @return Whether the string is a valid integer or not. */ public static boolean isInt(final String inp) { try { Integer.parseInt(inp); return true; - } catch (NumberFormatException nfex) { + } catch(NumberFormatException nfex) { return false; } } diff --git a/base/src/main/java/bjc/utils/parserutils/TreeConstructor.java b/base/src/main/java/bjc/utils/parserutils/TreeConstructor.java index 90141ef..7bff43e 100644 --- a/base/src/main/java/bjc/utils/parserutils/TreeConstructor.java +++ b/base/src/main/java/bjc/utils/parserutils/TreeConstructor.java @@ -23,7 +23,7 @@ public class TreeConstructor { * Alias interface for special operator types. * * @param <TokenType> - * The token type of the tree. + * The token type of the tree. */ public interface QueueFlattener<TokenType> extends Function<Deque<ITree<TokenType>>, ITree<TokenType>> { @@ -48,12 +48,11 @@ public class TreeConstructor { * Only binary operators are accepted. * * @param <TokenType> - * The elements of the parse tree + * The elements of the parse tree * @param tokens - * The list of tokens to build a tree from + * The list of tokens to build a tree from * @param isOperator - * The predicate to use to determine if something is a - * operator + * The predicate to use to determine if something is a operator * @return A AST from the expression */ public static <TokenType> ITree<TokenType> constructTree(final IList<TokenType> tokens, @@ -71,21 +70,20 @@ public class TreeConstructor { * parameters to handle non-binary operators. * * @param <TokenType> - * The elements of the parse tree. + * The elements of the parse tree. * * @param tokens - * The list of tokens to build a tree from. + * The list of tokens to build a tree from. * * @param isOperator - * The predicate to use to determine if something is a - * operator. + * The predicate to use to determine if something is a operator. * * @param isSpecialOperator - * The predicate to use to determine if an operator needs - * special handling. + * The predicate to use to determine if an operator needs special + * handling. * * @param handleSpecialOperator - * The function to use to handle special case operators. + * The function to use to handle special case operators. * * @return A AST from the expression * @@ -96,11 +94,11 @@ public class TreeConstructor { /* * Make sure our parameters are valid */ - if (tokens == null) + if(tokens == null) throw new NullPointerException("Tokens must not be null"); - else if (isOperator == null) + else if(isOperator == null) throw new NullPointerException("Operator predicate must not be null"); - else if (isSpecialOperator == null) + else if(isSpecialOperator == null) throw new NullPointerException("Special operator determiner must not be null"); /* diff --git a/base/src/main/java/bjc/utils/parserutils/defines/SimpleDefine.java b/base/src/main/java/bjc/utils/parserutils/defines/SimpleDefine.java index 42866c2..5d206bd 100644 --- a/base/src/main/java/bjc/utils/parserutils/defines/SimpleDefine.java +++ b/base/src/main/java/bjc/utils/parserutils/defines/SimpleDefine.java @@ -5,8 +5,8 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; public class SimpleDefine implements UnaryOperator<String> { - private Pattern patt; - private String repl; + private Pattern patt; + private String repl; public SimpleDefine(Pattern pattern, String replace) { patt = pattern; diff --git a/base/src/main/java/bjc/utils/parserutils/delims/DelimiterException.java b/base/src/main/java/bjc/utils/parserutils/delims/DelimiterException.java index 071afb4..4172d32 100644 --- a/base/src/main/java/bjc/utils/parserutils/delims/DelimiterException.java +++ b/base/src/main/java/bjc/utils/parserutils/delims/DelimiterException.java @@ -13,7 +13,7 @@ public class DelimiterException extends RuntimeException { * Create a new generic delimiter exception. * * @param res - * The reason for this exception. + * The reason for this exception. */ public DelimiterException(final String res) { super(res); diff --git a/base/src/main/java/bjc/utils/parserutils/delims/DelimiterGroup.java b/base/src/main/java/bjc/utils/parserutils/delims/DelimiterGroup.java index 73c3473..5d020a6 100644 --- a/base/src/main/java/bjc/utils/parserutils/delims/DelimiterGroup.java +++ b/base/src/main/java/bjc/utils/parserutils/delims/DelimiterGroup.java @@ -24,7 +24,7 @@ import bjc.utils.funcdata.IList; * @author EVE * * @param <T> - * The type of items in the sequence. + * The type of items in the sequence. */ public class DelimiterGroup<T> { /** @@ -47,17 +47,17 @@ public class DelimiterGroup<T> { /* * The token that opened the group, and any opening parameters. */ - private final T opener; - private final T[] params; + private final T opener; + private final T[] params; /** * Create a new instance of a delimiter group. * * @param open - * The item that opened this group. + * The item that opened this group. * * @param parms - * Any parameters from the opener. + * Any parameters from the opener. */ public OpenGroup(final T open, final T[] parms) { opener = open; @@ -72,7 +72,7 @@ public class DelimiterGroup<T> { * Add an item to this group instance. * * @param itm - * The item to add to this group instance. + * The item to add to this group instance. */ public void addItem(final ITree<T> itm) { currentGroup.add(itm); @@ -82,33 +82,33 @@ public class DelimiterGroup<T> { * Mark a subgroup. * * @param marker - * The item that indicated this subgroup. + * The item that indicated this subgroup. * * @param chars - * The characteristics for building the tree. + * The characteristics for building the tree. */ public void markSubgroup(final T marker, final SequenceCharacteristics<T> chars) { /* * Add all of the contents to the subgroup. */ final ITree<T> subgroupContents = new Tree<>(chars.contents); - for (final ITree<T> itm : currentGroup) { + for(final ITree<T> itm : currentGroup) { subgroupContents.addChild(itm); } /* * Handle subordinate sub-groups. */ - while (!contents.isEmpty()) { + while(!contents.isEmpty()) { final ITree<T> possibleSubordinate = contents.peek(); /* * Subordinate lower priority subgroups. */ - if (possibleSubordinate.getHead().equals(chars.subgroup)) { + if(possibleSubordinate.getHead().equals(chars.subgroup)) { final T otherMarker = possibleSubordinate.getChild(1).getHead(); - if (subgroups.get(marker) > subgroups.get(otherMarker)) { + if(subgroups.get(marker) > subgroups.get(otherMarker)) { subgroupContents.prependChild(contents.pop()); } else { break; @@ -129,10 +129,10 @@ public class DelimiterGroup<T> { * Convert this group into a tree. * * @param closer - * The item that closed this group. + * The item that closed this group. * * @param chars - * The characteristics for building the tree. + * The characteristics for building the tree. * * @return This group as a tree. */ @@ -140,20 +140,20 @@ public class DelimiterGroup<T> { /* * Mark any implied subgroups. */ - if (impliedSubgroups.containsKey(closer)) { + if(impliedSubgroups.containsKey(closer)) { markSubgroup(impliedSubgroups.get(closer), chars); } final ITree<T> res = new Tree<>(chars.contents); /* - * Add either the contents of the current group, - * or subgroups if they're their. + * Add either the contents of the current group, or + * subgroups if they're their. */ - if (contents.isEmpty()) { + if(contents.isEmpty()) { currentGroup.forEach(res::addChild); } else { - while (!contents.isEmpty()) { + while(!contents.isEmpty()) { res.prependChild(contents.poll()); } @@ -182,7 +182,7 @@ public class DelimiterGroup<T> { * Check if a group is excluded at the top level of this group. * * @param grupName - * The group to check. + * The group to check. * * @return Whether or not the provided group is excluded. */ @@ -194,16 +194,16 @@ public class DelimiterGroup<T> { * Check if the provided delimiter would close this group. * * @param del - * The string to check as a closing delimiter. + * The string to check as a closing delimiter. * * @return Whether or not the provided delimiter closes this * group. */ public boolean isClosing(final T del) { - if (closingDelimiters.contains(del)) return true; + if(closingDelimiters.contains(del)) return true; - for (final BiPredicate<T, T[]> pred : predClosers) { - if (pred.test(del, params)) return true; + for(final BiPredicate<T, T[]> pred : predClosers) { + if(pred.test(del, params)) return true; } return closingDelimiters.contains(del); @@ -242,7 +242,7 @@ public class DelimiterGroup<T> { * Checks if a given token marks a subgroup. * * @param tok - * The token to check. + * The token to check. * * @return Whether or not the token marks a subgroup. */ @@ -254,18 +254,18 @@ public class DelimiterGroup<T> { * Checks if a given token opens a group. * * @param marker - * The token to check. + * The token to check. * * @return The name of the group T opens, or null if it doesn't * open one. */ public IPair<T, T[]> doesOpen(final T marker) { - if (openDelimiters.containsKey(marker)) return new Pair<>(openDelimiters.get(marker), null); + if(openDelimiters.containsKey(marker)) return new Pair<>(openDelimiters.get(marker), null); - for (final Function<T, IPair<T, T[]>> pred : predOpeners) { + for(final Function<T, IPair<T, T[]>> pred : predOpeners) { final IPair<T, T[]> par = pred.apply(marker); - if (par.getLeft() != null) return par; + if(par.getLeft() != null) return par; } return new Pair<>(null, null); @@ -341,10 +341,10 @@ public class DelimiterGroup<T> { * Create a new empty delimiter group. * * @param name - * The name of the delimiter group + * The name of the delimiter group */ public DelimiterGroup(final T name) { - if (name == null) throw new NullPointerException("Group name must not be null"); + if(name == null) throw new NullPointerException("Group name must not be null"); groupName = name; @@ -367,16 +367,16 @@ public class DelimiterGroup<T> { * Adds one or more delimiters that close this group. * * @param closers - * Delimiters that close this group. + * Delimiters that close this group. */ @SafeVarargs public final void addClosing(final T... closers) { final List<T> closerList = Arrays.asList(closers); - for (final T closer : closerList) { - if (closer == null) + for(final T closer : closerList) { + if(closer == null) throw new NullPointerException("Closing delimiter must not be null"); - else if (closer.equals("")) + else if(closer.equals("")) /* * We can do this because equals works on * arbitrary objects, not just those of the same @@ -394,14 +394,14 @@ public class DelimiterGroup<T> { * group. * * @param exclusions - * The groups forbidden in the top level of this group. + * The groups forbidden in the top level of this group. */ @SafeVarargs public final void addTopLevelForbid(final T... exclusions) { - for (final T exclusion : exclusions) { - if (exclusion == null) + for(final T exclusion : exclusions) { + if(exclusion == null) throw new NullPointerException("Exclusion must not be null"); - else if (exclusion.equals("")) + else if(exclusion.equals("")) /* * We can do this because equals works on * arbitrary objects, not just those of the same @@ -418,14 +418,14 @@ public class DelimiterGroup<T> { * Adds one or more groups that cannot occur at all in this group. * * @param exclusions - * The groups forbidden inside this group. + * The groups forbidden inside this group. */ @SafeVarargs public final void addGroupForbid(final T... exclusions) { - for (final T exclusion : exclusions) { - if (exclusion == null) + for(final T exclusion : exclusions) { + if(exclusion == null) throw new NullPointerException("Exclusion must not be null"); - else if (exclusion.equals("")) + else if(exclusion.equals("")) /* * We can do this because equals works on * arbitrary objects, not just those of the same @@ -442,13 +442,13 @@ public class DelimiterGroup<T> { * Adds sub-group markers to this group. * * @param subgroup - * The token to mark a sub-group. + * The token to mark a sub-group. * * @param priority - * The priority of this sub-group. + * The priority of this sub-group. */ public void addSubgroup(final T subgroup, final int priority) { - if (subgroup == null) throw new NullPointerException("Subgroup marker must not be null"); + if(subgroup == null) throw new NullPointerException("Subgroup marker must not be null"); subgroups.put(subgroup, priority); } @@ -457,14 +457,15 @@ public class DelimiterGroup<T> { * Adds a marker that opens a group at the top level of this group. * * @param opener - * The marker that opens the group. + * The marker that opens the group. * * @param group - * The group opened by the marker. + * The group opened by the marker. */ public void addOpener(final T opener, final T group) { - if (opener == null) throw new NullPointerException("Opener must not be null"); - else if (group == null) throw new NullPointerException("Group to open must not be null"); + if(opener == null) + throw new NullPointerException("Opener must not be null"); + else if(group == null) throw new NullPointerException("Group to open must not be null"); openDelimiters.put(opener, group); } @@ -473,14 +474,15 @@ public class DelimiterGroup<T> { * Adds a marker that opens a group inside of this group. * * @param opener - * The marker that opens the group. + * The marker that opens the group. * * @param group - * The group opened by the marker. + * The group opened by the marker. */ public void addNestedOpener(final T opener, final T group) { - if (opener == null) throw new NullPointerException("Opener must not be null"); - else if (group == null) throw new NullPointerException("Group to open must not be null"); + if(opener == null) + throw new NullPointerException("Opener must not be null"); + else if(group == null) throw new NullPointerException("Group to open must not be null"); nestedOpenDelimiters.put(opener, group); } @@ -489,16 +491,20 @@ public class DelimiterGroup<T> { * Mark a closing delimiter as implying a subgroup. * * @param closer - * The closing delimiter. + * The closing delimiter. * * @param subgroup - * The subgroup to imply. + * The subgroup to imply. */ public void implySubgroup(final T closer, final T subgroup) { - if (closer == null) throw new NullPointerException("Closer must not be null"); - else if (subgroup == null) throw new NullPointerException("Subgroup must not be null"); - else if (!closingDelimiters.contains(closer)) throw new IllegalArgumentException(String.format("No closing delimiter '%s' defined", closer)); - else if (!subgroups.containsKey(subgroup)) throw new IllegalArgumentException(String.format("No subgroup '%s' defined", subgroup)); + if(closer == null) + throw new NullPointerException("Closer must not be null"); + else if(subgroup == null) + throw new NullPointerException("Subgroup must not be null"); + else if(!closingDelimiters.contains(closer)) + throw new IllegalArgumentException(String.format("No closing delimiter '%s' defined", closer)); + else if(!subgroups.containsKey(subgroup)) + throw new IllegalArgumentException(String.format("No subgroup '%s' defined", subgroup)); impliedSubgroups.put(closer, subgroup); } @@ -514,26 +520,26 @@ public class DelimiterGroup<T> { builder.append("], "); builder.append("closingDelimiters=["); - for (final T closer : closingDelimiters) { + for(final T closer : closingDelimiters) { builder.append(closer + ","); } builder.deleteCharAt(builder.length() - 1); builder.append("]"); - if (topLevelExclusions != null && !topLevelExclusions.isEmpty()) { + if(topLevelExclusions != null && !topLevelExclusions.isEmpty()) { builder.append(", "); builder.append("topLevelExclusions=["); - for (final T exclusion : topLevelExclusions) { + for(final T exclusion : topLevelExclusions) { builder.append(exclusion + ","); } builder.deleteCharAt(builder.length() - 1); builder.append("]"); } - if (groupExclusions != null && !groupExclusions.isEmpty()) { + if(groupExclusions != null && !groupExclusions.isEmpty()) { builder.append(", "); builder.append("groupExclusions=["); - for (final T exclusion : groupExclusions) { + for(final T exclusion : groupExclusions) { builder.append(exclusion + ","); } builder.deleteCharAt(builder.length() - 1); @@ -549,10 +555,10 @@ public class DelimiterGroup<T> { * Open an instance of this group. * * @param opener - * The item that opened this group. + * The item that opened this group. * * @param parms - * The parameters that opened this group + * The parameters that opened this group * * @return An opened instance of this group. */ @@ -564,8 +570,7 @@ public class DelimiterGroup<T> { * Adds a predicated opener to the top level of this group. * * @param pred - * The predicate that defines the opener and its - * parameters. + * The predicate that defines the opener and its parameters. */ public void addPredOpener(final Function<T, IPair<T, T[]>> pred) { predOpeners.add(pred); @@ -575,7 +580,7 @@ public class DelimiterGroup<T> { * Adds a predicated closer to the top level of this group. * * @param pred - * The predicate that defines the closer. + * The predicate that defines the closer. */ public void addPredCloser(final BiPredicate<T, T[]> pred) { predClosers.add(pred); @@ -585,7 +590,7 @@ public class DelimiterGroup<T> { * Set whether or not this group starts a new nesting set. * * @param forgetful - * Whether this group starts a new nesting set. + * Whether this group starts a new nesting set. */ public void setForgetful(final boolean forgetful) { this.forgetful = forgetful; diff --git a/base/src/main/java/bjc/utils/parserutils/delims/RegexCloser.java b/base/src/main/java/bjc/utils/parserutils/delims/RegexCloser.java index 4b29949..ac257d1 100644 --- a/base/src/main/java/bjc/utils/parserutils/delims/RegexCloser.java +++ b/base/src/main/java/bjc/utils/parserutils/delims/RegexCloser.java @@ -15,7 +15,7 @@ public class RegexCloser implements BiPredicate<String, String[]> { * Create a new regex closer. * * @param closer - * The format string to use for closing. + * The format string to use for closing. */ public RegexCloser(final String closer) { rep = closer; diff --git a/base/src/main/java/bjc/utils/parserutils/delims/RegexOpener.java b/base/src/main/java/bjc/utils/parserutils/delims/RegexOpener.java index ee93b73..15f11e3 100644 --- a/base/src/main/java/bjc/utils/parserutils/delims/RegexOpener.java +++ b/base/src/main/java/bjc/utils/parserutils/delims/RegexOpener.java @@ -22,10 +22,10 @@ public class RegexOpener implements Function<String, IPair<String, String[]>> { * Create a new regex opener. * * @param groupName - * The name of the opened group. + * The name of the opened group. * * @param groupRegex - * The regex that matches the opener. + * The regex that matches the opener. */ public RegexOpener(final String groupName, final String groupRegex) { name = groupName; @@ -37,12 +37,12 @@ public class RegexOpener implements Function<String, IPair<String, String[]>> { public IPair<String, String[]> apply(final String str) { final Matcher m = patt.matcher(str); - if (m.matches()) { + if(m.matches()) { final int numGroups = m.groupCount(); final String[] parms = new String[numGroups + 1]; - for (int i = 0; i <= numGroups; i++) { + for(int i = 0; i <= numGroups; i++) { parms[i] = m.group(i); } diff --git a/base/src/main/java/bjc/utils/parserutils/delims/SequenceCharacteristics.java b/base/src/main/java/bjc/utils/parserutils/delims/SequenceCharacteristics.java index 882b4c5..9e4c167 100644 --- a/base/src/main/java/bjc/utils/parserutils/delims/SequenceCharacteristics.java +++ b/base/src/main/java/bjc/utils/parserutils/delims/SequenceCharacteristics.java @@ -6,7 +6,7 @@ package bjc.utils.parserutils.delims; * @author EVE * * @param <T> - * The type of item in the tree. + * The type of item in the tree. */ public class SequenceCharacteristics<T> { /** @@ -29,11 +29,11 @@ public class SequenceCharacteristics<T> { * Create a new set of parameters for building a tree. * * @param root - * The root marker. + * The root marker. * @param contents - * The group/subgroup contents marker. + * The group/subgroup contents marker. * @param subgroup - * The subgroup marker. + * The subgroup marker. */ public SequenceCharacteristics(final T root, final T contents, final T subgroup) { this.root = root; @@ -55,23 +55,23 @@ public class SequenceCharacteristics<T> { @Override public boolean equals(final Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (!(obj instanceof SequenceCharacteristics)) return false; + if(this == obj) return true; + if(obj == null) return false; + if(!(obj instanceof SequenceCharacteristics)) return false; final SequenceCharacteristics<?> other = (SequenceCharacteristics<?>) obj; - if (contents == null) { - if (other.contents != null) return false; - } else if (!contents.equals(other.contents)) return false; + if(contents == null) { + if(other.contents != null) return false; + } else if(!contents.equals(other.contents)) return false; - if (root == null) { - if (other.root != null) return false; - } else if (!root.equals(other.root)) return false; + if(root == null) { + if(other.root != null) return false; + } else if(!root.equals(other.root)) return false; - if (subgroup == null) { - if (other.subgroup != null) return false; - } else if (!subgroup.equals(other.subgroup)) return false; + if(subgroup == null) { + if(other.subgroup != null) return false; + } else if(!subgroup.equals(other.subgroup)) return false; return true; } diff --git a/base/src/main/java/bjc/utils/parserutils/delims/SequenceDelimiter.java b/base/src/main/java/bjc/utils/parserutils/delims/SequenceDelimiter.java index ccfaffb..0eddebe 100644 --- a/base/src/main/java/bjc/utils/parserutils/delims/SequenceDelimiter.java +++ b/base/src/main/java/bjc/utils/parserutils/delims/SequenceDelimiter.java @@ -24,7 +24,7 @@ import bjc.utils.funcutils.StringUtils; * @author EVE * * @param <T> - * The type of items in the sequence. + * The type of items in the sequence. */ public class SequenceDelimiter<T> { /* @@ -63,10 +63,9 @@ public class SequenceDelimiter<T> { * </pre> * * @param chars - * The parameters on how to mark certain portions of the - * tree. + * The parameters on how to mark certain portions of the tree. * @param seq - * The sequence to delimit. + * The sequence to delimit. * * @return The sequence as a tree that matches its group structure. Each * node in the tree is either a data node, a subgroup node, or a @@ -89,14 +88,14 @@ public class SequenceDelimiter<T> { * recursive tree. * * @throws DelimiterException - * Thrown if something went wrong during sequence - * delimitation. + * Thrown if something went wrong during sequence delimitation. * */ public ITree<T> delimitSequence(final SequenceCharacteristics<T> chars, @SuppressWarnings("unchecked") final T... seq) throws DelimiterException { - if (initialGroup == null) throw new NullPointerException("Initial group must be specified."); - else if (chars == null) throw new NullPointerException("Sequence characteristics must not be null"); + if(initialGroup == null) + throw new NullPointerException("Initial group must be specified."); + else if(chars == null) throw new NullPointerException("Sequence characteristics must not be null"); /* * The stack of opened and not yet closed groups. @@ -128,7 +127,7 @@ public class SequenceDelimiter<T> { /* * Process each member of the sequence. */ - for (int i = 0; i < seq.length; i++) { + for(int i = 0; i < seq.length; i++) { final T tok = seq[i]; /* @@ -137,14 +136,14 @@ public class SequenceDelimiter<T> { final IPair<T, T[]> possibleOpenPar = groupStack.top().doesOpen(tok); T possibleOpen = possibleOpenPar.getLeft(); - if (possibleOpen == null) { + if(possibleOpen == null) { /* * Handle nested openers. * * Local openers take priority over nested ones * if they overlap. */ - if (allowedDelimiters.top().containsKey(tok)) { + if(allowedDelimiters.top().containsKey(tok)) { possibleOpen = allowedDelimiters.top().get(tok).iterator().next(); } } @@ -152,7 +151,7 @@ public class SequenceDelimiter<T> { /* * If we have an opening delimiter, handle it. */ - if (possibleOpen != null) { + if(possibleOpen != null) { final DelimiterGroup<T> group = groups.get(possibleOpen); /* @@ -163,10 +162,10 @@ public class SequenceDelimiter<T> { * top-level of this group, as well as nested * exclusions from all enclosing groups. */ - if (isForbidden(groupStack, forbiddenDelimiters, possibleOpen)) { + if(isForbidden(groupStack, forbiddenDelimiters, possibleOpen)) { T forbiddenBy; - if (whoForbid.containsKey(tok)) { + if(whoForbid.containsKey(tok)) { forbiddenBy = whoForbid.get(tok); } else { forbiddenBy = groupStack.top().getName(); @@ -188,7 +187,7 @@ public class SequenceDelimiter<T> { /* * Handle 'forgetful' groups that reset nesting */ - if (open.isForgetful()) { + if(open.isForgetful()) { allowedDelimiters.push(HashMultimap.create()); forbiddenDelimiters.push(HashMultiset.create()); } @@ -197,7 +196,7 @@ public class SequenceDelimiter<T> { * Add the nested opens from this group. */ final Multimap<T, T> currentAllowed = allowedDelimiters.top(); - for (final Entry<T, T> opener : open.getNestingOpeners().entrySet()) { + for(final Entry<T, T> opener : open.getNestingOpeners().entrySet()) { currentAllowed.put(opener.getKey(), opener.getValue()); } @@ -205,12 +204,12 @@ public class SequenceDelimiter<T> { * Add the nested exclusions from this group */ final Multiset<T> currentForbidden = forbiddenDelimiters.top(); - for (final T exclusion : open.getNestingExclusions()) { + for(final T exclusion : open.getNestingExclusions()) { currentForbidden.add(exclusion); whoForbid.put(exclusion, possibleOpen); } - } else if (!groupStack.empty() && groupStack.top().isClosing(tok)) { + } else if(!groupStack.empty() && groupStack.top().isClosing(tok)) { /* * Close the group. */ @@ -222,7 +221,7 @@ public class SequenceDelimiter<T> { * Remove nested exclusions from this group. */ final Multiset<T> currentForbidden = forbiddenDelimiters.top(); - for (final T excludedGroup : closed.getNestingExclusions()) { + for(final T excludedGroup : closed.getNestingExclusions()) { currentForbidden.remove(excludedGroup); whoForbid.remove(excludedGroup); @@ -232,18 +231,18 @@ public class SequenceDelimiter<T> { * Remove the nested opens from this group. */ final Multimap<T, T> currentAllowed = allowedDelimiters.top(); - for (final Entry<T, T> closer : closed.getNestingOpeners().entrySet()) { + for(final Entry<T, T> closer : closed.getNestingOpeners().entrySet()) { currentAllowed.remove(closer.getKey(), closer.getValue()); } /* * Handle 'forgetful' groups that reset nesting. */ - if (closed.isForgetful()) { + if(closed.isForgetful()) { allowedDelimiters.drop(); forbiddenDelimiters.drop(); } - } else if (!groupStack.empty() && groupStack.top().marksSubgroup(tok)) { + } else if(!groupStack.empty() && groupStack.top().marksSubgroup(tok)) { /* * Mark a subgroup. */ @@ -259,7 +258,7 @@ public class SequenceDelimiter<T> { /* * Error if not all groups were closed. */ - if (groupStack.size() > 1) { + if(groupStack.size() > 1) { final DelimiterGroup<T>.OpenGroup group = groupStack.top(); final StringBuilder msgBuilder = new StringBuilder(); @@ -294,7 +293,7 @@ public class SequenceDelimiter<T> { /* * Check if a delimiter is locally forbidden. */ - if (groupStack.empty()) { + if(groupStack.empty()) { localForbid = false; } else { localForbid = groupStack.top().excludes(groupName); @@ -307,10 +306,10 @@ public class SequenceDelimiter<T> { * Add a delimiter group. * * @param group - * The delimiter group. + * The delimiter group. */ public void addGroup(final DelimiterGroup<T> group) { - if (group == null) throw new NullPointerException("Group must not be null"); + if(group == null) throw new NullPointerException("Group must not be null"); groups.put(group.groupName, group); } @@ -319,11 +318,11 @@ public class SequenceDelimiter<T> { * Creates and adds a delimiter group using the provided settings. * * @param openers - * The tokens that open this group + * The tokens that open this group * @param groupName - * The name of the group + * The name of the group * @param closers - * The tokens that close this group + * The tokens that close this group */ public void addGroup(final T[] openers, final T groupName, @SuppressWarnings("unchecked") final T... closers) { final DelimiterGroup<T> group = new DelimiterGroup<>(groupName); @@ -332,7 +331,7 @@ public class SequenceDelimiter<T> { addGroup(group); - for (final T open : openers) { + for(final T open : openers) { group.addOpener(open, groupName); } } @@ -343,13 +342,13 @@ public class SequenceDelimiter<T> { builder.append("SequenceDelimiter ["); - if (groups != null) { + if(groups != null) { builder.append("groups="); builder.append(groups); builder.append(","); } - if (initialGroup != null) { + if(initialGroup != null) { builder.append("initialGroup="); builder.append(initialGroup); } @@ -363,7 +362,7 @@ public class SequenceDelimiter<T> { * Set the initial group of this delimiter. * * @param initialGroup - * The initial group of this delimiter. + * The initial group of this delimiter. */ public void setInitialGroup(final DelimiterGroup<T> initialGroup) { this.initialGroup = initialGroup; diff --git a/base/src/main/java/bjc/utils/parserutils/delims/StringDelimiter.java b/base/src/main/java/bjc/utils/parserutils/delims/StringDelimiter.java index e3eeea5..10c680c 100644 --- a/base/src/main/java/bjc/utils/parserutils/delims/StringDelimiter.java +++ b/base/src/main/java/bjc/utils/parserutils/delims/StringDelimiter.java @@ -16,12 +16,12 @@ public class StringDelimiter extends SequenceDelimiter<String> { * for ease of use for strings. * * @param seq - * The sequence to delimit. + * The sequence to delimit. * * @return The sequence as a tree. * * @throws DelimiterException - * if something went wrong with delimiting the sequence. + * if something went wrong with delimiting the sequence. * * @see SequenceDelimiter */ diff --git a/base/src/main/java/bjc/utils/parserutils/splitter/ChainTokenSplitter.java b/base/src/main/java/bjc/utils/parserutils/splitter/ChainTokenSplitter.java index 4736310..db851f0 100644 --- a/base/src/main/java/bjc/utils/parserutils/splitter/ChainTokenSplitter.java +++ b/base/src/main/java/bjc/utils/parserutils/splitter/ChainTokenSplitter.java @@ -23,7 +23,7 @@ public class ChainTokenSplitter implements TokenSplitter { * Append a series of splitters to the chain. * * @param splitters - * The splitters to append to the chain. + * The splitters to append to the chain. */ public void appendSplitters(final TokenSplitter... splitters) { spliters.addAll(splitters); @@ -33,7 +33,7 @@ public class ChainTokenSplitter implements TokenSplitter { * Prepend a series of splitters to the chain. * * @param splitters - * The splitters to append to the chain. + * The splitters to append to the chain. */ public void prependSplitters(final TokenSplitter... splitters) { spliters.prependAll(splitters); diff --git a/base/src/main/java/bjc/utils/parserutils/splitter/ConfigurableTokenSplitter.java b/base/src/main/java/bjc/utils/parserutils/splitter/ConfigurableTokenSplitter.java index 48ddcb4..556a2b1 100644 --- a/base/src/main/java/bjc/utils/parserutils/splitter/ConfigurableTokenSplitter.java +++ b/base/src/main/java/bjc/utils/parserutils/splitter/ConfigurableTokenSplitter.java @@ -24,7 +24,7 @@ public class ConfigurableTokenSplitter extends SimpleTokenSplitter { * Create a new token splitter with blank configuration. * * @param keepDelims - * Whether or not to keep delimiters. + * Whether or not to keep delimiters. */ public ConfigurableTokenSplitter(final boolean keepDelims) { super(null, keepDelims); @@ -43,10 +43,10 @@ public class ConfigurableTokenSplitter extends SimpleTokenSplitter { * Simple delimiters match one occurrence of themselves as literals. * * @param simpleDelims - * The simple delimiters to add. + * The simple delimiters to add. */ public void addSimpleDelimiters(final String... simpleDelims) { - for (final String simpleDelim : simpleDelims) { + for(final String simpleDelim : simpleDelims) { simpleDelimiters.add(simpleDelim); } } @@ -58,10 +58,10 @@ public class ConfigurableTokenSplitter extends SimpleTokenSplitter { * literals. * * @param multiDelims - * The multiple delimiters to add. + * The multiple delimiters to add. */ public void addMultiDelimiters(final String... multiDelims) { - for (final String multiDelim : multiDelims) { + for(final String multiDelim : multiDelims) { multipleDelimiters.add(multiDelim); } } @@ -73,10 +73,10 @@ public class ConfigurableTokenSplitter extends SimpleTokenSplitter { * expressions. * * @param rRawDelims - * The raw delimiters to add. + * The raw delimiters to add. */ public void addRawDelimiters(final String... rRawDelims) { - for (final String rRawDelim : rRawDelims) { + for(final String rRawDelim : rRawDelims) { rRawDelimiters.add(rRawDelim); } } @@ -88,15 +88,15 @@ public class ConfigurableTokenSplitter extends SimpleTokenSplitter { public void compile() { final StringBuilder rPattern = new StringBuilder(); - for (final String rRawDelimiter : rRawDelimiters) { + for(final String rRawDelimiter : rRawDelimiters) { rPattern.append(applyFormat("rawDelim", rRawDelimiter)); } - for (final String multipleDelimiter : multipleDelimiters) { + for(final String multipleDelimiter : multipleDelimiters) { rPattern.append(applyFormat("multipleDelim", multipleDelimiter)); } - for (final String simpleDelimiter : simpleDelimiters) { + for(final String simpleDelimiter : simpleDelimiters) { rPattern.append(applyFormat("simpleDelim", simpleDelimiter)); } @@ -107,7 +107,7 @@ public class ConfigurableTokenSplitter extends SimpleTokenSplitter { @Override public IList<String> split(final String input) { - if (spliter == null) throw new IllegalStateException("Must compile splitter before use"); + if(spliter == null) throw new IllegalStateException("Must compile splitter before use"); return super.split(input); } diff --git a/base/src/main/java/bjc/utils/parserutils/splitter/ExcludingTokenSplitter.java b/base/src/main/java/bjc/utils/parserutils/splitter/ExcludingTokenSplitter.java index 369e7ae..7edba52 100644 --- a/base/src/main/java/bjc/utils/parserutils/splitter/ExcludingTokenSplitter.java +++ b/base/src/main/java/bjc/utils/parserutils/splitter/ExcludingTokenSplitter.java @@ -24,7 +24,7 @@ public class ExcludingTokenSplitter implements TokenSplitter { * Create a new excluding token splitter. * * @param splitter - * The splitter to apply to non-excluded strings. + * The splitter to apply to non-excluded strings. */ public ExcludingTokenSplitter(final TokenSplitter splitter) { spliter = splitter; @@ -38,10 +38,10 @@ public class ExcludingTokenSplitter implements TokenSplitter { * Exclude literal strings from splitting. * * @param exclusions - * The strings to exclude from splitting. + * The strings to exclude from splitting. */ public final void addLiteralExclusions(final String... exclusions) { - for (final String exclusion : exclusions) { + for(final String exclusion : exclusions) { literalExclusions.add(exclusion); } } @@ -51,21 +51,22 @@ public class ExcludingTokenSplitter implements TokenSplitter { * splitting. * * @param exclusions - * The predicates to use for exclusions. + * The predicates to use for exclusions. */ @SafeVarargs public final void addPredicateExclusion(final Predicate<String>... exclusions) { - for (final Predicate<String> exclusion : exclusions) { + for(final Predicate<String> exclusion : exclusions) { predExclusions.add(exclusion); } } @Override public IList<String> split(final String input) { - if (literalExclusions.contains(input)) + if(literalExclusions.contains(input)) return new FunctionalList<>(input); - else if (predExclusions.anyMatch(pred -> pred.test(input))) + else if(predExclusions.anyMatch(pred -> pred.test(input))) return new FunctionalList<>(input); - else return spliter.split(input); + else + return spliter.split(input); } } diff --git a/base/src/main/java/bjc/utils/parserutils/splitter/FilteredTokenSplitter.java b/base/src/main/java/bjc/utils/parserutils/splitter/FilteredTokenSplitter.java index 5d954e0..87d950b 100644 --- a/base/src/main/java/bjc/utils/parserutils/splitter/FilteredTokenSplitter.java +++ b/base/src/main/java/bjc/utils/parserutils/splitter/FilteredTokenSplitter.java @@ -20,10 +20,10 @@ public class FilteredTokenSplitter implements TokenSplitter { * Create a new filtered token splitter. * * @param source - * The splitter to get tokens from. + * The splitter to get tokens from. * * @param filter - * The filter to pass tokens through. + * The filter to pass tokens through. */ public FilteredTokenSplitter(TokenSplitter source, Predicate<String> filter) { this.source = source; diff --git a/base/src/main/java/bjc/utils/parserutils/splitter/SimpleTokenSplitter.java b/base/src/main/java/bjc/utils/parserutils/splitter/SimpleTokenSplitter.java index c357886..c96f72a 100644 --- a/base/src/main/java/bjc/utils/parserutils/splitter/SimpleTokenSplitter.java +++ b/base/src/main/java/bjc/utils/parserutils/splitter/SimpleTokenSplitter.java @@ -21,10 +21,10 @@ public class SimpleTokenSplitter implements TokenSplitter { * Create a new simple token splitter. * * @param splitter - * The pattern to split around. + * The pattern to split around. * * @param keepDelims - * Whether or not delimiters should be kept. + * Whether or not delimiters should be kept. */ public SimpleTokenSplitter(final Pattern splitter, final boolean keepDelims) { spliter = splitter; @@ -34,9 +34,10 @@ public class SimpleTokenSplitter implements TokenSplitter { @Override public IList<String> split(final String input) { - if (keepDelim) + if(keepDelim) return RegexStringEditor.mapOccurances(input, spliter, ID.id(), ID.id()); - else return RegexStringEditor.mapOccurances(input, spliter, ID.id(), strang -> ""); + else + return RegexStringEditor.mapOccurances(input, spliter, ID.id(), strang -> ""); } @Override diff --git a/base/src/main/java/bjc/utils/parserutils/splitter/TokenSplitter.java b/base/src/main/java/bjc/utils/parserutils/splitter/TokenSplitter.java index ddb28a7..b042b8c 100644 --- a/base/src/main/java/bjc/utils/parserutils/splitter/TokenSplitter.java +++ b/base/src/main/java/bjc/utils/parserutils/splitter/TokenSplitter.java @@ -13,7 +13,7 @@ public interface TokenSplitter { * Split a string into a list of pieces. * * @param input - * The string to split. + * The string to split. * * @return The pieces of the string. */ diff --git a/base/src/main/java/bjc/utils/parserutils/splitter/TransformTokenSplitter.java b/base/src/main/java/bjc/utils/parserutils/splitter/TransformTokenSplitter.java index 80490f5..1aa894d 100644 --- a/base/src/main/java/bjc/utils/parserutils/splitter/TransformTokenSplitter.java +++ b/base/src/main/java/bjc/utils/parserutils/splitter/TransformTokenSplitter.java @@ -20,10 +20,10 @@ public class TransformTokenSplitter implements TokenSplitter { * Create a new transforming splitter. * * @param source - * The splitter to use as a source. + * The splitter to use as a source. * * @param transform - * The transform to apply to tokens. + * The transform to apply to tokens. */ public TransformTokenSplitter(TokenSplitter source, UnaryOperator<String> transform) { this.source = source; |
